Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[TRANSFORMATIONS] Add PagedSparseAttentionFusion (#39412)

Andrii Staikov419b3b2c281b
diff --git a/src/common/transformations/include/sources.cmake b/src/common/transformations/include/sources.cmake
index 837ad25279b..2d18b55b440 100644
--- a/src/common/transformations/include/sources.cmake
+++ b/src/common/transformations/include/sources.cmake
@@ -294,6 +294,7 @@ set(PAGED_ATTENTION_HEADERS
${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/paged_sparse_attention_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.hpp
diff --git a/src/common/transformations/include/transformations/paged_attention/paged_sparse_attention_fusion.hpp b/src/common/transformations/include/transformations/paged_attention/paged_sparse_attention_fusion.hpp
new file mode 100644
index 00000000000..1065e53a8fd
--- /dev/null
+++ b/src/common/transformations/include/transformations/paged_attention/paged_sparse_attention_fusion.hpp
@@ -0,0 +1,85 @@
+// 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 {
+namespace pass {
+
+/**
+ * @ingroup ov_transformation_common_api
+ * @brief Replaces stateful SparseAttention with PagedSparseAttention.
+ *
+ * Uses the dimension names from PagedAttentionExtension:
+ * B_token = total new tokens in the call, B_seq = number of sequences,
+ * H = query heads, Hk = key/value heads, S = query/key head size,
+ * Bs = physical cache block size (in tokens).
+ * Additional dimensions:
+ * Sv = value head size, Hs = selection heads, KB = selection capacity
+ * (maximum selected sparse blocks per token and selection head).
+ * SDPAToPagedAttention must prepare all token inputs before this matcher runs.
+ * They use B_token as the leading dimension and a singleton sequence axis
+ * inside the graph, as in StateManagementPattern. In particular, the external
+ * ngram_embeddings input keeps its rank-4 layout [B_token, 1, num_ngrams, embedding_size],
+ * so its existing consumers are unchanged.
+ * Bs is distinct from the sparse attention attribute key_block_size;
+ * KB counts selected sparse blocks, each containing key_block_size tokens.
+ *
+ * Matches causal SparseAttention with query_block_size = 1 and stateful K/V
+ * caches concatenated with current K/V on the sequence axis:
+ *
+ * ReadValue -> (Gather on batch axis) -> Concat(current K/V, axis 2)
+ * |
+ * query, block_indices, block_count ------> SparseAttention
+ *
+ * The replacement packs the current inputs as follows:
+ * query: [B_token, H, 1, S] -> [B_token, H * S]
+ * current key: [B_token, Hk, 1, S] -> [B_token, Hk * S]
+ * current value: [B_token, Hk, 1, Sv] -> [B_token, Hk * Sv]
+ * block_indices: [B_token, Hs, 1, KB] -> [B_token, Hs, KB]
+ * block_count: [B_token, Hs, 1] -> [B_token, Hs]
+ * Q/K/V use Transpose followed by Reshape({0, -1}, special_zero = true).
+ * Selections use Squeeze on the singleton sequence axis.
+ *
+ * PagedSparseAttention uses external paged KV caches and scheduling inputs:
+ * key_cache: [num_blocks, Hk, Bs, S]
+ * value_cache: [num_blocks, Hk, Bs, Sv]
+ * past_lens: [B_seq]
+ * subsequence_begins: [B_seq + 1]
+ * block_indices: [total_blocks] (physical cache block table)
+ * block_indices_begins: [B_seq + 1]
+ * Its selected_block_indices and selected_block_count inputs are the packed
+ * SparseAttention selections above; they contain logical sparse block indices
+ * and counts, respectively. They are separate from the physical block table.
+ * The output is restored from [B_token, H * Sv] to [B_token, H, 1, Sv].
+ * The block selection and output gate remain in the graph.
+ * Optional scale and sinks are preserved, with an explicit default scale and
+ * empty sinks supplied when absent.
+ *
+ * The enclosing model pass must add pa_params to the model and remove Assign
+ * sinks for var_ids_to_remove. Preparing the sparse indexer's paged state is
+ * a separate transformation.
+ * The replacement uses the internal core PagedSparseAttention operation.
+ */
+
+class TRANSFORMATIONS_API PagedSparseAttentionFusion : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PagedSparseAttentionFusion");
+ PagedSparseAttentionFusion(ov::pass::paged_attention::PaParams& pa_params,
+ const ov::pass::paged_attention::Options& options,
+ std::unordered_set<std::string>& var_ids_to_remove);
+
+private:
+ size_t m_layer_index = 0;
+};
+
+} // namespace pass
+} // namespace ov
diff --git a/src/common/transformations/include/transformations/utils/utils.hpp b/src/common/transformations/include/transformations/utils/utils.hpp
index 738fad30154..a13d4a089be 100644
--- a/src/common/transformations/include/transformations/utils/utils.hpp
+++ b/src/common/transformations/include/transformations/utils/utils.hpp
@@ -49,10 +49,11 @@ bool normalize_single_value(std::vector<T> vec, float& value, bool check_value_r
return true;
}
-template <class T>
+template <class... T>
bool has_op_with_type(const std::shared_ptr<const ov::Model>& function) {
+ static_assert(sizeof...(T) > 0, "has_op_with_type requires at least one operation type");
for (const auto& op : function->get_ops()) {
- if (ov::as_type_ptr<T>(op)) {
+ if (ov::is_type_any_of<T...>(op)) {
return true;
}
}
diff --git a/src/common/transformations/src/sources.cmake b/src/common/transformations/src/sources.cmake
index 3823ad2b820..c23731e2894 100644
--- a/src/common/transformations/src/sources.cmake
+++ b/src/common/transformations/src/sources.cmake
@@ -257,6 +257,7 @@ set(PAGED_ATTENTION_SOURCES
${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/paged_sparse_attention_fusion.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/position_ids_replacer.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/prev_sequence_length_pattern.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/state_management_pattern.cpp
diff --git a/src/common/transformations/src/transformations/paged_attention/paged_sparse_attention_fusion.cpp b/src/common/transformations/src/transformations/paged_attention/paged_sparse_attention_fusion.cpp
new file mode 100644
index 00000000000..38b836ba61b
--- /dev/null
+++ b/src/common/transformations/src/transformations/paged_attention/paged_sparse_attention_fusion.cpp
@@ -0,0 +1,216 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "transformations/paged_attention/paged_sparse_attention_fusion.hpp"
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "itt.hpp"
+#include "openvino/core/attribute_visitor.hpp"
+#include "openvino/core/graph_util.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/divide.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/op.hpp"
+#include "openvino/op/paged_sparse_attention.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/sparse_attention.hpp"
+#include "openvino/op/sqrt.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/transpose.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/util/read_value_base.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 {
+namespace v0 = ov::op::v0;
+namespace v1 = ov::op::v1;
+namespace v3 = ov::op::v3;
+namespace v8 = ov::op::v8;
+namespace v15 = ov::op::v15;
+namespace pattern = ov::pass::pattern;
+
+ov::Output<ov::Node> pack_heads(const ov::Output<ov::Node>& input) {
+ // Query: [B_token, H, 1, S] -> [B_token, 1, H, S] -> [B_token, H * S].
+ // Current key: [B_token, Hk, 1, S] -> [B_token, 1, Hk, S] -> [B_token, Hk * S].
+ // Current value: [B_token, Hk, 1, Sv] -> [B_token, 1, Hk, Sv] -> [B_token, Hk * Sv].
+ const auto order = v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3});
+ const auto transposed = std::make_shared<v1::Transpose>(input, order);
+ const auto shape = v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, -1});
+ const auto packed = std::make_shared<v1::Reshape>(transposed, shape, true);
+ return packed;
+}
+
+ov::Output<ov::Node> pack_selection(const ov::Output<ov::Node>& input) {
+ // Indices: [B_token, Hs, 1, KB] -> [B_token, Hs, KB].
+ // Counts: [B_token, Hs, 1] -> [B_token, Hs].
+ // Hs is the number of selection heads; KB is the maximum selected sparse blocks.
+ const auto axis = v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
+ const auto packed = std::make_shared<v15::Squeeze>(input, axis);
+ if (packed->get_output_element_type(0) == ov::element::i32) {
+ return packed;
+ }
+ return std::make_shared<v0::Convert>(packed, ov::element::i32);
+}
+
+struct CachePattern {
+ std::shared_ptr<ov::Node> read_value;
+ std::shared_ptr<ov::Node> current;
+ std::shared_ptr<ov::Node> concat;
+};
+
+CachePattern cache_pattern() {
+ auto read_value = pattern::wrap_type<ov::op::util::ReadValueBase>(pattern::rank_equals(4));
+ auto past = pattern::optional<v8::Gather>({read_value, pattern::any_input(), pattern::any_input()});
+ auto current = pattern::any_input(pattern::has_static_dims({1, 3}));
+ auto concat = pattern::wrap_type<v0::Concat>({past, current});
+ return {read_value, current, concat};
+}
+} // namespace
+
+ov::pass::PagedSparseAttentionFusion::PagedSparseAttentionFusion(ov::pass::paged_attention::PaParams& pa_params,
+ const ov::pass::paged_attention::Options& options,
+ std::unordered_set<std::string>& var_ids_to_remove) {
+ MATCHER_SCOPE(PagedSparseAttentionFusion);
+
+ const auto p_query = pattern::any_input(pattern::rank_equals(4) && pattern::has_static_dims({1, 3}));
+ const auto p_key = cache_pattern();
+ const auto p_value = cache_pattern();
+ const auto index_type_pred = pattern::type_matches_any({ov::element::i32, ov::element::i64});
+ const auto p_block_indices = pattern::any_input(pattern::rank_equals(4) && index_type_pred);
+ const auto p_block_count = pattern::any_input(pattern::rank_equals(3) && index_type_pred);
+ const auto p_key_length = pattern::any_input(pattern::rank_equals(1) && index_type_pred);
+ const auto p_scale = pattern::any_input(pattern::has_static_rank());
+ const auto p_sinks = pattern::any_input(pattern::rank_equals(1));
+
+ const auto attrs = pattern::attrs_match({{"causal", true}});
+ auto sparse_attention =
+ pattern::wrap_type<ov::op::v17::SparseAttention>(
+ {p_query, p_key.concat, p_value.concat, p_block_indices, p_block_count},
+ attrs) |
+ pattern::wrap_type<ov::op::v17::SparseAttention>(
+ {p_query, p_key.concat, p_value.concat, p_block_indices, p_block_count, p_key_length},
+ attrs) |
+ pattern::wrap_type<ov::op::v17::SparseAttention>(
+ {p_query, p_key.concat, p_value.concat, p_block_indices, p_block_count, p_key_length, p_scale},
+ attrs) |
+ pattern::wrap_type<ov::op::v17::SparseAttention>(
+ {p_query, p_key.concat, p_value.concat, p_block_indices, p_block_count, p_key_length, p_scale, p_sinks},
+ attrs);
+
+ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS, &pa_params, &var_ids_to_remove](
+ pattern::Matcher& m) {
+ if (transformation_callback(m.get_match_root())) {
+ return false;
+ }
+ const auto& pm = m.get_pattern_value_map();
+
+ const auto current_key = pm.at(p_key.current);
+ const auto current_value = pm.at(p_value.current);
+ const auto key_read =
+ ov::as_type_ptr<ov::op::util::ReadValueBase>(pm.at(p_key.read_value).get_node_shared_ptr());
+ const auto value_read =
+ ov::as_type_ptr<ov::op::util::ReadValueBase>(pm.at(p_value.read_value).get_node_shared_ptr());
+ const auto sparse_node = ov::as_type_ptr<ov::op::v17::SparseAttention>(m.get_match_root());
+ OPENVINO_ASSERT(key_read && value_read && sparse_node);
+
+ var_ids_to_remove.insert(key_read->get_variable_id());
+ var_ids_to_remove.insert(value_read->get_variable_id());
+
+ // As PagedSparseAttention shares the regular PagedAttentionExtension input names,
+ // we need to count how many cache inputs have already allocated by another
+ // attention conversion.
+ while (pa_params.exists("key_cache." + std::to_string(m_layer_index)) ||
+ pa_params.exists("value_cache." + std::to_string(m_layer_index)) ||
+ (options.use_per_layer_block_indices_inputs &&
+ pa_params.exists("block_indices." + std::to_string(m_layer_index)))) {
+ ++m_layer_index;
+ }
+ const auto layer = std::to_string(m_layer_index);
+ const auto& key_shape = current_key.get_partial_shape();
+ const auto& value_shape = current_value.get_partial_shape();
+ const auto key_cache = pa_params.add("key_cache." + layer, ov::element::dynamic, PartialShape::dynamic(4));
+ const auto value_cache = pa_params.add("value_cache." + layer, ov::element::dynamic, PartialShape::dynamic(4));
+ enable_keep_const_precision(key_cache);
+ enable_keep_const_precision(value_cache);
+
+ const auto past_lens = pa_params.add("past_lens", ov::element::i32, ov::PartialShape{-1});
+ const auto subsequence_begins = pa_params.add("subsequence_begins", ov::element::i32, ov::PartialShape{-1});
+ const auto cache_block_indices =
+ pa_params.add(options.use_per_layer_block_indices_inputs ? "block_indices." + layer : "block_indices",
+ ov::element::i32,
+ ov::PartialShape{-1});
+ const auto block_indices_begins = pa_params.add("block_indices_begins", ov::element::i32, ov::PartialShape{-1});
+
+ const auto packed_query = pack_heads(pm.at(p_query));
+ const auto packed_key = pack_heads(current_key);
+ const auto packed_value = pack_heads(current_value);
+
+ const auto packed_indices = pack_selection(pm.at(p_block_indices));
+ const auto packed_count = pack_selection(pm.at(p_block_count));
+
+ ov::Output<ov::Node> scale;
+ if (pm.count(p_scale)) {
+ scale = pm.at(p_scale);
+ if (scale.get_partial_shape().rank() == 1) {
+ scale = ov::op::util::make_try_fold<v15::Squeeze>(scale);
+ }
+ } else {
+ scale = v0::Constant::create(packed_query.get_element_type(),
+ ov::Shape{},
+ {1 / std::sqrt(pm.at(p_query).get_partial_shape()[3].get_length())});
+ }
+
+ auto attention_sinks = pm.count(p_sinks)
+ ? pm.at(p_sinks)
+ : v0::Constant::create(packed_query.get_element_type(), ov::Shape{0}, {});
+
+ const auto paged_sparse =
+ std::make_shared<ov::op::internal::PagedSparseAttention>(ov::OutputVector{packed_query,
+ packed_key,
+ packed_value,
+ key_cache,
+ value_cache,
+ past_lens,
+ subsequence_begins,
+ cache_block_indices,
+ block_indices_begins,
+ packed_indices,
+ packed_count,
+ scale,
+ attention_sinks},
+ sparse_node->get_key_block_size());
+ paged_sparse->set_friendly_name(sparse_node->get_friendly_name() + "/PagedSparseAttention");
+ paged_sparse->get_rt_info()["num_k_heads"] = key_shape[1].get_length();
+ paged_sparse->get_rt_info()["k_head_size"] = key_shape[3].get_length();
+ paged_sparse->get_rt_info()["num_v_heads"] = value_shape[1].get_length();
+ paged_sparse->get_rt_info()["v_head_size"] = value_shape[3].get_length();
+
+ // [B_token, H * Sv] -> [B_token, 1, H, Sv] -> [B_token, H, 1, Sv].
+ auto output_shape =
+ v0::Constant::create<int64_t>(ov::element::i64, ov::Shape{4}, {0, 1, -1, value_shape[3].get_length()});
+ const auto reshaped = std::make_shared<v1::Reshape>(paged_sparse, output_shape, true);
+ const auto output =
+ std::make_shared<v1::Transpose>(reshaped,
+ v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3}));
+
+ output->set_friendly_name(sparse_node->get_friendly_name());
+ ov::copy_runtime_info(sparse_node, paged_sparse);
+ ov::replace_node(sparse_node, output);
+ ++m_layer_index;
+ return true;
+ };
+
+ register_matcher(std::make_shared<pattern::Matcher>(sparse_attention, matcher_name), callback);
+}
diff --git a/src/common/transformations/tests/op_conversions/sdpa_to_paged_attention_test.cpp b/src/common/transformations/tests/op_conversions/sdpa_to_paged_attention_test.cpp
index a8e99c9d69e..e1a33296245 100644
--- a/src/common/transformations/tests/op_conversions/sdpa_to_paged_attention_test.cpp
+++ b/src/common/transformations/tests/op_conversions/sdpa_to_paged_attention_test.cpp
@@ -43,7 +43,9 @@
#include "openvino/op/mvn.hpp"
#include "openvino/op/pad.hpp"
#include "openvino/op/paged_attention.hpp"
+#include "openvino/op/paged_sparse_attention.hpp"
#include "openvino/op/power.hpp"
+#include "openvino/op/qsa_prepare.hpp"
#include "openvino/op/range.hpp"
#include "openvino/op/reduce_mean.hpp"
#include "openvino/op/reduce_prod.hpp"
@@ -56,6 +58,8 @@
#include "openvino/op/shape_of.hpp"
#include "openvino/op/sin.hpp"
#include "openvino/op/slice.hpp"
+#include "openvino/op/sparse_attention.hpp"
+#include "openvino/op/sparse_attention_indexer.hpp"
#include "openvino/op/split.hpp"
#include "openvino/op/sqrt.hpp"
#include "openvino/op/squeeze.hpp"
@@ -64,10 +68,12 @@
#include "openvino/op/tile.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/util/assign_base.hpp"
#include "openvino/op/util/variable.hpp"
#include "openvino/op/variadic_split.hpp"
#include "transformations/paged_attention/eliminate_conv_padding_mask_gating.hpp"
#include "transformations/paged_attention/gemma4_mtp_state_management_pattern.hpp"
+#include "transformations/paged_attention/paged_sparse_attention_fusion.hpp"
#include "transformations/paged_attention/position_ids_replacer.hpp"
#include "transformations/paged_attention/prev_sequence_length_pattern.hpp"
#include "transformations/paged_attention/state_management_pattern.hpp"
@@ -7968,6 +7974,340 @@ TEST_F(SDPAToPATest, SDPAToPA_Gemma4MTP_Gemma4MTPStateManagementPattern_Rank1Sca
disable_rt_info_check();
}
+// The subgraph matched by PagedSparseAttentionFusion, with the shapes of tiny-random-qwen38-flash-next layer 3.
+// Q/K/V are projected from inputs_embeds, so SDPAToPagedAttention packs the tokens as in the exported model:
+// inputs_embeds -> MatMul -> Reshape -> Transpose -> Q, current K/V
+// ReadValue -> Gather(beam_idx) -> Concat(current K/V, axis 2) -> SparseAttention <- Q, selection, key_length
+// The optional scale and sinks inputs and the selection element type vary between the test cases.
+namespace paged_sparse_attention_pattern {
+constexpr int64_t hidden_size = 16;
+constexpr int64_t num_heads = 4;
+constexpr int64_t num_kv_heads = 2;
+constexpr int64_t head_size = 64;
+constexpr float explicit_scale = 0.1f;
+
+enum class Scale { Absent, Scalar, Vector1 };
+
+struct Case {
+ std::string name;
+ element::Type data_type = element::f32; // Q/K/V, the K/V states and the scale
+ element::Type selection_type = element::i32;
+ Scale scale = Scale::Absent;
+ element::Type sinks_type = element::dynamic; // dynamic: no sinks input
+};
+
+void PrintTo(const Case& test_case, std::ostream* os) {
+ *os << test_case.name;
+}
+
+// [B, L, hidden] -> [B, L, heads * S] -> [B, L, heads, S] -> [B, heads, L, S]
+Output<Node> project_heads(const Output<Node>& inputs_embeds, int64_t heads, const element::Type& data_type) {
+ auto weights = v0::Constant::create(data_type,
+ Shape{static_cast<size_t>(hidden_size), static_cast<size_t>(heads * head_size)},
+ {0.1f});
+ auto projection = std::make_shared<v0::MatMul>(inputs_embeds, weights);
+ auto reshape = std::make_shared<v1::Reshape>(
+ projection,
+ v0::Constant::create(element::i64, Shape{4}, {int64_t{0}, int64_t{0}, heads, head_size}),
+ true);
+ return std::make_shared<v1::Transpose>(reshape, v0::Constant::create(element::i64, Shape{4}, {0, 2, 1, 3}));
+}
+
+// The explicit SparseAttention scale: a scalar or a single-element vector of the Q/K/V type.
+std::shared_ptr<Node> make_scale(const Case& test_case) {
+ const auto shape = test_case.scale == Scale::Vector1 ? Shape{1} : Shape{};
+ return v0::Constant::create(test_case.data_type, shape, {explicit_scale});
+}
+
+// One sink logit per query head, possibly of a higher precision than Q/K/V.
+std::shared_ptr<Node> make_sinks(const Case& test_case) {
+ return v0::Constant::create(test_case.sinks_type, Shape{num_heads}, {0.5f, 1.0f, 1.5f, 2.0f});
+}
+
+std::shared_ptr<ov::op::util::Variable> make_kv_variable(const std::string& name, const element::Type& data_type) {
+ return std::make_shared<ov::op::util::Variable>(
+ ov::op::util::VariableInfo{PartialShape{DYN, num_kv_heads, DYN, head_size}, data_type, name});
+}
+
+std::shared_ptr<ov::Model> make_model(const Case& test_case,
+ const PartialShape& inputs_embeds_shape = PartialShape{DYN, DYN, hidden_size}) {
+ OPENVINO_ASSERT(test_case.sinks_type.is_dynamic() || test_case.scale != Scale::Absent,
+ "SparseAttention inputs are positional: sinks require an explicit scale.");
+ const auto& data_type = test_case.data_type;
+ auto inputs_embeds = ov::test::utils::make_param(data_type, inputs_embeds_shape, "inputs_embeds");
+ auto beam_idx = ov::test::utils::make_param(element::i32, PartialShape{DYN}, "beam_idx");
+ auto block_indices =
+ ov::test::utils::make_param(test_case.selection_type, PartialShape{DYN, 1, DYN, 2}, "selected_block_indices");
+ auto block_count =
+ ov::test::utils::make_param(test_case.selection_type, PartialShape{DYN, 1, DYN}, "selected_block_count");
+ auto key_length = ov::test::utils::make_param(element::i64, PartialShape{DYN}, "key_length");
+
+ auto make_cache = [&](const std::string& name, const Output<Node>& current) {
+ auto variable = make_kv_variable(name, data_type);
+ auto read_value = std::make_shared<v6::ReadValue>(variable);
+ auto past =
+ std::make_shared<v8::Gather>(read_value, beam_idx, v0::Constant::create(element::i64, Shape{}, {0}));
+ auto concat = std::make_shared<v0::Concat>(OutputVector{past, current}, 2);
+ return std::make_pair(concat, std::make_shared<v6::Assign>(concat, variable));
+ };
+
+ auto query = project_heads(inputs_embeds, num_heads, data_type);
+ const auto [key_concat, key_assign] = make_cache("key.0", project_heads(inputs_embeds, num_kv_heads, data_type));
+ const auto [value_concat, value_assign] =
+ make_cache("value.0", project_heads(inputs_embeds, num_kv_heads, data_type));
+
+ OutputVector inputs{query, key_concat, value_concat, block_indices, block_count, key_length};
+ if (test_case.scale != Scale::Absent) {
+ inputs.push_back(make_scale(test_case));
+ }
+ if (!test_case.sinks_type.is_dynamic()) {
+ inputs.push_back(make_sinks(test_case));
+ }
+ auto sparse_attention = std::make_shared<ov::op::v17::SparseAttention>(inputs, /*key_block_size=*/4);
+ return std::make_shared<ov::Model>(
+ OutputVector{sparse_attention},
+ SinkVector{key_assign, value_assign},
+ ParameterVector{inputs_embeds, beam_idx, block_indices, block_count, key_length});
+}
+
+// Q/K/V: [B_token, H, 1, S] -> [B_token, 1, H, S] -> [B_token, H * S]
+Output<Node> pack_heads(const Output<Node>& input) {
+ auto transpose = std::make_shared<v1::Transpose>(input, v0::Constant::create(element::i64, Shape{4}, {0, 2, 1, 3}));
+ return std::make_shared<v1::Reshape>(transpose, v0::Constant::create(element::i64, Shape{2}, {0, -1}), true);
+}
+
+// Selection: [B_token, Hs, 1, KB] -> [B_token, Hs, KB] and [B_token, Hs, 1] -> [B_token, Hs], converted to the i32
+// required by PagedSparseAttention when SparseAttention gets i64 selections.
+Output<Node> squeeze_query_axis(const Output<Node>& input) {
+ Output<Node> squeezed = std::make_shared<v15::Squeeze>(input, v0::Constant::create(element::i64, Shape{1}, {2}));
+ if (input.get_element_type() != element::i32) {
+ squeezed = std::make_shared<v0::Convert>(squeezed, element::i32);
+ }
+ return squeezed;
+}
+
+// PagedSparseAttention as created by the fusion, with its output restored to the [B_token, H, 1, Sv] layout.
+// paging holds key_cache, value_cache, past_lens, subsequence_begins, block_indices and block_indices_begins.
+Output<Node> make_paged_sparse_attention(const Case& test_case,
+ const Output<Node>& query,
+ const Output<Node>& key,
+ const Output<Node>& value,
+ const OutputVector& paging,
+ const Output<Node>& selected_block_indices,
+ const Output<Node>& selected_block_count) {
+ // The scale is kept, a single-element constant one is folded to a scalar, and an absent one defaults to
+ // 1 / sqrt(S).
+ Output<Node> scale;
+ switch (test_case.scale) {
+ case Scale::Absent:
+ scale = v0::Constant::create(test_case.data_type, Shape{}, {1.0f / std::sqrt(static_cast<float>(head_size))});
+ break;
+ case Scale::Scalar:
+ case Scale::Vector1:
+ scale = v0::Constant::create(test_case.data_type, Shape{}, {explicit_scale});
+ break;
+ }
+ // The sinks are kept with their own precision; absent sinks become an empty tensor of the Q/K/V type.
+ Output<Node> sinks = test_case.sinks_type.is_dynamic()
+ ? v0::Constant::create(test_case.data_type, Shape{0}, std::vector<float>{})
+ : make_sinks(test_case);
+
+ OutputVector inputs{pack_heads(query), pack_heads(key), pack_heads(value)};
+ inputs.insert(inputs.end(), paging.begin(), paging.end());
+ inputs.insert(inputs.end(),
+ {squeeze_query_axis(selected_block_indices), squeeze_query_axis(selected_block_count), scale, sinks});
+ auto paged_sparse_attention =
+ std::make_shared<ov::op::internal::PagedSparseAttention>(inputs, /*key_block_size=*/4);
+ auto& rt_info = paged_sparse_attention->get_rt_info();
+ rt_info["num_k_heads"] = num_kv_heads;
+ rt_info["k_head_size"] = head_size;
+ rt_info["num_v_heads"] = num_kv_heads;
+ rt_info["v_head_size"] = head_size;
+
+ // [B_token, H * Sv] -> [B_token, 1, H, Sv] -> [B_token, H, 1, Sv]
+ auto reshape = std::make_shared<v1::Reshape>(
+ paged_sparse_attention,
+ v0::Constant::create(element::i64, Shape{4}, {int64_t{0}, int64_t{1}, int64_t{-1}, head_size}),
+ true);
+ return std::make_shared<v1::Transpose>(reshape, v0::Constant::create(element::i64, Shape{4}, {0, 2, 1, 3}));
+}
+
+// The model after the whole SDPAToPagedAttention: inputs_embeds is packed to [B_token, hidden], the K/V states and
+// beam_idx are gone, and the inputs created by the pass are added in its order.
+std::shared_ptr<ov::Model> make_model_ref(const Case& test_case) {
+ const auto& data_type = test_case.data_type;
+ auto inputs_embeds = ov::test::utils::make_param(data_type, PartialShape{DYN, DYN}, "inputs_embeds");
+ auto selected_block_indices =
+ ov::test::utils::make_param(test_case.selection_type, PartialShape{DYN, 1, DYN, 2}, "selected_block_indices");
+ auto selected_block_count =
+ ov::test::utils::make_param(test_case.selection_type, PartialShape{DYN, 1, DYN}, "selected_block_count");
+ auto key_length = ov::test::utils::make_param(element::i64, PartialShape{DYN}, "key_length");
+
+ auto max_context_len = ov::test::utils::make_param(element::i32, PartialShape{}, "max_context_len");
+ auto past_lens = ov::test::utils::make_param(element::i32, PartialShape{DYN}, "past_lens");
+ auto subsequence_begins = ov::test::utils::make_param(element::i32, PartialShape{DYN}, "subsequence_begins");
+ auto block_indices_begins = ov::test::utils::make_param(element::i32, PartialShape{DYN}, "block_indices_begins");
+ auto block_indices = ov::test::utils::make_param(element::i32, PartialShape{DYN}, "block_indices");
+ auto position_ids = ov::test::utils::make_param(element::i64, PartialShape{DYN}, "position_ids");
+ auto key_cache = ov::test::utils::make_param(element::dynamic, PartialShape::dynamic(4), "key_cache.0");
+ auto value_cache = ov::test::utils::make_param(element::dynamic, PartialShape::dynamic(4), "value_cache.0");
+ ov::enable_keep_const_precision(key_cache);
+ ov::enable_keep_const_precision(value_cache);
+
+ // [B_token, hidden] -> [B_token, 1, hidden]
+ auto tokens = std::make_shared<v0::Unsqueeze>(inputs_embeds, v0::Constant::create(element::i32, Shape{}, {1}));
+
+ auto output = make_paged_sparse_attention(
+ test_case,
+ project_heads(tokens, num_heads, data_type),
+ project_heads(tokens, num_kv_heads, data_type),
+ project_heads(tokens, num_kv_heads, data_type),
+ {key_cache, value_cache, past_lens, subsequence_begins, block_indices, block_indices_begins},
+ selected_block_indices,
+ selected_block_count);
+
+ return std::make_shared<ov::Model>(OutputVector{output},
+ ParameterVector{inputs_embeds,
+ selected_block_indices,
+ selected_block_count,
+ key_length,
+ max_context_len,
+ past_lens,
+ subsequence_begins,
+ block_indices_begins,
+ block_indices,
+ position_ids,
+ key_cache,
+ value_cache});
+}
+
+// The model right after PagedSparseAttentionFusion alone, for the packed make_model([B_token, 1, hidden]):
+// SparseAttention is replaced by PagedSparseAttention, while the K/V states stay in the graph, because removing
+// their Assigns and registering the new inputs are done by SDPAToPagedAttention after its matcher passes.
+std::shared_ptr<ov::Model> make_fusion_model_ref(const Case& test_case) {
+ const auto& data_type = test_case.data_type;
+ auto inputs_embeds = ov::test::utils::make_param(data_type, PartialShape{DYN, 1, hidden_size}, "inputs_embeds");
+ auto beam_idx = ov::test::utils::make_param(element::i32, PartialShape{DYN}, "beam_idx");
+ auto selected_block_indices =
+ ov::test::utils::make_param(test_case.selection_type, PartialShape{DYN, 1, DYN, 2}, "selected_block_indices");
+ auto selected_block_count =
+ ov::test::utils::make_param(test_case.selection_type, PartialShape{DYN, 1, DYN}, "selected_block_count");
+ auto key_length = ov::test::utils::make_param(element::i64, PartialShape{DYN}, "key_length");
+
+ // Inputs created by the fusion, in the order it adds them to PaParams.
+ auto key_cache = ov::test::utils::make_param(element::dynamic, PartialShape::dynamic(4), "key_cache.0");
+ auto value_cache = ov::test::utils::make_param(element::dynamic, PartialShape::dynamic(4), "value_cache.0");
+ ov::enable_keep_const_precision(key_cache);
+ ov::enable_keep_const_precision(value_cache);
+ auto past_lens = ov::test::utils::make_param(element::i32, PartialShape{DYN}, "past_lens");
+ auto subsequence_begins = ov::test::utils::make_param(element::i32, PartialShape{DYN}, "subsequence_begins");
+ auto block_indices = ov::test::utils::make_param(element::i32, PartialShape{DYN}, "block_indices");
+ auto block_indices_begins = ov::test::utils::make_param(element::i32, PartialShape{DYN}, "block_indices_begins");
+
+ // The current K/V feed both the remaining state chain and PagedSparseAttention.
+ auto query = project_heads(inputs_embeds, num_heads, data_type);
+ auto key = project_heads(inputs_embeds, num_kv_heads, data_type);
+ auto value = project_heads(inputs_embeds, num_kv_heads, data_type);
+ auto make_cache = [&](const std::string& name, const Output<Node>& current) {
+ auto variable = make_kv_variable(name, data_type);
+ auto read_value = std::make_shared<v6::ReadValue>(variable);
+ auto past =
+ std::make_shared<v8::Gather>(read_value, beam_idx, v0::Constant::create(element::i64, Shape{}, {0}));
+ auto concat = std::make_shared<v0::Concat>(OutputVector{past, current}, 2);
+ return std::make_shared<v6::Assign>(concat, variable);
+ };
+ auto key_assign = make_cache("key.0", key);
+ auto value_assign = make_cache("value.0", value);
+
+ auto output = make_paged_sparse_attention(
+ test_case,
+ query,
+ key,
+ value,
+ {key_cache, value_cache, past_lens, subsequence_begins, block_indices, block_indices_begins},
+ selected_block_indices,
+ selected_block_count);
+
+ return std::make_shared<ov::Model>(OutputVector{output},
+ SinkVector{key_assign, value_assign},
+ ParameterVector{inputs_embeds,
+ beam_idx,
+ selected_block_indices,
+ selected_block_count,
+ key_length,
+ key_cache,
+ value_cache,
+ past_lens,
+ subsequence_begins,
+ block_indices,
+ block_indices_begins});
+}
+
+const std::vector<Case> cases = {
+ {"default_scale"},
+ {"i64_selection", element::f32, element::i64},
+ {"scalar_scale", element::f32, element::i32, Scale::Scalar},
+ {"vector_scale", element::f32, element::i32, Scale::Vector1},
+ {"sinks", element::f32, element::i32, Scale::Scalar, element::f32},
+ {"f16_with_f32_sinks", element::f16, element::i32, Scale::Scalar, element::f32},
+};
+} // namespace paged_sparse_attention_pattern
+
+class PagedSparseAttentionFusionTest : public TransformationTestsF,
+ public WithParamInterface<paged_sparse_attention_pattern::Case> {
+public:
+ static std::string getTestCaseName(const TestParamInfo<paged_sparse_attention_pattern::Case>& info) {
+ return info.param.name;
+ }
+
+protected:
+ void SetUp() override {
+ TransformationTestsF::SetUp();
+ manager.set_per_pass_validation(false);
+ manager.register_pass<ov::pass::PagedSparseAttentionFusion>(pa_params, options, var_ids_to_remove);
+ }
+
+ // The fusion keeps references to these until the passes run in TearDown.
+ ov::pass::paged_attention::PaParams pa_params;
+ ov::pass::paged_attention::Options options{};
+ std::unordered_set<std::string> var_ids_to_remove;
+};
+
+TEST_P(PagedSparseAttentionFusionTest, SDPAToPA_Qwen38FlashNext_PagedSparseAttentionFusion) {
+ // Packed shapes, as the fusion sees them inside SDPAToPagedAttention.
+ model =
+ paged_sparse_attention_pattern::make_model(GetParam(),
+ PartialShape{DYN, 1, paged_sparse_attention_pattern::hidden_size});
+ model_ref = paged_sparse_attention_pattern::make_fusion_model_ref(GetParam());
+
+ comparator.enable(FunctionsComparator::CONST_VALUES);
+ comparator.enable(FunctionsComparator::ATTRIBUTES);
+ disable_rt_info_check();
+}
+
+class SDPAToPAPagedSparseAttentionTest : public TransformationTestsF,
+ public WithParamInterface<paged_sparse_attention_pattern::Case> {};
+
+TEST_P(SDPAToPAPagedSparseAttentionTest, SDPAToPA_Qwen38FlashNext_PagedSparseAttentionFusionPattern) {
+ model = paged_sparse_attention_pattern::make_model(GetParam());
+ model_ref = paged_sparse_attention_pattern::make_model_ref(GetParam());
+ manager.register_pass<ov::pass::SDPAToPagedAttention>();
+
+ comparator.enable(FunctionsComparator::CONST_VALUES);
+ comparator.enable(FunctionsComparator::ATTRIBUTES);
+ disable_rt_info_check();
+}
+
+INSTANTIATE_TEST_SUITE_P(SDPAToPA,
+ PagedSparseAttentionFusionTest,
+ ValuesIn(paged_sparse_attention_pattern::cases),
+ PagedSparseAttentionFusionTest::getTestCaseName);
+
+INSTANTIATE_TEST_SUITE_P(SDPAToPA,
+ SDPAToPAPagedSparseAttentionTest,
+ ValuesIn(paged_sparse_attention_pattern::cases),
+ PagedSparseAttentionFusionTest::getTestCaseName);
+
/*
As there's often a need to cover specific model's architecutres in these
tests, please, make sure you name the tests in the following manner:
diff --git a/src/common/transformations/tests/utils/utils_test.cpp b/src/common/transformations/tests/utils/utils_test.cpp
index 98d941db00d..401e3bea167 100644
--- a/src/common/transformations/tests/utils/utils_test.cpp
+++ b/src/common/transformations/tests/utils/utils_test.cpp
@@ -10,6 +10,11 @@
#include <queue>
#include <string>
+#include "openvino/core/model.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/relu.hpp"
+#include "openvino/op/sigmoid.hpp"
+#include "openvino/op/tanh.hpp"
#include "openvino/opsets/opset4_decl.hpp"
using namespace ov;
@@ -75,3 +80,14 @@ TEST(TransformationTests, HasConstantValueHelper) {
int64_scalar = opset4::Constant::create(element::i64, Shape{}, {12});
ASSERT_FALSE(op_util::has_constant_value<int64_t>(int64_scalar, 13));
}
+
+TEST(TransformationTests, HasOpWithTypeHelper) {
+ auto param = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{1});
+ auto relu = std::make_shared<ov::op::v0::Relu>(param);
+ auto model = std::make_shared<Model>(OutputVector{relu}, ParameterVector{param});
+
+ EXPECT_TRUE(op_util::has_op_with_type<ov::op::v0::Relu>(model));
+ EXPECT_FALSE(op_util::has_op_with_type<ov::op::v0::Sigmoid>(model));
+ EXPECT_TRUE((op_util::has_op_with_type<ov::op::v0::Sigmoid, ov::op::v0::Relu>(model)));
+ EXPECT_FALSE((op_util::has_op_with_type<ov::op::v0::Sigmoid, ov::op::v0::Tanh>(model)));
+}
diff --git a/src/core/include/openvino/pass/sdpa_to_paged_attention.hpp b/src/core/include/openvino/pass/sdpa_to_paged_attention.hpp
index fb9d7265264..1dcccadbe52 100644
--- a/src/core/include/openvino/pass/sdpa_to_paged_attention.hpp
+++ b/src/core/include/openvino/pass/sdpa_to_paged_attention.hpp
@@ -149,8 +149,8 @@ struct PaResults : public NamedNodeStore<ov::op::v0::Result, ov::ResultVector> {
* @brief The transformation replaces KV-cache processing part in LLMs by PagedAttention operation.
* NOTE:
* The transformation may throw an exception when some configuration of the model failed:
- * i.e. the SDPA node is absent in the model. This means the graph cannot be processed for the PA scenario,
- * so the GenAI pipeline (the only pipeline the transformation is used in so far) will fallback to the SDPA
+ * i.e. both SDPA and SparseAttention nodes are absent in the model. This means the graph cannot be processed for the PA
+ * scenario, so the GenAI pipeline (the only pipeline the transformation is used in so far) will fallback to the SDPA
* implementaion and run inference using it.
* \ingroup ov_pass_cpp_api
*/
diff --git a/src/core/src/pass/sdpa_to_paged_attention.cpp b/src/core/src/pass/sdpa_to_paged_attention.cpp
index 538c6d63db5..a92d2cdb65f 100644
--- a/src/core/src/pass/sdpa_to_paged_attention.cpp
+++ b/src/core/src/pass/sdpa_to_paged_attention.cpp
@@ -11,6 +11,7 @@
#include "openvino/op/gather.hpp"
#include "openvino/op/scaled_dot_product_attention.hpp"
#include "openvino/op/shape_of.hpp"
+#include "openvino/op/sparse_attention.hpp"
#include "openvino/op/subtract.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "openvino/pass/manager.hpp"
@@ -25,6 +26,7 @@
#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/paged_sparse_attention_fusion.hpp"
#include "transformations/paged_attention/position_ids_replacer.hpp"
#include "transformations/paged_attention/prev_sequence_length_pattern.hpp"
#include "transformations/paged_attention/state_management_pattern.hpp"
@@ -84,8 +86,10 @@ bool ov::pass::SDPAToPagedAttention::run_on_model(const std::shared_ptr<ov::Mode
"For proper conversion run: optimum-cli export openvino --task text-generation-with-past instead "
"of --task text-generation");
- OPENVINO_ASSERT(ov::op::util::has_op_with_type<ov::op::v13::ScaledDotProductAttention>(model),
- "No ScaledDotProductAttention operation observed in the graph, cannot perform "
+ const bool has_attention =
+ ov::op::util::has_op_with_type<ov::op::v13::ScaledDotProductAttention, ov::op::v17::SparseAttention>(model);
+ OPENVINO_ASSERT(has_attention,
+ "No ScaledDotProductAttention or SparseAttention operation observed in the graph, cannot perform "
"the SDPAToPagedAttention transformation.");
m_params = PaParams{model->get_parameters()};
@@ -120,6 +124,15 @@ bool ov::pass::SDPAToPagedAttention::run_on_model(const std::shared_ptr<ov::Mode
target.replace_source_output(processed_input_ids);
}
+ if (const auto ngram_embeddings = get_parameter(model, "ngram_embeddings")) {
+ const auto ngram_shape = ngram_embeddings->get_partial_shape();
+ OPENVINO_ASSERT(ngram_shape.rank().is_static() && ngram_shape.rank().get_length() == 4,
+ "Unexpected shape for ngram_embeddings input: expected rank 4 "
+ "[batch, seq_len, num_ngrams, embedding_size], observed ",
+ ngram_shape);
+ ngram_embeddings->set_partial_shape(PartialShape{-1, 1, ngram_shape[2], ngram_shape[3]});
+ }
+
std::unordered_set<std::string> var_ids_to_remove;
std::unordered_set<std::string> params_to_remove{"beam_idx", "attention_mask"};
@@ -167,6 +180,7 @@ bool ov::pass::SDPAToPagedAttention::run_on_model(const std::shared_ptr<ov::Mode
} else {
manager.register_pass<StateManagementPattern>(m_params, m_results, m_options, var_ids_to_remove);
}
+ manager.register_pass<PagedSparseAttentionFusion>(m_params, m_options, var_ids_to_remove);
manager.register_pass<EliminateConvPaddingMaskGating>();
auto paged_ssm_fusion = manager.register_pass<PagedSelectiveSSMFusion>(m_params, var_ids_to_remove);
manager.register_pass<PagedCausalConv1DFusion>(m_params, var_ids_to_remove);