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
[Transformations] QSAIndexer fusion transformation (#39342)
Mikhail Ryzhov154c1eecbad6
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.rstindex b3aa8a16c0c..4f9568133f3 100644--- 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.rst@@ -448,6 +448,24 @@ multiplication.* **Required**: *no** **Constraints**: ``scale > 0``.+* *query_norm*++ * **Description**: Whether query RMSNorm has been absorbed into the indexer. ``false`` is an intermediate+ graph-fusion state in which query normalization remains outside the operation.+ * **Type**: ``boolean``+ * **Default value**: ``true``+ * **Required**: *no*+ * **Constraints**: Must be ``true`` for execution.++* *query_rope*++ * **Description**: Whether query RoPE has been absorbed into the indexer. ``false`` is an intermediate+ graph-fusion state in which query rotation remains outside the operation.+ * **Type**: ``boolean``+ * **Default value**: ``true``+ * **Required**: *no*+ * **Constraints**: Must be ``true`` for execution.+**Inputs**diff --git a/src/common/transformations/include/sources.cmake b/src/common/transformations/include/sources.cmakeindex a2ce139028b..837ad25279b 100644--- a/src/common/transformations/include/sources.cmake+++ b/src/common/transformations/include/sources.cmake@@ -88,6 +88,7 @@ set(COMMON_OPTIMIZATIONS_HEADERS${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fuse_clamp_and_fake_quantize.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fuse_gated_delta_net.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fuse_moe_experts.hpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fuse_qsa_indexer.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fuse_ssm.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fused_names_cleanup.hpp@@ -292,6 +293,7 @@ set(PAGED_ATTENTION_HEADERS${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/gemma4_mtp_state_management_pattern.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/paged_causal_conv1d_fusion.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/paged_gated_delta_net_fusion.hpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/paged_qsa_indexer_fusion.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/position_ids_replacer.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/prev_sequence_length_pattern.hpp${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/state_management_pattern.hppdiff --git a/src/common/transformations/include/transformations/common_optimizations/fuse_qsa_indexer.hpp b/src/common/transformations/include/transformations/common_optimizations/fuse_qsa_indexer.hppnew file mode 100644index 00000000000..f025b4975d2--- /dev/null+++ b/src/common/transformations/include/transformations/common_optimizations/fuse_qsa_indexer.hpp@@ -0,0 +1,151 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <type_traits>++#include "openvino/pass/matcher_pass.hpp"+#include "openvino/pass/pass.hpp"+#include "transformations_visibility.hpp"++namespace ov::op::internal {+class QSAIndexer;+class PagedQSAIndexer;+} // namespace ov::op::internal++namespace ov::pass {++/**+ * @ingroup ov_transformation_common_api+ * @brief Fuses QSAPrepare and SparseAttentionIndexer into the stateful internal QSAIndexer op, leaving query-side+ * RMSNorm and RoPE outside the op (query_norm and query_rope disabled).+ * The disabled flags are intermediate fusion states only: query preprocessing must be absorbed by+ * FuseQSAIndexerQuery and both flags must be true before the indexer is executed.+ *+ * Query RawKeys cos/sin ... KeyLength Query+ * │ │ │ │ │+ * │ ┌──┴───────┴────────────┴──┐ Transpose RawKeys cos/sin ... KeyLength+ * │ │ QSAPrepare │ │ [layout adapters, padding: cache growth / trim]+ * │ └──┬────────┬──────────┬───┘ ┌──┴──────────┴───────┴───────────┴──┐+ * ┌──────┴───────┴──┐ │ │ ──► │ QSAIndexer │+ * │ SparseAttention │ incomplete keys / rope └──┬──────┬───────┬───────┬──────────┘+ * │ Indexer │ indices count Squeeze Squeeze incomplete+ * └──┬──────────┬───┘ block incomplete rope+ * indices count keys keys+ *+ * QSAIndexer takes [B, L, H, D] activations and head-first states, so the pass adds adapters:+ * - the [B, H, L, D] query is transposed;+ * - the raw keys get a head axis 2, and the block-key cache and incomplete keys get a head axis 1,+ * which is squeezed from the matching QSAIndexer outputs;+ * - key_length is converted to i32 and broadcast unless its statically known length equals the raw-key+ * batch size;+ * - cos / sin are broadcast unless their statically known batch sizes equal the raw-key batch size;+ * dynamic batch dimensions are not assumed equal without shape-symbol propagation;+ * - the block-key cache handling follows the padding argument:+ * - padding == true: the cache is grown by zero blocks when the incoming cache is smaller than the complete+ * blocks of the longest sequence, and the returned cache is sliced to the complete-block count expected+ * from QSAPrepare, for implementations that keep the cache shape;+ * - padding == false: the cache is passed as is, for implementations that follow the QSAPrepare-17 cache+ * contract at runtime (the returned cache holds max(key_length) / key_block_size blocks); the static+ * output shape of QSAIndexer still reports the input cache shape;+ * - q_norm_weight is a vector of ones.+ * block_topk is token_budget / key_block_size and scale is set explicitly to the default 1 / sqrt(head size).+ *+ * The rewrite is applied only when the query and the raw keys have compatible sequence lengths, the query+ * head count and head size are static, RoPE and the key norm are enabled, both source ops use the same+ * key_block_size and key length, and SparseAttentionIndexer consumes QSAPrepare output 0, has no index weights+ * and selects with one head. The other requirements are validated by the source ops.+ */+class TRANSFORMATIONS_API FuseQSAIndexer : public MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("FuseQSAIndexer");++ /// \param padding Grows the block-key cache before QSAIndexer and trims it after, see the class description.+ explicit FuseQSAIndexer(bool padding);+};++/**+ * @ingroup ov_transformation_common_api+ * @brief Moves the query RoPE into a dense or paged QSA indexer, enabling query_rope.+ *+ * x ─► RoPE(input_trans0213) ─► Transpose(0, 2, 1, 3) ─► QSAIndexer ──► x ─► QSAIndexer(query_rope)+ *+ * The RoPE is the plain rotate-half RoPE of the QSAIndexer rotary dimension, with Unsqueeze(axis=1) of the+ * QSAIndexer cos / sin (before their batch Broadcast). A Reshape with a constant target from [B, L, D] to+ * [B, 1, L, D] is also supported when L and D are static and positive. It is fused while query_rope is disabled.+ * QSAIndexer normalizes before it rotates, so it must run before FuseQSAIndexerQueryNorm, as FuseQSAIndexerQuery+ * does; the query_norm of the matched indexer is not checked.+ * The PagedQSAIndexer specialization requires the layout adapters produced by PagedQSAIndexerFusion:+ * query [B, L, H, D] -> [B * L, H * D] and cos/sin [B, L, rotary_dim] -> [B * L, rotary_dim].+ * It relies on that contract rather than revalidating the layouts. The patterns use optional rank-2+ * Reshape adapters, which the dense path bypasses. A new query Reshape preserves the layout target and attributes+ * while consuming the unprocessed query; other consumers of the original Reshape remain unchanged.+ * The paged single-token form may use a Reshape instead of the input Transpose, with no output Transpose before+ * the flattening Reshape. The input Reshape is not checked and must preserve the corresponding query layout:+ *+ * x[B, 1, H, D] ─► Reshape[B, H, 1, D] ─► RoPE ─► Reshape[B, H * D] ─► PagedQSAIndexer+ *+ * Both specializations share PassConfig disable settings and callbacks, which receive the concrete indexer node.+ */+template <class Indexer>+class TRANSFORMATIONS_API FuseQSAIndexerQueryRoPE : public MatcherPass {+ static_assert(std::is_same_v<Indexer, ov::op::internal::QSAIndexer> ||+ std::is_same_v<Indexer, ov::op::internal::PagedQSAIndexer>,+ "FuseQSAIndexerQueryRoPE supports QSAIndexer and PagedQSAIndexer");++public:+ OPENVINO_MATCHER_PASS_RTTI("FuseQSAIndexerQueryRoPE");++ FuseQSAIndexerQueryRoPE();+};++/**+ * @ingroup ov_transformation_common_api+ * @brief Moves the query RMSNorm into a dense or paged QSA indexer, enabling query_norm.+ *+ * x ─► RMS ─► QSAIndexer ──► x ─► QSAIndexer(query_norm)+ *+ * The RMS is the last-axis RMS that keeps the precision, and its epsilon equals the QSAIndexer epsilon. Both+ * non-affine RMS and affine RMS with matching gamma precision and shape [D] or [1,...,1,D] are supported;+ * affine gamma is flattened to [D] as q_norm_weight.+ * It is fused while query_norm is disabled, regardless of query_rope.+ * The PagedQSAIndexer specialization requires the layout adapters produced by PagedQSAIndexerFusion.+ * It matches RMS before the query's [B, L, H, D] -> [B * L, H * D] Reshape. The RMS axis+ * must be static and equal to indexer_head_dim, so a norm across flattened heads remains outside the indexer.+ * An optional rank-2 Reshape matches the paged layout adapter, which the dense path bypasses. A new Reshape+ * consumes the unprocessed query without modifying the original Reshape or its other consumers.+ * Both specializations share PassConfig disable settings and callbacks, which receive the concrete indexer node.+ */+template <class Indexer>+class TRANSFORMATIONS_API FuseQSAIndexerQueryNorm : public MatcherPass {+ static_assert(std::is_same_v<Indexer, ov::op::internal::QSAIndexer> ||+ std::is_same_v<Indexer, ov::op::internal::PagedQSAIndexer>,+ "FuseQSAIndexerQueryNorm supports QSAIndexer and PagedQSAIndexer");++public:+ OPENVINO_MATCHER_PASS_RTTI("FuseQSAIndexerQueryNorm");++ FuseQSAIndexerQueryNorm();+};++/**+ * @ingroup ov_transformation_common_api+ * @brief Absorbs canonical query RMS and RoPE into dense and paged QSA indexers.+ *+ * Register after RMSFusion and RoPEFusion, before passes that combine or decompose RMS/RoPE.+ * Does not run those model-wide canonicalization passes itself. Runs the dense and paged FuseQSAIndexerQueryRoPE+ * over the whole model first and FuseQSAIndexerQueryNorm second, with the caller's PassConfig, since QSAIndexer+ * normalizes before it rotates. Specializations share PassConfig callbacks and disable settings.+ * Paged indexers must retain the layout adapters generated by PagedQSAIndexerFusion.+ */+class TRANSFORMATIONS_API FuseQSAIndexerQuery : public ModelPass {+public:+ OPENVINO_MODEL_PASS_RTTI("FuseQSAIndexerQuery");++ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;+};++} // namespace ov::passdiff --git a/src/common/transformations/include/transformations/paged_attention/paged_qsa_indexer_fusion.hpp b/src/common/transformations/include/transformations/paged_attention/paged_qsa_indexer_fusion.hppnew file mode 100644index 00000000000..91c98543a32--- /dev/null+++ b/src/common/transformations/include/transformations/paged_attention/paged_qsa_indexer_fusion.hpp@@ -0,0 +1,56 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <string>+#include <unordered_set>++#include "openvino/pass/matcher_pass.hpp"+#include "openvino/pass/sdpa_to_paged_attention.hpp"+#include "transformations_visibility.hpp"++namespace ov::pass {++/**+ * @ingroup ov_transformation_common_api+ * @brief Converts a stateful internal QSAIndexer, as created by FuseQSAIndexer, to internal PagedQSAIndexer.+ *+ * query, raw keys, cos / sin ──────────────────────────► Reshape [B * L, width] ─┐+ * q / k norm weights ────────────────────────────────────────────────────────────┤+ * past_lens, subsequence_begins, ├─► PagedQSAIndexer+ * block_indices, block_indices_begins ───────────────────────────────────────────┤ │ │+ * index_key_cache.N, index_block_rope_cache.N, block_index_keys_cache.N ─────────┘ indices count+ * │ │+ * Reshape [B, L, S, ...], Transpose to [B, S, L, ...]+ *+ * The selections of PagedQSAIndexer are token-major, so they are restored to the dense [B, S, L, ...] layout of+ * QSAIndexer for the existing consumers.+ * The paging inputs are shared with PagedAttention, block_indices included, and are added to pa_params if missing.+ * The caller must add the new parameters from pa_params.items() to the model. Each converted indexer gets its own+ * three caches, which share the main KV page table, so their page size is the PagedAttention block size.+ * The dense states must be read from variables, directly or through the beam Gather, in the layout created by+ * FuseQSAIndexer. Their variable ids are added to var_ids_to_remove; the caller must remove the associated+ * Assign sinks.+ * The effective score scale is stored explicitly as a positive value in the paged op.+ *+ * Query normalization/rotation flags are preserved. FuseQSAIndexerQuery must absorb any remaining query+ * preprocessing and enable both flags before the paged indexer is executed.+ * The query and raw keys must have static head counts to construct the flattened inputs and cache shapes.+ * The pattern requires nonzero flattened widths that fit in int64_t and a nonzero rotary dimension.+ * The conversion relies on the QSAIndexer input [B, L] contract; after flattening, PagedQSAIndexer can validate only+ * the token count.+ * Supported data types are checked by the target plugin.+ */+class TRANSFORMATIONS_API PagedQSAIndexerFusion : public MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("PagedQSAIndexerFusion");++ PagedQSAIndexerFusion(paged_attention::PaParams& pa_params, std::unordered_set<std::string>& var_ids_to_remove);++private:+ size_t m_layer_index = 0;+};++} // namespace ov::passdiff --git a/src/common/transformations/src/sources.cmake b/src/common/transformations/src/sources.cmakeindex 2ee69a0dc4b..3823ad2b820 100644--- a/src/common/transformations/src/sources.cmake+++ b/src/common/transformations/src/sources.cmake@@ -50,6 +50,7 @@ set(COMMON_OPTIMIZATIONS_SOURCES${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fuse_clamp_and_fake_quantize.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fuse_gated_delta_net.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fuse_moe_experts.cpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fuse_qsa_indexer.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fuse_ssm.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/common_optimizations/fused_names_cleanup.cpp@@ -254,6 +255,7 @@ set(PAGED_ATTENTION_SOURCES${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/gemma4_mtp_state_management_pattern.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/paged_causal_conv1d_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/paged_gated_delta_net_fusion.cpp+ ${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/paged_qsa_indexer_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/paged_selective_ssm_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/position_ids_replacer.cpp${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/prev_sequence_length_pattern.cppdiff --git a/src/common/transformations/src/transformations/common_optimizations/fuse_qsa_indexer.cpp b/src/common/transformations/src/transformations/common_optimizations/fuse_qsa_indexer.cppnew file mode 100644index 00000000000..6483052a638--- /dev/null+++ b/src/common/transformations/src/transformations/common_optimizations/fuse_qsa_indexer.cpp@@ -0,0 +1,462 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/common_optimizations/fuse_qsa_indexer.hpp"++#include <algorithm>+#include <vector>++#include "itt.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/maximum.hpp"+#include "openvino/op/paged_qsa_indexer.hpp"+#include "openvino/op/qsa_indexer.hpp"+#include "openvino/op/qsa_prepare.hpp"+#include "openvino/op/reduce_max.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/sparse_attention_indexer.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/pass/node_registry.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/or.hpp"+#include "openvino/pass/pattern/op/pattern.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "ov_ops/rms.hpp"+#include "ov_ops/rotary_positional_embeddings.hpp"+#include "transformations/utils/utils.hpp"++namespace ov::pass {++namespace v0 = ov::op::v0;+namespace v1 = ov::op::v1;+namespace v3 = ov::op::v3;+namespace v17 = ov::op::v17;+namespace v8 = ov::op::v8;+namespace op_internal = ov::op::internal;+using QSAIndexerOutputIdx = op_internal::QSAIndexer::OutputIdx;++FuseQSAIndexer::FuseQSAIndexer(bool padding) {+ MATCHER_SCOPE(FuseQSAIndexer);+ using namespace ov::pass::pattern;++ constexpr size_t query_heads_axis = 1;+ constexpr size_t query_sequence_axis = 2;+ constexpr size_t query_head_dim_axis = 3;+ constexpr size_t keys_sequence_axis = 1;+ constexpr size_t rotary_dim_axis = 2;++ // QSAIndexer kernels are specialized for the query head count, the head size and the rotary dimension.+ // The ranks are fixed, since the callback reads the dimensions.+ const auto p_query = any_input(rank_equals(4) && has_static_dims({query_heads_axis, query_head_dim_axis}));+ const auto p_raw_keys = any_input(rank_equals(3));+ const auto p_past_block_keys = any_input();+ const auto p_key_length = any_input(rank_equals(1));+ const auto p_rope_cos = any_input(rank_equals(3) && has_static_dim(rotary_dim_axis));+ const auto p_rope_sin = any_input(rank_equals(3));+ const auto p_k_norm_weight = any_input(rank_equals(1));+ const auto p_incomplete_raw_keys = any_input();+ const auto p_incomplete_rope = any_input();+ const auto p_prepare = wrap_type_strict_index<v17::QSAPrepare>({p_raw_keys,+ p_past_block_keys,+ p_key_length,+ p_rope_cos,+ p_rope_sin,+ p_k_norm_weight,+ p_incomplete_raw_keys,+ p_incomplete_rope});++ const auto p_indexer = wrap_type<v17::SparseAttentionIndexer>({p_query, p_prepare->output(0), p_key_length},+ {{"num_selection_heads", 1}});++ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {+ const auto& pattern_map = m.get_pattern_value_map();+ const auto indexer =+ ov::as_type_ptr<v17::SparseAttentionIndexer>(pattern_map.at(p_indexer).get_node_shared_ptr());+ OPENVINO_ASSERT(indexer, "FuseQSAIndexer: matched node is expected to be SparseAttentionIndexer");+ if (transformation_callback(indexer)) {+ return false;+ }+ const auto prepare = ov::as_type_ptr<v17::QSAPrepare>(m.get_pattern_map().at(p_prepare));+ OPENVINO_ASSERT(prepare, "FuseQSAIndexer: matched node is expected to be QSAPrepare");++ const auto& query = pattern_map.at(p_query);+ const auto& raw_keys = pattern_map.at(p_raw_keys);+ const auto& k_norm_weight = pattern_map.at(p_k_norm_weight);+ const auto& head_dim = query.get_partial_shape()[query_head_dim_axis];+ // QSAIndexer takes the query and the raw keys for the same tokens, a single key_block_size and an enabled+ // key norm; the source ops validate the other head sizes against the query.+ if (!query.get_partial_shape()[query_sequence_axis].compatible(+ raw_keys.get_partial_shape()[keys_sequence_axis]) ||+ indexer->get_key_block_size() != prepare->get_key_block_size() ||+ !k_norm_weight.get_partial_shape()[0].compatible(head_dim)) {+ return false;+ }+ const auto& past_block_keys = pattern_map.at(p_past_block_keys);+ const auto& key_length = pattern_map.at(p_key_length);+ const auto& incomplete_raw_keys = pattern_map.at(p_incomplete_raw_keys);+ const auto& incomplete_rope = pattern_map.at(p_incomplete_rope);+ const auto& rope_cos = pattern_map.at(p_rope_cos);+ const auto& rope_sin = pattern_map.at(p_rope_sin);++ // The source ops validate the batch, the head size, element types and token_budget % key_block_size == 0.+ const auto key_block_size = prepare->get_key_block_size();+ const auto data_type = raw_keys.get_element_type();+ const auto& batch_dim = raw_keys.get_partial_shape()[0];+ op_internal::QSAIndexer::Config config;+ config.key_block_size = static_cast<size_t>(key_block_size);+ config.block_topk = static_cast<size_t>(indexer->get_token_budget() / key_block_size);+ config.indexer_rotary_dim = static_cast<size_t>(rope_cos.get_partial_shape()[rotary_dim_axis].get_length());+ config.indexer_head_dim = static_cast<size_t>(head_dim.get_length());+ config.epsilon = prepare->get_epsilon();+ config.scale = op_internal::QSAIndexer::effective_scale(config);+ config.query_norm = false;+ config.query_rope = false;++ // QSAIndexer takes [B, L, H, D] activations and head-first states, while the public ops are head-first for+ // the query and head-less for the keys.+ ov::pass::NodeRegistry rg;+ const ov::NodeVector sources{prepare, indexer};+ // The shape and length subgraphs are built in i32: plugins may run this pass after lowering i64, so i64+ // tensors created here could reach kernels or shape subgraphs that support only i32.+ const auto dims_of = [&sources](const ov::Output<ov::Node>& data, const std::vector<size_t>& axes) {+ return ov::op::util::node_to_get_shape_value_of_indices_from_shape_source(data,+ axes,+ sources,+ ov::element::i32);+ };++ const auto q_norm_weight =+ rg.make<v0::Constant>(data_type, ov::Shape{config.indexer_head_dim}, std::vector<float>{1.0f});+ const auto zero = v0::Constant::create(ov::element::i32, ov::Shape{1}, {0});+ const auto one = v0::Constant::create(ov::element::i32, ov::Shape{1}, {1});+ const auto activation_head_axis = v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});+ const auto state_head_axis = v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});+ const auto raw_keys_blhd = rg.make<v0::Unsqueeze>(raw_keys, activation_head_axis);+ const auto incomplete_raw_keys_with_head = rg.make<v0::Unsqueeze>(incomplete_raw_keys, state_head_axis);+ // The Broadcasts below are skipped only when the batches are proven equal by static values.+ const auto is_batch = [&batch_dim](const ov::Dimension& dim) {+ return dim.is_static() && batch_dim.is_static() && dim.get_length() == batch_dim.get_length();+ };+ // key_length is [N] or [1].+ ov::Output<ov::Node> batched_key_length = key_length;+ if (!is_batch(key_length.get_partial_shape()[0])) {+ batched_key_length = rg.make<v3::Broadcast>(key_length, dims_of(raw_keys, {0}));+ }++ // QSAPrepare broadcasts cos / sin of a single row over the batch, while QSAIndexer takes them per row.+ const auto rope_for_batch = [&](const ov::Output<ov::Node>& rope) -> ov::Output<ov::Node> {+ if (is_batch(rope.get_partial_shape()[0])) {+ return rope;+ }+ const auto target = rg.add(ov::op::util::make_try_fold<v0::Concat>(+ ov::OutputVector{dims_of(raw_keys, {0, keys_sequence_axis}),+ v0::Constant::create(ov::element::i32, ov::Shape{1}, {config.indexer_rotary_dim})},+ 0));+ return rg.make<v3::Broadcast>(rope, target);+ };++ const auto key_length_i32 = key_length.get_element_type() == ov::element::i32+ ? batched_key_length+ : rg.make<v0::Convert>(batched_key_length, ov::element::i32);++ // Without padding, QSAIndexer follows the QSAPrepare cache contract and takes the cache as is.+ // With padding, QSAIndexer keeps the cache shape, while QSAPrepare output 0 holds the complete blocks of the+ // longest sequence, so the cache is grown by zero blocks before the call.+ ov::Output<ov::Node> block_keys_cache = rg.make<v0::Unsqueeze>(past_block_keys, state_head_axis);+ ov::Output<ov::Node> needed_blocks;+ if (padding) {+ const auto max_key_length = rg.make<v1::ReduceMax>(key_length_i32, zero, true);+ needed_blocks = rg.make<v1::Divide>(max_key_length,+ v0::Constant::create(ov::element::i32, ov::Shape{1}, {key_block_size}));+ const auto past_block_count = dims_of(past_block_keys, {1});+ const auto missing_blocks = rg.make<v1::Subtract>(needed_blocks, past_block_count);+ const auto cache_growth_blocks = rg.make<v1::Maximum>(missing_blocks, zero);+ const auto cache_growth_shape = rg.add(ov::op::util::make_try_fold<v0::Concat>(+ ov::OutputVector{dims_of(raw_keys, {0}),+ one,+ cache_growth_blocks,+ v0::Constant::create(ov::element::i32, ov::Shape{1}, {config.indexer_head_dim})},+ 0));+ const auto zero_key = rg.make<v0::Constant>(data_type, ov::Shape{}, std::vector<float>{0.0f});+ const auto cache_padding = rg.make<v3::Broadcast>(zero_key, cache_growth_shape);+ constexpr int64_t state_blocks_axis = 2;+ block_keys_cache =+ rg.make<v0::Concat>(ov::OutputVector{block_keys_cache, cache_padding}, state_blocks_axis);+ }++ const auto query_blhd =+ rg.make<v1::Transpose>(query, v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3}));+ const auto fused = rg.make<op_internal::QSAIndexer>(ov::OutputVector{query_blhd,+ raw_keys_blhd,+ rope_for_batch(rope_cos),+ rope_for_batch(rope_sin),+ key_length_i32,+ q_norm_weight,+ k_norm_weight,+ block_keys_cache,+ incomplete_raw_keys_with_head,+ incomplete_rope},+ config);+ fused->set_friendly_name(indexer->get_friendly_name());+ register_new_node(fused);+ // The squeezed states replace QSAPrepare outputs 0 and 1, so they are named after them.+ const auto squeeze_state = [&](size_t fused_output, size_t prepare_output) {+ const auto squeeze = rg.make<v0::Squeeze>(fused->output(fused_output), state_head_axis);+ squeeze->set_friendly_name(prepare->get_friendly_name() + "." + std::to_string(prepare_output));+ return squeeze;+ };+ ov::Output<ov::Node> block_keys = squeeze_state(QSAIndexerOutputIdx::BLOCK_INDEX_KEYS_CACHE, 0);+ if (padding) {+ // QSAIndexer returns the grown cache on BLOCK_INDEX_KEYS_CACHE, while QSAPrepare output 0 holds only the+ // complete blocks of the longest sequence, so the replacement is sliced back to that block count.+ // A Constant key_length folds the count so the sliced shape stays as static as the original output.+ ov::Output<ov::Node> block_count = needed_blocks;+ if (const auto lengths = ov::as_type_ptr<v0::Constant>(key_length.get_node_shared_ptr())) {+ const auto values = lengths->cast_vector<int64_t>();+ if (!values.empty()) {+ const auto max_length = *std::max_element(values.begin(), values.end());+ block_count = v0::Constant::create(ov::element::i32, ov::Shape{1}, {max_length / key_block_size});+ }+ }+ block_keys.get_node()->set_friendly_name(prepare->get_friendly_name() + ".0.capacity");+ // Expose only the required block range, not any extra capacity added before QSAIndexer.+ const auto sliced = rg.make<v8::Slice>(block_keys, zero, block_count, one, one);+ sliced->set_friendly_name(prepare->get_friendly_name() + ".0");+ block_keys = sliced;+ }+ const auto incomplete_raw_keys_out = squeeze_state(QSAIndexerOutputIdx::PAST_INCOMPLETE_RAW_K, 1);+ ov::copy_runtime_info(sources, rg.get());++ // replace_node/replace_output_update_name do not support replacing two multi-output producers with one node.+ // Output::replace moves consumers, tensor names, and output runtime info.+ indexer->output(0).replace(fused->output(QSAIndexerOutputIdx::SELECTED_BLOCK_INDICES));+ indexer->output(1).replace(fused->output(QSAIndexerOutputIdx::SELECTED_BLOCK_COUNT));+ prepare->output(0).replace(block_keys);+ prepare->output(1).replace(incomplete_raw_keys_out);+ prepare->output(2).replace(fused->output(QSAIndexerOutputIdx::PAST_INCOMPLETE_ROPE));+ return true;+ };++ register_matcher(std::make_shared<Matcher>(p_indexer, matcher_name), callback);+}++template <class Indexer>+FuseQSAIndexerQueryRoPE<Indexer>::FuseQSAIndexerQueryRoPE() {+ MATCHER_SCOPE(FuseQSAIndexerQueryRoPE);+ using namespace ov::pass::pattern;+ using In = typename Indexer::InputIdx;++ const auto p_query = any_input();+ const auto p_rope_cos = any_input();+ const auto p_rope_sin = any_input();+ // NopElimination can replace the head-axis Unsqueeze of [batch, length, D] with a Reshape.+ const auto with_head_axis = [](const ov::Output<ov::Node>& rows) {+ const auto unsqueeze = wrap_type<v0::Unsqueeze>({rows, wrap_type<v0::Constant>(value_matches("1"))});+ const auto reshape = wrap_type<v1::Reshape>({rows, wrap_const()}, [](const ov::Output<ov::Node>& output) {+ const auto& shape = output.get_node()->get_input_partial_shape(0);+ return shape.rank() == 3 && shape[1].is_static() && shape[1].get_length() > 0 && shape[2].is_static() &&+ shape[2].get_length() > 0 &&+ output.get_partial_shape() == ov::PartialShape{shape[0], 1, shape[1], shape[2]};+ });+ return unsqueeze | reshape;+ };+ const auto p_head_first = optional<v1::Reshape>({p_query, any_input()});+ const auto p_rope = wrap_type<op_internal::RoPE>(+ {p_head_first, with_head_axis(p_rope_cos), with_head_axis(p_rope_sin)},+ [](const ov::Output<ov::Node>& output) {+ const auto rope = ov::as_type<op_internal::RoPE>(output.get_node());+ auto config = rope->get_config();+ config.input_trans0213 = false;+ const auto& cos_shape = rope->get_input_partial_shape(1);+ return op_internal::is_plain_rotate_half(config) && cos_shape.rank().is_static() &&+ cos_shape[-1] == static_cast<int64_t>(config.rotary_ndims);+ },+ {{"config.input_interleaved", false}, {"config.use_rope_cache", false}});+ const auto p_token_major = optional<v1::Transpose>({p_rope, wrap_type<v0::Constant>(value_matches("0, 2, 1, 3"))});+ const auto p_query_reshape = optional<v1::Reshape>({p_token_major, any_input()}, rank_equals(2));+ // FuseQSAIndexer broadcasts the cos / sin rows with a v3 Broadcast, which ConvertBroadcast3 may turn into a+ // numpy v1 Broadcast before this pass.+ const auto rope_rows = [](const ov::Output<ov::Node>& rows) {+ const auto batch_rows = optional<v3::Broadcast>({rows, any_input()}) |+ wrap_type<v1::Broadcast>({rows, any_input(), any_input()}, {{"mode", "numpy"}});+ return optional<v1::Reshape>({batch_rows, any_input()}, rank_equals(2));+ };+ const auto p_cos_reshape = rope_rows(p_rope_cos);+ const auto p_sin_reshape = rope_rows(p_rope_sin);+ OutputVector pattern_inputs(In::COUNT);+ for (auto& input : pattern_inputs) {+ input = any_input();+ }+ pattern_inputs[In::INDEX_QUERY] = p_query_reshape;+ pattern_inputs[In::ROPE_COS] = p_cos_reshape;+ pattern_inputs[In::ROPE_SIN] = p_sin_reshape;+ const auto p_indexer = wrap_type<Indexer>(pattern_inputs, {{"query_rope", false}});++ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {+ const auto& pattern_map = m.get_pattern_value_map();+ const auto indexer = ov::as_type_ptr<Indexer>(m.get_match_root());+ OPENVINO_ASSERT(indexer, "FuseQSAIndexerQueryRoPE: expected QSA indexer");+ if (transformation_callback(indexer)) {+ return false;+ }+ const auto rope = ov::as_type_ptr<op_internal::RoPE>(pattern_map.at(p_rope).get_node_shared_ptr());+ OPENVINO_ASSERT(rope, "FuseQSAIndexerQueryRoPE: expected RoPE");+ const bool head_first = pattern_map.count(p_head_first) != 0;+ const bool transposed = pattern_map.count(p_token_major) != 0;+ if (rope->get_config().input_trans0213 != transposed ||+ (!transposed && (!head_first || !pattern_map.count(p_query_reshape)))) {+ return false;+ }+ const auto query = transposed ? rope->input_value(0) : pattern_map.at(p_query);+ auto config = indexer->get_config();+ config.query_rope = true;+ auto inputs = indexer->input_values();+ NodeRegistry rg;+ NodeVector sources{rope};+ if (head_first && !transposed) {+ sources.push_back(pattern_map.at(p_head_first).get_node_shared_ptr());+ }+ if (transposed) {+ sources.push_back(pattern_map.at(p_token_major).get_node_shared_ptr());+ }+ if (pattern_map.count(p_query_reshape)) {+ const auto query_reshape = pattern_map.at(p_query_reshape).get_node_shared_ptr();+ inputs[In::INDEX_QUERY] =+ rg.add(query_reshape->clone_with_new_inputs({query, query_reshape->input_value(1)}));+ sources.push_back(query_reshape);+ } else {+ inputs[In::INDEX_QUERY] = query;+ }+ const auto fused = rg.make<Indexer>(inputs, config);+ fused->set_friendly_name(indexer->get_friendly_name());+ sources.push_back(indexer);+ ov::copy_runtime_info(sources, rg.get());+ ov::replace_node(indexer, fused);+ register_new_node(fused);+ return true;+ };+ register_matcher(std::make_shared<Matcher>(p_indexer, matcher_name), callback);+}++template <class Indexer>+FuseQSAIndexerQueryNorm<Indexer>::FuseQSAIndexerQueryNorm() {+ MATCHER_SCOPE(FuseQSAIndexerQueryNorm);+ using namespace ov::pass::pattern;+ using In = typename Indexer::InputIdx;++ const auto keeps_precision = rank_more_than(0) && [](const ov::Output<ov::Node>& output) {+ return output.get_element_type() == output.get_node()->get_input_element_type(0);+ };+ const auto gamma_matches = [](const ov::Output<ov::Node>& output) {+ // Predicates run before inputs are matched, so guard the gamma access.+ const auto rms = output.get_node();+ if (rms->get_input_size() != 2 || rms->get_input_element_type(1) != output.get_element_type()) {+ return false;+ }+ const auto& gamma_shape = rms->get_input_partial_shape(1);+ // Gamma can be flattened to [D] only when its leading dimensions are singleton.+ return gamma_shape.rank().is_static() && gamma_shape.size() > 0 &&+ gamma_shape[-1] == output.get_partial_shape()[-1] &&+ std::all_of(gamma_shape.begin(), gamma_shape.end() - 1, [](const Dimension& dim) {+ return dim == 1;+ });+ };+ const auto p_gamma = any_input();+ const auto p_rms_affine = wrap_type<op_internal::RMS>({any_input(), p_gamma},+ keeps_precision && gamma_matches,+ {{"axis", -1}, {"elementwise_affine", true}});+ const auto p_rms_non_affine =+ wrap_type<op_internal::RMS>({any_input()}, keeps_precision, {{"axis", -1}, {"elementwise_affine", false}});+ const auto p_rms = p_rms_affine | p_rms_non_affine;+ const auto p_query_reshape = optional<v1::Reshape>({p_rms, any_input()}, rank_equals(2));+ OutputVector pattern_inputs(In::COUNT);+ for (auto& input : pattern_inputs) {+ input = any_input();+ }+ pattern_inputs[In::INDEX_QUERY] = p_query_reshape;+ const auto p_indexer = wrap_type<Indexer>(pattern_inputs, {{"query_norm", false}});++ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {+ const auto& pattern_map = m.get_pattern_value_map();+ const auto indexer = ov::as_type_ptr<Indexer>(m.get_match_root());+ OPENVINO_ASSERT(indexer, "FuseQSAIndexerQueryNorm: expected QSA indexer");+ auto config = indexer->get_config();+ const auto rms = ov::as_type_ptr<op_internal::RMS>(pattern_map.at(p_rms).get_node_shared_ptr());+ OPENVINO_ASSERT(rms, "FuseQSAIndexerQueryNorm: expected RMS");+ // The indexer normalizes each head separately; an RMS spanning several heads is not equivalent.+ const auto head_dim = Dimension(static_cast<int64_t>(config.indexer_head_dim));+ if (rms->get_epsilon() != config.epsilon || rms->get_output_partial_shape(0)[-1] != head_dim ||+ transformation_callback(indexer)) {+ return false;+ }+ config.query_norm = true;+ auto inputs = indexer->input_values();+ NodeRegistry rg;+ NodeVector sources{rms, indexer};+ if (pattern_map.count(p_query_reshape)) {+ const auto query_reshape = pattern_map.at(p_query_reshape).get_node_shared_ptr();+ inputs[In::INDEX_QUERY] =+ rg.add(query_reshape->clone_with_new_inputs({rms->input_value(0), query_reshape->input_value(1)}));+ sources.push_back(query_reshape);+ } else {+ inputs[In::INDEX_QUERY] = rms->input_value(0);+ }+ if (pattern_map.count(p_gamma)) {+ auto gamma = pattern_map.at(p_gamma);+ if (gamma.get_partial_shape().size() > 1) {+ const auto shape =+ rg.make<v0::Constant>(element::i64,+ Shape{1},+ std::vector<int64_t>{static_cast<int64_t>(config.indexer_head_dim)});+ gamma = rg.add(ov::op::util::make_try_fold<v1::Reshape>(gamma, shape, false));+ }+ inputs[In::Q_NORM_WEIGHT] = gamma;+ } else {+ // The non-affine RMS has no learned scaling, so use unit weights.+ inputs[In::Q_NORM_WEIGHT] = rg.make<v0::Constant>(inputs[In::Q_NORM_WEIGHT].get_element_type(),+ Shape{config.indexer_head_dim},+ std::vector<float>{1.0f});+ }+ const auto fused = rg.make<Indexer>(inputs, config);+ fused->set_friendly_name(indexer->get_friendly_name());+ ov::copy_runtime_info(sources, rg.get());+ ov::replace_node(indexer, fused);+ register_new_node(fused);+ return true;+ };+ register_matcher(std::make_shared<Matcher>(p_indexer, matcher_name), callback);+}++template class FuseQSAIndexerQueryRoPE<op_internal::QSAIndexer>;+template class FuseQSAIndexerQueryRoPE<op_internal::PagedQSAIndexer>;+template class FuseQSAIndexerQueryNorm<op_internal::QSAIndexer>;+template class FuseQSAIndexerQueryNorm<op_internal::PagedQSAIndexer>;++bool FuseQSAIndexerQuery::run_on_model(const std::shared_ptr<ov::Model>& model) {+ RUN_ON_MODEL_SCOPE(FuseQSAIndexerQuery);+ // QSAIndexer normalizes before it rotates, so RoPE is absorbed over the whole model before RMS.+ GraphRewrite rope;+ rope.set_pass_config(get_pass_config());+ rope.add_matcher<FuseQSAIndexerQueryRoPE<op_internal::QSAIndexer>>();+ rope.add_matcher<FuseQSAIndexerQueryRoPE<op_internal::PagedQSAIndexer>>();+ GraphRewrite norm;+ norm.set_pass_config(get_pass_config());+ norm.add_matcher<FuseQSAIndexerQueryNorm<op_internal::QSAIndexer>>();+ norm.add_matcher<FuseQSAIndexerQueryNorm<op_internal::PagedQSAIndexer>>();+ const bool rope_fused = rope.run_on_model(model);+ return norm.run_on_model(model) || rope_fused;+}++} // namespace ov::passdiff --git a/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp b/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cppindex fea3e71f96f..fa28814ed3b 100644--- a/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp@@ -204,7 +204,10 @@ RoPEFusionGPTNEOX::RoPEFusionGPTNEOX(int rank) {auto int32_max = std::numeric_limits<std::int32_t>::max();auto x2 = op_util::NewGenSlice(x, "half_ndims", int32_max, 1, rank - 1);- auto x2neg = pattern::wrap_type<v1::Multiply>({x2 | varsplit->output(1), -1.0f}, {{"auto_broadcast", "numpy"}});+ auto minus_one = pattern::wrap_type<v0::Constant>(pattern::value_matches("-1"));+ auto minus_one_convert = pattern::optional<v0::Convert>({minus_one});+ auto x2neg =+ pattern::wrap_type<v1::Multiply>({x2 | varsplit->output(1), minus_one_convert}, {{"auto_broadcast", "numpy"}});auto x1 = op_util::NewGenSlice(x, 0, "half_ndims", 1, rank - 1);auto x_rotate_half = pattern::wrap_type<v0::Concat>({x2neg, x1 | varsplit->output(0)}, {{"axis", -1}});diff --git a/src/common/transformations/src/transformations/paged_attention/paged_qsa_indexer_fusion.cpp b/src/common/transformations/src/transformations/paged_attention/paged_qsa_indexer_fusion.cppnew file mode 100644index 00000000000..65ff41d45c1--- /dev/null+++ b/src/common/transformations/src/transformations/paged_attention/paged_qsa_indexer_fusion.cpp@@ -0,0 +1,215 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/paged_attention/paged_qsa_indexer_fusion.hpp"++#include <limits>+#include <utility>+#include <vector>++#include "itt.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/paged_qsa_indexer.hpp"+#include "openvino/op/qsa_indexer.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/op/util/read_value_base.hpp"+#include "openvino/pass/node_registry.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "transformations/rt_info/keep_const_precision.hpp"+#include "transformations/utils/utils.hpp"++namespace ov::pass {++namespace v0 = ov::op::v0;+namespace v1 = ov::op::v1;+namespace op_internal = ov::op::internal;+using QSAIndexerInputIdx = op_internal::QSAIndexer::InputIdx;+using QSAIndexerOutputIdx = op_internal::QSAIndexer::OutputIdx;+using PagedQSAIndexerInputIdx = op_internal::PagedQSAIndexer::InputIdx;++namespace {++constexpr size_t heads_axis = 2;++op_internal::PagedQSAIndexer::Config paged_config_from(const op_internal::QSAIndexer::Config& config) {+ op_internal::PagedQSAIndexer::Config result;+ result.key_block_size = config.key_block_size;+ result.block_topk = config.block_topk;+ result.num_selection_heads = config.num_selection_heads;+ result.indexer_rotary_dim = config.indexer_rotary_dim;+ result.indexer_head_dim = config.indexer_head_dim;+ result.epsilon = config.epsilon;+ result.scale = op_internal::QSAIndexer::effective_scale(config);+ result.query_norm = config.query_norm;+ result.query_rope = config.query_rope;+ return result;+}++} // namespace++PagedQSAIndexerFusion::PagedQSAIndexerFusion(paged_attention::PaParams& pa_params,+ std::unordered_set<std::string>& var_ids_to_remove) {+ MATCHER_SCOPE(PagedQSAIndexerFusion);+ using namespace ov::pass::pattern;++ // QSAIndexer activations are [B, L, H, D], cos / sin are [B, L, rotary_dim].+ const auto p_query = any_input();+ const auto p_raw_keys = any_input();+ const auto p_rope_cos = any_input();+ const auto p_rope_sin = any_input();++ // The dense states are read from variables, directly or through the beam Gather, in the FuseQSAIndexer layout.+ const auto read_state = [](const std::shared_ptr<ov::Node>& p_read_value) {+ return optional<ov::op::v8::Gather>({p_read_value, any_input(), any_input()});+ };+ const auto p_block_keys_read = wrap_type<ov::op::util::ReadValueBase>();+ const auto p_raw_keys_read = wrap_type<ov::op::util::ReadValueBase>();+ const auto p_rope_read = wrap_type<ov::op::util::ReadValueBase>();+ // With FuseQSAIndexer padding, the block-key cache is grown by a Concat.+ const auto p_block_keys_cache =+ optional<v0::Concat>({wrap_type<v0::Unsqueeze>({read_state(p_block_keys_read), any_input()}), any_input()});+ const auto p_incomplete_raw_keys = wrap_type<v0::Unsqueeze>({read_state(p_raw_keys_read), any_input()});++ const auto flattenable_inputs = [](const ov::Output<ov::Node>& output) {+ const auto indexer = ov::as_type_ptr<op_internal::QSAIndexer>(output.get_node_shared_ptr());+ OPENVINO_ASSERT(indexer, "PagedQSAIndexerFusion: matched node is expected to be QSAIndexer");+ const auto& config = indexer->get_config();+ // The [-1, width] adapters require nonzero widths that fit in int64_t.+ if (config.indexer_rotary_dim == 0) {+ return false;+ }+ const auto max_heads = static_cast<size_t>(std::numeric_limits<int64_t>::max()) / config.indexer_head_dim;+ for (const auto input : {QSAIndexerInputIdx::INDEX_QUERY, QSAIndexerInputIdx::RAW_INDEX_KEYS}) {+ const auto& shape = indexer->get_input_partial_shape(input);+ if (shape.rank().is_dynamic() || shape[heads_axis].is_dynamic()) {+ return false;+ }+ const auto heads = shape[heads_axis].get_length();+ if (heads == 0 || static_cast<size_t>(heads) > max_heads) {+ return false;+ }+ }+ return true;+ };+ const auto p_indexer = wrap_type<op_internal::QSAIndexer>({p_query,+ p_raw_keys,+ p_rope_cos,+ p_rope_sin,+ any_input(),+ any_input(),+ any_input(),+ p_block_keys_cache,+ p_incomplete_raw_keys,+ read_state(p_rope_read)},+ flattenable_inputs);++ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS, &pa_params, &var_ids_to_remove](Matcher& m) {+ const auto indexer = ov::as_type_ptr<op_internal::QSAIndexer>(m.get_match_root());+ OPENVINO_ASSERT(indexer, "PagedQSAIndexerFusion: matched node is expected to be QSAIndexer");+ if (transformation_callback(indexer)) {+ return false;+ }+ const auto& pattern_map = m.get_pattern_value_map();+ const auto& query = pattern_map.at(p_query);+ const auto& raw_keys = pattern_map.at(p_raw_keys);+ const auto& config = indexer->get_config();+ const auto data_type = query.get_element_type();+ const auto& query_shape = query.get_partial_shape();+ const auto& keys_shape = raw_keys.get_partial_shape();+ const auto query_heads = query_shape[heads_axis].get_length();+ const auto key_heads = keys_shape[heads_axis].get_length();+ const auto paged_config = paged_config_from(config);+ const auto head_dim = static_cast<int64_t>(config.indexer_head_dim);+ const auto rotary_dim = static_cast<int64_t>(config.indexer_rotary_dim);+ const auto query_width = query_heads * head_dim;+ const auto key_width = key_heads * head_dim;++ pa_params.add("past_lens", ov::element::i32, ov::PartialShape{-1});+ pa_params.add("subsequence_begins", ov::element::i32, ov::PartialShape{-1});+ pa_params.add("block_indices", ov::element::i32, ov::PartialShape{-1});+ pa_params.add("block_indices_begins", ov::element::i32, ov::PartialShape{-1});++ // The caches use the main KV page table, so the page dimensions are dynamic.+ const auto layer = std::to_string(m_layer_index++);+ const auto add_cache = [&](const std::string& name, const ov::PartialShape& shape) {+ const auto cache = pa_params.add(name + "." + layer, data_type, shape);+ enable_keep_const_precision(cache);+ return cache;+ };+ const auto index_key_cache = add_cache("index_key_cache", {-1, key_heads, -1, head_dim});+ const auto index_block_rope_cache = add_cache("index_block_rope_cache", {-1, -1, 2 * rotary_dim});+ const auto block_index_keys_cache = add_cache("block_index_keys_cache", {-1, key_heads, -1, head_dim});+ for (const auto& p_read_value : {p_block_keys_read, p_raw_keys_read, p_rope_read}) {+ const auto read_value =+ ov::as_type_ptr<ov::op::util::ReadValueBase>(pattern_map.at(p_read_value).get_node_shared_ptr());+ var_ids_to_remove.insert(read_value->get_variable_id());+ }++ ov::pass::NodeRegistry rg;+ const auto flatten = [&](const ov::Output<ov::Node>& data, int64_t width) {+ return rg.make<v1::Reshape>(data,+ v0::Constant::create(ov::element::i64, ov::Shape{2}, {int64_t{-1}, width}),+ false);+ };+ ov::OutputVector inputs(PagedQSAIndexerInputIdx::COUNT);+ inputs[PagedQSAIndexerInputIdx::INDEX_QUERY] = flatten(query, query_width);+ inputs[PagedQSAIndexerInputIdx::RAW_INDEX_KEYS] = flatten(raw_keys, key_width);+ inputs[PagedQSAIndexerInputIdx::ROPE_COS] = flatten(pattern_map.at(p_rope_cos), rotary_dim);+ inputs[PagedQSAIndexerInputIdx::ROPE_SIN] = flatten(pattern_map.at(p_rope_sin), rotary_dim);+ inputs[PagedQSAIndexerInputIdx::Q_NORM_WEIGHT] = indexer->input_value(QSAIndexerInputIdx::Q_NORM_WEIGHT);+ inputs[PagedQSAIndexerInputIdx::K_NORM_WEIGHT] = indexer->input_value(QSAIndexerInputIdx::K_NORM_WEIGHT);+ inputs[PagedQSAIndexerInputIdx::PAST_LENS] = pa_params["past_lens"];+ inputs[PagedQSAIndexerInputIdx::SUBSEQUENCE_BEGINS] = pa_params["subsequence_begins"];+ inputs[PagedQSAIndexerInputIdx::BLOCK_INDICES] = pa_params["block_indices"];+ inputs[PagedQSAIndexerInputIdx::BLOCK_INDICES_BEGINS] = pa_params["block_indices_begins"];+ inputs[PagedQSAIndexerInputIdx::INDEX_KEY_CACHE] = index_key_cache;+ inputs[PagedQSAIndexerInputIdx::INDEX_BLOCK_ROPE_CACHE] = index_block_rope_cache;+ inputs[PagedQSAIndexerInputIdx::BLOCK_INDEX_KEYS_CACHE] = block_index_keys_cache;++ const auto paged = rg.make<op_internal::PagedQSAIndexer>(inputs, paged_config);+ paged->set_friendly_name(indexer->get_friendly_name());++ // The token-major selections [B * L, S, ...] are restored to the QSAIndexer layout [B, S, L, ...].+ const auto batch_and_length = ov::op::util::node_to_get_shape_value_of_indices_from_shape_source(query, {0, 1});+ const auto selection_heads = static_cast<int64_t>(config.num_selection_heads);+ const auto restore = [&](size_t output, const std::vector<int64_t>& tail, const std::vector<int64_t>& order) {+ const auto shape = rg.make<v0::Concat>(+ ov::OutputVector{batch_and_length,+ v0::Constant::create(ov::element::i64, ov::Shape{tail.size()}, tail)},+ 0);+ const auto token_major = rg.make<v1::Reshape>(paged->output(output), shape, false);+ return rg.make<v1::Transpose>(token_major,+ v0::Constant::create(ov::element::i64, ov::Shape{order.size()}, order));+ };+ const auto indices = restore(0, {selection_heads, static_cast<int64_t>(config.block_topk)}, {0, 2, 1, 3});+ const auto count = restore(1, {selection_heads}, {0, 2, 1});+ rg.add(batch_and_length);+ ov::copy_runtime_info(indexer, rg.get());+ register_new_node(paged);++ indexer->output(QSAIndexerOutputIdx::SELECTED_BLOCK_INDICES).replace(indices);+ indexer->output(QSAIndexerOutputIdx::SELECTED_BLOCK_COUNT).replace(count);+ // The dense states pass through unchanged; the caller must retire their variable sinks.+ const std::vector<std::pair<size_t, size_t>> states{+ {QSAIndexerOutputIdx::BLOCK_INDEX_KEYS_CACHE, QSAIndexerInputIdx::BLOCK_INDEX_KEYS_CACHE},+ {QSAIndexerOutputIdx::PAST_INCOMPLETE_RAW_K, QSAIndexerInputIdx::PAST_INCOMPLETE_RAW_K},+ {QSAIndexerOutputIdx::PAST_INCOMPLETE_ROPE, QSAIndexerInputIdx::PAST_INCOMPLETE_ROPE}};+ for (const auto& [output, input] : states) {+ for (const auto& consumer : indexer->output(output).get_target_inputs()) {+ consumer.replace_source_output(indexer->input_value(input));+ }+ }+ return true;+ };++ register_matcher(std::make_shared<Matcher>(p_indexer, matcher_name), callback);+}++} // namespace ov::passdiff --git a/src/common/transformations/src/transformations/paged_attention/state_management_pattern.cpp b/src/common/transformations/src/transformations/paged_attention/state_management_pattern.cppindex 80bdd17ba54..c62b08de5a1 100644--- a/src/common/transformations/src/transformations/paged_attention/state_management_pattern.cpp+++ b/src/common/transformations/src/transformations/paged_attention/state_management_pattern.cpp@@ -59,10 +59,6 @@ namespace v6 = ov::op::v6;namespace v8 = ov::op::v8;namespace v13 = ov::op::v13;namespace v15 = ov::op::v15;-constexpr const char* NUM_K_HEADS = "num_k_heads";-constexpr const char* K_HEAD_SIZE = "k_head_size";-constexpr const char* NUM_V_HEADS = "num_v_heads";-constexpr const char* V_HEAD_SIZE = "v_head_size";using namespace ov::pass;using ov::OutputVector;@@ -883,10 +879,10 @@ ov::pass::StateManagementPattern::StateManagementPattern(PaParams& pa_params,auto paged_attention =std::make_shared<ov::op::PagedAttentionExtension>(pa_arguments, kv_params.write_kv_cache);- paged_attention->get_rt_info()[NUM_K_HEADS] = num_k_heads;- paged_attention->get_rt_info()[K_HEAD_SIZE] = k_head_size;- paged_attention->get_rt_info()[NUM_V_HEADS] = num_v_heads;- paged_attention->get_rt_info()[V_HEAD_SIZE] = v_head_size;+ paged_attention->get_rt_info()["num_k_heads"] = num_k_heads;+ paged_attention->get_rt_info()["k_head_size"] = k_head_size;+ paged_attention->get_rt_info()["num_v_heads"] = num_v_heads;+ paged_attention->get_rt_info()["v_head_size"] = v_head_size;// The output shape of PagedAttention will be converted to [batch, 1, head_num, head_size_v], the head_size_v// may be different from head_size_q/head_size_k. The head_size_v could be got from the shape of value inputdiff --git a/src/common/transformations/tests/common_optimizations/fuse_qsa_indexer_test.cpp b/src/common/transformations/tests/common_optimizations/fuse_qsa_indexer_test.cppnew file mode 100644index 00000000000..797d11c49e9--- /dev/null+++ b/src/common/transformations/tests/common_optimizations/fuse_qsa_indexer_test.cpp@@ -0,0 +1,726 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/common_optimizations/fuse_qsa_indexer.hpp"++#include <gtest/gtest.h>++#include <algorithm>+#include <cmath>+#include <memory>+#include <string>+#include <vector>++#include "common_test_utils/ov_test_utils.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/maximum.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/power.hpp"+#include "openvino/op/qsa_indexer.hpp"+#include "openvino/op/qsa_prepare.hpp"+#include "openvino/op/reduce_max.hpp"+#include "openvino/op/reduce_mean.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/sparse_attention_indexer.hpp"+#include "openvino/op/sqrt.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/op/variadic_split.hpp"+#include "ov_ops/rms.hpp"+#include "ov_ops/rotary_positional_embeddings.hpp"+#include "transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp"+#include "transformations/common_optimizations/rms_fusion.hpp"+#include "transformations/utils/utils.hpp"++namespace {++using namespace ov;+namespace v0 = ov::op::v0;+namespace v1 = ov::op::v1;+namespace v3 = ov::op::v3;+namespace v8 = ov::op::v8;+namespace v17 = ov::op::v17;+namespace op_internal = ov::op::internal;+using ov::op::util::make_try_fold;+using QSAIndexerInputIdx = op_internal::QSAIndexer::InputIdx;+using QSAIndexerOutputIdx = op_internal::QSAIndexer::OutputIdx;++enum class QueryLayout {+ BHLD, // [B, H, L, D] raw query, RMSNorm and RoPE in this layout+ BLHDTransposed, // [B, L, H, D] raw query transposed to [B, H, L, D] after the norm, RoPE after the Transpose+ BLHDRoPEBeforeTranspose, // [B, L, H, D] raw query with RMSNorm and RoPE applied before the Transpose+ BLHDTransposeAfterRoPE, // [B, L, H, D] raw query, followed by a Transpose for SparseAttentionIndexer+};++// The query steps that QSAIndexer is expected to absorb.+enum class QueryFusion {+ None, // the base fusion: the SparseAttentionIndexer query, transposed to [B, L, H, D]+ RoPE, // the query RoPE: the RoPE input+ Full, // the query RoPE and RMSNorm: the raw query+};++struct GraphOptions {+ std::string name;+ QueryFusion query_fusion = QueryFusion::Full;+ // FuseQSAIndexer padding argument: the block-key cache is grown and trimmed around QSAIndexer.+ bool padding = true;+ element::Type precision = element::f32;+ QueryLayout query_layout = QueryLayout::BLHDTransposed;+ // cos / sin have a single row, which QSAPrepare broadcasts over the batch.+ bool single_row_rope = false;+ bool dynamic_shapes = false;+ element::Type key_length_type = element::i32;+ // The block-key cache and the incomplete raw keys of QSAPrepare are also model outputs.+ bool extra_state_consumers = false;+ // The SparseAttentionIndexer query is also a model output.+ bool extra_query_consumer = false;+ // Plugin compilation canonicalizes the decomposed query RMSNorm and RoPE before query absorption.+ // Only for QueryLayout::BLHDTransposed.+ bool decomposed_query = false;+ // Negative cases.+ bool query_rope = true;+ bool distinct_query_rope = false;+ bool distinct_query_sin = false;+ bool interleaved_query_rope = false;+ bool input_interleaved_query_rope = false;+ bool cached_query_rope = false;+ bool affine_query = false;+ bool converted_query = false;+ bool rms_changes_precision = false;+ int64_t rms_axis = -1;+ int64_t query_rope_axis = 1;+ int64_t query_rotary_dim = 0;+ float query_epsilon = 0; // 0 is the QSAPrepare epsilon+ int64_t rotary_dim = 0; // 0 is the whole head+ bool dynamic_query_heads = false;+ bool dynamic_head_size = false;+ bool dynamic_key_length_rank = false;+ bool disable_key_norm = false;+ bool disable_rope = false;+ bool use_distinct_key_length = false;+ bool add_index_weights = false;+ int64_t num_selection_heads = 1;+ int64_t indexer_key_block_size = 4;+ int64_t query_sequence = 3;+ int64_t keys_sequence = 3;+ int64_t cache_blocks = -1;+ std::vector<int64_t> key_length_values;+};++constexpr int64_t query_heads = 4;+constexpr int64_t head_size = 16;+constexpr int64_t key_block_size = 4;+constexpr int64_t token_budget = 8;+constexpr float epsilon = 1e-6f;++// The model inputs, which FuseQSAIndexer keeps, and the SparseAttentionIndexer query built from the raw query.+struct SharedGraph {+ ParameterVector parameters;+ Output<Node> raw_query;+ Output<Node> rope_input;+ Output<Node> query; // SparseAttentionIndexer query+ Output<Node> raw_keys, cache, key_length, rope_cos, rope_sin, key_weight, incomplete_keys, incomplete_rope;+ Output<Node> indexer_key_length, index_weights;+};++Output<Node> head_transpose(const Output<Node>& data) {+ return std::make_shared<v1::Transpose>(data, v0::Constant::create(element::i64, Shape{4}, {0, 2, 1, 3}));+}++// The non-affine RMSNorm as exported: x * 1 / sqrt(mean(x ^ 2) + eps).+Output<Node> decomposed_rms(const Output<Node>& x, int64_t axis, float eps) {+ const auto type = x.get_element_type();+ const auto square = std::make_shared<v1::Power>(x, v0::Constant::create(type, Shape{}, {2.0f}));+ const auto mean =+ std::make_shared<v1::ReduceMean>(square, v0::Constant::create(element::i64, Shape{1}, {axis}), true);+ const auto sum = std::make_shared<v1::Add>(mean, v0::Constant::create(type, Shape{}, {eps}));+ const auto inv =+ std::make_shared<v1::Divide>(v0::Constant::create(type, Shape{}, {1.0f}), std::make_shared<v0::Sqrt>(sum));+ return std::make_shared<v1::Multiply>(x, inv);+}++SharedGraph make_shared_graph(const GraphOptions& o) {+ const auto batch = o.dynamic_shapes ? Dimension::dynamic() : Dimension(2);+ const auto sequence = o.dynamic_shapes ? Dimension::dynamic() : Dimension(o.keys_sequence);+ const auto query_sequence = o.dynamic_shapes ? Dimension::dynamic() : Dimension(o.query_sequence);+ const auto depth = o.dynamic_head_size ? Dimension::dynamic() : Dimension(head_size);+ const auto heads = o.dynamic_query_heads ? Dimension::dynamic() : Dimension(query_heads);+ const bool blhd = o.query_layout != QueryLayout::BHLD;+ const auto rotary = o.rotary_dim != 0 ? o.rotary_dim : head_size;+ const auto rope_shape = PartialShape{o.single_row_rope ? Dimension(1) : batch, sequence, Dimension(rotary)};++ SharedGraph g;+ const auto parameter = [&g](element::Type type, const PartialShape& shape) {+ g.parameters.push_back(std::make_shared<v0::Parameter>(type, shape));+ return g.parameters.back()->output(0);+ };+ g.raw_query = parameter(+ o.rms_changes_precision ? element::f16 : o.precision,+ blhd ? PartialShape{batch, query_sequence, heads, depth} : PartialShape{batch, heads, query_sequence, depth});+ g.raw_keys = parameter(o.precision, PartialShape{batch, sequence, depth});+ g.cache =+ parameter(o.precision,+ PartialShape{batch, o.cache_blocks < 0 ? Dimension::dynamic() : Dimension(o.cache_blocks), depth});+ g.key_length =+ o.key_length_values.empty()+ ? parameter(o.key_length_type, o.dynamic_key_length_rank ? PartialShape::dynamic() : PartialShape{batch})+ : Output<Node>(+ v0::Constant::create(o.key_length_type, Shape{o.key_length_values.size()}, o.key_length_values));+ g.incomplete_keys = parameter(o.precision, PartialShape{batch, Dimension(key_block_size - 1), depth});+ const auto cos = parameter(o.precision, rope_shape);+ const auto sin = parameter(o.precision, rope_shape);+ if (o.disable_rope) {+ g.rope_cos = g.rope_sin = g.incomplete_rope = v0::Constant::create(o.precision, Shape{0}, std::vector<float>{});+ } else {+ g.rope_cos = cos;+ g.rope_sin = sin;+ g.incomplete_rope = parameter(o.precision, PartialShape{batch, Dimension(2 * rotary)});+ }+ g.key_weight = o.disable_key_norm ? v0::Constant::create(o.precision, Shape{0}, std::vector<float>{})->output(0)+ : parameter(o.precision, PartialShape{depth});+ g.indexer_key_length = o.use_distinct_key_length ? parameter(o.key_length_type, PartialShape{batch}) : g.key_length;+ if (o.add_index_weights) {+ g.index_weights = parameter(o.precision, PartialShape{batch, query_sequence, heads});+ }+ const auto rms_epsilon = o.query_epsilon != 0 ? o.query_epsilon : epsilon;+ const auto rms =+ o.decomposed_query ? decomposed_rms(g.raw_query, o.rms_axis, rms_epsilon)+ : o.affine_query+ ? std::make_shared<op_internal::RMS>(g.raw_query,+ v0::Constant::create(o.precision, Shape{head_size}, {0.5f}),+ rms_epsilon,+ o.precision,+ o.rms_axis)+ : std::make_shared<op_internal::RMS>(g.raw_query, rms_epsilon, o.precision, o.rms_axis);++ g.rope_input = rms;+ if (o.decomposed_query) {+ // The rotate-half RoPE of the transposed query, as exported: x * cos + concat(-x2, x1) * sin.+ constexpr int64_t last_axis = 3;+ const auto x = head_transpose(rms);+ const auto half = rotary / 2;+ const auto halves =+ std::make_shared<v1::VariadicSplit>(x,+ v0::Constant::create(element::i64, Shape{1}, {last_axis}),+ v0::Constant::create(element::i64, Shape{2}, {half, half}));+ const auto minus_x2 =+ std::make_shared<v1::Multiply>(halves->output(1), v0::Constant::create(o.precision, Shape{}, {-1.0f}));+ const auto rotated = std::make_shared<v0::Concat>(OutputVector{minus_x2, halves->output(0)}, -1);+ const auto mul_cos = std::make_shared<v1::Multiply>(+ x,+ std::make_shared<v0::Unsqueeze>(cos, v0::Constant::create(element::i64, Shape{1}, {1})));+ const auto mul_sin = std::make_shared<v1::Multiply>(+ rotated,+ std::make_shared<v0::Unsqueeze>(sin, v0::Constant::create(element::i64, Shape{1}, {1})));+ g.query = std::make_shared<v1::Add>(mul_cos, mul_sin);+ } else if (o.query_rope) {+ const auto query_cos = o.distinct_query_rope ? parameter(o.precision, rope_shape) : cos;+ const auto query_sin = o.distinct_query_sin ? parameter(o.precision, rope_shape) : sin;+ op_internal::RoPE::Config rope_config;+ rope_config.rotary_ndims = static_cast<size_t>(o.query_rotary_dim ? o.query_rotary_dim : rotary);+ rope_config.is_interleaved = o.interleaved_query_rope;+ rope_config.input_interleaved = o.input_interleaved_query_rope;+ rope_config.use_rope_cache = o.cached_query_rope;+ rope_config.input_trans0213 = o.query_layout == QueryLayout::BLHDTransposed;+ rope_config.output_trans0213 = o.query_layout == QueryLayout::BLHDRoPEBeforeTranspose;+ g.query = std::make_shared<op_internal::RoPE>(+ OutputVector{+ rms,+ std::make_shared<v0::Unsqueeze>(query_cos,+ v0::Constant::create(element::i64, Shape{1}, {o.query_rope_axis})),+ std::make_shared<v0::Unsqueeze>(query_sin,+ v0::Constant::create(element::i64, Shape{1}, {o.query_rope_axis}))},+ rope_config);+ if (o.query_layout == QueryLayout::BLHDTransposeAfterRoPE) {+ g.query = head_transpose(g.query);+ }+ } else {+ g.query = rms;+ }+ if (o.converted_query) {+ g.query = std::make_shared<v0::Convert>(g.query, o.precision);+ }+ return g;+}++std::shared_ptr<Model> make_model(const SharedGraph& g,+ const std::vector<Output<Node>>& outputs,+ const GraphOptions& o) {+ ResultVector results;+ for (const auto& output : outputs) {+ results.push_back(std::make_shared<v0::Result>(output));+ }+ if (o.extra_state_consumers) {+ // The block-key cache and the incomplete raw keys, e.g. consumed by cache Assign ops.+ results.push_back(std::make_shared<v0::Result>(outputs[4]));+ results.push_back(std::make_shared<v0::Result>(outputs[2]));+ } else {+ results.pop_back();+ }+ if (o.extra_query_consumer) {+ results.push_back(std::make_shared<v0::Result>(g.query));+ }+ return std::make_shared<Model>(results, g.parameters);+}++std::shared_ptr<Model> getModel(const GraphOptions& o) {+ const auto g = make_shared_graph(o);+ const auto prepare = std::make_shared<v17::QSAPrepare>(g.raw_keys,+ g.cache,+ g.key_length,+ g.rope_cos,+ g.rope_sin,+ g.key_weight,+ g.incomplete_keys,+ g.incomplete_rope,+ key_block_size,+ epsilon);+ std::shared_ptr<v17::SparseAttentionIndexer> indexer;+ if (o.add_index_weights) {+ indexer = std::make_shared<v17::SparseAttentionIndexer>(g.query,+ prepare->output(0),+ g.indexer_key_length,+ g.index_weights,+ o.indexer_key_block_size,+ token_budget,+ o.num_selection_heads);+ } else {+ indexer = std::make_shared<v17::SparseAttentionIndexer>(g.query,+ prepare->output(0),+ g.indexer_key_length,+ o.indexer_key_block_size,+ token_budget,+ o.num_selection_heads);+ }+ const std::vector<Output<Node>> outputs{indexer->output(0),+ indexer->output(1),+ prepare->output(1),+ prepare->output(2),+ prepare->output(0)};+ return make_model(g, outputs, o);+}++std::shared_ptr<Model> getModelRef(const GraphOptions& o) {+ const auto g = make_shared_graph(o);+ const auto rotary = o.rotary_dim != 0 ? o.rotary_dim : head_size;+ const auto dims_of = [](const Output<Node>& data, const std::vector<size_t>& axes) {+ return ov::op::util::node_to_get_shape_value_of_indices_from_shape_source(data, axes, {}, element::i32);+ };++ Output<Node> key_length = g.key_length;+ if (o.dynamic_shapes) {+ key_length = std::make_shared<v3::Broadcast>(key_length, dims_of(g.raw_keys, {0}));+ }+ const auto rope_for_batch = [&](const Output<Node>& rope) -> Output<Node> {+ if (!o.single_row_rope && !o.dynamic_shapes) {+ return rope;+ }+ const auto target = make_try_fold<v0::Concat>(+ OutputVector{dims_of(g.raw_keys, {0, 1}), v0::Constant::create(element::i32, Shape{1}, {rotary})},+ 0);+ return std::make_shared<v3::Broadcast>(rope, target);+ };++ const auto zero = v0::Constant::create(element::i32, Shape{1}, {0});+ const auto one = v0::Constant::create(element::i32, Shape{1}, {1});+ const Output<Node> key_length_i32 = key_length.get_element_type() == element::i64+ ? std::make_shared<v0::Convert>(key_length, element::i32)+ : key_length;++ Output<Node> cache = std::make_shared<v0::Unsqueeze>(g.cache, v0::Constant::create(element::i64, Shape{1}, {1}));+ Output<Node> needed_blocks;+ if (o.padding) {+ // The block-key cache grows by zero blocks up to the complete blocks of the longest sequence.+ const auto longest = std::make_shared<v1::ReduceMax>(key_length_i32, zero, true);+ needed_blocks =+ std::make_shared<v1::Divide>(longest, v0::Constant::create(element::i32, Shape{1}, {key_block_size}));+ const auto missing_blocks = std::make_shared<v1::Subtract>(needed_blocks, dims_of(g.cache, {1}));+ const auto growth = std::make_shared<v1::Maximum>(missing_blocks, zero);+ const auto growth_shape =+ make_try_fold<v0::Concat>(OutputVector{dims_of(g.raw_keys, {0}),+ one,+ growth,+ v0::Constant::create(element::i32, Shape{1}, {head_size})},+ 0);+ const auto zeros =+ std::make_shared<v3::Broadcast>(v0::Constant::create(o.precision, Shape{}, {0.0f}), growth_shape);+ cache = std::make_shared<v0::Concat>(OutputVector{cache, zeros}, 2);+ }++ OutputVector inputs(QSAIndexerInputIdx::COUNT);+ switch (o.query_fusion) {+ case QueryFusion::None:+ inputs[QSAIndexerInputIdx::INDEX_QUERY] = head_transpose(g.query);+ break;+ case QueryFusion::RoPE:+ inputs[QSAIndexerInputIdx::INDEX_QUERY] = g.rope_input;+ break;+ case QueryFusion::Full:+ inputs[QSAIndexerInputIdx::INDEX_QUERY] = g.raw_query;+ break;+ }+ inputs[QSAIndexerInputIdx::RAW_INDEX_KEYS] =+ std::make_shared<v0::Unsqueeze>(g.raw_keys, v0::Constant::create(element::i64, Shape{1}, {2}));+ inputs[QSAIndexerInputIdx::ROPE_COS] = rope_for_batch(g.rope_cos);+ inputs[QSAIndexerInputIdx::ROPE_SIN] = rope_for_batch(g.rope_sin);+ inputs[QSAIndexerInputIdx::KEY_LENGTH] = key_length_i32;+ inputs[QSAIndexerInputIdx::Q_NORM_WEIGHT] =+ v0::Constant::create(o.precision, Shape{head_size}, {o.affine_query ? 0.5f : 1.0f});+ inputs[QSAIndexerInputIdx::K_NORM_WEIGHT] = g.key_weight;+ inputs[QSAIndexerInputIdx::BLOCK_INDEX_KEYS_CACHE] = cache;+ inputs[QSAIndexerInputIdx::PAST_INCOMPLETE_RAW_K] =+ std::make_shared<v0::Unsqueeze>(g.incomplete_keys, v0::Constant::create(element::i64, Shape{1}, {1}));+ inputs[QSAIndexerInputIdx::PAST_INCOMPLETE_ROPE] = g.incomplete_rope;++ op_internal::QSAIndexer::Config config;+ config.key_block_size = key_block_size;+ config.block_topk = token_budget / key_block_size;+ config.num_selection_heads = 1;+ config.indexer_rotary_dim = rotary;+ config.indexer_head_dim = head_size;+ config.epsilon = epsilon;+ config.scale = 1.0f / std::sqrt(static_cast<float>(head_size));+ config.query_norm = o.query_fusion == QueryFusion::Full;+ config.query_rope = o.query_fusion != QueryFusion::None;+ const auto fused = std::make_shared<op_internal::QSAIndexer>(inputs, config);+ Output<Node> block_keys = std::make_shared<v0::Squeeze>(fused->output(QSAIndexerOutputIdx::BLOCK_INDEX_KEYS_CACHE),+ v0::Constant::create(element::i64, Shape{1}, {1}));+ if (o.padding) {+ Output<Node> block_count = needed_blocks;+ if (!o.key_length_values.empty()) {+ int64_t max_length = 0;+ for (const auto length : o.key_length_values) {+ max_length = std::max(max_length, length);+ }+ block_count = v0::Constant::create(element::i32, Shape{1}, {max_length / key_block_size});+ }+ block_keys = std::make_shared<v8::Slice>(block_keys, zero, block_count, one, one);+ }++ const std::vector<Output<Node>> outputs{+ fused->output(QSAIndexerOutputIdx::SELECTED_BLOCK_INDICES),+ fused->output(QSAIndexerOutputIdx::SELECTED_BLOCK_COUNT),+ std::make_shared<v0::Squeeze>(fused->output(QSAIndexerOutputIdx::PAST_INCOMPLETE_RAW_K),+ v0::Constant::create(element::i64, Shape{1}, {1})),+ fused->output(QSAIndexerOutputIdx::PAST_INCOMPLETE_ROPE),+ block_keys,+ };+ return make_model(g, outputs, o);+}++class FuseQSAIndexerTest : public TransformationTestsF, public testing::WithParamInterface<GraphOptions> {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<GraphOptions>& info) {+ return info.param.name;+ }++protected:+ void SetUp() override {+ TransformationTestsF::SetUp();+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::RoPEFusion>(true);+ manager.register_pass<pass::RMSFusion>(false, true);+ manager.register_pass<pass::FuseQSAIndexer>(GetParam().padding);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+ }+};++class FuseQSAIndexerFusedTest : public FuseQSAIndexerTest {};++TEST_P(FuseQSAIndexerFusedTest, FusesSupportedQuerySteps) {+ model = getModel(GetParam());+ model_ref = getModelRef(GetParam());+ // QSAIndexer replaces two multi-output ops and keeps the SparseAttentionIndexer name, so the Results of the+ // incomplete RoPE state, formerly a QSAPrepare output, cannot keep the QSAPrepare name.+ disable_result_friendly_names_check();+}++GraphOptions with(std::string name, void (*setter)(GraphOptions&)) {+ GraphOptions options;+ options.name = std::move(name);+ setter(options);+ return options;+}++const std::vector<GraphOptions> fused_cases{+ with("qwen_indexer_static", [](GraphOptions&) {}),+ with("overprovisioned_cache_is_trimmed_to_key_length",+ [](GraphOptions& o) {+ o.cache_blocks = 3;+ o.key_length_values = {8, 6};+ o.extra_state_consumers = true;+ }),+ with("single_row_rope",+ [](GraphOptions& o) {+ o.single_row_rope = true;+ }),+ with("f16",+ [](GraphOptions& o) {+ o.precision = element::f16;+ }),+ with("dynamic_batch_and_sequence_without_symbols",+ [](GraphOptions& o) {+ o.dynamic_shapes = true;+ }),+ with("i64_key_length",+ [](GraphOptions& o) {+ o.key_length_type = element::i64;+ }),+ with("decomposed_query_norm_and_rope",+ [](GraphOptions& o) {+ o.decomposed_query = true;+ }),+ with("affine_query_norm_and_rope",+ [](GraphOptions& o) {+ o.affine_query = true;+ }),+ with("extra_state_consumers",+ [](GraphOptions& o) {+ o.extra_state_consumers = true;+ }),+ // The RMSNorm and RoPE stay for the other consumer, while QSAIndexer applies its own.+ with("extra_query_consumer",+ [](GraphOptions& o) {+ o.extra_query_consumer = true;+ }),+ with("no_padding",+ [](GraphOptions& o) {+ o.padding = false;+ }),+ with("no_padding_oversized_cache_passes_through",+ [](GraphOptions& o) {+ o.padding = false;+ o.cache_blocks = 3;+ o.key_length_values = {8, 6};+ o.extra_state_consumers = true;+ }),+ with("no_padding_dynamic_batch_and_sequence",+ [](GraphOptions& o) {+ o.padding = false;+ o.dynamic_shapes = true;+ }),+};++INSTANTIATE_TEST_SUITE_P(FuseQSAIndexer,+ FuseQSAIndexerFusedTest,+ testing::ValuesIn(fused_cases),+ FuseQSAIndexerTest::getTestCaseName);++TEST_F(TransformationTestsF, FuseQSAIndexerLeavesQueryAndOtherNonAffineRMSNormUnchanged) {+ GraphOptions o;+ o.decomposed_query = true;+ const auto add_other_norm = [](const std::shared_ptr<Model>& m) {+ const auto x = std::make_shared<v0::Parameter>(element::f32, PartialShape{2, head_size});+ const auto norm = decomposed_rms(x, -1, epsilon);+ m->add_parameters({x});+ m->add_results({std::make_shared<v0::Result>(norm)});+ };+ model = getModel(o);+ add_other_norm(model);+ o.query_fusion = QueryFusion::None;+ model_ref = getModelRef(o);+ add_other_norm(model_ref);+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ disable_result_friendly_names_check();+ manager.register_pass<pass::FuseQSAIndexer>(true);+}++TEST_F(TransformationTestsF, FuseQSAIndexerLeavesCanonicalQueryUnchanged) {+ GraphOptions o;+ o.query_fusion = QueryFusion::None;+ model = getModel(o);+ model_ref = getModelRef(o);+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ disable_result_friendly_names_check();+ manager.register_pass<pass::FuseQSAIndexer>(true);+}++TEST_F(TransformationTestsF, FuseQSAIndexerHonorsDisabledPass) {+ model = getModel(GraphOptions{});+ manager.register_pass<pass::FuseQSAIndexer>(true);+ manager.get_pass_config()->disable<pass::FuseQSAIndexer>();+}++TEST_F(TransformationTestsF, FuseQSAIndexerHonorsCallback) {+ model = getModel(GraphOptions{});+ manager.register_pass<pass::FuseQSAIndexer>(true);+ manager.get_pass_config()->set_callback<pass::FuseQSAIndexer>([](const std::shared_ptr<const Node>&) {+ return true;+ });+}++TEST_F(TransformationTestsF, FuseQSAIndexerQueryLeavesDecomposedQueryUnchanged) {+ GraphOptions o;+ o.decomposed_query = true;+ o.query_fusion = QueryFusion::None;+ model = getModelRef(o);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++// QSAIndexer keeps the query steps that do not match the kernel ones in the graph.+const std::vector<GraphOptions> partially_fused_cases{+ // The SparseAttentionIndexer query is not a [B, L, H, D] input rotated by the plain rotate-half RoPE of the+ // key cos / sin, so the query is passed as is.+ with("bhld_query",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::None;+ o.query_layout = QueryLayout::BHLD;+ }),+ with("bhld_query_without_rope",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::None;+ o.query_layout = QueryLayout::BHLD;+ o.query_rope = false;+ }),+ with("rope_output_transpose",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::None;+ o.query_layout = QueryLayout::BLHDRoPEBeforeTranspose;+ }),+ with("explicit_query_transpose",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::None;+ o.query_layout = QueryLayout::BLHDTransposeAfterRoPE;+ }),+ with("converted_query",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::None;+ o.converted_query = true;+ }),+ with("query_rope_wrong_unsqueeze_axis",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::None;+ o.query_rope_axis = 0;+ o.single_row_rope = true;+ }),+ with("distinct_query_rope",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::None;+ o.distinct_query_rope = true;+ }),+ with("distinct_query_sin",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::None;+ o.distinct_query_sin = true;+ }),+ with("interleaved_query_rope",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::None;+ o.interleaved_query_rope = true;+ }),+ with("input_interleaved_query_rope",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::None;+ o.input_interleaved_query_rope = true;+ }),+ with("cached_query_rope",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::None;+ o.cached_query_rope = true;+ }),+ with("distinct_query_rotary_dim",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::None;+ o.query_rotary_dim = head_size / 2;+ }),+ with("rms_changes_precision",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::RoPE;+ o.rms_changes_precision = true;+ }),+ with("rms_wrong_axis",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::RoPE;+ o.rms_axis = -2;+ }),+ with("distinct_query_epsilon",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::RoPE;+ o.query_epsilon = 2 * epsilon;+ }),+ with("nearly_equal_query_epsilon",+ [](GraphOptions& o) {+ o.query_fusion = QueryFusion::RoPE;+ o.query_epsilon = std::nextafter(epsilon, 2 * epsilon);+ }),+};++INSTANTIATE_TEST_SUITE_P(FuseQSAIndexerPartially,+ FuseQSAIndexerFusedTest,+ testing::ValuesIn(partially_fused_cases),+ FuseQSAIndexerTest::getTestCaseName);++class FuseQSAIndexerNotFusedTest : public FuseQSAIndexerTest {};++TEST_P(FuseQSAIndexerNotFusedTest, KeepsSourceOps) {+ model = getModel(GetParam());+}++const std::vector<GraphOptions> not_fused_cases{+ // QSAIndexer kernels are specialized for the head count and the head size.+ with("dynamic_query_heads",+ [](GraphOptions& o) {+ o.dynamic_query_heads = true;+ }),+ with("dynamic_head_size",+ [](GraphOptions& o) {+ o.dynamic_head_size = true;+ }),+ with("dynamic_key_length_rank",+ [](GraphOptions& o) {+ o.dynamic_key_length_rank = true;+ }),+ // QSAIndexer always applies the key RoPE and the key norm.+ with("disabled_rope",+ [](GraphOptions& o) {+ o.disable_rope = true;+ }),+ with("disabled_key_norm",+ [](GraphOptions& o) {+ o.disable_key_norm = true;+ }),+ with("distinct_key_length",+ [](GraphOptions& o) {+ o.use_distinct_key_length = true;+ }),+ with("index_weights",+ [](GraphOptions& o) {+ o.add_index_weights = true;+ }),+ // The public ops have a single key head, so QSAIndexer selects with one head.+ with("two_selection_heads",+ [](GraphOptions& o) {+ o.num_selection_heads = 2;+ }),+ with("distinct_key_block_size",+ [](GraphOptions& o) {+ o.indexer_key_block_size = 8;+ }),+ // QSAIndexer takes the raw query and the raw keys for the same tokens.+ with("query_broadcast_by_rope",+ [](GraphOptions& o) {+ o.query_sequence = 1;+ }),+ with("query_longer_than_keys",+ [](GraphOptions& o) {+ o.keys_sequence = 1;+ }),+};++INSTANTIATE_TEST_SUITE_P(FuseQSAIndexer,+ FuseQSAIndexerNotFusedTest,+ testing::ValuesIn(not_fused_cases),+ FuseQSAIndexerTest::getTestCaseName);++} // namespacediff --git a/src/common/transformations/tests/common_optimizations/fuse_rotary_positional_embeddings.cpp b/src/common/transformations/tests/common_optimizations/fuse_rotary_positional_embeddings.cppindex 02e8778cae7..a5228ebce05 100644--- a/src/common/transformations/tests/common_optimizations/fuse_rotary_positional_embeddings.cpp+++ b/src/common/transformations/tests/common_optimizations/fuse_rotary_positional_embeddings.cpp@@ -12,6 +12,7 @@#include "openvino/op/add.hpp"#include "openvino/op/broadcast.hpp"#include "openvino/op/concat.hpp"+#include "openvino/op/convert.hpp"#include "openvino/op/gather.hpp"#include "openvino/op/gather_elements.hpp"#include "openvino/op/gather_nd.hpp"@@ -224,7 +225,8 @@ static std::shared_ptr<ov::Model> buildROPE_GPTNEOX_4D(const int batch,const int ndims,const int num_heads,const int rotary_ndims,- bool sin_cos_preprocessing) {+ bool sin_cos_preprocessing,+ bool convert_minus_one = false) {auto batch_s = static_cast<size_t>(batch);auto seq_length_s = static_cast<size_t>(seq_length);auto ndims_s = static_cast<size_t>(ndims);@@ -290,15 +292,12 @@ static std::shared_ptr<ov::Model> buildROPE_GPTNEOX_4D(const int batch,{"new_axis_mask", {}},{"shrink_axis_mask", {}},{"ellipsis_mask", {}}});- auto Constant_396096 = makeConst(ov::element::f32,- ov::Shape({- 1,- 1,- 1,- 1,- }),- {-1.000000f});- auto neg_Multiply = makeOP<ov::opset1::Multiply>({slice_Slice_420, Constant_396096}, {{"auto_broadcast", "numpy"}});+ ov::Output<ov::Node> minus_one =+ makeConst(convert_minus_one ? ov::element::i32 : ov::element::f32, ov::Shape({1, 1, 1, 1}), {-1});+ if (convert_minus_one) {+ minus_one = std::make_shared<v0::Convert>(minus_one, ov::element::f32);+ }+ auto neg_Multiply = makeOP<ov::opset1::Multiply>({slice_Slice_420, minus_one}, {{"auto_broadcast", "numpy"}});auto slice_Slice_414 =makeOP<ov::opset1::StridedSlice>({slice_Slice_351, {0, 0, 0, 0}, {0, 0, 0, rotary_ndims / 2}, {1, 1, 1, 1}},{{"begin_mask", {1, 1, 1, 0}},@@ -415,6 +414,41 @@ TEST_F(TransformationTestsF, ConvertToROPE_GPTNEOX_no_gather) {}}+TEST_F(TransformationTestsF, ConvertToROPE_GPTNEOX_with_converted_minus_one) {+ disable_rt_info_check();+ const int batch = 2;+ const int seq_len = 16;+ const int ndims = 80;+ const int num_heads = 32;+ const int rotary_ndims = 20;+ const int max_position_embeddings = 2048;++ model = buildROPE_GPTNEOX_4D(batch, seq_len, max_position_embeddings, ndims, num_heads, rotary_ndims, false, true);+ manager.register_pass<ov::pass::RoPEFusion>();+ auto input =+ std::make_shared<ov::opset1::Parameter>(ov::element::f32, ov::Shape{batch, seq_len, num_heads, ndims * 3});+ auto param_cos = std::make_shared<ov::opset1::Parameter>(ov::element::f32, ov::Shape{1, 1, seq_len, rotary_ndims});+ auto param_sin = std::make_shared<ov::opset1::Parameter>(ov::element::f32, ov::Shape{1, 1, seq_len, rotary_ndims});+ auto rope = makeOP<ov::op::internal::RoPE>({input, param_cos, param_sin},+ {{"config.slice_start", 0},+ {"config.slice_stop", ndims},+ {"config.input_trans0213", true},+ {"config.input_interleaved", false},+ {"config.output_trans0213", false},+ {"config.is_interleaved", false},+ {"config.is_chatglm", false},+ {"config.support_2d_rope", false},+ {"config.support_3d_rope", false},+ {"config.is_qwen", false},+ {"config.use_rope_cache", false},+ {"config.is_ltx_video", false},+ {"config.head_cnt", 0},+ {"config.head_size", 0},+ {"config.rotary_ndims", rotary_ndims},+ {"config.gather_position_arg_id", 0}});+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{rope}, ov::ParameterVector{input, param_cos, param_sin});+}+TEST_F(TransformationTestsF, ConvertToROPE_GPTNEOX_with_gather) {disable_rt_info_check();const int batch = 2;diff --git a/src/common/transformations/tests/common_optimizations/paged_qsa_indexer_fusion_test.cpp b/src/common/transformations/tests/common_optimizations/paged_qsa_indexer_fusion_test.cppnew file mode 100644index 00000000000..bae8e781d0c--- /dev/null+++ b/src/common/transformations/tests/common_optimizations/paged_qsa_indexer_fusion_test.cpp@@ -0,0 +1,1402 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/paged_attention/paged_qsa_indexer_fusion.hpp"++#include <gtest/gtest.h>++#include <algorithm>+#include <cmath>+#include <limits>+#include <memory>+#include <string>+#include <type_traits>+#include <unordered_set>+#include <utility>+#include <vector>++#include "common_test_utils/ov_test_utils.hpp"+#include "common_test_utils/test_assertions.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/op/assign.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/paged_qsa_indexer.hpp"+#include "openvino/op/qsa_indexer.hpp"+#include "openvino/op/qsa_prepare.hpp"+#include "openvino/op/read_value.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/sparse_attention_indexer.hpp"+#include "openvino/op/squeeze.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/op/util/variable.hpp"+#include "openvino/pass/manager.hpp"+#include "openvino/pass/pattern/matcher.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "openvino/pass/sdpa_to_paged_attention.hpp"+#include "ov_ops/rms.hpp"+#include "ov_ops/rotary_positional_embeddings.hpp"+#include "transformations/common_optimizations/fuse_qsa_indexer.hpp"+#include "transformations/common_optimizations/nop_elimination.hpp"+#include "transformations/utils/utils.hpp"++namespace {++using namespace ov;+namespace v0 = ov::op::v0;+namespace v1 = ov::op::v1;+namespace v6 = ov::op::v6;+namespace v8 = ov::op::v8;+namespace op_internal = ov::op::internal;+using QSAIndexerInputIdx = op_internal::QSAIndexer::InputIdx;+using QSAIndexerOutputIdx = op_internal::QSAIndexer::OutputIdx;+using PagedQSAIndexerInputIdx = op_internal::PagedQSAIndexer::InputIdx;++constexpr int64_t query_heads = 4;+constexpr int64_t key_heads = 1;+constexpr int64_t head_size = 16;+constexpr int64_t rotary_dim = 8;+constexpr int64_t key_block_size = 4;+constexpr int64_t block_topk = 2;+constexpr int64_t selection_heads = 1;+constexpr float epsilon = 1e-6f;++Output<Node> i64(const std::vector<int64_t>& values) {+ return v0::Constant::create(element::i64, Shape{values.size()}, values);+}++std::shared_ptr<v0::Parameter> make_named_param(const std::string& name,+ element::Type type,+ const PartialShape& shape) {+ const auto param = std::make_shared<v0::Parameter>(type, shape);+ param->set_friendly_name(name);+ param->get_output_tensor(0).set_names({name});+ return param;+}++struct GraphOptions {+ bool query_norm = true;+ bool gathered_states = false;+ bool variable_states = true;+ bool query_rope = true;+ int64_t rope_length = -1;+ float scale = 1.0f / std::sqrt(static_cast<float>(head_size));+ // FuseQSAIndexer padding: the block-key cache is grown by a Concat.+ bool padding = true;+};++GraphOptions unpadded() {+ GraphOptions o;+ o.padding = false;+ return o;+}++// The dense QSAIndexer as created by FuseQSAIndexer, with its states kept in variables.+std::shared_ptr<Model> make_model(const GraphOptions& o, bool paged, element::Type data_type = element::f32) {+ ParameterVector params;+ const auto param = [¶ms](element::Type type, const PartialShape& shape) {+ params.push_back(std::make_shared<v0::Parameter>(type, shape));+ return params.back();+ };+ const auto query = param(data_type, PartialShape{-1, -1, query_heads, head_size});+ const auto raw_keys = param(data_type, PartialShape{-1, -1, key_heads, head_size});+ const auto rope_cos = param(data_type, PartialShape{-1, o.rope_length, rotary_dim});+ const auto rope_sin = param(data_type, PartialShape{-1, o.rope_length, rotary_dim});+ const auto key_length = param(element::i32, PartialShape{-1});+ const auto beam_idx = o.gathered_states ? param(element::i32, PartialShape{-1}) : nullptr;++ SinkVector sinks;+ std::vector<std::shared_ptr<op::util::Variable>> variables;+ const auto read_state = [&](const std::string& id, const PartialShape& shape) -> Output<Node> {+ if (!o.variable_states) {+ return param(data_type, shape);+ }+ variables.push_back(std::make_shared<op::util::Variable>(op::util::VariableInfo{shape, data_type, id}));+ Output<Node> state = std::make_shared<v6::ReadValue>(variables.back());+ if (o.gathered_states) {+ state = std::make_shared<v8::Gather>(state, beam_idx, v0::Constant::create(element::i64, Shape{}, {0}));+ }+ return state;+ };+ const auto past_block_keys = read_state("block_keys", PartialShape{-1, -1, head_size});+ const auto incomplete_raw_keys = read_state("incomplete_raw_keys", PartialShape{-1, key_block_size - 1, head_size});+ const auto incomplete_rope = read_state("incomplete_rope", PartialShape{-1, 2 * rotary_dim});+ Output<Node> block_keys_cache = std::make_shared<v0::Unsqueeze>(past_block_keys, i64({1}));+ if (o.padding) {+ const auto cache_padding = param(data_type, PartialShape{-1, key_heads, -1, head_size});+ block_keys_cache = std::make_shared<v0::Concat>(OutputVector{block_keys_cache, cache_padding}, 2);+ }+ const auto incomplete_raw_keys_with_head = std::make_shared<v0::Unsqueeze>(incomplete_raw_keys, i64({1}));+ const auto q_norm_weight = v0::Constant::create(data_type, Shape{head_size}, {1.0f});+ const auto k_norm_weight = v0::Constant::create(data_type, Shape{head_size}, {0.5f});++ op_internal::QSAIndexer::Config config;+ config.key_block_size = key_block_size;+ config.block_topk = block_topk;+ config.num_selection_heads = selection_heads;+ config.indexer_rotary_dim = rotary_dim;+ config.indexer_head_dim = head_size;+ config.epsilon = epsilon;+ config.scale = o.scale;+ config.query_norm = o.query_norm;+ config.query_rope = o.query_rope;++ Output<Node> indices, count, block_keys_state, raw_keys_state, rope_state;+ if (paged) {+ const auto past_lens = make_named_param("past_lens", element::i32, PartialShape{-1});+ const auto subsequence_begins = make_named_param("subsequence_begins", element::i32, PartialShape{-1});+ const auto block_indices = make_named_param("block_indices", element::i32, PartialShape{-1});+ const auto block_indices_begins = make_named_param("block_indices_begins", element::i32, PartialShape{-1});+ const auto index_key_cache =+ make_named_param("index_key_cache.0", data_type, PartialShape{-1, key_heads, -1, head_size});+ const auto index_block_rope_cache =+ make_named_param("index_block_rope_cache.0", data_type, PartialShape{-1, -1, 2 * rotary_dim});+ const auto block_index_keys_cache =+ make_named_param("block_index_keys_cache.0", data_type, PartialShape{-1, key_heads, -1, head_size});+ params.insert(params.end(),+ {past_lens,+ subsequence_begins,+ block_indices,+ block_indices_begins,+ index_key_cache,+ index_block_rope_cache,+ block_index_keys_cache});++ const auto flatten = [](const Output<Node>& data, int64_t width) {+ return std::make_shared<v1::Reshape>(data, i64({-1, width}), false);+ };+ OutputVector inputs(PagedQSAIndexerInputIdx::COUNT);+ inputs[PagedQSAIndexerInputIdx::INDEX_QUERY] = flatten(query, query_heads * head_size);+ inputs[PagedQSAIndexerInputIdx::RAW_INDEX_KEYS] = flatten(raw_keys, key_heads * head_size);+ inputs[PagedQSAIndexerInputIdx::ROPE_COS] = flatten(rope_cos, rotary_dim);+ inputs[PagedQSAIndexerInputIdx::ROPE_SIN] = flatten(rope_sin, rotary_dim);+ inputs[PagedQSAIndexerInputIdx::Q_NORM_WEIGHT] = q_norm_weight;+ inputs[PagedQSAIndexerInputIdx::K_NORM_WEIGHT] = k_norm_weight;+ inputs[PagedQSAIndexerInputIdx::PAST_LENS] = past_lens;+ inputs[PagedQSAIndexerInputIdx::SUBSEQUENCE_BEGINS] = subsequence_begins;+ inputs[PagedQSAIndexerInputIdx::BLOCK_INDICES] = block_indices;+ inputs[PagedQSAIndexerInputIdx::BLOCK_INDICES_BEGINS] = block_indices_begins;+ inputs[PagedQSAIndexerInputIdx::INDEX_KEY_CACHE] = index_key_cache;+ inputs[PagedQSAIndexerInputIdx::INDEX_BLOCK_ROPE_CACHE] = index_block_rope_cache;+ inputs[PagedQSAIndexerInputIdx::BLOCK_INDEX_KEYS_CACHE] = block_index_keys_cache;+ op_internal::PagedQSAIndexer::Config paged_config;+ paged_config.key_block_size = config.key_block_size;+ paged_config.block_topk = config.block_topk;+ paged_config.num_selection_heads = config.num_selection_heads;+ paged_config.indexer_rotary_dim = config.indexer_rotary_dim;+ paged_config.indexer_head_dim = config.indexer_head_dim;+ paged_config.epsilon = config.epsilon;+ paged_config.scale = o.scale == 0.0f ? 1.0f / std::sqrt(static_cast<float>(head_size)) : o.scale;+ paged_config.query_norm = config.query_norm;+ paged_config.query_rope = config.query_rope;+ const auto paged_indexer = std::make_shared<op_internal::PagedQSAIndexer>(inputs, paged_config);++ const auto batch_and_length = op::util::node_to_get_shape_value_of_indices_from_shape_source(query, {0, 1});+ const auto restore = [&](size_t output, const std::vector<int64_t>& tail, const std::vector<int64_t>& order) {+ const auto shape = std::make_shared<v0::Concat>(OutputVector{batch_and_length, i64(tail)}, 0);+ const auto token_major = std::make_shared<v1::Reshape>(paged_indexer->output(output), shape, false);+ return std::make_shared<v1::Transpose>(token_major, i64(order));+ };+ indices = restore(0, {selection_heads, block_topk}, {0, 2, 1, 3});+ count = restore(1, {selection_heads}, {0, 2, 1});+ block_keys_state = block_keys_cache;+ raw_keys_state = incomplete_raw_keys_with_head;+ rope_state = incomplete_rope;+ } else {+ OutputVector inputs(QSAIndexerInputIdx::COUNT);+ inputs[QSAIndexerInputIdx::INDEX_QUERY] = query;+ inputs[QSAIndexerInputIdx::RAW_INDEX_KEYS] = raw_keys;+ inputs[QSAIndexerInputIdx::ROPE_COS] = rope_cos;+ inputs[QSAIndexerInputIdx::ROPE_SIN] = rope_sin;+ inputs[QSAIndexerInputIdx::KEY_LENGTH] = key_length;+ inputs[QSAIndexerInputIdx::Q_NORM_WEIGHT] = q_norm_weight;+ inputs[QSAIndexerInputIdx::K_NORM_WEIGHT] = k_norm_weight;+ inputs[QSAIndexerInputIdx::BLOCK_INDEX_KEYS_CACHE] = block_keys_cache;+ inputs[QSAIndexerInputIdx::PAST_INCOMPLETE_RAW_K] = incomplete_raw_keys_with_head;+ inputs[QSAIndexerInputIdx::PAST_INCOMPLETE_ROPE] = incomplete_rope;+ const auto indexer = std::make_shared<op_internal::QSAIndexer>(inputs, config);+ indices = indexer->output(QSAIndexerOutputIdx::SELECTED_BLOCK_INDICES);+ count = indexer->output(QSAIndexerOutputIdx::SELECTED_BLOCK_COUNT);+ block_keys_state = indexer->output(QSAIndexerOutputIdx::BLOCK_INDEX_KEYS_CACHE);+ raw_keys_state = indexer->output(QSAIndexerOutputIdx::PAST_INCOMPLETE_RAW_K);+ rope_state = indexer->output(QSAIndexerOutputIdx::PAST_INCOMPLETE_ROPE);+ }++ ResultVector results{std::make_shared<v0::Result>(indices), std::make_shared<v0::Result>(count)};+ const OutputVector states{std::make_shared<v0::Squeeze>(block_keys_state, i64({1})),+ std::make_shared<v0::Squeeze>(raw_keys_state, i64({1})),+ rope_state};+ for (size_t i = 0; i < states.size(); ++i) {+ if (o.variable_states) {+ sinks.push_back(std::make_shared<v6::Assign>(states[i], variables[i]));+ } else {+ results.push_back(std::make_shared<v0::Result>(states[i]));+ }+ }+ return std::make_shared<Model>(results, sinks, params);+}++class QSAIndexerOperatorTest : public testing::Test, public testing::WithParamInterface<bool> {};++TEST_P(QSAIndexerOperatorTest, SelectionShapesAndCloneSupportFusion) {+ const auto model = make_model(GraphOptions{false, false, true, false}, GetParam());+ const auto parameters = model->get_parameters();+ parameters.at(0)->set_partial_shape({2, 3, query_heads, head_size});+ parameters.at(1)->set_partial_shape({2, 3, key_heads, head_size});+ model->validate_nodes_and_infer_types();++ std::shared_ptr<Node> indexer;+ for (const auto& node : model->get_ops()) {+ if (GetParam() ? ov::is_type<op_internal::PagedQSAIndexer>(node) : ov::is_type<op_internal::QSAIndexer>(node)) {+ indexer = node;+ break;+ }+ }+ ASSERT_NE(indexer, nullptr);+ const auto expected_indices =+ GetParam() ? PartialShape{6, selection_heads, block_topk} : PartialShape{2, selection_heads, 3, block_topk};+ const auto expected_count = GetParam() ? PartialShape{6, selection_heads} : PartialShape{2, selection_heads, 3};+ EXPECT_EQ(indexer->get_output_partial_shape(0), expected_indices);+ EXPECT_EQ(indexer->get_output_partial_shape(1), expected_count);+ EXPECT_EQ(indexer->get_output_element_type(0), element::i32);+ EXPECT_EQ(indexer->get_output_element_type(1), element::i32);++ const auto clone = indexer->clone_with_new_inputs(indexer->input_values());+ EXPECT_EQ(clone->get_type_info(), indexer->get_type_info());+ EXPECT_EQ(clone->get_output_partial_shape(0), expected_indices);+ EXPECT_EQ(clone->get_output_partial_shape(1), expected_count);+ if (GetParam()) {+ const auto paged_clone = ov::as_type_ptr<op_internal::PagedQSAIndexer>(clone);+ ASSERT_NE(paged_clone, nullptr);+ EXPECT_FALSE(paged_clone->get_config().query_norm);+ EXPECT_FALSE(paged_clone->get_config().query_rope);+ } else {+ const auto dense_clone = ov::as_type_ptr<op_internal::QSAIndexer>(clone);+ ASSERT_NE(dense_clone, nullptr);+ EXPECT_FALSE(dense_clone->get_config().query_norm);+ EXPECT_FALSE(dense_clone->get_config().query_rope);+ for (const auto& [output, input] :+ {std::pair{QSAIndexerOutputIdx::BLOCK_INDEX_KEYS_CACHE, QSAIndexerInputIdx::BLOCK_INDEX_KEYS_CACHE},+ std::pair{QSAIndexerOutputIdx::PAST_INCOMPLETE_RAW_K, QSAIndexerInputIdx::PAST_INCOMPLETE_RAW_K},+ std::pair{QSAIndexerOutputIdx::PAST_INCOMPLETE_ROPE, QSAIndexerInputIdx::PAST_INCOMPLETE_ROPE}}) {+ EXPECT_EQ(clone->get_output_partial_shape(output), clone->get_input_partial_shape(input));+ EXPECT_EQ(clone->get_output_element_type(output), clone->get_input_element_type(input));+ }+ }+}++INSTANTIATE_TEST_SUITE_P(PagedQSAIndexerFusion,+ QSAIndexerOperatorTest,+ testing::Values(false, true),+ [](const testing::TestParamInfo<bool>& info) {+ return info.param ? "Paged" : "Dense";+ });++std::unordered_set<std::string> run_paged_qsa_indexer_fusion(const std::shared_ptr<Model>& model) {+ pass::paged_attention::PaParams pa_params{model->get_parameters()};+ std::unordered_set<std::string> var_ids_to_remove;+ pass::Manager manager;+ manager.set_per_pass_validation(false);+ manager.register_pass<pass::PagedQSAIndexerFusion>(pa_params, var_ids_to_remove);+ manager.run_passes(model);+ model->add_parameters(pa_params.items());+ model->validate_nodes_and_infer_types();+ return var_ids_to_remove;+}++class PagedQSAIndexerFusionTest : public TransformationTestsF, public testing::WithParamInterface<GraphOptions> {};++class PagedQSAIndexerFusionConvertedTest : public PagedQSAIndexerFusionTest {};++TEST_P(PagedQSAIndexerFusionConvertedTest, ConvertsToPagedQSAIndexer) {+ model = make_model(GetParam(), false);+ model_ref = make_model(GetParam(), true);+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ disable_rt_info_check();+ const auto var_ids_to_remove = run_paged_qsa_indexer_fusion(model);+ EXPECT_EQ(var_ids_to_remove,+ (std::unordered_set<std::string>{"block_keys", "incomplete_raw_keys", "incomplete_rope"}));+}++INSTANTIATE_TEST_SUITE_P(PagedQSAIndexerFusion,+ PagedQSAIndexerFusionConvertedTest,+ testing::Values(GraphOptions{},+ GraphOptions{true, true},+ GraphOptions{false},+ GraphOptions{true, false, true, false},+ GraphOptions{false, false, true, false},+ GraphOptions{true, false, true, true, -1, 0.0f},+ GraphOptions{true, false, true, true, -1, 0.5f},+ unpadded()),+ [](const testing::TestParamInfo<GraphOptions>& info) {+ const auto& o = info.param;+ std::string name = o.gathered_states ? "GatheredStates" : "DirectStates";+ name += o.query_norm ? "_QueryNorm" : "_NoQueryNorm";+ name += o.query_rope ? "_QueryRoPE" : "_NoQueryRoPE";+ if (o.scale == 0.0f) {+ name += "_DefaultScale";+ } else if (o.scale == 0.5f) {+ name += "_CustomScale";+ }+ if (!o.padding) {+ name += "_NoPadding";+ }+ return name;+ });++TEST_F(TransformationTestsF, PagedQSAIndexerFusionAcceptsDynamicFeatureDimensions) {+ model = make_model(GraphOptions{}, false);+ model_ref = make_model(GraphOptions{}, true);+ const auto make_feature_dims_dynamic = [](const std::shared_ptr<Model>& m) {+ const auto params = m->get_parameters();+ params[0]->set_partial_shape({-1, -1, query_heads, -1});+ params[1]->set_partial_shape({-1, -1, key_heads, -1});+ params[2]->set_partial_shape({-1, -1, -1});+ params[3]->set_partial_shape({-1, -1, -1});+ m->validate_nodes_and_infer_types();+ };+ make_feature_dims_dynamic(model);+ make_feature_dims_dynamic(model_ref);+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ disable_rt_info_check();+ EXPECT_EQ(run_paged_qsa_indexer_fusion(model),+ (std::unordered_set<std::string>{"block_keys", "incomplete_raw_keys", "incomplete_rope"}));+}++TEST_F(TransformationTestsF, PagedQSAIndexerFusionDefersPrecisionSupportToPlugin) {+ model = make_model(GraphOptions{}, false, element::f64);+ model_ref = make_model(GraphOptions{}, true, element::f64);+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ disable_rt_info_check();+ EXPECT_EQ(run_paged_qsa_indexer_fusion(model),+ (std::unordered_set<std::string>{"block_keys", "incomplete_raw_keys", "incomplete_rope"}));+}++class PagedQSAIndexerFusionNotConvertedTest : public PagedQSAIndexerFusionTest {};++TEST_P(PagedQSAIndexerFusionNotConvertedTest, KeepsQSAIndexer) {+ model = make_model(GetParam(), false);+ model_ref = make_model(GetParam(), false);+ EXPECT_TRUE(run_paged_qsa_indexer_fusion(model).empty());+}++// States not read from variables cannot be converted to paged caches.+INSTANTIATE_TEST_SUITE_P(PagedQSAIndexerFusion,+ PagedQSAIndexerFusionNotConvertedTest,+ testing::Values(GraphOptions{true, false, false}));++TEST(PagedQSAIndexerFusion, SDPAToPagedAttentionConvertsStatefulQSAPrepareAndIndexer) {+ ParameterVector params{make_named_param("input_ids", element::i64, PartialShape{-1, -1}),+ make_named_param("beam_idx", element::i32, PartialShape{-1})};+ const auto param = [¶ms](element::Type type, const PartialShape& shape) {+ params.push_back(std::make_shared<v0::Parameter>(type, shape));+ return params.back();+ };+ // SDPAToPagedAttention requires an SDPA in the model.+ const auto sdpa_input = param(element::f32, PartialShape{-1, query_heads, -1, head_size});+ const auto sdpa =+ std::make_shared<ov::op::v13::ScaledDotProductAttention>(sdpa_input, sdpa_input, sdpa_input, false);++ const auto query = param(element::f32, PartialShape{-1, query_heads, -1, head_size});+ const auto raw_keys = param(element::f32, PartialShape{-1, -1, head_size});+ const auto key_length = param(element::i32, PartialShape{-1});+ const auto rope_cos = param(element::f32, PartialShape{-1, -1, rotary_dim});+ const auto rope_sin = param(element::f32, PartialShape{-1, -1, rotary_dim});+ const auto k_norm_weight = v0::Constant::create(element::f32, Shape{head_size}, {0.5f});++ std::vector<std::shared_ptr<op::util::Variable>> variables;+ const auto read_state = [&](const std::string& id, const PartialShape& shape) {+ variables.push_back(std::make_shared<op::util::Variable>(op::util::VariableInfo{shape, element::f32, id}));+ return std::make_shared<v8::Gather>(std::make_shared<v6::ReadValue>(variables.back()),+ params[1],+ v0::Constant::create(element::i64, Shape{}, {0}));+ };+ const auto past_block_keys = read_state("block_keys", PartialShape{-1, -1, head_size});+ const auto incomplete_raw_keys = read_state("incomplete_raw_keys", {-1, key_block_size - 1, head_size});+ const auto incomplete_rope = read_state("incomplete_rope", {-1, 2 * rotary_dim});+ const auto prepare = std::make_shared<ov::op::v17::QSAPrepare>(raw_keys,+ past_block_keys,+ key_length,+ rope_cos,+ rope_sin,+ k_norm_weight,+ incomplete_raw_keys,+ incomplete_rope,+ key_block_size,+ epsilon);+ const auto indexer = std::make_shared<ov::op::v17::SparseAttentionIndexer>(query,+ prepare->output(0),+ key_length,+ key_block_size,+ block_topk * key_block_size,+ selection_heads);+ SinkVector sinks;+ for (size_t i = 0; i < variables.size(); ++i) {+ sinks.push_back(std::make_shared<v6::Assign>(prepare->output(i), variables[i]));+ }+ const auto model = std::make_shared<Model>(ResultVector{std::make_shared<v0::Result>(sdpa),+ std::make_shared<v0::Result>(indexer->output(0)),+ std::make_shared<v0::Result>(indexer->output(1))},+ sinks,+ params);++ pass::Manager manager;+ manager.register_pass<pass::SDPAToPagedAttention>();+ manager.run_passes(model);++ size_t paged_indexers = 0;+ for (const auto& node : model->get_ops()) {+ EXPECT_FALSE(+ (ov::is_type_any_of<ov::op::v17::QSAPrepare, ov::op::v17::SparseAttentionIndexer, op_internal::QSAIndexer>(+ node)))+ << node;+ paged_indexers += ov::is_type<op_internal::PagedQSAIndexer>(node);+ }+ EXPECT_EQ(paged_indexers, 1);+ EXPECT_TRUE(model->get_sinks().empty());+ const auto& model_params = model->get_parameters();+ for (const auto& name : {"index_key_cache.0", "index_block_rope_cache.0", "block_index_keys_cache.0"}) {+ EXPECT_TRUE(std::any_of(model_params.begin(), model_params.end(), [&name](const auto& p) {+ return p->get_output_tensor(0).get_names().count(name) > 0;+ })) << name;+ }+}++std::shared_ptr<Model> make_model_with_modified_indexer(const std::string& name) {+ const auto model = make_model(GraphOptions{}, false);+ std::shared_ptr<op_internal::QSAIndexer> indexer;+ for (const auto& node : model->get_ops()) {+ indexer = ov::as_type_ptr<op_internal::QSAIndexer>(node);+ if (indexer) {+ break;+ }+ }+ OPENVINO_ASSERT(indexer, "Expected a dense QSAIndexer in the test model");+ auto inputs = indexer->input_values();+ auto config = indexer->get_config();+ if (name == "zero_block_size") {+ config.key_block_size = 0;+ } else if (name == "selection_heads") {+ config.num_selection_heads = 2;+ } else if (name == "nonfinite_scale") {+ config.scale = std::numeric_limits<float>::infinity();+ } else if (name == "head_dimension") {+ config.indexer_head_dim = head_size / 2;+ } else if (name == "head_count") {+ inputs[QSAIndexerInputIdx::RAW_INDEX_KEYS] =+ v0::Constant::create(element::f32, Shape{1, 1, 3, head_size}, {0.0f});+ } else if (name == "dynamic_head_count") {+ model->get_parameters()[0]->set_partial_shape({-1, -1, -1, head_size});+ model->get_parameters()[1]->set_partial_shape({-1, -1, -1, head_size});+ } else if (name == "zero_query_heads") {+ model->get_parameters()[0]->set_partial_shape({-1, -1, 0, head_size});+ } else if (name == "overflowing_query_width") {+ const auto overflow_heads = std::numeric_limits<int64_t>::max() / head_size + 1;+ model->get_parameters()[0]->set_partial_shape({-1, -1, overflow_heads, head_size});+ } else if (name == "weight_shape") {+ inputs[QSAIndexerInputIdx::K_NORM_WEIGHT] = v0::Constant::create(element::f32, Shape{head_size - 1}, {1.0f});+ } else if (name == "weight_type") {+ inputs[QSAIndexerInputIdx::Q_NORM_WEIGHT] = v0::Constant::create(element::f16, Shape{head_size}, {1.0f});+ } else if (name == "rotary_dimension") {+ config.indexer_rotary_dim = rotary_dim - 1;+ } else if (name == "zero_rotary_dimension") {+ config.indexer_rotary_dim = 0;+ for (const auto i : {2, 3}) {+ const auto param = model->get_parameters()[i];+ param->set_partial_shape({-1, -1, 0});+ param->validate_and_infer_types();+ }+ const auto rope_state =+ ov::as_type_ptr<v6::ReadValue>(inputs[QSAIndexerInputIdx::PAST_INCOMPLETE_ROPE].get_node_shared_ptr());+ OPENVINO_ASSERT(rope_state);+ rope_state->get_variable()->update_data_shape(PartialShape{-1, 0});+ rope_state->validate_and_infer_types();+ } else if (name == "incompatible_key_rope_cos" || name == "incompatible_key_rope_sin") {+ model->get_parameters()[0]->set_partial_shape({1, Dimension(1, 3), query_heads, head_size});+ model->get_parameters()[1]->set_partial_shape({1, 1, key_heads, head_size});+ const auto idx =+ name == "incompatible_key_rope_cos" ? QSAIndexerInputIdx::ROPE_COS : QSAIndexerInputIdx::ROPE_SIN;+ inputs[idx] = v0::Constant::create(element::f32, Shape{1, 3, rotary_dim}, {1.0f});+ } else {+ model->get_parameters()[0]->set_partial_shape({1, 3, query_heads, head_size});+ model->get_parameters()[1]->set_partial_shape({1, 3, key_heads, head_size});+ inputs[QSAIndexerInputIdx::ROPE_COS] = v0::Constant::create(element::f32, Shape{1, 5, rotary_dim}, {1.0f});+ }+ const auto replacement = std::make_shared<op_internal::QSAIndexer>(inputs, config);+ ov::replace_node(indexer, replacement);+ model->validate_nodes_and_infer_types();+ return model;+}++class PagedQSAIndexerDeferredShapeValidationTest : public testing::TestWithParam<std::string> {};++TEST_P(PagedQSAIndexerDeferredShapeValidationTest, RejectsIncompatibleConcreteInputShapes) {+ const auto model = make_model_with_modified_indexer(GetParam());+ EXPECT_EQ(run_paged_qsa_indexer_fusion(model),+ (std::unordered_set<std::string>{"block_keys", "incomplete_raw_keys", "incomplete_rope"}));+ model->get_parameters()[0]->set_partial_shape({1, 1, query_heads, head_size});+ const auto name = GetParam() == "incompatible_key_rope_cos" ? "rope_cos" : "rope_sin";+ OV_EXPECT_THROW_HAS_SUBSTRING(model->validate_nodes_and_infer_types(),+ ov::NodeValidationFailure,+ std::string("PagedQSAIndexer expects ") + name);+}++INSTANTIATE_TEST_SUITE_P(PagedQSAIndexerFusion,+ PagedQSAIndexerDeferredShapeValidationTest,+ testing::Values("incompatible_key_rope_cos", "incompatible_key_rope_sin"),+ [](const testing::TestParamInfo<std::string>& info) {+ return info.param;+ });++class QSAIndexerInvalidInputsTest : public testing::TestWithParam<std::string> {};++TEST_P(QSAIndexerInvalidInputsTest, RejectsInvalidInputsAtConstruction) {+ EXPECT_THROW(make_model_with_modified_indexer(GetParam()), ov::NodeValidationFailure);+}++INSTANTIATE_TEST_SUITE_P(QSAIndexer,+ QSAIndexerInvalidInputsTest,+ testing::Values("zero_block_size",+ "selection_heads",+ "nonfinite_scale",+ "head_dimension",+ "head_count",+ "weight_shape",+ "weight_type",+ "rotary_dimension",+ "rope_token_count"),+ [](const testing::TestParamInfo<std::string>& info) {+ return info.param;+ });++class PagedQSAIndexerInvalidProductionInputsTest : public TransformationTestsF,+ public testing::WithParamInterface<std::string> {+public:+ void SetUp() override {+ TransformationTestsF::SetUp();+ model = make_model_with_modified_indexer(GetParam());+ pa_params = std::make_unique<pass::paged_attention::PaParams>(model->get_parameters());+ manager.register_pass<pass::PagedQSAIndexerFusion>(*pa_params, removed_ids);+ }++ void TearDown() override {+ TransformationTestsF::TearDown();+ ASSERT_NE(pa_params, nullptr);+ EXPECT_TRUE(removed_ids.empty());+ EXPECT_TRUE(pa_params->items().empty());+ }++private:+ std::unique_ptr<pass::paged_attention::PaParams> pa_params;+ std::unordered_set<std::string> removed_ids;+};++TEST_P(PagedQSAIndexerInvalidProductionInputsTest, DoesNotFuseOrAddCaches) {}++INSTANTIATE_TEST_SUITE_P(+ PagedQSAIndexerFusion,+ PagedQSAIndexerInvalidProductionInputsTest,+ testing::Values("zero_rotary_dimension", "zero_query_heads", "dynamic_head_count", "overflowing_query_width"),+ [](const testing::TestParamInfo<std::string>& info) {+ return info.param;+ });++struct QueryOptions {+ std::string name;+ float norm_epsilon = epsilon;+ int64_t norm_axis = -1;+ bool affine = false;+ bool changes_precision = false;+ bool distinct_cos = false;+ bool distinct_sin = false;+ bool interleaved = false;+ bool extra_consumers = false;+ bool shared_query_reshape = false;+ bool with_rope = true;+ bool with_norm = true;+ bool flat_norm = false;+ bool non_unit_unused_weight = false;+ bool rope_before_norm = false;+ bool indexer_query_norm = false;+ bool indexer_query_rope = false;+ bool absorb_norm = true;+ bool absorb_rope = true;+ bool rope_rows_special_zero = false;+ // A static single-token query whose head transposes around a head-first RoPE are Reshapes, as in SDPAToPA output.+ bool single_token_head_first = false;+ bool query_is_reshape = false;+ int64_t rope_length = -1;+ int64_t rope_axis = 1;+ // Reshape target expressing the cos / sin head-axis Unsqueeze; empty keeps the Unsqueeze.+ std::vector<int64_t> rope_rows_target;+};++template <class Indexer>+struct QueryGraph {+ std::shared_ptr<Model> model;+ std::shared_ptr<Indexer> indexer;+ OutputVector inputs;+ Output<Node> raw_query;+ Output<Node> norm;+ Output<Node> rotated;+ Output<Node> query;+};++template <class Indexer>+QueryGraph<Indexer> make_query_graph(const QueryOptions& o) {+ using In = typename Indexer::InputIdx;+ constexpr bool paged = std::is_same<Indexer, op_internal::PagedQSAIndexer>::value;+ QueryGraph<Indexer> graph;+ graph.model = make_model(GraphOptions{false, false, paged, false, o.rope_length}, paged);+ for (const auto& node : graph.model->get_ops()) {+ graph.indexer = ov::as_type_ptr<Indexer>(node);+ if (graph.indexer) {+ break;+ }+ }+ OPENVINO_ASSERT(graph.indexer, "Expected a query indexer in the test model");+ graph.inputs = graph.indexer->input_values();+ const auto unflatten = [](const Output<Node>& input) {+ if constexpr (std::is_same_v<Indexer, op_internal::PagedQSAIndexer>) {+ return input.get_node_shared_ptr()->input_value(0);+ } else {+ return input;+ }+ };+ graph.raw_query = o.flat_norm ? graph.inputs[In::INDEX_QUERY] : unflatten(graph.inputs[In::INDEX_QUERY]);+ if (o.single_token_head_first) {+ const auto query = ov::as_type_ptr<v0::Parameter>(graph.raw_query.get_node_shared_ptr());+ OPENVINO_ASSERT(query, "Expected the query Parameter");+ query->set_partial_shape(PartialShape{-1, 1, query_heads, head_size});+ graph.model->validate_nodes_and_infer_types();+ }+ if (o.query_is_reshape) {+ graph.raw_query = std::make_shared<v1::Reshape>(graph.raw_query, i64({0, 0, 0, 0}), true);+ }+ const auto make_norm = [&](const Output<Node>& input) -> Output<Node> {+ const auto norm_input =+ o.changes_precision ? Output<Node>(std::make_shared<v0::Convert>(input, element::f16)) : input;+ if (o.affine) {+ return std::make_shared<op_internal::RMS>(norm_input,+ v0::Constant::create(element::f32, Shape{head_size}, {0.5f}),+ o.norm_epsilon,+ element::f32,+ o.norm_axis);+ }+ return std::make_shared<op_internal::RMS>(norm_input, o.norm_epsilon, element::f32, o.norm_axis);+ };+ const auto other_rows = [&](const Output<Node>& rows) -> Output<Node> {+ const auto param = std::make_shared<v0::Parameter>(rows.get_element_type(), rows.get_partial_shape());+ graph.model->add_parameters({param});+ return param;+ };+ const auto cos = unflatten(graph.inputs[In::ROPE_COS]);+ const auto sin = unflatten(graph.inputs[In::ROPE_SIN]);+ std::shared_ptr<Node> rope;+ const auto make_rope = [&](const Output<Node>& input) -> Output<Node> {+ op_internal::RoPE::Config config;+ config.rotary_ndims = rotary_dim;+ config.input_trans0213 = !o.single_token_head_first;+ config.is_interleaved = o.interleaved;+ const auto with_head_axis = [&o](const Output<Node>& rows) -> Output<Node> {+ if (o.rope_rows_target.empty()) {+ return std::make_shared<v0::Unsqueeze>(rows, i64({o.rope_axis}));+ }+ return std::make_shared<v1::Reshape>(rows, i64(o.rope_rows_target), o.rope_rows_special_zero);+ };+ auto rope_input = input;+ if (o.single_token_head_first) {+ rope_input = std::make_shared<v1::Reshape>(input, i64({0, query_heads, 1, head_size}), true);+ }+ rope = std::make_shared<op_internal::RoPE>(OutputVector{rope_input,+ with_head_axis(o.distinct_cos ? other_rows(cos) : cos),+ with_head_axis(o.distinct_sin ? other_rows(sin) : sin)},+ config);+ if (o.single_token_head_first) {+ return rope;+ }+ return std::make_shared<v1::Transpose>(rope, i64({0, 2, 1, 3}));+ };+ graph.norm = graph.raw_query;+ graph.query = graph.raw_query;+ if (o.rope_before_norm) {+ graph.rotated = make_rope(graph.raw_query);+ if (o.with_norm) {+ graph.query = graph.norm = make_norm(graph.rotated);+ } else {+ graph.query = graph.rotated;+ }+ } else {+ if (o.with_norm) {+ graph.query = graph.norm = make_norm(graph.raw_query);+ }+ if (o.with_rope) {+ graph.query = graph.rotated = make_rope(graph.query);+ }+ }+ if (o.extra_consumers) {+ graph.model->add_results({std::make_shared<v0::Result>(rope), std::make_shared<v0::Result>(graph.norm)});+ }+ return graph;+}++template <class Indexer>+void replace_query_indexer(QueryGraph<Indexer>& graph,+ const QueryOptions& o,+ const Output<Node>& query,+ const typename Indexer::Config& config) {+ using In = typename Indexer::InputIdx;+ if constexpr (std::is_same_v<Indexer, op_internal::PagedQSAIndexer>) {+ const auto flatten = graph.inputs[In::INDEX_QUERY].get_node_shared_ptr();+ graph.inputs[In::INDEX_QUERY] =+ o.flat_norm ? query : Output<Node>(std::make_shared<v1::Reshape>(query, flatten->input_value(1), false));+ if (o.shared_query_reshape) {+ const auto shared_query =+ query == graph.query+ ? graph.inputs[In::INDEX_QUERY]+ : Output<Node>(std::make_shared<v1::Reshape>(graph.query, flatten->input_value(1), false));+ graph.model->add_results({std::make_shared<v0::Result>(shared_query)});+ }+ } else {+ graph.inputs[In::INDEX_QUERY] = query;+ }+ ov::replace_node(graph.indexer, std::make_shared<Indexer>(graph.inputs, config));+}++template <class Indexer = op_internal::PagedQSAIndexer>+std::shared_ptr<Model> getQueryModel(const QueryOptions& o) {+ using In = typename Indexer::InputIdx;+ auto graph = make_query_graph<Indexer>(o);+ auto config = graph.indexer->get_config();+ config.query_norm = o.indexer_query_norm;+ config.query_rope = o.indexer_query_rope;+ if (o.non_unit_unused_weight) {+ graph.inputs[In::Q_NORM_WEIGHT] = v0::Constant::create(element::f32, Shape{head_size}, {0.5f});+ }+ replace_query_indexer(graph, o, graph.query, config);+ return graph.model;+}++template <class Indexer = op_internal::PagedQSAIndexer>+std::shared_ptr<Model> getQueryModelRef(const QueryOptions& o) {+ using In = typename Indexer::InputIdx;+ auto graph = make_query_graph<Indexer>(o);+ auto config = graph.indexer->get_config();+ config.query_norm = o.indexer_query_norm || (o.with_norm && o.absorb_norm);+ config.query_rope = o.indexer_query_rope || (o.with_rope && o.absorb_rope);+ if (o.affine && o.with_norm && o.absorb_norm) {+ graph.inputs[In::Q_NORM_WEIGHT] = v0::Constant::create(element::f32, Shape{head_size}, {0.5f});+ } else if (o.non_unit_unused_weight && !o.absorb_norm) {+ graph.inputs[In::Q_NORM_WEIGHT] = v0::Constant::create(element::f32, Shape{head_size}, {0.5f});+ }+ const bool norm_outside = o.with_norm && !o.absorb_norm;+ const bool rope_outside = o.with_rope && !o.absorb_rope;+ Output<Node> query = graph.query;+ if (!norm_outside && !rope_outside) {+ query = graph.raw_query;+ } else if (!rope_outside) {+ query = graph.norm;+ } else if (!norm_outside) {+ query = graph.rotated;+ }+ replace_query_indexer(graph, o, query, config);+ return graph.model;+}++class FusePagedQSAIndexerQueryTest : public TransformationTestsF, public testing::WithParamInterface<QueryOptions> {+protected:+ void SetUp() override {+ TransformationTestsF::SetUp();+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+ }+};++TEST_P(FusePagedQSAIndexerQueryTest, AbsorbsOnlyCompatibleQuerySteps) {+ model = getQueryModel(GetParam());+ model_ref = getQueryModelRef(GetParam());+}++const std::vector<QueryOptions> query_cases = [] {+ std::vector<QueryOptions> cases{QueryOptions{"partial_rotary"}};+ auto shared = QueryOptions{"shared_query_reshape"};+ shared.shared_query_reshape = true;+ cases.push_back(shared);+ shared.name = "shared_query_reshape_norm_only";+ shared.with_rope = false;+ shared.absorb_rope = false;+ cases.push_back(shared);+ shared = QueryOptions{"shared_query_reshape_rope_only"};+ shared.shared_query_reshape = true;+ shared.with_norm = false;+ shared.absorb_norm = false;+ cases.push_back(shared);+ auto o = QueryOptions{"extra_consumers"};+ o.extra_consumers = true;+ cases.push_back(o);+ o = QueryOptions{"unused_query_weight"};+ o.non_unit_unused_weight = true;+ cases.push_back(o);+ o = QueryOptions{"without_rope"};+ o.with_rope = false;+ o.absorb_rope = false;+ cases.push_back(o);+ o = QueryOptions{"wrong_rope_axis"};+ o.rope_axis = 2;+ o.absorb_norm = o.absorb_rope = false;+ cases.push_back(o);+ o = QueryOptions{"flat_norm"};+ o.with_rope = false;+ o.flat_norm = true;+ o.absorb_norm = o.absorb_rope = false;+ cases.push_back(o);+ for (const auto& name : {"wrong_epsilon", "wrong_axis", "affine", "changes_precision"}) {+ o = QueryOptions{name};+ o.absorb_norm = false;+ if (o.name == "wrong_epsilon")+ o.norm_epsilon = 2 * epsilon;+ else if (o.name == "wrong_axis")+ o.norm_axis = -2;+ else if (o.name == "affine") {+ o.affine = true;+ o.absorb_norm = true;+ } else+ o.changes_precision = true;+ cases.push_back(o);+ }+ // The RMS stage runs after the RoPE stage, so a RoPE after the RMS stays outside.+ o = QueryOptions{"rope_before_norm"};+ o.rope_before_norm = true;+ o.absorb_rope = false;+ cases.push_back(o);+ for (const auto& name : {"distinct_cos", "distinct_sin", "interleaved"}) {+ o = QueryOptions{name};+ o.absorb_norm = o.absorb_rope = false;+ o.distinct_cos = o.name == "distinct_cos";+ o.distinct_sin = o.name == "distinct_sin";+ o.interleaved = o.name == "interleaved";+ cases.push_back(o);+ }+ // NopElimination replaces the tiny model's head-axis Unsqueeze with this Reshape.+ o = QueryOptions{"tiny_model_rope_rows"};+ o.rope_length = 1;+ o.rope_rows_target = {-1, 1, 1, rotary_dim};+ cases.push_back(o);+ o = QueryOptions{"copy_rope_rows_dimension"};+ o.rope_length = 1;+ o.rope_rows_target = {0, 1, 1, rotary_dim};+ o.rope_rows_special_zero = true;+ cases.push_back(o);+ o = QueryOptions{"multiple_rope_rows_preserved"};+ o.rope_length = 2;+ o.rope_rows_target = {-1, 1, 2, rotary_dim};+ cases.push_back(o);+ o = QueryOptions{"multiple_rope_rows"};+ o.rope_length = 2;+ o.rope_rows_target = {-1, 1, 1, rotary_dim};+ o.absorb_norm = o.absorb_rope = false;+ cases.push_back(o);+ o = QueryOptions{"single_token_head_first"};+ o.rope_length = 1;+ o.single_token_head_first = true;+ cases.push_back(o);+ o = QueryOptions{"single_token_head_first_without_norm"};+ o.rope_length = 1;+ o.single_token_head_first = true;+ o.with_norm = false;+ o.absorb_norm = false;+ cases.push_back(o);+ o = QueryOptions{"query_reshape_before_transposing_rope"};+ o.with_norm = false;+ o.absorb_norm = false;+ o.query_is_reshape = true;+ cases.push_back(o);+ o = QueryOptions{"moved_rope_rows"};+ o.rope_length = 1;+ o.rope_rows_target = {1, -1, 1, rotary_dim};+ o.absorb_norm = o.absorb_rope = false;+ cases.push_back(o);+ return cases;+}();++INSTANTIATE_TEST_SUITE_P(PagedQSAIndexerFusion,+ FusePagedQSAIndexerQueryTest,+ testing::ValuesIn(query_cases),+ [](const testing::TestParamInfo<QueryOptions>& info) {+ return info.param.name;+ });++TEST_F(TransformationTestsF, FuseQSAIndexerQueryWithDynamicHeadFirstReshapeTarget) {+ QueryOptions options;+ options.rope_length = 1;+ options.single_token_head_first = true;+ model = getQueryModel(options);+ model_ref = getQueryModelRef(options);+ for (const auto& function : {model, model_ref}) {+ function->get_parameters().front()->set_partial_shape(PartialShape{-1, 1, -1, head_size});+ function->validate_nodes_and_infer_types();+ }++ size_t rope_count = 0;+ for (const auto& node : model->get_ops()) {+ const auto rope = ov::as_type_ptr<op_internal::RoPE>(node);+ if (!rope) {+ continue;+ }+ ++rope_count;+ const auto reshape = ov::as_type_ptr<v1::Reshape>(rope->get_input_node_shared_ptr(0));+ ASSERT_NE(reshape, nullptr);+ const auto shape = std::make_shared<v0::ShapeOf>(reshape->input_value(0));+ const auto batch =+ std::make_shared<v8::Gather>(shape, i64({0}), v0::Constant::create(element::i64, Shape{}, {0}));+ const auto target = std::make_shared<v0::Concat>(OutputVector{batch, i64({query_heads, 1, head_size})}, 0);+ reshape->input(1).replace_source_output(target);+ }+ ASSERT_EQ(rope_count, 1);+ model->validate_nodes_and_infer_types();++ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++TEST_F(TransformationTestsF, FuseQSAIndexerQueryAfterNopElimination) {+ QueryOptions options;+ options.rope_length = 1;+ model = getQueryModel(options);+ model_ref = getQueryModelRef(options);++ pass::NopElimination nop_elimination;+ ASSERT_TRUE(nop_elimination.run_on_model(model));+ nop_elimination.run_on_model(model_ref);++ size_t rope_count = 0;+ for (const auto& node : model->get_ops()) {+ const auto rope = ov::as_type_ptr<op_internal::RoPE>(node);+ if (!rope) {+ continue;+ }+ ++rope_count;+ for (const auto idx : {1, 2}) {+ const auto reshape = ov::as_type_ptr<v1::Reshape>(rope->get_input_node_shared_ptr(idx));+ ASSERT_NE(reshape, nullptr);+ EXPECT_EQ(reshape->get_input_partial_shape(0), (PartialShape{-1, 1, rotary_dim}));+ EXPECT_FALSE(reshape->get_special_zero());+ const auto target = ov::as_type_ptr<v0::Constant>(reshape->get_input_node_shared_ptr(1));+ ASSERT_NE(target, nullptr);+ EXPECT_EQ(target->cast_vector<int64_t>(), (std::vector<int64_t>{-1, 1, 1, rotary_dim}));+ }+ }+ ASSERT_EQ(rope_count, 1);++ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++TEST_F(TransformationTestsF, FuseQSAIndexerQueryRejectsDynamicRoPERowsTarget) {+ QueryOptions options;+ options.rope_length = 1;+ options.rope_rows_target = {-1, 1, 1, rotary_dim};+ model = getQueryModel(options);++ const auto other = std::make_shared<v0::Parameter>(element::f32, PartialShape{-1});+ const auto target =+ std::make_shared<v0::Concat>(OutputVector{std::make_shared<v0::ShapeOf>(other), i64({1, 1, rotary_dim})}, 0);+ model->add_parameters({other});+ size_t rope_count = 0;+ for (const auto& node : model->get_ops()) {+ const auto rope = ov::as_type_ptr<op_internal::RoPE>(node);+ if (!rope) {+ continue;+ }+ ++rope_count;+ for (const auto idx : {1, 2}) {+ const auto reshape = ov::as_type_ptr<v1::Reshape>(rope->get_input_node_shared_ptr(idx));+ ASSERT_NE(reshape, nullptr);+ reshape->input(1).replace_source_output(target);+ reshape->validate_and_infer_types();+ EXPECT_EQ(reshape->get_output_partial_shape(0), (PartialShape{-1, 1, 1, rotary_dim}));+ }+ }+ ASSERT_EQ(rope_count, 1);+ model->validate_nodes_and_infer_types();++ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++std::shared_ptr<Model> combine_query_models(const std::shared_ptr<Model>& mixed, const std::shared_ptr<Model>& dense) {+ mixed->add_parameters(dense->get_parameters());+ mixed->add_results(dense->get_results());+ return mixed;+}++TEST_F(TransformationTestsF, FuseQSAIndexerQueryHandlesMixedRoPERowsAdapters) {+ QueryOptions options;+ options.rope_length = 1;+ model = combine_query_models(getQueryModel(options), getQueryModel<op_internal::QSAIndexer>(options));+ model_ref = combine_query_models(getQueryModelRef(options), getQueryModelRef<op_internal::QSAIndexer>(options));++ size_t rope_count = 0;+ for (const auto& node : model->get_ops()) {+ const auto rope = ov::as_type_ptr<op_internal::RoPE>(node);+ if (!rope) {+ continue;+ }+ const auto idx = rope_count++ == 0 ? 1 : 2;+ const auto unsqueeze = ov::as_type_ptr<v0::Unsqueeze>(rope->get_input_node_shared_ptr(idx));+ ASSERT_NE(unsqueeze, nullptr);+ rope->input(idx).replace_source_output(+ std::make_shared<v1::Reshape>(unsqueeze->input_value(0), i64({-1, 1, 1, rotary_dim}), false));+ rope->validate_and_infer_types();+ }+ ASSERT_EQ(rope_count, 2);++ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++TEST_F(TransformationTestsF, FuseQSAIndexerQueryHandlesDenseAndPagedIndexersIdempotently) {+ model = combine_query_models(getQueryModel(QueryOptions{}), getQueryModel<op_internal::QSAIndexer>(QueryOptions{}));+ model_ref = combine_query_models(getQueryModelRef(QueryOptions{}),+ getQueryModelRef<op_internal::QSAIndexer>(QueryOptions{}));+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++TEST_F(TransformationTestsF, FuseQSAIndexerQueryIgnoresInactiveNormWeights) {+ QueryOptions options;+ options.non_unit_unused_weight = true;+ model = combine_query_models(getQueryModel(options), getQueryModel<op_internal::QSAIndexer>(options));+ model_ref = combine_query_models(getQueryModelRef(options), getQueryModelRef<op_internal::QSAIndexer>(options));+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++class FuseQSAIndexerBroadcastGammaTest : public TransformationTestsF, public testing::WithParamInterface<bool> {};++TEST_P(FuseQSAIndexerBroadcastGammaTest, FlattensDenseAndPagedNormWeights) {+ QueryOptions options;+ options.affine = true;+ const auto prepare = [&](const std::shared_ptr<Model>& source, const std::shared_ptr<Model>& reference) {+ Output<Node> gamma = v0::Constant::create(element::f32, Shape{1, 1, 1, head_size}, {0.5f});+ if (GetParam()) {+ const auto param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1, 1, head_size});+ source->add_parameters({param});+ gamma = param;+ const auto ref_param = std::make_shared<v0::Parameter>(element::f32, Shape{1, 1, 1, head_size});+ reference->add_parameters({ref_param});+ const auto flat_gamma = std::make_shared<v1::Reshape>(ref_param, i64({head_size}), false);+ for (const auto& node : reference->get_ops()) {+ if (ov::is_type<op_internal::QSAIndexer>(node)) {+ node->input(op_internal::QSAIndexer::InputIdx::Q_NORM_WEIGHT).replace_source_output(flat_gamma);+ } else if (ov::is_type<op_internal::PagedQSAIndexer>(node)) {+ node->input(op_internal::PagedQSAIndexer::InputIdx::Q_NORM_WEIGHT)+ .replace_source_output(flat_gamma);+ }+ }+ }+ for (const auto& node : source->get_ops()) {+ if (const auto rms = ov::as_type_ptr<op_internal::RMS>(node)) {+ rms->input(1).replace_source_output(gamma);+ }+ }+ };+ model = getQueryModel(options);+ model_ref = getQueryModelRef(options);+ prepare(model, model_ref);+ const auto dense = getQueryModel<op_internal::QSAIndexer>(options);+ const auto dense_ref = getQueryModelRef<op_internal::QSAIndexer>(options);+ prepare(dense, dense_ref);+ model = combine_query_models(model, dense);+ model_ref = combine_query_models(model_ref, dense_ref);+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++INSTANTIATE_TEST_SUITE_P(FuseQSAIndexerQuery,+ FuseQSAIndexerBroadcastGammaTest,+ testing::Bool(),+ [](const testing::TestParamInfo<bool>& info) {+ return info.param ? "parameter" : "constant";+ });++class FuseQSAIndexerQueryGammaTest : public TransformationTestsF, public testing::WithParamInterface<std::string> {};++TEST_P(FuseQSAIndexerQueryGammaTest, KeepsRMSWithUnsupportedGamma) {+ const auto& param = GetParam();+ QueryOptions options;+ options.affine = param != "missing";+ options.with_rope = false;+ model = combine_query_models(getQueryModel(options), getQueryModel<op_internal::QSAIndexer>(options));+ const auto check_pattern = [&](bool expected) {+ pass::FuseQSAIndexerQueryNorm<op_internal::QSAIndexer> dense_matcher;+ pass::FuseQSAIndexerQueryNorm<op_internal::PagedQSAIndexer> paged_matcher;+ size_t indexer_count = 0;+ for (const auto& node : model->get_ops()) {+ if (ov::is_type<op_internal::QSAIndexer>(node)) {+ EXPECT_EQ(dense_matcher.get_matcher()->match(node), expected);+ ++indexer_count;+ } else if (ov::is_type<op_internal::PagedQSAIndexer>(node)) {+ EXPECT_EQ(paged_matcher.get_matcher()->match(node), expected);+ ++indexer_count;+ }+ }+ EXPECT_EQ(indexer_count, 2);+ };+ check_pattern(true);++ size_t rms_count = 0;+ for (const auto& node : model->get_ops()) {+ if (const auto rms = ov::as_type_ptr<op_internal::RMS>(node)) {+ if (param == "missing" || param == "inactive") {+ // Make elementwise_affine disagree with the number of RMS inputs.+ rms->set_elementwise_affine(param == "missing");+ } else {+ const auto type = param == "mixed_precision" ? element::f16 : element::f32;+ const auto shape = param == "dynamic_rank" ? PartialShape::dynamic()+ : param == "scalar" ? PartialShape{}+ : param == "wrong_last_dim" ? PartialShape{1, 1, 1, head_size + 1}+ : param == "non_singleton" ? PartialShape{1, 1, query_heads, head_size}+ : param == "dynamic_leading" ? PartialShape{1, 1, -1, head_size}+ : PartialShape{head_size};+ const auto gamma = std::make_shared<v0::Parameter>(type, shape);+ model->add_parameters({gamma});+ rms->input(1).replace_source_output(gamma);+ }+ ++rms_count;+ }+ }+ ASSERT_EQ(rms_count, 2);+ check_pattern(false);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++INSTANTIATE_TEST_SUITE_P(FuseQSAIndexerQuery,+ FuseQSAIndexerQueryGammaTest,+ testing::Values("mixed_precision",+ "missing",+ "inactive",+ "dynamic_rank",+ "scalar",+ "wrong_last_dim",+ "non_singleton",+ "dynamic_leading"),+ [](const testing::TestParamInfo<std::string>& info) {+ return info.param;+ });++TEST_F(TransformationTestsF, FuseQSAIndexerQueryNormIgnoresEnabledQueryRoPE) {+ QueryOptions options;+ options.with_rope = false;+ options.absorb_rope = false;+ options.indexer_query_rope = true;+ model = combine_query_models(getQueryModel(options), getQueryModel<op_internal::QSAIndexer>(options));+ model_ref = combine_query_models(getQueryModelRef(options), getQueryModelRef<op_internal::QSAIndexer>(options));+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++TEST_F(TransformationTestsF, FuseQSAIndexerQueryRoPEIgnoresEnabledQueryNorm) {+ QueryOptions options;+ options.with_norm = false;+ options.absorb_norm = false;+ options.indexer_query_norm = true;+ model = combine_query_models(getQueryModel(options), getQueryModel<op_internal::QSAIndexer>(options));+ model_ref = combine_query_models(getQueryModelRef(options), getQueryModelRef<op_internal::QSAIndexer>(options));+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++TEST(FuseQSAIndexerQuery, UsesTypedRootsAndOptionalLayoutAdapters) {+ const auto verify = [](const std::shared_ptr<pass::MatcherPass>& matcher,+ const DiscreteTypeInfo& expected_type,+ const std::vector<size_t>& adapter_inputs) {+ const auto root = ov::as_type_ptr<pass::pattern::op::WrapType>(+ matcher->get_matcher()->get_pattern_value().get_node_shared_ptr());+ ASSERT_NE(root, nullptr);+ EXPECT_EQ(root->get_wrapped_types(), (std::vector<DiscreteTypeInfo>{expected_type}));+ for (const auto input : adapter_inputs) {+ const auto adapter =+ ov::as_type_ptr<pass::pattern::op::Optional>(root->input_value(input).get_node_shared_ptr());+ ASSERT_NE(adapter, nullptr);+ EXPECT_EQ(adapter->get_optional_types(),+ (std::vector<DiscreteTypeInfo>{v1::Reshape::get_type_info_static()}));+ }+ };+ const auto& dense_type = op_internal::QSAIndexer::get_type_info_static();+ const auto& paged_type = op_internal::PagedQSAIndexer::get_type_info_static();+ verify(std::make_shared<pass::FuseQSAIndexerQueryRoPE<op_internal::QSAIndexer>>(),+ dense_type,+ {QSAIndexerInputIdx::INDEX_QUERY, QSAIndexerInputIdx::ROPE_COS, QSAIndexerInputIdx::ROPE_SIN});+ verify(std::make_shared<pass::FuseQSAIndexerQueryNorm<op_internal::QSAIndexer>>(),+ dense_type,+ {QSAIndexerInputIdx::INDEX_QUERY});+ verify(+ std::make_shared<pass::FuseQSAIndexerQueryRoPE<op_internal::PagedQSAIndexer>>(),+ paged_type,+ {PagedQSAIndexerInputIdx::INDEX_QUERY, PagedQSAIndexerInputIdx::ROPE_COS, PagedQSAIndexerInputIdx::ROPE_SIN});+ verify(std::make_shared<pass::FuseQSAIndexerQueryNorm<op_internal::PagedQSAIndexer>>(),+ paged_type,+ {PagedQSAIndexerInputIdx::INDEX_QUERY});+}++TEST(FuseQSAIndexerQuery, SpecializationsSharePassConfigTypes) {+ using DenseRoPE = pass::FuseQSAIndexerQueryRoPE<op_internal::QSAIndexer>;+ using PagedRoPE = pass::FuseQSAIndexerQueryRoPE<op_internal::PagedQSAIndexer>;+ using DenseNorm = pass::FuseQSAIndexerQueryNorm<op_internal::QSAIndexer>;+ using PagedNorm = pass::FuseQSAIndexerQueryNorm<op_internal::PagedQSAIndexer>;+ EXPECT_EQ(DenseRoPE::get_type_info_static(), PagedRoPE::get_type_info_static());+ EXPECT_EQ(DenseNorm::get_type_info_static(), PagedNorm::get_type_info_static());+}++template <class Broadcast = op::v3::Broadcast>+void broadcast_query_rope_rows(const std::shared_ptr<Model>& query_model, const std::vector<int64_t>& target_shape) {+ query_model->get_parameters().at(0)->set_partial_shape({2, 2, query_heads, head_size});+ std::shared_ptr<op_internal::PagedQSAIndexer> indexer;+ for (const auto& node : query_model->get_ops()) {+ indexer = ov::as_type_ptr<op_internal::PagedQSAIndexer>(node);+ if (indexer) {+ break;+ }+ }+ ASSERT_NE(indexer, nullptr);+ for (const auto idx : {PagedQSAIndexerInputIdx::ROPE_COS, PagedQSAIndexerInputIdx::ROPE_SIN}) {+ const auto reshape = ov::as_type_ptr<v1::Reshape>(indexer->input_value(idx).get_node_shared_ptr());+ ASSERT_NE(reshape, nullptr);+ const auto rows = ov::as_type_ptr<v0::Parameter>(reshape->input_value(0).get_node_shared_ptr());+ ASSERT_NE(rows, nullptr);+ rows->set_partial_shape({2, 1, rotary_dim});+ reshape->input(0).replace_source_output(std::make_shared<Broadcast>(rows, i64(target_shape)));+ }+ query_model->validate_nodes_and_infer_types();+}++TEST_F(TransformationTestsF, FuseQSAIndexerQueryRoPEAcceptsBatchBroadcast) {+ model = getQueryModel(QueryOptions{});+ model_ref = getQueryModelRef(QueryOptions{});+ broadcast_query_rope_rows(model, {2, 2, rotary_dim});+ broadcast_query_rope_rows(model_ref, {2, 2, rotary_dim});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++// ConvertBroadcast3 can run before the query fusion.+TEST_F(TransformationTestsF, FuseQSAIndexerQueryRoPEAcceptsOpset1BatchBroadcast) {+ model = getQueryModel(QueryOptions{});+ model_ref = getQueryModelRef(QueryOptions{});+ broadcast_query_rope_rows<v1::Broadcast>(model, {2, 2, rotary_dim});+ broadcast_query_rope_rows<v1::Broadcast>(model_ref, {2, 2, rotary_dim});+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+}++class FuseQSAIndexerQueryModeTest : public TransformationTestsF, public testing::WithParamInterface<bool> {};++TEST_P(FuseQSAIndexerQueryModeTest, FusesOnlySelectedIndexerType) {+ const QueryOptions options;+ model = combine_query_models(getQueryModel(options), getQueryModel<op_internal::QSAIndexer>(options));+ model_ref = combine_query_models(GetParam() ? getQueryModelRef(options) : getQueryModel(options),+ GetParam() ? getQueryModel<op_internal::QSAIndexer>(options)+ : getQueryModelRef<op_internal::QSAIndexer>(options));+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ if (GetParam()) {+ manager.register_pass<pass::FuseQSAIndexerQueryRoPE<op_internal::PagedQSAIndexer>>();+ manager.register_pass<pass::FuseQSAIndexerQueryNorm<op_internal::PagedQSAIndexer>>();+ } else {+ manager.register_pass<pass::FuseQSAIndexerQueryRoPE<op_internal::QSAIndexer>>();+ manager.register_pass<pass::FuseQSAIndexerQueryNorm<op_internal::QSAIndexer>>();+ }+}++INSTANTIATE_TEST_SUITE_P(FuseQSAIndexer,+ FuseQSAIndexerQueryModeTest,+ testing::Values(false, true),+ [](const testing::TestParamInfo<bool>& info) {+ return info.param ? "Paged" : "Dense";+ });++struct QueryPolicy {+ std::string name;+ bool paged;+ bool norm;+ bool callback;+};++class FuseQSAIndexerQueryPolicyTest : public TransformationTestsF, public testing::WithParamInterface<QueryPolicy> {};++TEST_P(FuseQSAIndexerQueryPolicyTest, HonorsIndividualMatcherConfiguration) {+ const auto& policy = GetParam();+ QueryOptions options;+ options.with_rope = !policy.norm;+ options.affine = !policy.norm;+ options.absorb_norm = policy.norm;+ options.absorb_rope = !policy.norm;+ model = combine_query_models(getQueryModel(options), getQueryModel<op_internal::QSAIndexer>(options));+ model_ref =+ combine_query_models(policy.callback && !policy.paged ? getQueryModelRef(options) : getQueryModel(options),+ policy.callback && policy.paged ? getQueryModelRef<op_internal::QSAIndexer>(options)+ : getQueryModel<op_internal::QSAIndexer>(options));+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ comparator.enable(FunctionsComparator::CONST_VALUES);+ manager.register_pass<pass::FuseQSAIndexerQuery>();+ if (!policy.norm) {+ manager.get_pass_config()->disable<pass::FuseQSAIndexerQueryNorm<op_internal::QSAIndexer>>();+ }+ const auto configure = [&](auto matcher) {+ using Pass = decltype(matcher);+ if (policy.callback) {+ manager.get_pass_config()->set_callback<Pass>(+ [paged = policy.paged](const std::shared_ptr<const Node>& node) {+ return paged == ov::is_type<op_internal::PagedQSAIndexer>(node);+ });+ } else {+ manager.get_pass_config()->disable<Pass>();+ }+ };+ if (policy.norm && policy.paged)+ configure(pass::FuseQSAIndexerQueryNorm<op_internal::PagedQSAIndexer>{});+ else if (policy.norm)+ configure(pass::FuseQSAIndexerQueryNorm<op_internal::QSAIndexer>{});+ else if (policy.paged)+ configure(pass::FuseQSAIndexerQueryRoPE<op_internal::PagedQSAIndexer>{});+ else+ configure(pass::FuseQSAIndexerQueryRoPE<op_internal::QSAIndexer>{});+}++INSTANTIATE_TEST_SUITE_P(PagedQSAIndexerFusion,+ FuseQSAIndexerQueryPolicyTest,+ testing::Values(QueryPolicy{"DisableDenseRoPE", false, false, false},+ QueryPolicy{"DisableDenseNorm", false, true, false},+ QueryPolicy{"DisablePagedRoPE", true, false, false},+ QueryPolicy{"DisablePagedNorm", true, true, false},+ QueryPolicy{"DenseRoPECallback", false, false, true},+ QueryPolicy{"DenseNormCallback", false, true, true},+ QueryPolicy{"PagedRoPECallback", true, false, true},+ QueryPolicy{"PagedNormCallback", true, true, true}),+ [](const testing::TestParamInfo<QueryPolicy>& info) {+ return info.param.name;+ });++} // namespacediff --git a/src/common/transformations/tests/sources.cmake b/src/common/transformations/tests/sources.cmakeindex bd9e0370cca..5a3c647440a 100644--- a/src/common/transformations/tests/sources.cmake+++ b/src/common/transformations/tests/sources.cmake@@ -67,6 +67,7 @@ set(COMMON_OPTIMIZATIONS_TESTS_SRCS${CMAKE_CURRENT_LIST_DIR}/common_optimizations/fuse_clamp_and_fake_quantize.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/fuse_gated_delta_net.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/fuse_moe_test.cpp+ ${CMAKE_CURRENT_LIST_DIR}/common_optimizations/fuse_qsa_indexer_test.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/fuse_rotary_positional_embeddings.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/fuse_ssm.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/fused_names_cleanup.cpp@@ -106,6 +107,7 @@ set(COMMON_OPTIMIZATIONS_TESTS_SRCS${CMAKE_CURRENT_LIST_DIR}/common_optimizations/pad_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/paged_causal_conv1d_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/paged_gated_delta_net_fusion.cpp+ ${CMAKE_CURRENT_LIST_DIR}/common_optimizations/paged_qsa_indexer_fusion_test.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/paged_selective_ssm_fusion.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/preprocessing_fusion_tests.cpp${CMAKE_CURRENT_LIST_DIR}/common_optimizations/pull_through_reduce_test.cppdiff --git a/src/core/dev_api/dev_headers.cmake b/src/core/dev_api/dev_headers.cmakeindex abd1e685ec0..f5a0b8448a1 100644--- a/src/core/dev_api/dev_headers.cmake+++ b/src/core/dev_api/dev_headers.cmake@@ -34,6 +34,7 @@ set(DEV_HEADERS${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/qsa_indexer.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.hppindex c06e4460db2..0bffebff6c6 100644--- a/src/core/dev_api/openvino/op/paged_qsa_indexer.hpp+++ b/src/core/dev_api/openvino/op/paged_qsa_indexer.hpp@@ -14,8 +14,8 @@ 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+/// RoPE coefficients of the main attention (`rope_cos`/`rope_sin`), applies query RMSNorm+/// and 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@@ -55,7 +55,9 @@ public:size_t indexer_rotary_dim = 0; ///< <= indexer_head_dim, evensize_t indexer_head_dim = 0; ///< D_idxfloat epsilon = 1e-6f; ///< RMSNorm epsilon- float scale = 0.0f; ///< positive score multiplier; 0 is resolved to 1 / sqrt(indexer_head_dim) by the op+ float scale = 0.0f; ///< positive score multiplier; 0 is resolved to 1 / sqrt(indexer_head_dim) by the op+ bool query_norm = true; ///< Query RMSNorm is fused; false is an intermediate fusion state only.+ bool query_rope = true; ///< Query RoPE is fused; false is an intermediate fusion state only.};PagedQSAIndexer() = default;diff --git a/src/plugins/intel_gpu/include/intel_gpu/op/qsa_indexer.hpp b/src/core/dev_api/openvino/op/qsa_indexer.hppsimilarity index 86%rename from src/plugins/intel_gpu/include/intel_gpu/op/qsa_indexer.hpprename to src/core/dev_api/openvino/op/qsa_indexer.hppindex db067fd1cea..2f5784ccb19 100644--- a/src/plugins/intel_gpu/include/intel_gpu/op/qsa_indexer.hpp+++ b/src/core/dev_api/openvino/op/qsa_indexer.hpp@@ -10,18 +10,18 @@#include "openvino/core/node.hpp"#include "openvino/op/op.hpp"-namespace ov::intel_gpu::op {+namespace ov::op::internal {-/// \brief GPU-internal non-paged, stateful complete-block plan producer for Qwen Sparse Attention (QSA).+/// \brief 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 {+class OPENVINO_API QSAIndexer : public ov::op::Op {public:- OPENVINO_OP("QSAIndexer", "gpu_opset");+ OPENVINO_OP("QSAIndexer");/// @brief Fixed input order of the QSAIndexer op.struct InputIdx {@@ -57,7 +57,9 @@ public:size_t indexer_rotary_dim = 0; ///< <= indexer_head_dim, evensize_t indexer_head_dim = 0; ///< D_idxfloat epsilon = 1e-6F; ///< RMSNorm epsilon- float scale = 0.0F; ///< positive score multiplier; 0 selects the default 1 / sqrt(indexer_head_dim)+ float scale = 0.0F; ///< positive score multiplier; 0 selects the default 1 / sqrt(indexer_head_dim)+ bool query_norm = true; ///< Query RMSNorm is fused; false is an intermediate fusion state only.+ bool query_rope = true; ///< Query RoPE is fused; false is an intermediate fusion state only.};QSAIndexer() = default;@@ -85,4 +87,4 @@ private:Config m_config{};};-} // namespace ov::intel_gpu::op+} // namespace ov::op::internaldiff --git a/src/core/src/op/paged_qsa_indexer.cpp b/src/core/src/op/paged_qsa_indexer.cppindex 226cd3829e6..8a5aeebb1d3 100644--- a/src/core/src/op/paged_qsa_indexer.cpp+++ b/src/core/src/op/paged_qsa_indexer.cpp@@ -73,6 +73,8 @@ bool PagedQSAIndexer::visit_attributes(ov::AttributeVisitor& visitor) {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);+ visitor.on_attribute("query_norm", m_config.query_norm);+ visitor.on_attribute("query_rope", m_config.query_rope);return true;}diff --git a/src/core/src/op/qsa_indexer.cpp b/src/core/src/op/qsa_indexer.cppnew file mode 100644index 00000000000..cab51505238--- /dev/null+++ b/src/core/src/op/qsa_indexer.cpp@@ -0,0 +1,226 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/qsa_indexer.hpp"++#include <cmath>+#include <initializer_list>+#include <limits>+#include <string>+#include <utility>++#include "itt.hpp"++namespace ov::op::internal {++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");+ }+ const auto max_dimension = static_cast<size_t>(std::numeric_limits<int64_t>::max());+ if (c.key_block_size > max_dimension || c.block_topk > max_dimension || c.num_selection_heads > max_dimension ||+ c.indexer_head_dim > max_dimension || c.indexer_rotary_dim > max_dimension / 2) {+ return fail("QSAIndexer dimensions must fit in int64_t");+ }+ 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) {+ OV_OP_SCOPE(internal_QSAIndexer_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);+ visitor.on_attribute("query_norm", m_config.query_norm);+ visitor.on_attribute("query_rope", m_config.query_rope);+ return true;+}++void QSAIndexer::validate_and_infer_types() {+ OV_OP_SCOPE(internal_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);+ // 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::Q_NORM_WEIGHT,+ InputIdx::K_NORM_WEIGHT,+ InputIdx::BLOCK_INDEX_KEYS_CACHE,+ InputIdx::PAST_INCOMPLETE_RAW_K,+ InputIdx::PAST_INCOMPLETE_ROPE}) {+ const auto& in_et = get_input_element_type(idx);+ NODE_VALIDATION_CHECK(this,+ element::Type::merge(float_et, float_et, in_et),+ "QSAIndexer 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(),+ "QSAIndexer expects floating-point inputs, got ",+ float_et);++ 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 = index_query_ps.rank().is_static() ? index_query_ps[0] : ov::Dimension::dynamic();+ const auto length = index_query_ps.rank().is_static() ? index_query_ps[1] : ov::Dimension::dynamic();+ const auto h_iq = index_query_ps.rank().is_static() ? index_query_ps[2] : ov::Dimension::dynamic();+ const auto h_ik = raw_index_keys_ps.rank().is_static() ? raw_index_keys_ps[2] : ov::Dimension::dynamic();++ NODE_VALIDATION_CHECK(this,+ index_query_ps.compatible(ov::PartialShape{batch, length, -1, di}),+ "QSAIndexer expects index_query shaped [B, L, H_iq, indexer_head_dim], got ",+ index_query_ps);+ NODE_VALIDATION_CHECK(this,+ raw_index_keys_ps.compatible(ov::PartialShape{batch, length, h_ik, di}),+ "QSAIndexer expects raw_index_keys shaped [B, L, H_ik, indexer_head_dim], got ",+ raw_index_keys_ps);+ NODE_VALIDATION_CHECK(this,+ get_input_partial_shape(InputIdx::ROPE_COS).compatible(ov::PartialShape{batch, length, rot}),+ "QSAIndexer expects rope_cos shaped [B, L, 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{batch, length, rot}),+ "QSAIndexer expects rope_sin shaped [B, L, 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}),+ "QSAIndexer 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}),+ "QSAIndexer expects k_norm_weight shaped [indexer_head_dim], got ",+ get_input_partial_shape(InputIdx::K_NORM_WEIGHT));+ NODE_VALIDATION_CHECK(+ this,+ get_input_partial_shape(InputIdx::BLOCK_INDEX_KEYS_CACHE).compatible(ov::PartialShape{batch, h_ik, -1, di}),+ "QSAIndexer expects block_index_keys_cache shaped [B, H_ik, blocks, indexer_head_dim], got ",+ get_input_partial_shape(InputIdx::BLOCK_INDEX_KEYS_CACHE));+ NODE_VALIDATION_CHECK(+ this,+ get_input_partial_shape(InputIdx::PAST_INCOMPLETE_RAW_K).compatible(ov::PartialShape{batch, h_ik, r - 1, di}),+ "QSAIndexer expects past_incomplete_raw_k shaped "+ "[B, H_ik, key_block_size-1, indexer_head_dim], got ",+ get_input_partial_shape(InputIdx::PAST_INCOMPLETE_RAW_K));+ NODE_VALIDATION_CHECK(+ this,+ get_input_partial_shape(InputIdx::PAST_INCOMPLETE_ROPE).compatible(ov::PartialShape{batch, rope_row}),+ "QSAIndexer expects past_incomplete_rope shaped [B, 2*indexer_rotary_dim], got ",+ get_input_partial_shape(InputIdx::PAST_INCOMPLETE_ROPE));++ // The kernels read key_length as int32_t.+ const auto& key_length_et = get_input_element_type(InputIdx::KEY_LENGTH);+ NODE_VALIDATION_CHECK(this,+ key_length_et.is_dynamic() || key_length_et == element::i32,+ "QSAIndexer expects an i32 key_length input, got ",+ key_length_et);+ NODE_VALIDATION_CHECK(this,+ get_input_partial_shape(InputIdx::KEY_LENGTH).compatible(ov::PartialShape{batch}),+ "QSAIndexer expects key_length shaped [B], got ",+ get_input_partial_shape(InputIdx::KEY_LENGTH));++ 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_ik_value != 0 && h_iq_value % 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 {+ OV_OP_SCOPE(internal_QSAIndexer_clone_with_new_inputs);+ check_new_args_count(this, new_args);+ return std::make_shared<QSAIndexer>(new_args, m_config);+}++} // namespace ov::op::internaldiff --git a/src/core/src/pass/sdpa_to_paged_attention.cpp b/src/core/src/pass/sdpa_to_paged_attention.cppindex bbb878eb67c..538c6d63db5 100644--- a/src/core/src/pass/sdpa_to_paged_attention.cpp+++ b/src/core/src/pass/sdpa_to_paged_attention.cpp@@ -15,6 +15,7 @@#include "openvino/op/unsqueeze.hpp"#include "openvino/pass/manager.hpp"#include "transformations/common_optimizations/fuse_gated_delta_net.hpp"+#include "transformations/common_optimizations/fuse_qsa_indexer.hpp"#include "transformations/common_optimizations/fuse_ssm.hpp"#include "transformations/common_optimizations/sdpa_fusion.hpp"#include "transformations/op_conversions/convert_slice_to_strided_slice.hpp"@@ -22,6 +23,7 @@#include "transformations/paged_attention/gemma4_mtp_state_management_pattern.hpp"#include "transformations/paged_attention/paged_causal_conv1d_fusion.hpp"#include "transformations/paged_attention/paged_gated_delta_net_fusion.hpp"+#include "transformations/paged_attention/paged_qsa_indexer_fusion.hpp"#include "transformations/paged_attention/paged_selective_ssm_fusion.hpp"#include "transformations/paged_attention/position_ids_replacer.hpp"#include "transformations/paged_attention/prev_sequence_length_pattern.hpp"@@ -157,6 +159,9 @@ bool ov::pass::SDPAToPagedAttention::run_on_model(const std::shared_ptr<ov::Mode// nodes are in the expected form before running// PagedGatedDeltaNetFusion.auto ssm_fusion = manager.register_pass<SelectiveSSMFusion>();+ // The dense block-key cache is replaced by the paged one, so it is not padded.+ manager.register_pass<FuseQSAIndexer>(false);+ manager.register_pass<PagedQSAIndexerFusion>(m_params, var_ids_to_remove);if (m_options.is_draft_model) {manager.register_pass<Gemma4MTPStateManagementPattern>(m_params, params_to_remove, m_options);} else {diff --git a/src/core/src/sources.cmake b/src/core/src/sources.cmakeindex d0642b41dc1..f2af28b91bc 100644--- a/src/core/src/sources.cmake+++ b/src/core/src/sources.cmake@@ -202,6 +202,7 @@ set(LIBRARY_SRC${CMAKE_CURRENT_LIST_DIR}/op/prior_box_clustered.cpp${CMAKE_CURRENT_LIST_DIR}/op/proposal.cpp${CMAKE_CURRENT_LIST_DIR}/op/psroi_pooling.cpp+ ${CMAKE_CURRENT_LIST_DIR}/op/qsa_indexer.cpp${CMAKE_CURRENT_LIST_DIR}/op/qsa_prepare.cpp${CMAKE_CURRENT_LIST_DIR}/op/random_uniform.cpp${CMAKE_CURRENT_LIST_DIR}/op/range.cppdiff --git a/src/core/tests/type_prop/qsa_indexer.cpp b/src/core/tests/type_prop/qsa_indexer.cppnew file mode 100644index 00000000000..7467def960d--- /dev/null+++ b/src/core/tests/type_prop/qsa_indexer.cpp@@ -0,0 +1,120 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/qsa_indexer.hpp"++#include <gtest/gtest.h>++#include <limits>+#include <sstream>+#include <tuple>++#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"+#include "openvino/pass/serialize.hpp"+#include "openvino/runtime/core.hpp"++namespace {+using ov::PartialShape;+using ov::op::internal::QSAIndexer;+using ov::op::v0::Parameter;++ov::OutputVector make_inputs() {+ const auto f32 = ov::element::f32;+ return {std::make_shared<Parameter>(f32, PartialShape{2, 3, 2, 16}),+ std::make_shared<Parameter>(f32, PartialShape{2, 3, 1, 16}),+ std::make_shared<Parameter>(f32, PartialShape{2, 3, 8}),+ std::make_shared<Parameter>(f32, PartialShape{2, 3, 8}),+ std::make_shared<Parameter>(ov::element::i32, PartialShape{2}),+ std::make_shared<Parameter>(f32, PartialShape{16}),+ std::make_shared<Parameter>(f32, PartialShape{16}),+ std::make_shared<Parameter>(f32, PartialShape{2, 1, 4, 16}),+ std::make_shared<Parameter>(f32, PartialShape{2, 1, 3, 16}),+ std::make_shared<Parameter>(f32, PartialShape{2, 16})};+}++QSAIndexer::Config make_config() {+ QSAIndexer::Config config;+ config.block_topk = 2;+ config.indexer_head_dim = 16;+ config.indexer_rotary_dim = 8;+ config.epsilon = 1e-5f;+ config.scale = 0.5f;+ return config;+}++void expect_config_eq(const QSAIndexer::Config& actual, const QSAIndexer::Config& expected) {+ EXPECT_EQ(actual.key_block_size, expected.key_block_size);+ EXPECT_EQ(actual.block_topk, expected.block_topk);+ EXPECT_EQ(actual.num_selection_heads, expected.num_selection_heads);+ EXPECT_EQ(actual.indexer_rotary_dim, expected.indexer_rotary_dim);+ EXPECT_EQ(actual.indexer_head_dim, expected.indexer_head_dim);+ EXPECT_EQ(actual.epsilon, expected.epsilon);+ EXPECT_EQ(actual.scale, expected.scale);+ EXPECT_EQ(actual.query_norm, expected.query_norm);+ EXPECT_EQ(actual.query_rope, expected.query_rope);+}++class QSAIndexerAttributesTest : public testing::TestWithParam<std::tuple<bool, bool>> {};++TEST_P(QSAIndexerAttributesTest, PreservesSharedTypeAndConfigThroughCloneAndIR) {+ auto config = make_config();+ std::tie(config.query_norm, config.query_rope) = GetParam();+ const auto inputs = make_inputs();+ const auto indexer = std::make_shared<QSAIndexer>(inputs, config);+ EXPECT_EQ(indexer->get_output_size(), QSAIndexer::OutputIdx::COUNT);+ EXPECT_EQ(indexer->get_output_partial_shape(0), (PartialShape{2, 1, 3, 2}));+ EXPECT_EQ(indexer->get_output_partial_shape(1), (PartialShape{2, 1, 3}));+ EXPECT_EQ(indexer->get_index_query_heads(), 2u);+ EXPECT_EQ(indexer->get_index_key_heads(), 1u);++ const auto clone = ov::as_type_ptr<QSAIndexer>(indexer->clone_with_new_inputs(inputs));+ ASSERT_NE(clone, nullptr);+ expect_config_eq(clone->get_config(), config);+ for (size_t i = 0; i < QSAIndexer::OutputIdx::COUNT; ++i) {+ EXPECT_EQ(clone->get_output_partial_shape(i), indexer->get_output_partial_shape(i));+ EXPECT_EQ(clone->get_output_element_type(i), indexer->get_output_element_type(i));+ }++ ov::ParameterVector parameters;+ for (const auto& input : inputs) {+ parameters.push_back(ov::as_type_ptr<Parameter>(input.get_node_shared_ptr()));+ }+ const auto model = std::make_shared<ov::Model>(indexer->outputs(), parameters);+ std::ostringstream xml, bin;+ ov::pass::Serialize(xml, bin).run_on_model(model);+ ov::Core core;+ core.add_extension<QSAIndexer>();+ const auto restored = core.read_model(xml.str(), ov::Tensor{ov::element::u8, ov::Shape{0}});+ const auto loaded = ov::as_type_ptr<QSAIndexer>(restored->get_results()[0]->input_value(0).get_node_shared_ptr());+ ASSERT_NE(loaded, nullptr);+ expect_config_eq(loaded->get_config(), config);+}++INSTANTIATE_TEST_SUITE_P(QSAIndexer,+ QSAIndexerAttributesTest,+ testing::Combine(testing::Bool(), testing::Bool()),+ ([](const testing::TestParamInfo<QSAIndexerAttributesTest::ParamType>& info) {+ const auto [norm, rope] = info.param;+ return std::string(norm ? "NormOn" : "NormOff") + (rope ? "_RoPEOn" : "_RoPEOff");+ }));++TEST(QSAIndexerTest, RejectsDimensionsThatCannotBeRepresented) {+ auto config = make_config();+ config.block_topk = static_cast<size_t>(std::numeric_limits<int64_t>::max()) + 1;+ EXPECT_THROW(std::ignore = std::make_shared<QSAIndexer>(make_inputs(), config), ov::NodeValidationFailure);+ config = make_config();+ config.num_selection_heads = static_cast<size_t>(std::numeric_limits<int64_t>::max()) + 1;+ EXPECT_THROW(std::ignore = std::make_shared<QSAIndexer>(make_inputs(), config), ov::NodeValidationFailure);+}++TEST(QSAIndexerTest, SupportsDynamicShapes) {+ auto inputs = make_inputs();+ inputs[0] = std::make_shared<Parameter>(ov::element::f32, PartialShape::dynamic(4));+ inputs[1] = std::make_shared<Parameter>(ov::element::f32, PartialShape::dynamic(4));+ const auto indexer = std::make_shared<QSAIndexer>(inputs, make_config());+ EXPECT_EQ(indexer->get_output_partial_shape(0), (PartialShape{-1, 1, -1, 2}));+ EXPECT_EQ(indexer->get_output_partial_shape(1), (PartialShape{-1, 1, -1}));+}+} // namespacediff --git a/src/core/tests/type_prop/sources.cmake b/src/core/tests/type_prop/sources.cmakeindex 9ab162702ec..7dbe36b8441 100644--- a/src/core/tests/type_prop/sources.cmake+++ b/src/core/tests/type_prop/sources.cmake@@ -153,6 +153,7 @@ set(OV_CORE_TESTS_TYPE_PROP_SRCS${CMAKE_CURRENT_LIST_DIR}/prior_box_clustered.cpp${CMAKE_CURRENT_LIST_DIR}/proposal.cpp${CMAKE_CURRENT_LIST_DIR}/psroi_pooling.cpp+ ${CMAKE_CURRENT_LIST_DIR}/qsa_indexer.cpp${CMAKE_CURRENT_LIST_DIR}/qsa_prepare.cpp${CMAKE_CURRENT_LIST_DIR}/random_uniform.cpp${CMAKE_CURRENT_LIST_DIR}/range.cppdiff --git a/src/core/tests/visitors/op/paged_qsa_indexer.cpp b/src/core/tests/visitors/op/paged_qsa_indexer.cppindex 3202360bece..503d091eda1 100644--- a/src/core/tests/visitors/op/paged_qsa_indexer.cpp+++ b/src/core/tests/visitors/op/paged_qsa_indexer.cpp@@ -6,33 +6,43 @@#include <gtest/gtest.h>+#include <cstring>+#include <sstream>+#include "openvino/op/parameter.hpp"+#include "openvino/pass/serialize.hpp"+#include "openvino/runtime/core.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>();-+namespace {+ov::OutputVector make_paged_indexer_args() {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})};+ return {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})};+}+} // namespace++TEST(attributes, paged_qsa_indexer) {+ using ov::op::internal::PagedQSAIndexer;+ NodeBuilder::opset().insert<PagedQSAIndexer>();+ const auto args = make_paged_indexer_args();PagedQSAIndexer::Config config;config.key_block_size = 4;@@ -42,6 +52,8 @@ TEST(attributes, paged_qsa_indexer) {config.indexer_head_dim = 4;config.epsilon = 1e-5f;config.scale = 0.5f;+ config.query_norm = false;+ config.query_rope = false;const auto op = std::make_shared<PagedQSAIndexer>(args, config);NodeBuilder builder(op, args);@@ -55,5 +67,64 @@ TEST(attributes, paged_qsa_indexer) {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_config.query_norm, config.query_norm);+ EXPECT_EQ(restored_config.query_rope, config.query_rope);EXPECT_EQ(restored->get_output_size(), 2);+ const auto clone = ov::as_type_ptr<PagedQSAIndexer>(restored->clone_with_new_inputs(restored->input_values()));+ ASSERT_NE(clone, nullptr);+ EXPECT_EQ(clone->get_config().query_norm, config.query_norm);+ EXPECT_EQ(clone->get_config().query_rope, config.query_rope);+}++TEST(serialize, paged_qsa_indexer_legacy_query_flags) {+ using ov::op::internal::PagedQSAIndexer;+ const auto args = make_paged_indexer_args();+ PagedQSAIndexer::Config config;+ config.block_topk = 3;+ config.indexer_rotary_dim = 2;+ config.indexer_head_dim = 4;+ config.query_norm = false;+ config.query_rope = false;+ const auto indexer = std::make_shared<PagedQSAIndexer>(args, config);+ ov::ParameterVector parameters;+ for (const auto& arg : args) {+ parameters.push_back(ov::as_type_ptr<Parameter>(arg.get_node_shared_ptr()));+ }+ const auto model =+ std::make_shared<ov::Model>(ov::OutputVector{indexer->output(0), indexer->output(1)}, parameters);+ std::ostringstream xml, bin;+ ov::pass::Serialize(xml, bin).run_on_model(model);+ const auto weights_data = bin.str();+ ov::Tensor weights(ov::element::u8, ov::Shape{weights_data.size()});+ if (!weights_data.empty()) {+ std::memcpy(weights.data(), weights_data.data(), weights_data.size());+ }++ ov::Core core;+ core.add_extension<PagedQSAIndexer>();+ const auto find_indexer = [](const std::shared_ptr<ov::Model>& loaded) {+ for (const auto& node : loaded->get_ops()) {+ if (const auto found = ov::as_type_ptr<PagedQSAIndexer>(node)) {+ return found;+ }+ }+ return std::shared_ptr<PagedQSAIndexer>{};+ };+ const auto current = find_indexer(core.read_model(xml.str(), weights));+ ASSERT_NE(current, nullptr);+ EXPECT_FALSE(current->get_config().query_norm);+ EXPECT_FALSE(current->get_config().query_rope);++ auto legacy_xml = xml.str();+ for (const std::string attribute : {"query_norm", "query_rope"}) {+ const auto start = legacy_xml.find(" " + attribute + "=\"");+ ASSERT_NE(start, std::string::npos);+ const auto end = legacy_xml.find('"', start + attribute.size() + 3);+ ASSERT_NE(end, std::string::npos);+ legacy_xml.erase(start, end - start + 1);+ }+ const auto legacy = find_indexer(core.read_model(legacy_xml, weights));+ ASSERT_NE(legacy, nullptr);+ EXPECT_TRUE(legacy->get_config().query_norm);+ EXPECT_TRUE(legacy->get_config().query_rope);}diff --git a/src/plugins/intel_cpu/src/nodes/paged_qsa_indexer.cpp b/src/plugins/intel_cpu/src/nodes/paged_qsa_indexer.cppindex b694d04a7f8..2e0709abb79 100644--- a/src/plugins/intel_cpu/src/nodes/paged_qsa_indexer.cpp+++ b/src/plugins/intel_cpu/src/nodes/paged_qsa_indexer.cpp@@ -161,6 +161,11 @@ bool PagedQSAIndexer::isSupportedOperation(const std::shared_ptr<const ov::Node>errorMessage = "Only PagedQSAIndexer operation is supported";return false;}+ const auto& config = paged_qsa_indexer->get_config();+ if (!config.query_norm || !config.query_rope) {+ errorMessage = "PagedQSAIndexer CPU implementation requires query_norm and query_rope to be enabled.";+ return false;+ }static constexpr size_t float_ports[] = {InputIdx::INDEX_QUERY,InputIdx::RAW_INDEX_KEYS,InputIdx::ROPE_COS,diff --git a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cppindex a88ee201659..9a2e41ed9b6 100644--- a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp+++ b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp@@ -70,6 +70,7 @@#include "transformations/common_optimizations/convert_quantize_dequantize.hpp"#include "transformations/common_optimizations/fq_mul_fusion.hpp"#include "transformations/common_optimizations/fuse_gated_delta_net.hpp"+#include "transformations/common_optimizations/fuse_qsa_indexer.hpp"#include "transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp"#include "transformations/common_optimizations/lora_subgraph_fusion.hpp"#include "transformations/common_optimizations/lstm_cell_fusion.hpp"@@ -599,6 +600,7 @@ void Transformations::PreLpt(const std::vector<ov::element::Type>& defaultPrecisov::pass::KeepConstAndDecompression);CPU_REGISTER_PASS_COMMON(manager, ov::pass::AUGRUCellFusion);CPU_REGISTER_PASS_COMMON(manager, SDPASubgraphFusion);+ CPU_REGISTER_PASS_COMMON(manager, ov::pass::FuseQSAIndexer, false);CPU_REGISTER_PASS_X64(manager, SparseAttentionKVCacheFusion);CPU_REGISTER_PASS_COMMON(manager, ov::pass::GatedDeltaNetFusion);CPU_REGISTER_PASS_COMMON(manager, ov::pass::CommonOptimizations);@@ -1207,6 +1209,7 @@ void Transformations::PostLpt() {ov::pass::RMSFusion,false /* force_tail_convert */,enable_without_gamma);+ CPU_REGISTER_PASS_COMMON(postLPTPassManager, ov::pass::FuseQSAIndexerQuery);CPU_REGISTER_PASS_X64(postLPTPassManager, ov::intel_cpu::DecomposeRMSNorm);CPU_SET_CALLBACK_X64(postLPTPassManager,diff --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.hppdeleted file mode 100644index 9f8ea88f6d8..00000000000--- a/src/plugins/intel_gpu/include/intel_gpu/op/paged_qsa_indexer.hpp+++ /dev/null@@ -1,31 +0,0 @@-// 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/plugin/primitives_list.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hppindex b7fa9d9f8ae..e4b87b59c66 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,7 +337,7 @@ REGISTER_FACTORY(internal, Swoosh);#ifdef ENABLE_MLIR_FOR_GPUREGISTER_FACTORY(internal, MLIR);#endif-REGISTER_FACTORY(internal, PagedQSAIndexerGPU);+REGISTER_FACTORY(internal, PagedQSAIndexer);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.hppindex 61c30cb5543..b8e19c5c0e3 100644--- 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.hpp@@ -6,22 +6,22 @@#include <vector>-#include "intel_gpu/op/paged_qsa_indexer.hpp"+#include "openvino/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+/// @details See ov::op::internal::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;+ using InputIdx = ov::op::internal::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)+ paged_qsa_indexer(const primitive_id& id, const std::vector<input_info>& inputs, const ov::op::internal::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),@@ -39,8 +39,8 @@ struct paged_qsa_indexer : public primitive_base<paged_qsa_indexer> {float epsilon = 1e-6F;float scale = 0.0F;- ov::intel_gpu::op::PagedQSAIndexer::Config get_config() const {- ov::intel_gpu::op::PagedQSAIndexer::Config config;+ ov::op::internal::PagedQSAIndexer::Config get_config() const {+ ov::op::internal::PagedQSAIndexer::Config config;config.key_block_size = key_block_size;config.block_topk = block_topk;config.num_selection_heads = num_selection_heads;diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/qsa_indexer.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/qsa_indexer.hppindex 55dd1d196a9..68eefc019ea 100644--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/qsa_indexer.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/qsa_indexer.hpp@@ -6,23 +6,23 @@#include <vector>-#include "intel_gpu/op/qsa_indexer.hpp"+#include "openvino/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.+/// past_incomplete_raw_k and past_incomplete_rope state. See ov::op::internal::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;+ using InputIdx = ov::op::internal::QSAIndexer::InputIdx;+ using OutputIdx = ov::op::internal::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)+ qsa_indexer(const primitive_id& id, const std::vector<input_info>& inputs, const ov::op::internal::QSAIndexer::Config& config): primitive_base(id,inputs,@@ -44,8 +44,8 @@ struct qsa_indexer : public primitive_base<qsa_indexer> {float epsilon = 1e-6F;float scale = 0.0F;- ov::intel_gpu::op::QSAIndexer::Config get_config() const {- ov::intel_gpu::op::QSAIndexer::Config config;+ ov::op::internal::QSAIndexer::Config get_config() const {+ ov::op::internal::QSAIndexer::Config config;config.key_block_size = key_block_size;config.block_topk = block_topk;config.num_selection_heads = num_selection_heads;diff --git a/src/plugins/intel_gpu/sources.cmake b/src/plugins/intel_gpu/sources.cmakeindex ecb2379638e..68492694e67 100644--- a/src/plugins/intel_gpu/sources.cmake+++ b/src/plugins/intel_gpu/sources.cmake@@ -228,9 +228,7 @@ 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.cppdiff --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.cppindex 678524c14d2..2d5fac4c5fa 100644--- 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.cpp@@ -20,7 +20,7 @@namespace ov::intel_gpu::ocl {using namespace cldnn;-using QSAIn = ov::intel_gpu::op::PagedQSAIndexer::InputIdx;+using QSAIn = ov::op::internal::PagedQSAIndexer::InputIdx;namespace {@@ -461,7 +461,7 @@ bool PagedQSAIndexerImplementationManager::validate_impl(const cldnn::program_noconst 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)) {+ if (!ov::op::internal::PagedQSAIndexer::validate_config(desc->get_config(), reason)) {return false;}diff --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.cppindex 6a114ccbc9c..173a9e4bc57 100644--- 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.cpp@@ -22,8 +22,8 @@namespace ov::intel_gpu::ocl {using namespace cldnn;-using QSAIn = ov::intel_gpu::op::QSAIndexer::InputIdx;-using QSAOut = ov::intel_gpu::op::QSAIndexer::OutputIdx;+using QSAIn = ov::op::internal::QSAIndexer::InputIdx;+using QSAOut = ov::op::internal::QSAIndexer::OutputIdx;namespace {@@ -50,7 +50,7 @@ JitConstants make_jit(JitConstants jit, const std::shared_ptr<const qsa_indexer>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())));+ jit.add(qsa::float_constant("QSA_IDX_SCALE", ov::op::internal::QSAIndexer::effective_scale(desc->get_config())));return jit;}@@ -475,7 +475,7 @@ bool QSAIndexerImplementationManager::validate_impl(const cldnn::program_node& nconst auto desc = node.as<cldnn::qsa_indexer>().get_primitive();std::string reason;- if (!ov::intel_gpu::op::QSAIndexer::validate_config(desc->get_config(), reason)) {+ if (!ov::op::internal::QSAIndexer::validate_config(desc->get_config(), reason)) {return false;}diff --git a/src/plugins/intel_gpu/src/graph/paged_qsa_indexer.cpp b/src/plugins/intel_gpu/src/graph/paged_qsa_indexer.cppindex ac0d3ef1cb9..38170dc1610 100644--- a/src/plugins/intel_gpu/src/graph/paged_qsa_indexer.cpp+++ b/src/plugins/intel_gpu/src/graph/paged_qsa_indexer.cpp@@ -57,7 +57,7 @@ std::string paged_qsa_indexer_inst::to_string(const paged_qsa_indexer_node& nodepaged_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),+ OPENVINO_ASSERT(ov::op::internal::PagedQSAIndexer::validate_config(node.get_primitive()->get_config(), reason),"[GPU] Invalid paged_qsa_indexer primitive: ",reason);}diff --git a/src/plugins/intel_gpu/src/graph/qsa_indexer.cpp b/src/plugins/intel_gpu/src/graph/qsa_indexer.cppindex 30fa2606dc6..51785293be9 100644--- a/src/plugins/intel_gpu/src/graph/qsa_indexer.cpp+++ b/src/plugins/intel_gpu/src/graph/qsa_indexer.cpp@@ -68,7 +68,7 @@ std::string qsa_indexer_inst::to_string(const qsa_indexer_node& node) {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),+ OPENVINO_ASSERT(ov::op::internal::QSAIndexer::validate_config(node.get_primitive()->get_config(), reason),"[GPU] Invalid qsa_indexer primitive: ",reason);}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.cppindex 7f68a4de151..1f2db9c9d49 100644--- a/src/plugins/intel_gpu/src/plugin/ops/paged_qsa_indexer.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/paged_qsa_indexer.cpp@@ -2,32 +2,31 @@// SPDX-License-Identifier: Apache-2.0//-#include "intel_gpu/op/paged_qsa_indexer.hpp"+#include "openvino/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;+static void CreatePagedQSAIndexerOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::PagedQSAIndexer>& op) {+ using In = ov::op::internal::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),+ OPENVINO_ASSERT(ov::op::internal::PagedQSAIndexer::validate_config(op->get_config(), reason),"[GPU] Cannot lower PagedQSAIndexer op '",layer_name,"': ",reason);+ OPENVINO_ASSERT(op->get_config().query_norm && op->get_config().query_rope,+ "[GPU] PagedQSAIndexer '",+ layer_name,+ "': only query_norm == true and query_rope == true are supported");OPENVINO_ASSERT(op->get_config().num_selection_heads == 1,"[GPU] PagedQSAIndexer '",layer_name,@@ -56,6 +55,6 @@ static void CreatePagedQSAIndexerGPUOp(ProgramBuilder& p, const std::shared_ptr<p.add_primitive(*op, prim);}-REGISTER_FACTORY_IMPL(internal, PagedQSAIndexerGPU);+REGISTER_FACTORY_IMPL(internal, PagedQSAIndexer);} // 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.cppindex 5764008302a..bae8d2783a2 100644--- a/src/plugins/intel_gpu/src/plugin/ops/qsa_indexer.cpp+++ b/src/plugins/intel_gpu/src/plugin/ops/qsa_indexer.cpp@@ -2,27 +2,27 @@// SPDX-License-Identifier: Apache-2.0//-#include "intel_gpu/op/qsa_indexer.hpp"+#include "openvino/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});+static void CreateQSAIndexerOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::QSAIndexer>& op) {+ validate_inputs_count(op, {ov::op::internal::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);+ OPENVINO_ASSERT(ov::op::internal::QSAIndexer::validate_config(op->get_config(), reason), "[GPU] Cannot lower QSAIndexer op '", layer_name, "': ", reason);- using In = ov::intel_gpu::op::QSAIndexer::InputIdx;+ using In = ov::op::internal::QSAIndexer::InputIdx;+ OPENVINO_ASSERT(op->get_config().query_norm && op->get_config().query_rope,+ "[GPU] QSAIndexer '",+ layer_name,+ "': only query_norm == true and query_rope == true are supported");OPENVINO_ASSERT(op->get_config().num_selection_heads == 1,"[GPU] QSAIndexer '",layer_name,diff --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.cppdeleted file mode 100644index 69f4d075003..00000000000--- a/src/plugins/intel_gpu/src/plugin/transformations/op/paged_qsa_indexer.cpp+++ /dev/null@@ -1,14 +0,0 @@-// 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.cppdeleted file mode 100644index 33a1dd3faa5..00000000000--- a/src/plugins/intel_gpu/src/plugin/transformations/op/qsa_indexer.cpp+++ /dev/null@@ -1,153 +0,0 @@-// 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_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cppindex 3293536d666..e18e72a339f 100644--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp@@ -151,6 +151,7 @@#include "transformations/common_optimizations/broadcast_transition.hpp"#include "transformations/common_optimizations/common_optimizations.hpp"#include "transformations/common_optimizations/convert_quantize_dequantize.hpp"+#include "transformations/common_optimizations/fuse_qsa_indexer.hpp"#include "transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp"#include "transformations/common_optimizations/fuse_gated_delta_net.hpp"#include "transformations/common_optimizations/glu_fusion.hpp"@@ -917,6 +918,8 @@ void TransformationsPipeline::apply_activation_scaling_transformations(const stdmanager.register_pass<ov::pass::MoveEltwiseUpThroughDataMovScalar>(allowed_data_movement_ops);manager.register_pass<ov::pass::RoPEFusion>(true);+ manager.register_pass<ov::pass::FuseQSAIndexer>(true);+ manager.register_pass<ov::pass::FuseQSAIndexerQuery>();manager.register_pass<ov::intel_gpu::FuseRoPEInputDeinterleave>();pass_config->disable<ov::pass::RoPEFusionGPTJ>();pass_config->disable<ov::pass::RoPEFusionIOSlicing>();diff --git a/src/plugins/intel_gpu/tests/unit/sources.cmake b/src/plugins/intel_gpu/tests/unit/sources.cmakeindex e8d8a1f8bf0..8f7937f7d6c 100644--- a/src/plugins/intel_gpu/tests/unit/sources.cmake+++ b/src/plugins/intel_gpu/tests/unit/sources.cmake@@ -512,9 +512,7 @@ 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.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.cppindex c367cc59621..1bdcda3f551 100644--- 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.cpp@@ -47,7 +47,10 @@#include <openvino/op/paged_sparse_attention.hpp>#include <openvino/op/parameter.hpp>#include <openvino/op/read_value.hpp>+#include <openvino/op/reshape.hpp>#include <openvino/op/result.hpp>+#include <openvino/op/transpose.hpp>+#include <openvino/op/unsqueeze.hpp>#include <openvino/op/util/variable.hpp>#include <set>#include <sstream>@@ -55,7 +58,11 @@#include <tuple>#include <vector>+#include "openvino/op/paged_qsa_indexer.hpp"+#include "openvino/op/qsa_indexer.hpp"#include "openvino/runtime/core.hpp"+#include "ov_ops/rms.hpp"+#include "ov_ops/rotary_positional_embeddings.hpp"#include "primitive_inst.h"#include "random_generator.hpp"#include "test_utils.h"@@ -65,8 +72,8 @@ using namespace ::tests;namespace {-using PagedIn = ov::intel_gpu::op::PagedQSAIndexer::InputIdx;-using DenseIdxIn = ov::intel_gpu::op::QSAIndexer::InputIdx;+using PagedIn = ov::op::internal::PagedQSAIndexer::InputIdx;+using DenseIdxIn = ov::op::internal::QSAIndexer::InputIdx;using SparsePAIn = cldnn::sparse_pa::InputIdx;using SparseSDPAIn = ov::intel_gpu::op::SparseSDPA::InputIdx;@@ -687,7 +694,7 @@ std::unique_ptr<network> build_paged_network(engine& engine, const paged_inputs&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;+ ov::op::internal::PagedQSAIndexer::Config cfg;cfg.key_block_size = d.r;cfg.block_topk = d.block_topk;cfg.num_selection_heads = 1;@@ -981,7 +988,7 @@ std::unique_ptr<network> build_dense_network(engine& engine, const dense_inputs&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;+ ov::op::internal::QSAIndexer::Config cfg;cfg.key_block_size = d.r;cfg.block_topk = d.block_topk;cfg.num_selection_heads = 1;@@ -1242,21 +1249,15 @@ void dump_pair_outputs(const pair_outputs& gpu) {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);+void validate_selection(const split_reference& ref, const selection_plan& plan, std::vector<std::vector<size_t>>& selections) {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);+ ASSERT_EQ(plan.count.size(), ref.q_len);+ ASSERT_EQ(plan.sel.size(), ref.q_len * d.block_topk);+ selections.resize(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;+ ASSERT_EQ(static_cast<size_t>(plan.count[t]), expected_count) << "t=" << t;if (expected_count == 0) {continue;}@@ -1268,7 +1269,7 @@ void validate_pair(const split_reference& ref, const pair_outputs& gpu, float atconst 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];+ const int32_t b = 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";@@ -1276,6 +1277,18 @@ void validate_pair(const split_reference& ref, const pair_outputs& gpu, float at}selections[t].assign(seen.begin(), seen.end());}+}++/// Checks the GPU plan against the reference scores, then compares attention computed+/// over that same plan using a combined absolute+relative tolerance.+void validate_pair(const split_reference& ref, const pair_outputs& gpu, float atol, float rtol) {+ dump_pair_outputs(gpu);+ const auto& d = ref.d;+ std::vector<std::vector<size_t>> selections;+ validate_selection(ref, gpu.plan, selections);+ if (::testing::Test::HasFatalFailure()) {+ return;+ }const auto expected = ref.attention(selections);ASSERT_EQ(gpu.attn.size(), expected.size());@@ -1296,7 +1309,7 @@ void validate_pair(const split_reference& ref, const pair_outputs& gpu, float at/// 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;+ using Out = ov::op::internal::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));@@ -1566,7 +1579,7 @@ void run_dense_state_chain_test(const split_dims& d, const std::vector<size_t>&if (!qsa_ops_available()) {GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";}- using Out = ov::intel_gpu::op::QSAIndexer::OutputIdx;+ using Out = ov::op::internal::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);@@ -2310,8 +2323,8 @@ ov::OutputVector make_dense_indexer_args(const split_dims& d, size_t h_ik = 1) {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;+ov::op::internal::PagedQSAIndexer::Config make_paged_indexer_config(const split_dims& d) {+ ov::op::internal::PagedQSAIndexer::Config c;c.key_block_size = d.r;c.block_topk = d.block_topk;c.num_selection_heads = 1;@@ -2322,8 +2335,8 @@ ov::intel_gpu::op::PagedQSAIndexer::Config make_paged_indexer_config(const splitreturn c;}-ov::intel_gpu::op::QSAIndexer::Config make_dense_indexer_config(const split_dims& d) {- ov::intel_gpu::op::QSAIndexer::Config c;+ov::op::internal::QSAIndexer::Config make_dense_indexer_config(const split_dims& d) {+ ov::op::internal::QSAIndexer::Config c;c.key_block_size = d.r;c.block_topk = d.block_topk;c.num_selection_heads = 1;@@ -2334,48 +2347,208 @@ ov::intel_gpu::op::QSAIndexer::Config make_dense_indexer_config(const split_dimsreturn c;}+class QSAIndexerPluginTest : public ::testing::TestWithParam<bool> {};++TEST_P(QSAIndexerPluginTest, LowersFusionOutputAndImportsCompiledModel) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }++ const auto paged = GetParam();+ split_dims dims;+ tests::random_generator rg(GET_SUITE_NAME);+ const auto ref = make_split_reference(rg, dims, 20, 7, Positions::MRoPELike);+ const auto paged_in = paged_inputs_from_reference(ref);+ const auto dense_in = dense_inputs_from_reference(ref);+ const auto args = paged ? make_paged_indexer_args(dims, paged_in.num_pages, paged_in.spp) : make_dense_indexer_args(dims);+ std::shared_ptr<ov::Node> indexer;+ if (paged) {+ auto config = make_paged_indexer_config(dims);+ indexer = std::make_shared<ov::op::internal::PagedQSAIndexer>(args, config);+ } else {+ ov::op::internal::QSAIndexer::Config config;+ config.key_block_size = dims.r;+ config.block_topk = dims.block_topk;+ config.num_selection_heads = 1;+ config.indexer_rotary_dim = dims.rotary;+ config.indexer_head_dim = dims.Di;+ config.epsilon = dims.eps;+ indexer = std::make_shared<ov::op::internal::QSAIndexer>(args, config);+ }+ ov::ParameterVector parameters;+ for (const auto& arg : args) {+ const auto parameter = ov::as_type_ptr<ov::op::v0::Parameter>(arg.get_node_shared_ptr());+ ASSERT_NE(parameter, nullptr);+ parameters.push_back(parameter);+ }+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{indexer->output(0), indexer->output(1)}, parameters);+ ov::Core core;+ auto compiled = core.compile_model(model, "GPU", ov::hint::inference_precision(ov::element::f16));++ const auto run = [&](ov::CompiledModel& compiled_model) {+ auto request = compiled_model.create_infer_request();+ const auto set_f16 = [&](size_t i, const ov::Shape& shape, const std::vector<float>& values) {+ ov::Tensor tensor(ov::element::f16, shape);+ ASSERT_EQ(tensor.get_size(), values.size());+ auto* data = tensor.data<ov::float16>();+ std::transform(values.begin(), values.end(), data, [](float value) {+ return ov::float16(value);+ });+ request.set_input_tensor(i, tensor);+ };+ const auto set_i32 = [&](size_t i, const std::vector<int32_t>& values) {+ ov::Tensor tensor(ov::element::i32, ov::Shape{values.size()});+ std::copy(values.begin(), values.end(), tensor.data<int32_t>());+ request.set_input_tensor(i, tensor);+ };+ if (paged) {+ const auto [cos, sin] = rope_rows(ref.rotary, dims.rotary, paged_in.position_ids);+ set_f16(PagedIn::INDEX_QUERY, {ref.q_len, dims.Hiq * dims.Di}, paged_in.index_query);+ set_f16(PagedIn::RAW_INDEX_KEYS, {ref.q_len, dims.Di}, paged_in.raw_index_keys);+ set_f16(PagedIn::ROPE_COS, {ref.q_len, dims.rotary}, cos);+ set_f16(PagedIn::ROPE_SIN, {ref.q_len, dims.rotary}, sin);+ set_f16(PagedIn::Q_NORM_WEIGHT, {dims.Di}, paged_in.q_norm);+ set_f16(PagedIn::K_NORM_WEIGHT, {dims.Di}, paged_in.k_norm);+ set_i32(PagedIn::PAST_LENS, paged_in.past_lens);+ set_i32(PagedIn::SUBSEQUENCE_BEGINS, paged_in.subsequence_begins);+ set_i32(PagedIn::BLOCK_INDICES, paged_in.block_indices);+ set_i32(PagedIn::BLOCK_INDICES_BEGINS, paged_in.block_indices_begins);+ set_f16(PagedIn::INDEX_KEY_CACHE, {paged_in.num_pages, 1, dims.page_size, dims.Di}, paged_in.raw_k_cache);+ set_f16(PagedIn::INDEX_BLOCK_ROPE_CACHE,+ {paged_in.num_pages, paged_in.spp, 2 * dims.rotary},+ rope_cache_rows(ref.rotary, dims.rotary, paged_in.position_cache));+ set_f16(PagedIn::BLOCK_INDEX_KEYS_CACHE, {paged_in.num_pages, 1, paged_in.spp, dims.Di}, paged_in.block_index_keys_cache);+ } else {+ set_f16(DenseIdxIn::INDEX_QUERY, {1, ref.q_len, dims.Hiq, dims.Di}, dense_in.index_query);+ set_f16(DenseIdxIn::RAW_INDEX_KEYS, {1, ref.q_len, 1, dims.Di}, dense_in.raw_index_keys);+ set_f16(DenseIdxIn::ROPE_COS, {1, ref.q_len, dims.rotary}, dense_in.rope_cos);+ set_f16(DenseIdxIn::ROPE_SIN, {1, ref.q_len, dims.rotary}, dense_in.rope_sin);+ set_i32(DenseIdxIn::KEY_LENGTH, dense_in.key_length);+ set_f16(DenseIdxIn::Q_NORM_WEIGHT, {dims.Di}, dense_in.q_norm);+ set_f16(DenseIdxIn::K_NORM_WEIGHT, {dims.Di}, dense_in.k_norm);+ set_f16(DenseIdxIn::BLOCK_INDEX_KEYS_CACHE, {1, 1, dense_in.summary_cap, dims.Di}, dense_in.block_index_keys_cache);+ set_f16(DenseIdxIn::PAST_INCOMPLETE_RAW_K, {1, 1, dims.r - 1, dims.Di}, dense_in.raw_state);+ set_f16(DenseIdxIn::PAST_INCOMPLETE_ROPE, {1, 2 * dims.rotary}, dense_in.rope_state);+ }+ ASSERT_FALSE(::testing::Test::HasFatalFailure());+ request.infer();+ const auto indices = request.get_output_tensor(0);+ const auto counts = request.get_output_tensor(1);+ const auto* indices_data = indices.data<int32_t>();+ const auto* counts_data = counts.data<int32_t>();+ selection_plan plan{std::vector<int32_t>(indices_data, indices_data + indices.get_size()),+ std::vector<int32_t>(counts_data, counts_data + counts.get_size())};+ std::vector<std::vector<size_t>> selections;+ validate_selection(ref, plan, selections);+ };++ run(compiled);+ ASSERT_FALSE(::testing::Test::HasFatalFailure());+ std::stringstream cache;+ compiled.export_model(cache);+ cache.seekg(0);+ auto restored = core.import_model(cache, "GPU");+ run(restored);+}++TEST_P(QSAIndexerPluginTest, AbsorbsQueryPreprocessingBeforeLowering) {+ if (!qsa_ops_available()) {+ GTEST_SKIP() << "Intel subgroup extensions are not supported on this device";+ }++ const split_dims d;+ const auto query = make_param({1, 2, I(d.Hiq), I(d.Di)});+ const auto cos = make_param({1, 2, I(d.rotary)});+ const auto sin = make_param({1, 2, I(d.rotary)});+ const auto i64 = [](const std::vector<int64_t>& values) {+ return ov::op::v0::Constant::create(ov::element::i64, ov::Shape{values.size()}, values);+ };+ const auto rms = std::make_shared<ov::op::internal::RMS>(query, d.eps, ov::element::f16, -1);+ ov::op::internal::RoPE::Config rope_config;+ rope_config.rotary_ndims = d.rotary;+ rope_config.input_trans0213 = true;+ const auto rope = std::make_shared<ov::op::internal::RoPE>(+ ov::OutputVector{rms, std::make_shared<ov::op::v0::Unsqueeze>(cos, i64({1})), std::make_shared<ov::op::v0::Unsqueeze>(sin, i64({1}))},+ rope_config);+ const auto query_blhd = std::make_shared<ov::op::v1::Transpose>(rope, i64({0, 2, 1, 3}));+ auto args = GetParam() ? make_paged_indexer_args(d, 8, d.page_size / d.r) : make_dense_indexer_args(d);+ std::shared_ptr<ov::Node> indexer;+ if (GetParam()) {+ args[PagedIn::INDEX_QUERY] = std::make_shared<ov::op::v1::Reshape>(query_blhd, i64({-1, I(d.Hiq * d.Di)}), false);+ args[PagedIn::ROPE_COS] = std::make_shared<ov::op::v1::Reshape>(cos, i64({-1, I(d.rotary)}), false);+ args[PagedIn::ROPE_SIN] = std::make_shared<ov::op::v1::Reshape>(sin, i64({-1, I(d.rotary)}), false);+ auto config = make_paged_indexer_config(d);+ config.query_norm = config.query_rope = false;+ indexer = std::make_shared<ov::op::internal::PagedQSAIndexer>(args, config);+ } else {+ args[DenseIdxIn::INDEX_QUERY] = query_blhd;+ args[DenseIdxIn::ROPE_COS] = cos;+ args[DenseIdxIn::ROPE_SIN] = sin;+ auto config = make_dense_indexer_config(d);+ config.query_norm = config.query_rope = false;+ indexer = std::make_shared<ov::op::internal::QSAIndexer>(args, config);+ }+ ov::ParameterVector parameters{query, cos, sin};+ for (size_t i = 0; i < args.size(); ++i) {+ if (i == DenseIdxIn::INDEX_QUERY || i == DenseIdxIn::ROPE_COS || i == DenseIdxIn::ROPE_SIN) {+ continue;+ }+ parameters.push_back(ov::as_type_ptr<ov::op::v0::Parameter>(args[i].get_node_shared_ptr()));+ }+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{indexer->output(0), indexer->output(1)}, parameters);+ ov::Core core;+ EXPECT_NO_THROW(core.compile_model(model, "GPU", ov::hint::inference_precision(ov::element::f16)));+}++INSTANTIATE_TEST_SUITE_P(QSA,+ QSAIndexerPluginTest,+ ::testing::Bool(),+ ([](const ::testing::TestParamInfo<bool>& info) {+ return info.param ? "Paged" : "Dense";+ }));+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;+ ASSERT_TRUE(ov::op::internal::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));+ ASSERT_FALSE(ov::op::internal::PagedQSAIndexer::validate_config(c, reason));c = base;c.block_topk = 0;- ASSERT_FALSE(ov::intel_gpu::op::PagedQSAIndexer::validate_config(c, reason));+ ASSERT_FALSE(ov::op::internal::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));+ ASSERT_FALSE(ov::op::internal::PagedQSAIndexer::validate_config(c, reason));c = base;c.scale = -1.0f;- ASSERT_FALSE(ov::intel_gpu::op::PagedQSAIndexer::validate_config(c, reason));+ ASSERT_FALSE(ov::op::internal::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)));+ ASSERT_TRUE(ov::op::internal::PagedQSAIndexer::validate_config(c, reason)) << reason;+ EXPECT_FLOAT_EQ(ov::op::internal::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;+ using In = ov::op::internal::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);+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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));+ auto node = std::make_shared<ov::op::internal::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);@@ -2386,7 +2559,7 @@ TEST(qsa_ops_gpu_test, paged_qsa_indexer_output_shapes_and_clone) {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)+ ASSERT_NE(std::dynamic_pointer_cast<ov::op::internal::PagedQSAIndexer>(clone), nullptr)<< "clone_with_new_inputs() must not silently downgrade to the base ov::op::internal::PagedQSAIndexer type";}@@ -2394,60 +2567,60 @@ 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);+ auto node = std::make_shared<ov::op::internal::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)));+ EXPECT_FLOAT_EQ(ov::op::internal::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);+ ASSERT_THROW((void)std::make_shared<ov::op::internal::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;+ using In = ov::op::internal::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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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;+ using In = ov::op::internal::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;+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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)));+ using In = ov::op::internal::QSAIndexer::InputIdx;+ using Out = ov::op::internal::QSAIndexer::OutputIdx;+ std::shared_ptr<ov::op::internal::QSAIndexer> node;+ ASSERT_NO_THROW(node = std::make_shared<ov::op::internal::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)}));@@ -2460,35 +2633,35 @@ TEST(qsa_ops_gpu_test, dense_qsa_indexer_validates_state_rope_and_key_length) {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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::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";+ EXPECT_THROW((void)std::make_shared<ov::op::internal::QSAIndexer>(args, make_dense_indexer_config(d)), ov::Exception) << "summary type";}cldnn::sparse_pa::Config make_sparse_pa_config(const split_dims& d) {@@ -2639,6 +2812,32 @@ void expect_compile_error(ov::Core& core, const std::shared_ptr<ov::Node>& op, c}}+TEST(qsa_ops_gpu_test, plugin_rejects_incomplete_query_fusion) {+ ov::Core core;+ if (!gpu_in_core(core)) {+ GTEST_SKIP() << "GPU plugin is not available in ov::Core";+ }+ const split_dims d;+ for (const bool paged : {false, true}) {+ for (const auto& [norm, rope] : {std::pair{false, false}, std::pair{false, true}, std::pair{true, false}}) {+ SCOPED_TRACE(::testing::Message() << "paged=" << paged << " norm=" << norm << " rope=" << rope);+ std::shared_ptr<ov::Node> indexer;+ if (paged) {+ auto config = make_paged_indexer_config(d);+ config.query_norm = norm;+ config.query_rope = rope;+ indexer = std::make_shared<ov::op::internal::PagedQSAIndexer>(make_paged_indexer_args(d, 8, d.page_size / d.r), config);+ } else {+ auto config = make_dense_indexer_config(d);+ config.query_norm = norm;+ config.query_rope = rope;+ indexer = std::make_shared<ov::op::internal::QSAIndexer>(make_dense_indexer_args(d), config);+ }+ expect_compile_error(core, indexer, {}, "only query_norm == true and query_rope == true are supported");+ }+ }+}+TEST(qsa_ops_gpu_test, plugin_rejects_unsupported_indexer_heads_and_precision) {ov::Core core;if (!gpu_in_core(core)) {@@ -2653,7 +2852,7 @@ TEST(qsa_ops_gpu_test, plugin_rejects_unsupported_indexer_heads_and_precision) {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);+ return std::make_shared<ov::op::internal::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");