Skip to content

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

[Transformations] Add Paged SSM Fusion (#37391)

Andrii Staikov494512b6f666
diff --git a/src/common/transformations/include/transformations/common_optimizations/fuse_ssm.hpp b/src/common/transformations/include/transformations/common_optimizations/fuse_ssm.hpp
index 145fe6ba3b6..861d3710cd6 100644
--- a/src/common/transformations/include/transformations/common_optimizations/fuse_ssm.hpp
+++ b/src/common/transformations/include/transformations/common_optimizations/fuse_ssm.hpp
@@ -84,7 +84,7 @@ public:
class TRANSFORMATIONS_API FuseSSMLoop : public ov::pass::MatcherPass {
public:
OPENVINO_MATCHER_PASS_RTTI("FuseSSMLoop");
- FuseSSMLoop();
+ FuseSSMLoop(size_t& fused_count);
};
/// This pass transforms a loop-based SSM sub-graph into a single internal `SelectiveSSM` operation.
@@ -124,6 +124,13 @@ public:
OPENVINO_MODEL_PASS_RTTI("SelectiveSSMFusion");
SelectiveSSMFusion() = default;
bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+
+ size_t get_fused_count() const {
+ return m_fused_count;
+ }
+
+private:
+ size_t m_fused_count = 0;
};
} // namespace ov::pass
diff --git a/src/common/transformations/include/transformations/paged_attention/paged_selective_ssm_fusion.hpp b/src/common/transformations/include/transformations/paged_attention/paged_selective_ssm_fusion.hpp
new file mode 100644
index 00000000000..b3c7da36841
--- /dev/null
+++ b/src/common/transformations/include/transformations/paged_attention/paged_selective_ssm_fusion.hpp
@@ -0,0 +1,80 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#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 Fuses SelectiveSSM into internal::PagedSelectiveSSM with paged attention.
+ *
+ * The stateful SelectiveSSM keeps its recurrent state in a Variable that is read through
+ * ReadValue. For continuous batching that state has to be managed through a paged block
+ * table instead. This pass replaces the matched SelectiveSSM with internal::PagedSelectiveSSM,
+ * wiring in the shared paged-attention scheduling parameters and a per-layer state table.
+ *
+ * Graph before:
+ *
+ * (ReadValue)
+ * recurrent_state
+ * A dt B x C |
+ * | | | | | |
+ * v v v v v v
+ * +--------------------------------------+
+ * | SelectiveSSM |
+ * +--------------------------------------+
+ * | |
+ * out0 | y state | out1
+ * v v
+ * Assign
+ *
+ * is transformed to
+ *
+ * After - PagedSelectiveSSM, recurrent state kept in a paged block table:
+ *
+ * A per-head decay rates [num_heads]
+ * dt, B, x, C flattened [batch, len, ...] -> [tokens, ...]
+ * selective_ssm_state_table.N paged state table, updated in place
+ * subsequence_begins per-sequence token spans
+ * la.block_indices logical -> physical block rows
+ * la.block_indices_begins per-sequence block spans
+ * la.past_lens num_processed_tokens
+ * la.cache_interval state snapshot interval
+ * | (11 inputs)
+ * v
+ * +--------------------------------------+
+ * | PagedSelectiveSSM | (11 inputs, 1 output)
+ * +--------------------------------------+
+ * |
+ * out0 | y
+ * v
+ * Reshape -> restore [batch, len, num_heads, head_dim]
+ * v
+ * ...
+ */
+class TRANSFORMATIONS_API PagedSelectiveSSMFusion : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("PagedSelectiveSSMFusion");
+ PagedSelectiveSSMFusion(ov::pass::paged_attention::PaParams& pa_params,
+ std::unordered_set<std::string>& var_ids_to_remove);
+
+ // Number of SelectiveSSM nodes converted to PagedSelectiveSSM once the pass has run.
+ size_t get_fused_count() const {
+ return m_layer_index;
+ }
+
+private:
+ size_t m_layer_index = 0;
+};
+
+} // namespace pass
+} // namespace ov
diff --git a/src/common/transformations/src/sources.cmake b/src/common/transformations/src/sources.cmake
index 58edf81977f..a5ba00a8166 100644
--- a/src/common/transformations/src/sources.cmake
+++ b/src/common/transformations/src/sources.cmake
@@ -251,6 +251,7 @@ set(PAGED_ATTENTION_SOURCES
${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/eliminate_conv_padding_mask_gating.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_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.cpp
${CMAKE_CURRENT_LIST_DIR}/transformations/paged_attention/state_management_pattern.cpp
diff --git a/src/common/transformations/src/transformations/common_optimizations/fuse_ssm.cpp b/src/common/transformations/src/transformations/common_optimizations/fuse_ssm.cpp
index a7f29f351aa..9294ac97b55 100644
--- a/src/common/transformations/src/transformations/common_optimizations/fuse_ssm.cpp
+++ b/src/common/transformations/src/transformations/common_optimizations/fuse_ssm.cpp
@@ -160,7 +160,7 @@ ov::pass::RemoveConcatSliceAfterLoopSSM::RemoveConcatSliceAfterLoopSSM() {
register_matcher(m, callback);
}
-ov::pass::FuseSSMLoop::FuseSSMLoop() {
+ov::pass::FuseSSMLoop::FuseSSMLoop(size_t& fused_count) {
auto dt = pattern::any_input(pattern::shape_matches("[?, ?, head_num]"));
auto x = pattern::any_input(pattern::shape_matches("[?, ?, head_num, head_dim]"));
auto init_state = pattern::any_input(pattern::shape_matches("[?, head_num, head_dim, state_size]"));
@@ -201,7 +201,7 @@ ov::pass::FuseSSMLoop::FuseSSMLoop() {
init_state,
pattern::any_input()}); // output accumulator buffer
- ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {
+ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS, &fused_count](ov::pass::pattern::Matcher& m) {
const auto& pattern_map = m.get_pattern_value_map();
auto loop_node = pattern_map.at(loop_output).get_node_shared_ptr();
@@ -223,6 +223,7 @@ ov::pass::FuseSSMLoop::FuseSSMLoop() {
ov::copy_runtime_info(m.get_matched_nodes(), selective_ssm);
ov::replace_node(loop_node, selective_ssm);
+ ++fused_count;
return true;
};
@@ -235,6 +236,6 @@ bool ov::pass::SelectiveSSMFusion::run_on_model(const std::shared_ptr<ov::Model>
ov::pass::SymbolicOptimizations symbolic_optimizations(false, get_pass_config());
auto symbolic_ctx_manager = symbolic_optimizations.get_manager();
symbolic_ctx_manager->register_pass<ov::pass::RemoveConcatSliceAfterLoopSSM>();
- symbolic_ctx_manager->register_pass<ov::pass::FuseSSMLoop>();
+ symbolic_ctx_manager->register_pass<ov::pass::FuseSSMLoop>(m_fused_count);
return symbolic_optimizations.run_on_model(model);
}
diff --git a/src/common/transformations/src/transformations/paged_attention/paged_selective_ssm_fusion.cpp b/src/common/transformations/src/transformations/paged_attention/paged_selective_ssm_fusion.cpp
new file mode 100644
index 00000000000..3076fec9696
--- /dev/null
+++ b/src/common/transformations/src/transformations/paged_attention/paged_selective_ssm_fusion.cpp
@@ -0,0 +1,169 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "transformations/paged_attention/paged_selective_ssm_fusion.hpp"
+
+#include <memory>
+#include <string>
+#include <unordered_set>
+
+#include "itt.hpp"
+#include "openvino/core/graph_util.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_selective_ssm.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/selective_ssm.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/util/read_value_base.hpp"
+#include "openvino/pass/pattern/matcher.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "transformations/rt_info/keep_const_precision.hpp"
+
+using ov::pass::pattern::any_input;
+using ov::pass::pattern::optional;
+using ov::pass::pattern::wrap_type;
+
+namespace v0 = ov::op::v0;
+
+namespace {
+
+constexpr const char* SELECTIVE_SSM_STATE_TABLE_PREFIX = "selective_ssm_state_table.";
+
+std::string make_selective_ssm_state_table_name(const size_t layer_index) {
+ return std::string(SELECTIVE_SSM_STATE_TABLE_PREFIX) + std::to_string(layer_index);
+}
+
+ov::PartialShape make_selective_ssm_state_table_shape(const ov::PartialShape& state_shape) {
+ // SelectiveSSM recurrent_state shape is [B, H, D, S].
+ // PagedSelectiveSSM state table keeps the same head/head_dim/state_size layout but
+ // replaces the batch dimension with the (dynamic) number of physical blocks.
+ if (state_shape.rank().is_static() && state_shape.rank().get_length() == 4) {
+ return ov::PartialShape{ov::Dimension::dynamic(), state_shape[1], state_shape[2], state_shape[3]};
+ }
+ return ov::PartialShape::dynamic(4);
+}
+
+// Flattens [B, L, ...tail] to [B*L, ...tail] via a runtime shape subgraph, keeping every dim past batch and length.
+// The [-1, ...tail] target shape is assembled from ShapeOf so dynamic trailing dims are handled; it constant-folds
+// to a literal shape when the trailing dims are static.
+ov::Output<ov::Node> flatten_batch_length(const ov::Output<ov::Node>& input) {
+ const auto rank = input.get_partial_shape().size();
+ std::vector<int64_t> tail_dim_indices;
+ tail_dim_indices.reserve(rank - 2);
+ for (size_t i = 2; i < rank; ++i) {
+ tail_dim_indices.push_back(static_cast<int64_t>(i));
+ }
+
+ const auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(input, ov::element::i64);
+ const auto tail_idx = v0::Constant::create(ov::element::i64, ov::Shape{tail_dim_indices.size()}, tail_dim_indices);
+ const auto axis_0 = v0::Constant::create(ov::element::i64, ov::Shape{}, {0});
+ const auto tail_dims = std::make_shared<ov::op::v8::Gather>(shape_of, tail_idx, axis_0);
+ const auto flat_dim = v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1});
+ const auto flat_shape = std::make_shared<v0::Concat>(ov::OutputVector{flat_dim, tail_dims}, 0);
+ const auto reshaped = std::make_shared<ov::op::v1::Reshape>(input, flat_shape, false);
+
+ ov::copy_runtime_info(input.get_node_shared_ptr(), {shape_of, tail_dims, flat_shape, reshaped});
+ return reshaped;
+}
+} // namespace
+
+namespace ov::pass {
+
+PagedSelectiveSSMFusion::PagedSelectiveSSMFusion(ov::pass::paged_attention::PaParams& pa_params,
+ std::unordered_set<std::string>& var_ids_to_remove) {
+ // SelectiveSSM inputs: A, dt, B, x, C, recurrent_state (state at index 5).
+ auto a = any_input(ov::pass::pattern::rank_equals(1));
+ auto dt = any_input(ov::pass::pattern::rank_equals(3));
+ auto b = any_input(ov::pass::pattern::rank_equals(4));
+ auto x = any_input(ov::pass::pattern::rank_equals(4));
+ auto c = any_input(ov::pass::pattern::rank_equals(4));
+
+ auto cache_param = any_input();
+ auto read_value = wrap_type<ov::op::util::ReadValueBase>({cache_param});
+ auto gathered_state = optional<ov::op::util::GatherBase>({read_value, any_input(), any_input()});
+ auto ssm = wrap_type<ov::op::internal::SelectiveSSM>({a, dt, b, x, c, gathered_state});
+
+ ov::matcher_pass_callback callback =
+ [OV_CAPTURE_CPY_AND_THIS, &pa_params, &var_ids_to_remove](ov::pass::pattern::Matcher& m) {
+ if (transformation_callback(m.get_match_root())) {
+ return false;
+ }
+
+ const auto& pm = m.get_pattern_value_map();
+ const auto ssm_node = ov::as_type_ptr<ov::op::internal::SelectiveSSM>(pm.at(ssm).get_node_shared_ptr());
+ if (!ssm_node || ssm_node->get_output_size() != 2) {
+ return false;
+ }
+
+ pa_params.add("subsequence_begins", ov::element::i32, ov::PartialShape{-1});
+ pa_params.add("la.block_indices", ov::element::i32, ov::PartialShape{-1});
+ pa_params.add("la.block_indices_begins", ov::element::i32, ov::PartialShape{-1});
+ pa_params.add("la.past_lens", ov::element::i32, ov::PartialShape{-1});
+ pa_params.add("la.cache_interval", ov::element::i32, ov::PartialShape{-1});
+
+ const auto state_consumers = ssm_node->output(1).get_target_inputs();
+ const auto& state_out = pm.at(read_value);
+
+ const auto state_table_param =
+ pa_params.add(make_selective_ssm_state_table_name(m_layer_index++),
+ ov::element::dynamic,
+ make_selective_ssm_state_table_shape(state_out.get_partial_shape()));
+ enable_keep_const_precision(state_table_param);
+
+ const auto rv = ov::as_type_ptr<ov::op::util::ReadValueBase>(pm.at(read_value).get_node_shared_ptr());
+ OPENVINO_ASSERT(rv, "Matched cache node is expected to be ReadValue");
+ var_ids_to_remove.insert(rv->get_variable_id());
+
+ // Flatten [B, L, ...] inputs to [B*L, ...]. A carries no batch/length dims and is passed through.
+ const auto dt_flat = flatten_batch_length(pm.at(dt));
+ const auto b_flat = flatten_batch_length(pm.at(b));
+ const auto x_flat = flatten_batch_length(pm.at(x));
+ const auto c_flat = flatten_batch_length(pm.at(c));
+
+ const auto paged_ssm =
+ std::make_shared<ov::op::internal::PagedSelectiveSSM>(pm.at(a),
+ dt_flat,
+ b_flat,
+ x_flat,
+ c_flat,
+ state_table_param->output(0),
+ pa_params["subsequence_begins"],
+ pa_params["la.block_indices"],
+ pa_params["la.block_indices_begins"],
+ pa_params["la.past_lens"],
+ pa_params["la.cache_interval"]);
+
+ paged_ssm->set_friendly_name(ssm_node->get_friendly_name() + "/PagedSelectiveSSM");
+
+ // PagedSelectiveSSM output is [B*L, H, D]; reshape back to the matched SelectiveSSM output [B, L, H, D].
+ const auto x_shape = std::make_shared<ov::op::v3::ShapeOf>(pm.at(x), ov::element::i64);
+ const auto paged_ssm_out = std::make_shared<ov::op::v1::Reshape>(paged_ssm, x_shape, false);
+ paged_ssm_out->set_friendly_name(ssm_node->get_friendly_name());
+
+ ov::copy_runtime_info(ssm_node, {paged_ssm, x_shape, paged_ssm_out});
+
+ // Reconnect consumer to the original state source so it becomes a dead branch.
+ for (const auto& state_consumer : state_consumers) {
+ state_consumer.replace_source_output(ssm_node->input_value(5));
+ }
+
+ if (!ov::replace_output_update_name(ssm_node->output(0), paged_ssm_out->output(0))) {
+ ssm_node->output(0).replace(paged_ssm_out->output(0));
+ }
+
+ register_new_node(paged_ssm_out);
+ register_new_node(paged_ssm);
+ return true;
+ };
+
+ const auto matcher = std::make_shared<ov::pass::pattern::Matcher>(ssm, "PagedSelectiveSSMFusion");
+ register_matcher(matcher, callback);
+}
+
+} // namespace ov::pass
diff --git a/src/common/transformations/tests/common_optimizations/fuse_ssm.cpp b/src/common/transformations/tests/common_optimizations/fuse_ssm.cpp
index b08904d0d83..92a7858d0f5 100644
--- a/src/common/transformations/tests/common_optimizations/fuse_ssm.cpp
+++ b/src/common/transformations/tests/common_optimizations/fuse_ssm.cpp
@@ -6,185 +6,20 @@
#include <gtest/gtest.h>
-#include <climits>
#include <memory>
#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/assign.hpp"
#include "openvino/op/constant.hpp"
-#include "openvino/op/convert.hpp"
-#include "openvino/op/exp.hpp"
-#include "openvino/op/gather.hpp"
-#include "openvino/op/loop.hpp"
-#include "openvino/op/multiply.hpp"
-#include "openvino/op/reduce_prod.hpp"
-#include "openvino/op/reduce_sum.hpp"
-#include "openvino/op/reshape.hpp"
#include "openvino/op/result.hpp"
-#include "openvino/op/scatter_update.hpp"
#include "openvino/op/selective_ssm.hpp"
-#include "openvino/op/shape_of.hpp"
-#include "openvino/op/slice.hpp"
-#include "openvino/op/squeeze.hpp"
-#include "openvino/op/subtract.hpp"
-#include "openvino/op/tile.hpp"
-#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/util/variable.hpp"
+#include "ssm_test_models.hpp"
namespace ov::test {
namespace {
-// Builds a loop-based SSM recurrence model matching the time-major export where all
-// discretization is performed outside the loop and consumed as 5D per-step slices:
-// dA = reshape(exp(A * dt), [B, T, H, 1, 1]) (Loop input 2)
-// dBx = unsqueeze(dt*B, -2) * unsqueeze(x, -1) -> [B, T, H, P, N] (Loop input 3)
-// C = unsqueeze(C_expanded, -2) -> [B, T, H, 1, N] (Loop input 4)
-// Per step: state_t = state_{t-1} * dA_t + dBx_t; y_t = reduce_sum(state_t * C_t, axis=state_size).
-// B/C are provided per group and expanded to heads via Unsqueeze/Tile/Reshape outside the loop.
-// External Loop inputs (in order): trip_count, exec_cond, dA, dBx, C, recurrent_state, output_buffer.
-// External Loop outputs: output[B,T,H,P], output_recurrent_state[B,H,P,N].
-//
-// \param with_post_loop appends the flatten/Concat/Slice/Reshape round-trip seen in real models.
-// \param break_body replaces the state `Add` with `Subtract` so the body no longer matches the SSM recurrence.
-std::shared_ptr<ov::Model> build_looped_ssm(int32_t num_heads,
- int32_t num_groups,
- int32_t head_dim,
- int32_t state_size,
- bool with_post_loop = false,
- bool break_body = false) {
- using namespace ov::op;
-
- const auto dtype = ov::element::f32;
- const int32_t heads_per_group = num_heads / num_groups;
-
- ov::PartialShape dt_shape{-1, -1, num_heads};
- ov::PartialShape B_shape{-1, -1, num_groups, state_size};
- ov::PartialShape x_shape{-1, -1, num_heads, head_dim};
- ov::PartialShape C_shape{-1, -1, num_groups, state_size};
- ov::PartialShape state_shape{-1, num_heads, head_dim, state_size};
-
- auto dt = std::make_shared<v0::Parameter>(dtype, dt_shape);
- auto B = std::make_shared<v0::Parameter>(dtype, B_shape);
- auto x = std::make_shared<v0::Parameter>(dtype, x_shape);
- auto C = std::make_shared<v0::Parameter>(dtype, C_shape);
- auto h0 = std::make_shared<v0::Parameter>(dtype, state_shape);
-
- // A is a per-head constant embedded in the graph (log-decay rates).
- auto A = v0::Constant::create(dtype, {static_cast<size_t>(num_heads)}, std::vector<float>(num_heads, -0.5f));
-
- // Expand B/C from [B, T, G, N] to [B, T, H, N] via Unsqueeze -> Tile -> Reshape.
- auto expand_groups = [&](const std::shared_ptr<v0::Parameter>& src) {
- auto unsq_axis = v0::Constant::create(ov::element::i32, {}, {3});
- auto src_5d = std::make_shared<v0::Unsqueeze>(src, unsq_axis);
- auto tile_shape = v0::Constant::create(ov::element::i64, {5}, {1, 1, 1, heads_per_group, 1});
- auto tiled = std::make_shared<v0::Tile>(src_5d, tile_shape);
- auto target = v0::Constant::create(ov::element::i64, {4}, {0, 0, num_heads, state_size});
- return std::make_shared<v1::Reshape>(tiled, target, true);
- };
- auto B_expanded = expand_groups(B);
- auto C_expanded = expand_groups(C);
-
- // Discretization is performed outside the loop and materialized as 5D per-step tensors:
- // dA = reshape(exp(A * dt), [B, T, H, 1, 1])
- // dBx = unsqueeze(unsqueeze(dt, -1) * B_expanded, -2) * unsqueeze(x, -1) -> [B, T, H, P, N]
- // C = unsqueeze(C_expanded, -2) -> [B, T, H, 1, N]
- auto minus1_outer = v0::Constant::create(ov::element::i32, {1}, {-1});
- auto minus2_outer = v0::Constant::create(ov::element::i32, {1}, {-2});
- auto dA_shape = v0::Constant::create(ov::element::i64, {5}, {0, 0, 0, 1, 1});
- auto dA_outer =
- std::make_shared<v1::Reshape>(std::make_shared<v0::Exp>(std::make_shared<v1::Multiply>(A, dt)), dA_shape, true);
- auto dB_outer = std::make_shared<v1::Multiply>(std::make_shared<v0::Unsqueeze>(dt, minus1_outer), B_expanded);
- auto dBx_outer = std::make_shared<v1::Multiply>(std::make_shared<v0::Unsqueeze>(dB_outer, minus2_outer),
- std::make_shared<v0::Unsqueeze>(x, minus1_outer));
- auto C_5d_outer = std::make_shared<v0::Unsqueeze>(C_expanded, minus2_outer);
-
- // output accumulator buffer: zeros with shape [B, T, H, P]
- auto shape_of_x = std::make_shared<v3::ShapeOf>(x);
- auto core_init = std::make_shared<v3::Broadcast>(v0::Constant::create(dtype, {}, {0.0f}), shape_of_x);
-
- // trip count = seq_len (dim 1 of x)
- auto trip_index = v0::Constant::create(ov::element::i64, {1}, {1});
- auto trip_axis = v0::Constant::create(ov::element::i64, {}, {0});
- auto trip_count_i64 = std::make_shared<v8::Gather>(shape_of_x, trip_index, trip_axis);
- auto trip_count = std::make_shared<v0::Convert>(trip_count_i64, ov::element::i32);
-
- // -------- Loop body --------
- auto timestep = std::make_shared<v0::Parameter>(ov::element::i32, ov::Shape{});
- auto dA_t = std::make_shared<v0::Parameter>(dtype, ov::PartialShape{-1, 1, num_heads, 1, 1});
- auto dBx_t = std::make_shared<v0::Parameter>(dtype, ov::PartialShape{-1, 1, num_heads, head_dim, state_size});
- auto C_t = std::make_shared<v0::Parameter>(dtype, ov::PartialShape{-1, 1, num_heads, 1, state_size});
- auto last_state = std::make_shared<v0::Parameter>(dtype, ov::PartialShape{-1, num_heads, head_dim, state_size});
- auto core_out = std::make_shared<v0::Parameter>(dtype, ov::PartialShape{-1, -1, num_heads, head_dim});
-
- auto axis1 = v0::Constant::create(ov::element::i32, {}, {1});
- auto minus1 = v0::Constant::create(ov::element::i32, {1}, {-1});
-
- auto dA_sq = std::make_shared<v0::Squeeze>(dA_t, axis1); // [B, H, 1, 1]
- auto dBx_sq = std::make_shared<v0::Squeeze>(dBx_t, axis1); // [B, H, P, N]
- auto C_sq = std::make_shared<v0::Squeeze>(C_t, axis1); // [B, H, 1, N]
-
- auto state_decay = std::make_shared<v1::Multiply>(last_state, dA_sq);
- std::shared_ptr<ov::Node> state_new;
- if (break_body) {
- state_new = std::make_shared<v1::Subtract>(state_decay, dBx_sq);
- } else {
- state_new = std::make_shared<v1::Add>(state_decay, dBx_sq);
- }
-
- auto y = std::make_shared<v1::Multiply>(state_new, C_sq);
- auto y_sum = std::make_shared<v1::ReduceSum>(y, minus1, false);
- auto y_unsq = std::make_shared<v0::Unsqueeze>(y_sum, axis1);
-
- auto timestep_unsq = std::make_shared<v0::Unsqueeze>(timestep, v0::Constant::create(ov::element::i32, {1}, {0}));
- auto core_out_new = std::make_shared<v3::ScatterUpdate>(core_out, timestep_unsq, y_unsq, axis1);
-
- auto body_cond = v0::Constant::create(ov::element::boolean, {1}, {true});
- auto body = std::make_shared<ov::Model>(ov::OutputVector{body_cond, state_new, core_out_new},
- ov::ParameterVector{timestep, dA_t, dBx_t, C_t, last_state, core_out},
- "ssm_body");
-
- // -------- Loop --------
- auto loop = std::make_shared<v5::Loop>(trip_count, v0::Constant::create(ov::element::boolean, {1}, {true}));
- loop->set_function(body);
- loop->set_sliced_input(dA_t, dA_outer, 0, 1, 1, -1, 1);
- loop->set_sliced_input(dBx_t, dBx_outer, 0, 1, 1, -1, 1);
- loop->set_sliced_input(C_t, C_5d_outer, 0, 1, 1, -1, 1);
- loop->set_merged_input(last_state, h0, state_new);
- loop->set_merged_input(core_out, core_init, core_out_new);
- loop->set_special_body_ports({0, 0});
-
- auto output = loop->get_iter_value(core_out_new, -1); // Loop output(0)
- auto state_out = loop->get_iter_value(state_new, -1); // Loop output(1)
-
- ov::Output<ov::Node> final_output = output;
- ov::Output<ov::Node> final_state = state_out;
-
- if (with_post_loop) {
- auto reshape_m1 = v0::Constant::create(ov::element::i64, {1}, {-1});
- auto flat_out = std::make_shared<v1::Reshape>(output, reshape_m1, false);
- auto flat_state = std::make_shared<v1::Reshape>(state_out, reshape_m1, false);
- auto packed = std::make_shared<v0::Concat>(ov::OutputVector{flat_out, flat_state}, 0);
-
- auto out_shape = std::make_shared<v3::ShapeOf>(core_init);
- auto state_ref_shape = std::make_shared<v3::ShapeOf>(h0);
- auto reduce_axis0 = v0::Constant::create(ov::element::i64, {1}, {0});
- auto out_numel = std::make_shared<v1::ReduceProd>(out_shape, reduce_axis0, true);
-
- auto s_start = v0::Constant::create(ov::element::i64, {1}, {0});
- auto s_step = v0::Constant::create(ov::element::i64, {1}, {1});
- auto s_axis = v0::Constant::create(ov::element::i64, {1}, {0});
- auto s_end_inf = v0::Constant::create(ov::element::i64, {1}, {LLONG_MAX});
-
- auto out_slice = std::make_shared<v8::Slice>(packed, s_start, out_numel, s_step, s_axis);
- auto state_slice = std::make_shared<v8::Slice>(packed, out_numel, s_end_inf, s_step, s_axis);
- final_output = std::make_shared<v1::Reshape>(out_slice, out_shape, false);
- final_state = std::make_shared<v1::Reshape>(state_slice, state_ref_shape, false);
- }
-
- return std::make_shared<ov::Model>(ov::OutputVector{final_output, final_state},
- ov::ParameterVector{dt, B, x, C, h0});
-}
+using ov::test::ssm::build_looped_ssm;
std::shared_ptr<ov::Model> build_fused_ssm(int32_t num_heads,
int32_t num_groups,
@@ -203,13 +38,20 @@ std::shared_ptr<ov::Model> build_fused_ssm(int32_t num_heads,
auto B = std::make_shared<v0::Parameter>(dtype, B_shape);
auto x = std::make_shared<v0::Parameter>(dtype, x_shape);
auto C = std::make_shared<v0::Parameter>(dtype, C_shape);
- auto h0 = std::make_shared<v0::Parameter>(dtype, state_shape);
auto A = v0::Constant::create(dtype, {static_cast<size_t>(num_heads)}, std::vector<float>(num_heads, -0.5f));
- auto ssm = std::make_shared<ov::op::internal::SelectiveSSM>(ov::OutputVector{A, dt, B, x, C, h0});
+ const auto state_src = ssm::make_recurrent_state_source(state_shape, /*plain_parameter_state=*/false);
+ auto ssm = std::make_shared<ov::op::internal::SelectiveSSM>(ov::OutputVector{A, dt, B, x, C, state_src.state});
+
+ ov::ParameterVector params{dt, B, x, C};
+ params.insert(params.end(), state_src.params.begin(), state_src.params.end());
- return std::make_shared<ov::Model>(ov::OutputVector{ssm->output(0), ssm->output(1)},
- ov::ParameterVector{dt, B, x, C, h0});
+ auto assign = std::make_shared<v6::Assign>(ssm->output(1), state_src.variable);
+ auto result = std::make_shared<v0::Result>(ssm->output(0));
+ return std::make_shared<ov::Model>(ov::ResultVector{result},
+ ov::SinkVector{assign},
+ params,
+ ov::op::util::VariableVector{state_src.variable});
}
} // namespace
diff --git a/src/common/transformations/tests/common_optimizations/paged_selective_ssm_fusion.cpp b/src/common/transformations/tests/common_optimizations/paged_selective_ssm_fusion.cpp
new file mode 100644
index 00000000000..24038ece481
--- /dev/null
+++ b/src/common/transformations/tests/common_optimizations/paged_selective_ssm_fusion.cpp
@@ -0,0 +1,251 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "transformations/paged_attention/paged_selective_ssm_fusion.hpp"
+
+#include <gtest/gtest.h>
+
+#include <string>
+#include <unordered_set>
+#include <vector>
+
+#include "common_test_utils/ov_test_utils.hpp"
+#include "openvino/op/assign.hpp"
+#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/paged_selective_ssm.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/selective_ssm.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/util/variable.hpp"
+#include "openvino/pass/constant_folding.hpp"
+#include "openvino/pass/manager.hpp"
+#include "openvino/pass/sdpa_to_paged_attention.hpp"
+
+namespace {
+
+using namespace ov;
+using ov::pass::paged_attention::PaParams;
+namespace v0 = ov::op::v0;
+namespace v1 = ov::op::v1;
+namespace v3 = ov::op::v3;
+namespace v6 = ov::op::v6;
+namespace v8 = ov::op::v8;
+namespace internal = ov::op::internal;
+
+// SelectiveSSM dimensions: batch B, seq_len L, num_heads H, num_groups G, head_dim P, state_size N.
+constexpr int64_t B = 2;
+constexpr int64_t L = 3;
+constexpr int64_t H = 4;
+constexpr int64_t G = 2;
+constexpr int64_t P = 8;
+constexpr int64_t N = 6;
+
+std::shared_ptr<v0::Parameter> make_param(const std::string& name,
+ ov::element::Type et,
+ const ov::PartialShape& shape) {
+ auto p = std::make_shared<v0::Parameter>(et, shape);
+ p->set_friendly_name(name);
+ p->get_output_tensor(0).set_names({name});
+ return p;
+}
+
+struct SSMInputs {
+ std::shared_ptr<v0::Parameter> a;
+ std::shared_ptr<v0::Parameter> dt;
+ std::shared_ptr<v0::Parameter> b;
+ std::shared_ptr<v0::Parameter> x;
+ std::shared_ptr<v0::Parameter> c;
+ std::shared_ptr<v0::Parameter> recurrent_state;
+};
+
+SSMInputs make_ssm_inputs() {
+ SSMInputs in;
+ in.a = make_param("A", element::f32, Shape{static_cast<size_t>(H)});
+ in.dt = make_param("dt", element::f32, Shape{B, L, H});
+ in.b = make_param("B", element::f32, Shape{B, L, G, N});
+ in.x = make_param("x", element::f32, Shape{B, L, H, P});
+ in.c = make_param("C", element::f32, Shape{B, L, G, N});
+ in.recurrent_state = make_param("past_ssm_state", element::f32, Shape{B, H, P, N});
+ in.recurrent_state->get_output_tensor(0).set_names({"cache_params.past.ssm_state.0"});
+ return in;
+}
+
+struct GatheredState {
+ std::shared_ptr<v0::Parameter> beam_idx;
+ std::shared_ptr<ov::op::util::Variable> variable;
+ std::shared_ptr<v6::ReadValue> read_value;
+ std::shared_ptr<v8::Gather> gathered_state;
+};
+
+GatheredState make_gathered_state(const SSMInputs& in) {
+ GatheredState s;
+ s.beam_idx = make_param("beam_idx", element::i32, PartialShape{-1});
+ s.variable = std::make_shared<ov::op::util::Variable>(
+ ov::op::util::VariableInfo{PartialShape{B, H, P, N}, element::f32, "ssm_var_0"});
+ s.read_value = std::make_shared<v6::ReadValue>(in.recurrent_state->output(0), s.variable);
+ const auto gather_axis = v0::Constant::create(element::i64, Shape{}, {0});
+ s.gathered_state = std::make_shared<v8::Gather>(s.read_value, s.beam_idx, gather_axis);
+ return s;
+}
+
+// Mirrors flatten_batch_length from paged_selective_ssm_fusion.cpp: [B, L, ...tail] -> [B*L, ...tail]
+ov::Output<ov::Node> ref_flatten_batch_length(const ov::Output<ov::Node>& input) {
+ const auto rank = input.get_partial_shape().size();
+ std::vector<int64_t> tail_dim_indices;
+ tail_dim_indices.reserve(rank - 2);
+ for (size_t i = 2; i < rank; ++i) {
+ tail_dim_indices.push_back(static_cast<int64_t>(i));
+ }
+ const auto shape_of = std::make_shared<v3::ShapeOf>(input, element::i64);
+ const auto tail_idx = v0::Constant::create(element::i64, Shape{tail_dim_indices.size()}, tail_dim_indices);
+ const auto axis_0 = v0::Constant::create(element::i64, Shape{}, {0});
+ const auto tail_dims = std::make_shared<v8::Gather>(shape_of, tail_idx, axis_0);
+ const auto flat_dim = v0::Constant::create(element::i64, Shape{1}, {-1});
+ const auto flat_shape = std::make_shared<v0::Concat>(OutputVector{flat_dim, tail_dims}, 0);
+ return std::make_shared<v1::Reshape>(input, flat_shape, false);
+}
+
+ov::Output<ov::Node> build_paged_ssm_block(const SSMInputs& in,
+ const std::shared_ptr<v0::Parameter>& state_table,
+ const std::shared_ptr<v0::Parameter>& subseq_begins,
+ const std::shared_ptr<v0::Parameter>& block_indices,
+ const std::shared_ptr<v0::Parameter>& block_indices_begins,
+ const std::shared_ptr<v0::Parameter>& past_lens,
+ const std::shared_ptr<v0::Parameter>& cache_interval,
+ const std::string& ssm_friendly_name) {
+ const auto dt_flat = ref_flatten_batch_length(in.dt);
+ const auto b_flat = ref_flatten_batch_length(in.b);
+ const auto x_flat = ref_flatten_batch_length(in.x);
+ const auto c_flat = ref_flatten_batch_length(in.c);
+
+ auto paged_ssm = std::make_shared<internal::PagedSelectiveSSM>(in.a,
+ dt_flat,
+ b_flat,
+ x_flat,
+ c_flat,
+ state_table->output(0),
+ subseq_begins->output(0),
+ block_indices->output(0),
+ block_indices_begins->output(0),
+ past_lens->output(0),
+ cache_interval->output(0));
+ paged_ssm->set_friendly_name(ssm_friendly_name + "/PagedSelectiveSSM");
+
+ const auto x_shape = std::make_shared<v3::ShapeOf>(in.x, element::i64);
+ auto paged_ssm_out = std::make_shared<v1::Reshape>(paged_ssm, x_shape, false);
+ paged_ssm_out->set_friendly_name(ssm_friendly_name);
+ return paged_ssm_out->output(0);
+}
+
+struct PagedParams {
+ std::shared_ptr<v0::Parameter> subseq_begins;
+ std::shared_ptr<v0::Parameter> block_indices;
+ std::shared_ptr<v0::Parameter> block_indices_begins;
+ std::shared_ptr<v0::Parameter> past_lens;
+ std::shared_ptr<v0::Parameter> cache_interval;
+};
+
+PagedParams make_paged_params() {
+ PagedParams p;
+ p.subseq_begins = make_param("subsequence_begins", element::i32, PartialShape{-1});
+ p.block_indices = make_param("la.block_indices", element::i32, PartialShape{-1});
+ p.block_indices_begins = make_param("la.block_indices_begins", element::i32, PartialShape{-1});
+ p.past_lens = make_param("la.past_lens", element::i32, PartialShape{-1});
+ p.cache_interval = make_param("la.cache_interval", element::i32, PartialShape{-1});
+ return p;
+}
+
+std::shared_ptr<ov::Model> build_model_stateful() {
+ auto in = make_ssm_inputs();
+ auto st = make_gathered_state(in);
+
+ auto ssm = std::make_shared<internal::SelectiveSSM>(in.a, in.dt, in.b, in.x, in.c, st.gathered_state);
+
+ auto out = std::make_shared<v0::Result>(ssm->output(0));
+ auto assign = std::make_shared<v6::Assign>(ssm->output(1), st.variable);
+
+ ParameterVector params{in.a, in.dt, in.b, in.x, in.c, in.recurrent_state, st.beam_idx};
+ return std::make_shared<ov::Model>(ResultVector{out}, SinkVector{assign}, params);
+}
+
+std::shared_ptr<ov::Model> build_reference_model() {
+ auto in = make_ssm_inputs();
+ auto pp = make_paged_params();
+ // SelectiveSSM recurrent_state [B,H,P,N] -> state table [num_blocks,H,P,N].
+ auto state_table =
+ make_param("selective_ssm_state_table.0", element::dynamic, PartialShape{Dimension::dynamic(), H, P, N});
+
+ const auto paged_ssm_out = build_paged_ssm_block(in,
+ state_table,
+ pp.subseq_begins,
+ pp.block_indices,
+ pp.block_indices_begins,
+ pp.past_lens,
+ pp.cache_interval,
+ "SelectiveSSM");
+
+ auto out = std::make_shared<v0::Result>(paged_ssm_out);
+
+ // The Assign is reconnected to Gather(ReadValue) as a dead branch.
+ auto st = make_gathered_state(in);
+ auto assign = std::make_shared<v6::Assign>(st.gathered_state->output(0), st.variable);
+
+ ParameterVector params{in.a,
+ in.dt,
+ in.b,
+ in.x,
+ in.c,
+ in.recurrent_state,
+ st.beam_idx,
+ pp.subseq_begins,
+ pp.block_indices,
+ pp.block_indices_begins,
+ pp.past_lens,
+ pp.cache_interval,
+ state_table};
+ return std::make_shared<ov::Model>(ResultVector{out}, SinkVector{assign}, params);
+}
+
+} // namespace
+
+class PagedSelectiveSSMFusionTest : public ::TransformationTestsF {};
+
+std::unordered_set<std::string> run_paged_selective_ssm_fusion(const std::shared_ptr<ov::Model>& model) {
+ PaParams pa_params{model->get_parameters()};
+ std::unordered_set<std::string> var_ids_to_remove;
+
+ ov::pass::Manager manager;
+ manager.set_per_pass_validation(false);
+ manager.register_pass<ov::pass::PagedSelectiveSSMFusion>(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;
+}
+
+TEST_F(PagedSelectiveSSMFusionTest, FusePagedSSM) {
+ model = build_model_stateful();
+ model_ref = build_reference_model();
+
+ const auto var_ids_to_remove = run_paged_selective_ssm_fusion(model);
+ EXPECT_EQ(var_ids_to_remove.count("ssm_var_0"), 1u);
+}
+
+TEST(PagedSelectiveSSMFusionCount, ReportsConvertedCount) {
+ auto model = build_model_stateful();
+ PaParams pa_params{model->get_parameters()};
+ std::unordered_set<std::string> var_ids_to_remove;
+
+ ov::pass::Manager manager;
+ manager.set_per_pass_validation(false);
+ auto pass = manager.register_pass<ov::pass::PagedSelectiveSSMFusion>(pa_params, var_ids_to_remove);
+ manager.run_passes(model);
+
+ EXPECT_EQ(pass->get_fused_count(), 1u);
+}
\ No newline at end of file
diff --git a/src/common/transformations/tests/common_optimizations/ssm_test_models.hpp b/src/common/transformations/tests/common_optimizations/ssm_test_models.hpp
new file mode 100644
index 00000000000..23a548cbb21
--- /dev/null
+++ b/src/common/transformations/tests/common_optimizations/ssm_test_models.hpp
@@ -0,0 +1,234 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <climits>
+#include <memory>
+#include <vector>
+
+#include "openvino/core/model.hpp"
+#include "openvino/op/add.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/exp.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/loop.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/read_value.hpp"
+#include "openvino/op/reduce_prod.hpp"
+#include "openvino/op/reduce_sum.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/scatter_update.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/slice.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/subtract.hpp"
+#include "openvino/op/tile.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/op/util/variable.hpp"
+
+namespace ov::test::ssm {
+
+// Recurrent-state source for a SelectiveSSM. By default it is the realistic Gather(ReadValue(state_var))
+// chain exported by stateful SSM models (e.g. granite-4.0-h-micro), which PagedSelectiveSSMFusion can
+// convert.
+struct RecurrentStateSource {
+ ov::Output<ov::Node> state;
+ std::shared_ptr<ov::op::util::Variable> variable; // null when plain_parameter_state is true
+ ov::ParameterVector params;
+};
+
+inline RecurrentStateSource make_recurrent_state_source(const ov::PartialShape& state_shape,
+ bool plain_parameter_state) {
+ using namespace ov::op;
+ if (plain_parameter_state) {
+ auto h0 = std::make_shared<v0::Parameter>(ov::element::f32, state_shape);
+ return {h0->output(0), nullptr, {h0}};
+ }
+ auto past_state = std::make_shared<v0::Parameter>(ov::element::f32, state_shape);
+ auto variable = std::make_shared<ov::op::util::Variable>(
+ ov::op::util::VariableInfo{state_shape, ov::element::f32, "ssm_var_0"});
+ auto read_value = std::make_shared<v6::ReadValue>(past_state, variable);
+ auto beam_idx = std::make_shared<v0::Parameter>(ov::element::i32, ov::PartialShape{-1});
+ auto gather_axis = v0::Constant::create(ov::element::i64, {}, {0});
+ auto gathered = std::make_shared<v8::Gather>(read_value, beam_idx, gather_axis);
+ return {gathered->output(0), variable, {past_state, beam_idx}};
+}
+
+// Builds a loop-based SSM recurrence model matching the time-major export where all
+// discretization is performed outside the loop and consumed as 5D per-step slices:
+// dA = reshape(exp(A * dt), [B, T, H, 1, 1]) (Loop input 2)
+// dBx = unsqueeze(dt*B, -2) * unsqueeze(x, -1) -> [B, T, H, P, N] (Loop input 3)
+// C = unsqueeze(C_expanded, -2) -> [B, T, H, 1, N] (Loop input 4)
+// Per step: state_t = state_{t-1} * dA_t + dBx_t; y_t = reduce_sum(state_t * C_t, axis=state_size).
+// B/C are provided per group and expanded to heads via Unsqueeze/Tile/Reshape outside the loop.
+// External Loop inputs (in order): trip_count, exec_cond, dA, dBx, C, recurrent_state, output_buffer.
+// External Loop outputs: output[B,T,H,P], output_recurrent_state[B,H,P,N].
+//
+// The default builds a realistic Gather(ReadValue(state_var)) recurrent state (paged-convertible); with
+// plain_parameter_state the state is a bare Parameter so the fused SelectiveSSM is not paged-convertible.
+//
+// \param with_post_loop appends the flatten/Concat/Slice/Reshape round-trip seen in real models.
+// \param break_body replaces the state `Add` with `Subtract` so the body no longer matches the SSM recurrence.
+// \param plain_parameter_state feeds the recurrent state from a bare Parameter instead of Gather(ReadValue).
+inline std::shared_ptr<ov::Model> build_looped_ssm(int32_t num_heads,
+ int32_t num_groups,
+ int32_t head_dim,
+ int32_t state_size,
+ bool with_post_loop = false,
+ bool break_body = false,
+ bool plain_parameter_state = false) {
+ using namespace ov::op;
+
+ const auto dtype = ov::element::f32;
+ const int32_t heads_per_group = num_heads / num_groups;
+
+ ov::PartialShape dt_shape{-1, -1, num_heads};
+ ov::PartialShape B_shape{-1, -1, num_groups, state_size};
+ ov::PartialShape x_shape{-1, -1, num_heads, head_dim};
+ ov::PartialShape C_shape{-1, -1, num_groups, state_size};
+ ov::PartialShape state_shape{-1, num_heads, head_dim, state_size};
+
+ auto dt = std::make_shared<v0::Parameter>(dtype, dt_shape);
+ auto B = std::make_shared<v0::Parameter>(dtype, B_shape);
+ auto x = std::make_shared<v0::Parameter>(dtype, x_shape);
+ auto C = std::make_shared<v0::Parameter>(dtype, C_shape);
+ const auto state_src = make_recurrent_state_source(state_shape, plain_parameter_state);
+ const auto& h0 = state_src.state;
+
+ // A is a per-head constant embedded in the graph (log-decay rates).
+ auto A = v0::Constant::create(dtype, {static_cast<size_t>(num_heads)}, std::vector<float>(num_heads, -0.5f));
+
+ // Expand B/C from [B, T, G, N] to [B, T, H, N] via Unsqueeze -> Tile -> Reshape.
+ auto expand_groups = [&](const std::shared_ptr<v0::Parameter>& src) {
+ auto unsq_axis = v0::Constant::create(ov::element::i32, {}, {3});
+ auto src_5d = std::make_shared<v0::Unsqueeze>(src, unsq_axis);
+ auto tile_shape = v0::Constant::create(ov::element::i64, {5}, {1, 1, 1, heads_per_group, 1});
+ auto tiled = std::make_shared<v0::Tile>(src_5d, tile_shape);
+ auto target = v0::Constant::create(ov::element::i64, {4}, {0, 0, num_heads, state_size});
+ return std::make_shared<v1::Reshape>(tiled, target, true);
+ };
+ auto B_expanded = expand_groups(B);
+ auto C_expanded = expand_groups(C);
+
+ // Discretization is performed outside the loop and materialized as 5D per-step tensors:
+ // dA = reshape(exp(A * dt), [B, T, H, 1, 1])
+ // dBx = unsqueeze(unsqueeze(dt, -1) * B_expanded, -2) * unsqueeze(x, -1) -> [B, T, H, P, N]
+ // C = unsqueeze(C_expanded, -2) -> [B, T, H, 1, N]
+ auto minus1_outer = v0::Constant::create(ov::element::i32, {1}, {-1});
+ auto minus2_outer = v0::Constant::create(ov::element::i32, {1}, {-2});
+ auto dA_shape = v0::Constant::create(ov::element::i64, {5}, {0, 0, 0, 1, 1});
+ auto dA_outer =
+ std::make_shared<v1::Reshape>(std::make_shared<v0::Exp>(std::make_shared<v1::Multiply>(A, dt)), dA_shape, true);
+ auto dB_outer = std::make_shared<v1::Multiply>(std::make_shared<v0::Unsqueeze>(dt, minus1_outer), B_expanded);
+ auto dBx_outer = std::make_shared<v1::Multiply>(std::make_shared<v0::Unsqueeze>(dB_outer, minus2_outer),
+ std::make_shared<v0::Unsqueeze>(x, minus1_outer));
+ auto C_5d_outer = std::make_shared<v0::Unsqueeze>(C_expanded, minus2_outer);
+
+ // output accumulator buffer: zeros with shape [B, T, H, P]
+ auto shape_of_x = std::make_shared<v3::ShapeOf>(x);
+ auto core_init = std::make_shared<v3::Broadcast>(v0::Constant::create(dtype, {}, {0.0f}), shape_of_x);
+
+ // trip count = seq_len (dim 1 of x)
+ auto trip_index = v0::Constant::create(ov::element::i64, {1}, {1});
+ auto trip_axis = v0::Constant::create(ov::element::i64, {}, {0});
+ auto trip_count_i64 = std::make_shared<v8::Gather>(shape_of_x, trip_index, trip_axis);
+ auto trip_count = std::make_shared<v0::Convert>(trip_count_i64, ov::element::i32);
+
+ // -------- Loop body --------
+ auto timestep = std::make_shared<v0::Parameter>(ov::element::i32, ov::Shape{});
+ auto dA_t = std::make_shared<v0::Parameter>(dtype, ov::PartialShape{-1, 1, num_heads, 1, 1});
+ auto dBx_t = std::make_shared<v0::Parameter>(dtype, ov::PartialShape{-1, 1, num_heads, head_dim, state_size});
+ auto C_t = std::make_shared<v0::Parameter>(dtype, ov::PartialShape{-1, 1, num_heads, 1, state_size});
+ auto last_state = std::make_shared<v0::Parameter>(dtype, ov::PartialShape{-1, num_heads, head_dim, state_size});
+ auto core_out = std::make_shared<v0::Parameter>(dtype, ov::PartialShape{-1, -1, num_heads, head_dim});
+
+ auto axis1 = v0::Constant::create(ov::element::i32, {}, {1});
+ auto minus1 = v0::Constant::create(ov::element::i32, {1}, {-1});
+
+ auto dA_sq = std::make_shared<v0::Squeeze>(dA_t, axis1); // [B, H, 1, 1]
+ auto dBx_sq = std::make_shared<v0::Squeeze>(dBx_t, axis1); // [B, H, P, N]
+ auto C_sq = std::make_shared<v0::Squeeze>(C_t, axis1); // [B, H, 1, N]
+
+ auto state_decay = std::make_shared<v1::Multiply>(last_state, dA_sq);
+ std::shared_ptr<ov::Node> state_new;
+ if (break_body) {
+ state_new = std::make_shared<v1::Subtract>(state_decay, dBx_sq);
+ } else {
+ state_new = std::make_shared<v1::Add>(state_decay, dBx_sq);
+ }
+
+ auto y = std::make_shared<v1::Multiply>(state_new, C_sq);
+ auto y_sum = std::make_shared<v1::ReduceSum>(y, minus1, false);
+ auto y_unsq = std::make_shared<v0::Unsqueeze>(y_sum, axis1);
+
+ auto timestep_unsq = std::make_shared<v0::Unsqueeze>(timestep, v0::Constant::create(ov::element::i32, {1}, {0}));
+ auto core_out_new = std::make_shared<v3::ScatterUpdate>(core_out, timestep_unsq, y_unsq, axis1);
+
+ auto body_cond = v0::Constant::create(ov::element::boolean, {1}, {true});
+ auto body = std::make_shared<ov::Model>(ov::OutputVector{body_cond, state_new, core_out_new},
+ ov::ParameterVector{timestep, dA_t, dBx_t, C_t, last_state, core_out},
+ "ssm_body");
+
+ // -------- Loop --------
+ auto loop = std::make_shared<v5::Loop>(trip_count, v0::Constant::create(ov::element::boolean, {1}, {true}));
+ loop->set_function(body);
+ loop->set_sliced_input(dA_t, dA_outer, 0, 1, 1, -1, 1);
+ loop->set_sliced_input(dBx_t, dBx_outer, 0, 1, 1, -1, 1);
+ loop->set_sliced_input(C_t, C_5d_outer, 0, 1, 1, -1, 1);
+ loop->set_merged_input(last_state, h0, state_new);
+ loop->set_merged_input(core_out, core_init, core_out_new);
+ loop->set_special_body_ports({0, 0});
+
+ auto output = loop->get_iter_value(core_out_new, -1); // Loop output(0)
+ auto state_out = loop->get_iter_value(state_new, -1); // Loop output(1)
+
+ ov::Output<ov::Node> final_output = output;
+ ov::Output<ov::Node> final_state = state_out;
+
+ if (with_post_loop) {
+ auto reshape_m1 = v0::Constant::create(ov::element::i64, {1}, {-1});
+ auto flat_out = std::make_shared<v1::Reshape>(output, reshape_m1, false);
+ auto flat_state = std::make_shared<v1::Reshape>(state_out, reshape_m1, false);
+ auto packed = std::make_shared<v0::Concat>(ov::OutputVector{flat_out, flat_state}, 0);
+
+ auto out_shape = std::make_shared<v3::ShapeOf>(core_init);
+ auto state_ref_shape = std::make_shared<v3::ShapeOf>(h0);
+ auto reduce_axis0 = v0::Constant::create(ov::element::i64, {1}, {0});
+ auto out_numel = std::make_shared<v1::ReduceProd>(out_shape, reduce_axis0, true);
+
+ auto s_start = v0::Constant::create(ov::element::i64, {1}, {0});
+ auto s_step = v0::Constant::create(ov::element::i64, {1}, {1});
+ auto s_axis = v0::Constant::create(ov::element::i64, {1}, {0});
+ auto s_end_inf = v0::Constant::create(ov::element::i64, {1}, {LLONG_MAX});
+
+ auto out_slice = std::make_shared<v8::Slice>(packed, s_start, out_numel, s_step, s_axis);
+ auto state_slice = std::make_shared<v8::Slice>(packed, out_numel, s_end_inf, s_step, s_axis);
+ final_output = std::make_shared<v1::Reshape>(out_slice, out_shape, false);
+ final_state = std::make_shared<v1::Reshape>(state_slice, state_ref_shape, false);
+ }
+
+ ov::ParameterVector params{dt, B, x, C};
+ params.insert(params.end(), state_src.params.begin(), state_src.params.end());
+
+ if (plain_parameter_state) {
+ return std::make_shared<ov::Model>(ov::OutputVector{final_output, final_state}, params);
+ }
+
+ // Realistic stateful form: the recurrent state is written back through Assign(state_var).
+ auto assign = std::make_shared<v6::Assign>(final_state, state_src.variable);
+ auto result = std::make_shared<v0::Result>(final_output);
+ return std::make_shared<ov::Model>(ov::ResultVector{result},
+ ov::SinkVector{assign},
+ params,
+ ov::op::util::VariableVector{state_src.variable});
+}
+
+} // namespace ov::test::ssm
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 75b27e1e268..3dfb3c4acf5 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
@@ -6,6 +6,7 @@
#include <gtest/gtest.h>
+#include "../common_optimizations/ssm_test_models.hpp"
#include "common_test_utils/ov_test_utils.hpp"
#include "openvino/core/model.hpp"
#include "openvino/op/abs.hpp"
@@ -17,6 +18,7 @@
#include "openvino/op/clamp.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
#include "openvino/op/cos.hpp"
#include "openvino/op/divide.hpp"
#include "openvino/op/einsum.hpp"
@@ -7471,6 +7473,31 @@ TEST(SDPAToPA_ActivationFakeQuantizeOnKV_PerChannel, NotTolerated) {
OV_EXPECT_THROW(manager.run_passes(model), ov::Exception, ::testing::HasSubstr("undeclared parameters"));
}
+// SDPAToPagedAttention must not silently leave stateful SSM nodes in the graph. SelectiveSSMFusion fuses
+// the loop-based SSM into a SelectiveSSM, but its plain-Parameter recurrent state (no Gather(ReadValue))
+// prevents PagedSelectiveSSMFusion from converting it, so the two fused counts diverge and the
+// transformation throws.
+TEST(SDPAToPA_SelectiveSSM_Unconvertible, StatefulSSMLeftInGraphThrows) {
+ auto model = make_single_layer_sdpa_model(/*fq_on_k=*/false, /*fq_on_v=*/false, /*gqa=*/false);
+
+ // plain_parameter_state=true keeps the fused SelectiveSSM unconvertible by PagedSelectiveSSMFusion.
+ auto ssm_model = ov::test::ssm::build_looped_ssm(/*num_heads=*/4,
+ /*num_groups=*/2,
+ /*head_dim=*/8,
+ /*state_size=*/16,
+ /*with_post_loop=*/false,
+ /*break_body=*/false,
+ /*plain_parameter_state=*/true);
+ model->add_parameters(ssm_model->get_parameters());
+ model->add_results(ssm_model->get_results());
+
+ ov::pass::Manager manager;
+ manager.register_pass<ov::pass::SDPAToPagedAttention>();
+ OV_EXPECT_THROW(manager.run_passes(model),
+ ov::Exception,
+ ::testing::HasSubstr("Stateful SSM nodes cannot be left in the graph"));
+}
+
/*
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/sources.cmake b/src/common/transformations/tests/sources.cmake
index ee57b06d2e1..314d3103987 100644
--- a/src/common/transformations/tests/sources.cmake
+++ b/src/common/transformations/tests/sources.cmake
@@ -104,6 +104,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_selective_ssm_fusion.cpp
${CMAKE_CURRENT_LIST_DIR}/common_optimizations/preprocessing_fusion_tests.cpp
${CMAKE_CURRENT_LIST_DIR}/common_optimizations/pull_through_reduce_test.cpp
${CMAKE_CURRENT_LIST_DIR}/common_optimizations/push_constant_to_subgraphs.cpp
diff --git a/src/core/src/pass/sdpa_to_paged_attention.cpp b/src/core/src/pass/sdpa_to_paged_attention.cpp
index 523ef335bd5..2f8b72b1473 100644
--- a/src/core/src/pass/sdpa_to_paged_attention.cpp
+++ b/src/core/src/pass/sdpa_to_paged_attention.cpp
@@ -22,6 +22,7 @@
#include "transformations/paged_attention/eliminate_conv_padding_mask_gating.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_selective_ssm_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"
@@ -151,10 +152,11 @@ bool ov::pass::SDPAToPagedAttention::run_on_model(const std::shared_ptr<ov::Mode
manager.register_pass<ov::pass::GatedDeltaNetFusion>(); // This pass is required to ensure that all GatedDeltaNet
// nodes are in the expected form before running
// PagedGatedDeltaNetFusion.
- manager.register_pass<SelectiveSSMFusion>();
+ auto ssm_fusion = manager.register_pass<SelectiveSSMFusion>();
manager.register_pass<StateManagementPattern>(m_params, m_results, m_options, var_ids_to_remove);
manager.register_pass<EliminateConvPaddingMaskGating>();
manager.register_pass<AttentionMaskShapeReplacer>(input_ids_node);
+ auto paged_ssm_fusion = manager.register_pass<PagedSelectiveSSMFusion>(m_params, var_ids_to_remove);
manager.register_pass<PagedCausalConv1DFusion>(m_params, var_ids_to_remove);
manager.register_pass<PagedGatedDeltaNetFusion>(m_params, var_ids_to_remove);
manager.register_pass<PrevSequenceLengthPattern>(processed_input_ids, max_context_len, position_ids);
@@ -167,6 +169,13 @@ bool ov::pass::SDPAToPagedAttention::run_on_model(const std::shared_ptr<ov::Mode
manager.register_pass<PositionIDsReplacerLFM2>(position_ids);
manager.run_passes(model);
+ OPENVINO_ASSERT(ssm_fusion->get_fused_count() == paged_ssm_fusion->get_fused_count(),
+ "SelectiveSSMFusion fused ",
+ ssm_fusion->get_fused_count(),
+ " SelectiveSSM node(s), but PagedSelectiveSSMFusion converted ",
+ paged_ssm_fusion->get_fused_count(),
+ ". Stateful SSM nodes cannot be left in the graph.");
+
{
// Remove all Assigns aggressively, the path from the kv-cache concat to Assign can be complicated,
// but there is no reason to track it and reject part of the Assigns, because the model will remain