OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
Fuse RoPE with slice-assign using scatterNDupdate output (#37698)
Chon Ming Lee2a0ab605325e
diff --git a/src/common/transformations/include/transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp b/src/common/transformations/include/transformations/common_optimizations/fuse_rotary_positional_embeddings.hppindex d9a790fbcf6..9a3dda36f4d 100644--- a/src/common/transformations/include/transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp+++ b/src/common/transformations/include/transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp@@ -24,6 +24,7 @@ class TRANSFORMATIONS_API RoPEShareCosSin;class TRANSFORMATIONS_API RoPEFusionGPTOSS;class TRANSFORMATIONS_API RoPEFusionLtxVideo;class TRANSFORMATIONS_API RoPEFusionCohere;+class TRANSFORMATIONS_API RoPEFusionSliceAssign;} // namespace pass} // namespace ov@@ -112,6 +113,12 @@ public:RoPEFusionCohere();};+class ov::pass::RoPEFusionSliceAssign : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("RoPEFusionSliceAssign");+ RoPEFusionSliceAssign();+};+/*** @ingroup ov_transformation_common_api* @brief Fuses special sub-graph into an internal Rotary Positional Embedding operationdiff --git a/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp b/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cppindex d94b90f82c1..57e8d7f384b 100644--- a/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp@@ -22,6 +22,7 @@#include "openvino/op/matmul.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/reshape.hpp"+#include "openvino/op/scatter_nd_update.hpp"#include "openvino/op/scatter_update.hpp"#include "openvino/op/shape_of.hpp"#include "openvino/op/sin.hpp"@@ -29,6 +30,7 @@#include "openvino/op/split.hpp"#include "openvino/op/squeeze.hpp"#include "openvino/op/strided_slice.hpp"+#include "openvino/op/subtract.hpp"#include "openvino/op/transpose.hpp"#include "openvino/op/unsqueeze.hpp"#include "openvino/op/util/shape_of_base.hpp"@@ -53,6 +55,7 @@ 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 op_util = ov::op::util;RoPEFusion::RoPEFusion(bool support_2d_rope) : m_support_2d_rope(support_2d_rope) {}@@ -83,6 +86,7 @@ bool RoPEFusion::run_on_model(const std::shared_ptr<ov::Model>& model) {}symbolic_ctx_manager->register_pass<ov::pass::RoPEFusionQwen>();symbolic_ctx_manager->register_pass<ov::pass::RoPEFusionLtxVideo>();+ symbolic_ctx_manager->register_pass<ov::pass::RoPEFusionSliceAssign>();symbolic_ctx_manager->register_pass<ov::pass::RoPEShareCosSin>();return symbolic_optimizations.run_on_model(model);}@@ -1418,4 +1422,154 @@ RoPEFusionCohere::RoPEFusionCohere() {this->register_matcher(m, callback);}+RoPEFusionSliceAssign::RoPEFusionSliceAssign() {+ MATCHER_SCOPE(RoPEFusionSliceAssign);+ using namespace pattern;++ // x [B,S,H,D] -> VariadicSplit(-1, [D/2, D/2]) -> x1, x2+ // out1 = x1*cos - x2*sin (first half; Subtract, or Add of negated x2*sin)+ // out2 = x2*cos + x1*sin (second half)+ // scatter1 = ScatterNDUpdate(any, idx1, reshape(out1))+ // scatter2 = ScatterNDUpdate(scatter1, idx2, reshape(out2))+ // result = reshape(scatter2)+ //+ // When idx1/idx2 are provably sequential and together cover the whole+ // buffer, the scatters equal concat(out1, out2) and the subgraph collapses+ // to a single RoPE op.+ auto x = any_input(rank_equals(4));++ auto cos = any_input(shape_matches("[..., half_ndims]"));+ auto sin = any_input(shape_matches("[..., half_ndims]"));++ auto split = wrap_type_strict_index<v1::VariadicSplit>({x, any_input(), {"half_ndims", "?"}},+ shape_matches("[?, ?, ?, half_ndims]"));+ auto x1 = split->output(0);+ auto x2 = split->output(1);++ // out1 = x1*cos - x2*sin. Multiply/Add operand order is handled by the matcher's+ // commutativity; the negated x2*sin form appears as Add(x1*cos, (x2*sin)*(-1)).+ auto mul_x1_cos = wrap_type<v1::Multiply>({x1, cos}, {{"auto_broadcast", "numpy"}});+ auto mul_x2_sin = wrap_type<v1::Multiply>({x2, sin}, {{"auto_broadcast", "numpy"}});+ auto neg_const = wrap_type<v0::Constant>(value_matches("-1"));+ auto neg_x2_sin = wrap_type<v1::Multiply>({mul_x2_sin, neg_const});+ auto out1 = wrap_type<v1::Subtract>({mul_x1_cos, mul_x2_sin}) | wrap_type<v1::Add>({mul_x1_cos, neg_x2_sin});++ // out2 = x2*cos + x1*sin+ auto mul_x2_cos = wrap_type<v1::Multiply>({x2, cos}, {{"auto_broadcast", "numpy"}});+ auto mul_x1_sin = wrap_type<v1::Multiply>({x1, sin}, {{"auto_broadcast", "numpy"}});+ auto out2 = wrap_type<v1::Add>({mul_x2_cos, mul_x1_sin});++ const auto scatter_overwrites = [](const Output<Node>& output) {+ const auto scatter = ov::as_type_ptr<v15::ScatterNDUpdate>(output.get_node_shared_ptr());+ return !scatter || scatter->get_reduction() == v15::ScatterNDUpdate::Reduction::NONE;+ };+ const auto target_has_no_zero = [](const Output<Node>& output) {+ const auto reshape = ov::as_type_ptr<v1::Reshape>(output.get_node_shared_ptr());+ if (!reshape->get_special_zero())+ return true;+ const auto target = ov::as_type_ptr<v0::Constant>(reshape->input_value(1).get_node_shared_ptr());+ if (!target)+ return false;+ for (const auto& dim : target->cast_vector<int64_t>()) {+ if (dim == 0)+ return false;+ }+ return true;+ };++ auto data1 = any_input();+ auto updates1 = wrap_type<v1::Reshape>({out1, any_input()});+ auto idx1 = wrap_type<v0::Constant>();+ auto scatter1 = wrap_type<op_util::ScatterNDBase>({data1, idx1, updates1}, scatter_overwrites);++ auto updates2 = wrap_type<v1::Reshape>({out2, any_input()});+ auto idx2 = wrap_type<v0::Constant>();+ auto scatter2 = wrap_type<op_util::ScatterNDBase>({scatter1, idx2, updates2}, scatter_overwrites);+ auto result = wrap_type<v1::Reshape>({scatter2, any_input()}, target_has_no_zero);++ matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](pattern::Matcher& m) {+ const auto& pattern_map = m.get_pattern_value_map();+ auto root = m.get_match_root();++ const auto& x_val = pattern_map.at(x);+ const auto& cos_val = pattern_map.at(cos);+ const auto& sin_val = pattern_map.at(sin);+ const auto& idx1_val = pattern_map.at(idx1);+ const auto& idx2_val = pattern_map.at(idx2);++ auto symbols = m.get_symbols();+ const auto& half_ndims = symbols["half_ndims"];+ if (!half_ndims.is_integer())+ return false;+ const size_t half = static_cast<size_t>(half_ndims.i());+ if (half == 0)+ return false;+ const size_t head_size = 2 * half; // D = 2 * (D/2): evenness is implied by the equal halves++ // Verify the scatter indices are sequential: idx1 = [0..N/2), idx2 = [N/2..N).+ // N/2 (half_elems) is read from the index constant's shape, so x itself needn't be static.+ auto idx1_const = ov::as_type_ptr<v0::Constant>(idx1_val.get_node_shared_ptr());+ auto idx2_const = ov::as_type_ptr<v0::Constant>(idx2_val.get_node_shared_ptr());+ if (!idx1_const || !idx2_const)+ return false;++ const auto idx1_shape = idx1_const->get_shape();+ const auto idx2_shape = idx2_const->get_shape();+ if (idx1_shape.size() != 2 || idx1_shape[1] != 1 || idx2_shape.size() != 2 || idx2_shape[1] != 1)+ return false;+ if (idx1_shape[0] != idx2_shape[0])+ return false;+ const size_t half_elems = idx1_shape[0];+ if (half_elems == 0)+ return false;++ const auto idx1_data = idx1_const->cast_vector<int64_t>();+ const auto idx2_data = idx2_const->cast_vector<int64_t>();+ for (size_t i = 0; i < half_elems; ++i) {+ const int64_t expected1 = static_cast<int64_t>((i / half) * head_size + (i % half));+ if (idx1_data[i] != expected1 || idx2_data[i] != expected1 + static_cast<int64_t>(half))+ return false;+ }++ ov::op::internal::RoPE::Config config;+ config.rotary_ndims = head_size;+ config.cos_sin_ndims = half;+ config.is_interleaved = false;++ // The final reshape already outputs the rope shape iff its shape matches x's shape; if it+ // flattens (e.g. [1,S,H,D] -> [1,S,H*D]) we keep the Reshape and feed it the fused RoPE.+ const bool replace_root = root->get_output_partial_shape(0) == x_val.get_partial_shape();++ auto rope = std::make_shared<ov::op::internal::RoPE>(OutputVector{x_val, cos_val, sin_val}, config);++ NodeVector matched_nodes;+ for (const auto& kv : pattern_map) {+ const auto node = kv.second.get_node_shared_ptr();+ if (ov::is_type<v0::Constant>(node) || node == x_val.get_node_shared_ptr() ||+ node == cos_val.get_node_shared_ptr() || node == sin_val.get_node_shared_ptr())+ continue;+ matched_nodes.push_back(node);+ }++ if (replace_root) {+ // The final reshape outputs the rope shape -> replace it directly.+ rope->set_friendly_name(root->get_friendly_name());+ ov::copy_runtime_info(matched_nodes, rope);+ ov::replace_node(root, rope);+ register_new_node(rope);+ } else {+ // The final reshape flattens the rope output (e.g. [1,S,H,D] -> [1,S,H*D]).+ // Reuse the existing root Reshape (keeping its name/RT info) and just feed it+ // the fused RoPE in place of the scatter chain.+ ov::copy_runtime_info(matched_nodes, rope);+ root->input(0).replace_source_output(rope);+ register_new_node(rope);+ }+ return true;+ };++ auto m = std::make_shared<pattern::Matcher>(result, matcher_name);+ this->register_matcher(m, callback);+}+} // namespace ov::passdiff --git a/src/common/transformations/tests/common_optimizations/fuse_rotary_positional_embeddings.cpp b/src/common/transformations/tests/common_optimizations/fuse_rotary_positional_embeddings.cppindex e2d24a1aac7..241991cb269 100644--- a/src/common/transformations/tests/common_optimizations/fuse_rotary_positional_embeddings.cpp+++ b/src/common/transformations/tests/common_optimizations/fuse_rotary_positional_embeddings.cpp@@ -16,12 +16,14 @@#include "openvino/op/gather_elements.hpp"#include "openvino/op/gather_nd.hpp"#include "openvino/op/reshape.hpp"+#include "openvino/op/scatter_nd_update.hpp"#include "openvino/op/scatter_update.hpp"#include "openvino/op/shape_of.hpp"#include "openvino/op/slice.hpp"#include "openvino/op/split.hpp"#include "openvino/op/squeeze.hpp"#include "openvino/op/strided_slice.hpp"+#include "openvino/op/subtract.hpp"#include "openvino/op/transpose.hpp"#include "openvino/op/unsqueeze.hpp"#include "openvino/op/variadic_split.hpp"@@ -2418,3 +2420,161 @@ TEST_P(ConvertToROPECohereTest, basic) {INSTANTIATE_TEST_SUITE_P(TransformationTestsF,ConvertToROPECohereTest,::testing::Combine(::testing::Bool(), ::testing::Bool()));++namespace {+// Builds the decomposed "slice-assign" RoPE subgraph that RoPEFusionSliceAssign targets:+// x[1,S,H,D] -> VariadicSplit(-1,[D/2,D/2]) -> x1,x2+// out1 = x1*cos - x2*sin (Subtract, or Add of x2*sin*(-1) when add_negated_form)+// out2 = x2*cos + x1*sin+// scatter1 = ScatterNDUpdate(zeros[total], idx1, reshape(out1,[N/2]))+// scatter2 = ScatterNDUpdate(scatter1, idx2, reshape(out2,[N/2]))+// result = reshape(scatter2, [1,S,H,D])+// cos_sin_shape lets tests exercise the cos/sin guard (rank 2..4 with last dim D/2 == valid).+// flatten_result=true makes the final reshape flatten to [B,S,H*D] (result shape != x shape), which+// exercises the pass's !replace_root branch (rebuild the final Reshape); false keeps the identity+// [B,S,H,D] shape (replace_root branch).+// inferred_split_len=true builds the split as [D/2, -1] (the -1 "infer remaining dim" sentinel),+// which is what real PyTorch exports emit (e.g. SmolVLA) instead of the explicit [D/2, D/2].+std::shared_ptr<ov::Model> make_slice_assign_rope_model(bool add_negated_form,+ const ov::PartialShape& cos_sin_shape,+ bool flatten_result = false,+ bool i32_indices = false,+ bool inferred_split_len = false) {+ using namespace ov;+ const int batch = 1, seq = 2, heads = 2, dim = 4, half = dim / 2;+ const int total = batch * seq * heads * dim, half_elems = total / 2;++ auto x = std::make_shared<opset1::Parameter>(element::f32, PartialShape{batch, seq, heads, dim});+ auto cos = std::make_shared<opset1::Parameter>(element::f32, cos_sin_shape);+ auto sin = std::make_shared<opset1::Parameter>(element::f32, cos_sin_shape);++ auto split_axis = makeConst(element::i64, {}, std::vector<int64_t>{-1});+ auto split_len = makeConst(element::i64,+ {2},+ inferred_split_len ? std::vector<int64_t>{half, -1} : std::vector<int64_t>{half, half});+ auto split = makeOP<opset1::VariadicSplit>({x, split_axis, split_len});++ auto mul_x1_cos = makeOP<opset1::Multiply>({split->output(0), cos}, {{"auto_broadcast", "numpy"}});+ auto mul_x2_sin = makeOP<opset1::Multiply>({split->output(1), sin}, {{"auto_broadcast", "numpy"}});+ std::shared_ptr<Node> out1;+ if (add_negated_form) {+ auto neg = makeConst(element::f32, {}, std::vector<float>{-1.0f});+ auto neg_x2_sin = makeOP<opset1::Multiply>({mul_x2_sin, neg}, {{"auto_broadcast", "numpy"}});+ out1 = makeOP<opset1::Add>({mul_x1_cos, neg_x2_sin}, {{"auto_broadcast", "numpy"}});+ } else {+ out1 = makeOP<opset1::Subtract>({mul_x1_cos, mul_x2_sin}, {{"auto_broadcast", "numpy"}});+ }+ auto mul_x2_cos = makeOP<opset1::Multiply>({split->output(1), cos}, {{"auto_broadcast", "numpy"}});+ auto mul_x1_sin = makeOP<opset1::Multiply>({split->output(0), sin}, {{"auto_broadcast", "numpy"}});+ auto out2 = makeOP<opset1::Add>({mul_x2_cos, mul_x1_sin}, {{"auto_broadcast", "numpy"}});++ std::vector<int64_t> idx1v(half_elems), idx2v(half_elems);+ for (int k = 0; k < half_elems; ++k) {+ idx1v[k] = (k / half) * dim + (k % half);+ idx2v[k] = idx1v[k] + half;+ }+ const Shape idx_shape{static_cast<size_t>(half_elems), 1};+ auto make_idx = [&](const std::vector<int64_t>& v) -> std::shared_ptr<Node> {+ if (i32_indices)+ return makeConst(element::i32, idx_shape, std::vector<int32_t>(v.begin(), v.end()));+ return makeConst(element::i64, idx_shape, v);+ };+ auto zeros = makeConst(element::f32, {static_cast<size_t>(total)}, std::vector<float>(total, 0.0f));+ auto upd_shape = makeConst(element::i64, {1}, std::vector<int64_t>{half_elems});+ auto upd1 = makeOP<opset1::Reshape>({out1, upd_shape}, {{"special_zero", false}});+ auto idx1 = make_idx(idx1v);+ auto scatter1 = makeOP<op::v3::ScatterNDUpdate>({zeros, idx1, upd1});+ auto upd2 = makeOP<opset1::Reshape>({out2, upd_shape}, {{"special_zero", false}});+ auto idx2 = make_idx(idx2v);+ auto scatter2 = makeOP<op::v3::ScatterNDUpdate>({scatter1, idx2, upd2});+ std::shared_ptr<Node> result;+ if (flatten_result) {+ auto out_shape = makeConst(element::i64, {3}, std::vector<int64_t>{batch, seq, heads * dim});+ result = makeOP<opset1::Reshape>({scatter2, out_shape}, {{"special_zero", false}});+ } else {+ auto out_shape = makeConst(element::i64, {4}, std::vector<int64_t>{batch, seq, heads, dim});+ result = makeOP<opset1::Reshape>({scatter2, out_shape}, {{"special_zero", false}});+ }++ return std::make_shared<Model>(OutputVector{result}, ParameterVector{x, cos, sin});+}++std::shared_ptr<ov::Model> make_fused_rope_ref(bool flatten_result = false) {+ using namespace ov;+ const int batch = 1, seq = 2, heads = 2, dim = 4;+ auto x = std::make_shared<opset1::Parameter>(element::f32, PartialShape{batch, seq, heads, dim});+ auto cos = std::make_shared<opset1::Parameter>(element::f32, PartialShape{batch, seq, 1, dim / 2});+ auto sin = std::make_shared<opset1::Parameter>(element::f32, PartialShape{batch, seq, 1, dim / 2});+ std::shared_ptr<Node> rope = makeOP<op::internal::RoPE>({x, cos, sin},+ {{"config.slice_start", 0},+ {"config.slice_stop", 0},+ {"config.input_trans0213", false},+ {"config.output_trans0213", false},+ {"config.is_interleaved", false},+ {"config.rotary_ndims", dim},+ {"config.cos_sin_ndims", dim / 2},+ {"config.is_chatglm", false},+ {"config.support_2d_rope", false},+ {"config.support_3d_rope", false},+ {"config.is_qwen", false},+ {"config.use_rope_cache", false},+ {"config.is_ltx_video", false},+ {"config.head_cnt", 0},+ {"config.head_size", 0},+ {"config.gather_position_arg_id", 0}});+ if (flatten_result) {+ auto out_shape = makeConst(element::i64, {3}, std::vector<int64_t>{batch, seq, heads * dim});+ rope = makeOP<opset1::Reshape>({rope, out_shape}, {{"special_zero", false}});+ }+ return std::make_shared<Model>(OutputVector{rope}, ParameterVector{x, cos, sin});+}+} // namespace++TEST_F(TransformationTestsF, ConvertToROPE_SliceAssign_Subtract) {+ disable_rt_info_check();+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ model = make_slice_assign_rope_model(/*add_negated_form=*/false, /*cos_sin_shape=*/{1, 2, 1, 2});+ manager.register_pass<ov::pass::RoPEFusion>();+ model_ref = make_fused_rope_ref();+}++TEST_F(TransformationTestsF, ConvertToROPE_SliceAssign_AddNegated) {+ disable_rt_info_check();+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ model = make_slice_assign_rope_model(/*add_negated_form=*/true, /*cos_sin_shape=*/{1, 2, 1, 2});+ manager.register_pass<ov::pass::RoPEFusion>();+ model_ref = make_fused_rope_ref();+}++TEST_F(TransformationTestsF, ConvertToROPE_SliceAssign_InferredSplitLength) {+ disable_rt_info_check();+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ model = make_slice_assign_rope_model(/*add_negated_form=*/false,+ /*cos_sin_shape=*/{1, 2, 1, 2},+ /*flatten_result=*/false,+ /*i32_indices=*/false,+ /*inferred_split_len=*/true);+ manager.register_pass<ov::pass::RoPEFusion>();+ model_ref = make_fused_rope_ref();+}++TEST_F(TransformationTestsF, ConvertToROPE_SliceAssign_FlattenedResult) {+ disable_rt_info_check();+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ model = make_slice_assign_rope_model(/*add_negated_form=*/false,+ /*cos_sin_shape=*/{1, 2, 1, 2},+ /*flatten_result=*/true);+ manager.register_pass<ov::pass::RoPEFusion>();+ model_ref = make_fused_rope_ref(/*flatten_result=*/true);+}++TEST_F(TransformationTestsF, ConvertToROPE_SliceAssign_I32Indices) {+ disable_rt_info_check();+ comparator.enable(FunctionsComparator::ATTRIBUTES);+ model = make_slice_assign_rope_model(/*add_negated_form=*/false,+ /*cos_sin_shape=*/{1, 2, 1, 2},+ /*flatten_result=*/false,+ /*i32_indices=*/true);+ manager.register_pass<ov::pass::RoPEFusion>();+ model_ref = make_fused_rope_ref();+}