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
[GGUF] Preserve RMS/RoPE fusion and Q4_K prefill performance (#39742)
Maxim Vafin739714d6de96
diff --git a/src/frontends/gguf/src/builder/blocks/ffn.cpp b/src/frontends/gguf/src/builder/blocks/ffn.cppindex 3be441eaf7e..f15867341f2 100644--- a/src/frontends/gguf/src/builder/blocks/ffn.cpp+++ b/src/frontends/gguf/src/builder/blocks/ffn.cpp@@ -25,7 +25,13 @@ std::string gated_gate_up(GraphEmitter& e,e.add_weight(gate_w);e.add_weight(up_w);const auto& shape = e.value(ffn_norm).get_partial_shape();- const bool rank3 = shape.rank() == 4 && shape[1] == 1 && shape[3].is_static() &&+ const auto gate_type = e.weight_qtype(gate_w);+ const auto up_type = e.weight_qtype(up_w);+ // Retain Q4_K GeGLU rank 4 for GPU FC selection; u2 weights need rank 3 for fusion.+ const bool rank4_geglu = glu_op == "GGML_GLU_OP_GEGLU" &&+ (gate_type == GGUF_TYPE_Q4_K || up_type == GGUF_TYPE_Q4_K) &&+ !gguf_has_u2_weights(gate_type) && !gguf_has_u2_weights(up_type);+ const bool rank3 = !rank4_geglu && shape.rank() == 4 && shape[1] == 1 && shape[3].is_static() &&e.value(gate_w).get_partial_shape().rank() == 2 && e.value(up_w).get_partial_shape().rank() == 2;const std::map<std::string, ov::Any> attributes{{"activation_rank", rank3 ? 3 : 4}};auto gate = e.add_op("GGML_OP_MUL_MAT", gate_name, {gate_w, ffn_norm}, 0, attributes);diff --git a/src/frontends/gguf/src/pass/simplify_activation_shapes.cpp b/src/frontends/gguf/src/pass/simplify_activation_shapes.cppindex 07658396a2c..7c8219b7cd9 100644--- a/src/frontends/gguf/src/pass/simplify_activation_shapes.cpp+++ b/src/frontends/gguf/src/pass/simplify_activation_shapes.cpp@@ -10,10 +10,14 @@#include "openvino/core/graph_util.hpp"#include "openvino/core/rt_info.hpp"+#include "openvino/op/add.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/matmul.hpp"+#include "openvino/op/multiply.hpp"#include "openvino/op/normalize_l2.hpp"#include "openvino/op/reduce_mean.hpp"#include "openvino/op/reduce_sum.hpp"@@ -24,7 +28,11 @@#include "openvino/op/util/binary_elementwise_arithmetic.hpp"#include "openvino/op/util/symbolic_info.hpp"#include "openvino/op/util/unary_elementwise_arithmetic.hpp"+#include "openvino/op/variadic_split.hpp"#include "openvino/pass/manager.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp"+#include "transformations/common_optimizations/rms_fusion.hpp"#include "transformations/symbolic_transformations/symbolic_optimizations.hpp"#include "transformations/symbolic_transformations/utils.hpp"#include "transformations/utils/utils.hpp"@@ -74,6 +82,82 @@ bool consumes_matmul(const ov::Node& node) {});}+// Keep MatMul-fed RMS and residual paths intact for later fusion.+std::unordered_set<const ov::Node*> rms_matmul_nodes(const ov::NodeVector& nodes) {+ ov::pass::RMSFusionMatcher rms_fusion(false, true, true);+ const auto matcher = rms_fusion.get_matcher();+ std::unordered_set<const ov::Node*> preserved;+ const auto preserve_match = [&](const std::shared_ptr<ov::Node>& root) {+ if (!matcher->match(root))+ return false;+ const auto matched = matcher->get_matched_nodes();+ const bool last_axis = std::any_of(matched.begin(), matched.end(), [](const std::shared_ptr<ov::Node>& n) {+ const auto mean = ov::as_type_ptr<ov::op::v1::ReduceMean>(n);+ if (!mean || !mean->get_keep_dims())+ return false;+ const auto axes = mean->get_input_node_shared_ptr(1);+ return ov::op::util::has_constant_value<int64_t>(axes, -1) ||+ ov::op::util::has_constant_value<int64_t>(axes, 3);+ });+ if (!last_axis)+ return false;+ for (const auto& matched_node : matched)+ preserved.insert(matched_node.get());+ for (const auto& target : root->output(0).get_target_inputs()) {+ const auto add = target.get_node();+ if (ov::is_type<ov::op::v1::Add>(add) && activation_shape(add->get_output_partial_shape(0)) &&+ activation_shape(add->get_input_partial_shape(1 - target.get_index())))+ preserved.insert(add);+ }+ return true;+ };+ for (const auto& node : nodes) {+ if (!ov::is_type<ov::op::v0::MatMul>(node) || !activation_shape(node->get_output_partial_shape(0)))+ continue;+ for (const auto& target : node->output(0).get_target_inputs()) {+ const auto root = target.get_node()->shared_from_this();+ if (!ov::is_type_any_of<ov::op::v1::Multiply, ov::op::v1::Divide>(root) || !preserve_match(root))+ continue;+ for (const auto& next : root->output(0).get_target_inputs()) {+ const auto gamma = next.get_node()->shared_from_this();+ if (ov::is_type<ov::op::v1::Multiply>(gamma))+ preserve_match(gamma);+ }+ }+ }+ return preserved;+}++std::unordered_set<const ov::Node*> rope_nodes(const ov::NodeVector& nodes) {+ ov::pass::RoPEFusionGPTOSS rope_fusion;+ const auto matcher = rope_fusion.get_matcher();+ std::unordered_set<const ov::Node*> preserved;+ if (!matcher)+ return preserved;+ for (const auto& node : nodes) {+ const auto concat = ov::as_type_ptr<ov::op::v0::Concat>(node);+ if (!concat || !activation_shape(concat->get_output_partial_shape(0)) ||+ (concat->get_axis() != -1 && concat->get_axis() != 3) || !matcher->match(node))+ continue;+ const auto pattern_nodes = matcher->get_pattern_map();+ const auto split = std::find_if(pattern_nodes.begin(), pattern_nodes.end(), [](const auto& match) {+ const auto pattern = ov::as_type_ptr<ov::pass::pattern::op::WrapType>(match.first);+ return pattern && pattern->get_wrapped_types().size() == 1 &&+ pattern->get_wrapped_type() == ov::op::v1::VariadicSplit::get_type_info_static();+ });+ if (split == pattern_nodes.end())+ continue;+ const auto axis = split->second->get_input_node_shared_ptr(1);+ if ((!ov::op::util::has_constant_value<int64_t>(axis, -1) &&+ !ov::op::util::has_constant_value<int64_t>(axis, 3)) ||+ !matcher->get_symbols().at("half_ndims").is_integer())+ continue;+ for (const auto& matched : matcher->get_matched_nodes())+ preserved.insert(matched.get());+ }+ return preserved;+}+} // namespacebool SimplifyActivationShapes::run_on_model(const std::shared_ptr<ov::Model>& model) {@@ -82,6 +166,8 @@ bool SimplifyActivationShapes::run_on_model(const std::shared_ptr<ov::Model>& mosymbols.register_pass<ov::pass::SymbolicPropagation>();symbols.run_passes(model);const auto nodes = model->get_ordered_ops();+ const auto rms_nodes = rms_matmul_nodes(nodes);+ const auto rope_pattern_nodes = rope_nodes(nodes);std::unordered_set<const ov::Node*> constants;std::map<ov::Output<ov::Node>, ov::Output<ov::Node>> squeezed;for (const auto& node : nodes) {@@ -96,8 +182,9 @@ bool SimplifyActivationShapes::run_on_model(const std::shared_ptr<ov::Model>& moconst auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});bool changed = false;for (const auto& node : nodes) {- if (constants.count(node.get()) || node->get_output_size() != 1 ||- !node->get_output_element_type(0).is_real() || transformation_callback(node)) {+ if (constants.count(node.get()) || rms_nodes.count(node.get()) || rope_pattern_nodes.count(node.get()) ||+ node->get_output_size() != 1 || !node->get_output_element_type(0).is_real() ||+ transformation_callback(node)) {continue;}const auto shape = node->get_output_partial_shape(0);diff --git a/src/frontends/gguf/src/pass/simplify_activation_shapes.hpp b/src/frontends/gguf/src/pass/simplify_activation_shapes.hppindex 1ab988e7fbd..f4e7548dc09 100644--- a/src/frontends/gguf/src/pass/simplify_activation_shapes.hpp+++ b/src/frontends/gguf/src/pass/simplify_activation_shapes.hpp@@ -9,7 +9,7 @@namespace ov::frontend::gguf::pass {// Remove GGML's singleton activation axis through elementwise and normalization paths,-// preserving the original layout at consumers that require it.+// preserving layout at MatMul boundaries and fusion-sensitive RMS/RoPE paths.class SimplifyActivationShapes : public ov::pass::ModelPass {public:OPENVINO_MODEL_PASS_RTTI("ov::frontend::gguf::pass::SimplifyActivationShapes");diff --git a/src/frontends/gguf/tests/test_shared_linear_inputs.cpp b/src/frontends/gguf/tests/test_shared_linear_inputs.cppindex f3938d30b45..ab7f8ec90eb 100644--- a/src/frontends/gguf/tests/test_shared_linear_inputs.cpp+++ b/src/frontends/gguf/tests/test_shared_linear_inputs.cpp@@ -2,7 +2,12 @@// SPDX-License-Identifier: Apache-2.0//+#include <algorithm>#include <cmath>+#include <cstdint>+#include <tuple>+#include <utility>+#include <vector>#include "builder/blocks/common.hpp"#include "builder/blocks/ffn.hpp"@@ -16,6 +21,7 @@#include "openvino/op/parameter.hpp"#include "openvino/op/transpose.hpp"#include "pass/materialize_weights.hpp"+#include "quant/weights.hpp"#include "utils.hpp"namespace {@@ -47,6 +53,18 @@ std::shared_ptr<ov::Node> linear_node(const ov::Output<ov::Node>& output) {node = node->get_input_node_shared_ptr(0);return node;}++DecoderConfig geglu_config(int width, const GgufWeightTable& weights) {+ DecoderParameters parameters;+ parameters.dimensions.layers = 1;+ parameters.dimensions.embedding = width;+ parameters.dimensions.query_heads = 1;+ parameters.dimensions.kv_heads = 1;+ parameters.dimensions.head_size = width;+ parameters.normalization.epsilon = 1e-5f;+ parameters.activation = FfnActivation::GeGlu;+ return DecoderConfig(parameters, weights);+}} // namespaceTEST(GGUFSharedLinearInputs, PreservesBatchesDynamicShapesAndEmptyTokens) {@@ -343,3 +361,183 @@ TEST(GGUFSharedLinearInputs, GateUpProjectionKeepsGLUBranchesRank3) {}}}++TEST(GGUFSharedLinearInputs, SwiGLUQ4KProjectionsRemainRankThree) {+ GgufWeightTable weights;+ GraphEmitter emitter(weights, "test");+ emitter.add_input("x", ov::element::f32, {2, 1, -1, 256});+ for (const auto* name : {"ffn_gate.weight", "ffn_up.weight"}) {+ auto& weight = weights[name];+ weight.shape = {3, 256};+ weight.qtype = GGUF_TYPE_Q4_K;+ weight.source_name = name;+ weight.data = ov::Tensor(ov::element::u8, {3 * 144});+ std::fill_n(weight.data.data<uint8_t>(), weight.data.get_size(), 0);+ }+ const auto output = blocks::swiglu_gate_up(emitter,+ "ffn_gate.weight",+ "ffn_up.weight",+ "x",+ "ffn_gate",+ "ffn_up",+ "ffn_swiglu",+ false);+ for (const auto* name : {"ffn_gate", "ffn_up", "ffn_swiglu"})+ EXPECT_EQ(emitter.value(name).get_partial_shape(), (ov::PartialShape{2, -1, 3})) << name;+ EXPECT_EQ(emitter.value(output).get_partial_shape(), (ov::PartialShape{2, 1, -1, 3}));+}++TEST(GGUFSharedLinearInputs, GeGLUKeepsDenseProjectionsRankThree) {+ GgufWeightTable weights;+ GraphEmitter emitter(weights, "test");+ const auto x = emitter.add_input("x", ov::element::f32, {2, 1, -1, 8});+ for (const auto* name : {"ffn_gate.weight", "ffn_up.weight"}) {+ weights[name] = ov::Tensor(ov::element::f32, {3, 8});+ for (size_t i = 0; i < 24; ++i)+ weights[name].data.data<float>()[i] = (static_cast<int>(i % 7) - 3) / 8.f;+ }+ weights["ffn_down.weight"] = ov::Tensor(ov::element::f32, {8, 3});+ blocks::geglu_ffn(emitter, geglu_config(8, weights), "", "x");+ for (const auto* name : {"ffn_gate", "ffn_up", "ffn_geglu"}) {+ EXPECT_EQ(emitter.value(name).get_partial_shape(), (ov::PartialShape{2, -1, 3})) << name;+ }+ const auto model =+ std::make_shared<ov::Model>(ov::OutputVector{emitter.value("ffn_geglu")}, ov::ParameterVector{x});+ ASSERT_TRUE(pass::MaterializeGGUFWeights().run_on_model(model));+ for (const size_t tokens : {1, 3}) {+ ov::Tensor input(ov::element::f32, {2, 1, tokens, 8});+ for (size_t i = 0; i < input.get_size(); ++i)+ input.data<float>()[i] = (static_cast<int>(i % 11) - 5) / 4.f;+ ov::TensorVector outputs{ov::Tensor(ov::element::f32, {2, tokens, 3})};+ ASSERT_TRUE(model->evaluate(outputs, {input}));+ EXPECT_EQ(outputs[0].get_shape(), (ov::Shape{2, tokens, 3}));+ for (size_t row = 0; row < 2 * tokens; ++row) {+ for (size_t n = 0; n < 3; ++n) {+ float projection = 0;+ for (size_t k = 0; k < 8; ++k)+ projection +=+ input.data<float>()[row * 8 + k] * weights["ffn_gate.weight"].data.data<float>()[n * 8 + k];+ const float gelu =+ 0.5f * projection *+ (1.f + std::tanh(0.7978845608f * (projection + 0.044715f * projection * projection * projection)));+ EXPECT_NEAR(outputs[0].data<float>()[row * 3 + n], gelu * projection, 1e-6f);+ }+ }+ }+}++TEST(GGUFSharedLinearInputs, GeGLUSelectsProjectionRankForQuantizedWeights) {+ const std::vector<std::tuple<GgufTensorType, GgufTensorType, int>> formats{+ {GGUF_TYPE_Q4_0, GGUF_TYPE_Q4_0, 3},+ {GGUF_TYPE_Q4_K, GGUF_TYPE_Q4_K, 4},+ {GGUF_TYPE_Q4_K, GGUF_TYPE_Q4_0, 4},+ {GGUF_TYPE_Q4_0, GGUF_TYPE_Q4_K, 4},+ {GGUF_TYPE_Q2_0, GGUF_TYPE_Q4_K, 3},+ {GGUF_TYPE_Q4_K, GGUF_TYPE_Q2_K, 3},+ {GGUF_TYPE_PQ2_0, GGUF_TYPE_PQ2_0, 3},+ {GGUF_TYPE_PTQ1_0, GGUF_TYPE_PTQ1_0, 3},+ };+ const auto bytes_per_row = [](GgufTensorType type) {+ switch (type) {+ case GGUF_TYPE_Q2_0:+ return 72;+ case GGUF_TYPE_Q2_K:+ return 84;+ case GGUF_TYPE_PQ2_0:+ return 68;+ case GGUF_TYPE_PTQ1_0:+ return 56;+ case GGUF_TYPE_Q4_K:+ case GGUF_TYPE_Q4_0:+ return 144;+ default:+ OPENVINO_THROW("Unexpected test weight format");+ }+ };+ for (const auto& [gate_type, up_type, rank] : formats) {+ SCOPED_TRACE(static_cast<int>(gate_type));+ SCOPED_TRACE(static_cast<int>(up_type));+ GgufWeightTable weights;+ GraphEmitter emitter(weights, "test");+ emitter.add_input("x", ov::element::f32, {2, 1, -1, 256});+ for (const auto& [name, type] :+ {std::pair{"ffn_gate.weight", gate_type}, std::pair{"ffn_up.weight", up_type}}) {+ auto& weight = weights[name];+ weight.shape = {3, 256};+ weight.qtype = type;+ weight.source_name = name;+ weight.data = ov::Tensor(ov::element::u8, {3 * static_cast<size_t>(bytes_per_row(type))});+ std::fill_n(weight.data.data<uint8_t>(), weight.data.get_size(), 0);+ }+ weights["ffn_down.weight"] = ov::Tensor(ov::element::f32, {256, 3});+ const auto output = blocks::geglu_ffn(emitter, geglu_config(256, weights), "", "x");+ const auto expected = rank == 3 ? ov::PartialShape{2, -1, 3} : ov::PartialShape{2, 1, -1, 3};+ for (const auto* name : {"ffn_gate", "ffn_up", "ffn_geglu"}) {+ EXPECT_EQ(emitter.value(name).get_partial_shape(), expected) << name;+ }+ EXPECT_EQ(emitter.value(output).get_partial_shape(), (ov::PartialShape{2, 1, -1, 256}));+ }+}++TEST(GGUFSharedLinearInputs, GeGLUQ4KRankFourPreservesBatchesAndTokens) {+ GgufWeightTable weights;+ GraphEmitter emitter(weights, "test");+ const auto x = emitter.add_input("x", ov::element::f32, {2, 1, -1, 256});+ for (const auto& [name, code] :+ {std::pair{"ffn_gate.weight", uint8_t{0x11}}, std::pair{"ffn_up.weight", uint8_t{0x23}}}) {+ auto& weight = weights[name];+ weight.shape = {3, 256};+ weight.qtype = GGUF_TYPE_Q4_K;+ weight.source_name = name;+ weight.data = ov::Tensor(ov::element::u8, {3 * 144});+ auto bytes = weight.data.data<uint8_t>();+ std::fill_n(bytes, weight.data.get_size(), 0);+ for (size_t row = 0; row < 3; ++row) {+ auto block = bytes + row * 144;+ block[1] = 0x20; // 1/128 in little-endian f16+ std::fill_n(block + 4, 12, 0x01);+ std::fill_n(block + 16, 128, code);+ }+ }+ weights["ffn_down.weight"] = ov::Tensor(ov::element::f32, {256, 3});+ const auto output = blocks::geglu_ffn(emitter, geglu_config(256, weights), "", "x");+ EXPECT_EQ(emitter.value("ffn_geglu").get_partial_shape(), (ov::PartialShape{2, 1, -1, 3}));+ EXPECT_EQ(emitter.value(output).get_partial_shape(), (ov::PartialShape{2, 1, -1, 256}));+ const auto model =+ std::make_shared<ov::Model>(ov::OutputVector{emitter.value("ffn_geglu")}, ov::ParameterVector{x});+ ASSERT_TRUE(pass::MaterializeGGUFWeights().run_on_model(model));+ std::vector<ov::Tensor> dense;+ for (const auto* name : {"ffn_gate.weight", "ffn_up.weight"}) {+ const auto weight_model =+ std::make_shared<ov::Model>(ov::OutputVector{make_weight_node(weights[name])}, ov::ParameterVector{});+ ov::TensorVector output{ov::Tensor(ov::element::f32, {3, 256})};+ ASSERT_TRUE(weight_model->evaluate(output, {}));+ ASSERT_TRUE(std::any_of(output[0].data<const float>(),+ output[0].data<const float>() + output[0].get_size(),+ [](float value) {+ return value != 0.f;+ }));+ dense.push_back(output[0]);+ }+ for (const size_t tokens : {1, 3}) {+ ov::Tensor input(ov::element::f32, {2, 1, tokens, 256});+ for (size_t i = 0; i < input.get_size(); ++i)+ input.data<float>()[i] = (static_cast<int>(i % 11) - 5) / 4.f;+ ov::TensorVector outputs{ov::Tensor(ov::element::f32, {2, 1, tokens, 3})};+ ASSERT_TRUE(model->evaluate(outputs, {input}));+ EXPECT_EQ(outputs[0].get_shape(), (ov::Shape{2, 1, tokens, 3}));+ for (size_t row = 0; row < 2 * tokens; ++row) {+ for (size_t column = 0; column < 3; ++column) {+ float gate = 0.f;+ float up = 0.f;+ for (size_t k = 0; k < 256; ++k) {+ gate += input.data<float>()[row * 256 + k] * dense[0].data<const float>()[column * 256 + k];+ up += input.data<float>()[row * 256 + k] * dense[1].data<const float>()[column * 256 + k];+ }+ const float gelu =+ 0.5f * gate * (1.f + std::tanh(0.7978845608f * (gate + 0.044715f * gate * gate * gate)));+ EXPECT_NEAR(outputs[0].data<float>()[row * 3 + column], gelu * up, 2e-6f);+ }+ }+ }+}diff --git a/src/frontends/gguf/tests/test_simplify_activation_shapes.cpp b/src/frontends/gguf/tests/test_simplify_activation_shapes.cppindex 67ab35c18d5..b4deeb4675b 100644--- a/src/frontends/gguf/tests/test_simplify_activation_shapes.cpp+++ b/src/frontends/gguf/tests/test_simplify_activation_shapes.cpp@@ -2,20 +2,33 @@// SPDX-License-Identifier: Apache-2.0//+#include <sstream>+#include <tuple>+#include "common_test_utils/ov_test_utils.hpp"+#include "openvino/decompositions/rms_norm.hpp"#include "openvino/op/add.hpp"+#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/exp.hpp"#include "openvino/op/gather.hpp"#include "openvino/op/matmul.hpp"+#include "openvino/op/multiply.hpp"#include "openvino/op/parameter.hpp"+#include "openvino/op/power.hpp"#include "openvino/op/reshape.hpp"#include "openvino/op/shape_of.hpp"#include "openvino/op/squeeze.hpp"#include "openvino/op/swish.hpp"#include "openvino/op/unsqueeze.hpp"#include "openvino/op/variadic_split.hpp"+#include "ov_ops/rms.hpp"+#include "ov_ops/rotary_positional_embeddings.hpp"#include "pass/simplify_activation_shapes.hpp"+#include "transformations/common_optimizations/fuse_rotary_positional_embeddings.hpp"+#include "transformations/common_optimizations/nop_elimination.hpp"+#include "transformations/common_optimizations/rms_fusion.hpp"+#include "transformations/symbolic_transformations/dereshape_matmul.hpp"namespace {@@ -92,6 +105,230 @@ TEST_F(GGUFActivationShapes, KeepsMatMulOutputConsumersAtRankFour) {comparator.enable(FunctionsComparator::CONSUMERS_COUNT);}+std::shared_ptr<ov::Model> matmul_rms_model(bool with_scale, bool with_residual, const ov::PartialShape& input_shape) {+ const auto x = std::make_shared<v0::Parameter>(ov::element::f32, input_shape);+ const auto target = v0::Constant::create(ov::element::i64, {4}, {-1, 1, 1, 8});+ const auto expanded = std::make_shared<v1::Reshape>(x, target, false);+ const auto weights = v0::Constant::create(ov::element::f32, {8, 8}, {0.25f});+ const auto fc = std::make_shared<v0::MatMul>(expanded, weights, false, true);+ const auto axes = v0::Constant::create(ov::element::i64, {1}, {-1});+ const auto eps = v0::Constant::create(ov::element::f32, {}, {1e-5f});+ const auto gamma = v0::Constant::create(ov::element::f32, {8}, {0.5f});+ ov::pass::NodeRegistry reg;+ ov::Output<ov::Node> value =+ ov::decomposition::rms_norm(reg, fc, axes, eps, with_scale ? gamma->output(0) : ov::Output<ov::Node>{});+ if (with_residual)+ value = std::make_shared<v1::Add>(value, expanded);+ return std::make_shared<ov::Model>(ov::OutputVector{value}, ov::ParameterVector{x});+}++std::shared_ptr<ov::Model> matmul_rms_model_ref(bool with_scale,+ bool with_residual,+ const ov::PartialShape& input_shape) {+ const auto x = std::make_shared<v0::Parameter>(ov::element::f32, input_shape);+ const auto target = v0::Constant::create(ov::element::i64, {4}, {-1, 1, 1, 8});+ const auto expanded = std::make_shared<v1::Reshape>(x, target, false);+ const auto weights = v0::Constant::create(ov::element::f32, {8, 8}, {0.25f});+ const auto fc = std::make_shared<v0::MatMul>(expanded, weights, false, true);+ const auto gamma = v0::Constant::create(ov::element::f32, {8}, {0.5f});+ ov::Output<ov::Node> value = with_scale+ ? std::make_shared<ov::op::internal::RMS>(fc, gamma, 1e-5f, ov::element::f32)+ : std::make_shared<ov::op::internal::RMS>(fc, 1e-5f, ov::element::f32);+ if (with_residual)+ value = std::make_shared<v1::Add>(value, expanded);+ return std::make_shared<ov::Model>(ov::OutputVector{value}, ov::ParameterVector{x});+}++using MatMulRmsFusionParams = std::tuple<bool, bool, ov::PartialShape>;++class GGUFMatMulRmsFusion : public GGUFActivationShapes, public testing::WithParamInterface<MatMulRmsFusionParams> {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<MatMulRmsFusionParams>& info) {+ const auto& [with_scale, with_residual, input_shape] = info.param;+ std::ostringstream name;+ name << (with_scale ? "Scaled" : "Unscaled") << (with_residual ? "Residual" : "NoResidual")+ << (input_shape[0].is_dynamic() ? "Dynamic" : "Static");+ return name.str();+ }++protected:+ void SetUp() override {+ GGUFActivationShapes::SetUp();+ const auto& [with_scale, with_residual, input_shape] = GetParam();+ model = matmul_rms_model(with_scale, with_residual, input_shape);+ model_ref = matmul_rms_model_ref(with_scale, with_residual, input_shape);+ manager.register_pass<ov::pass::RMSFusion>(false, true, true);+ manager.register_pass<ov::pass::EliminateSqueeze>();+ manager.register_pass<ov::pass::DeReshapeFullyConnected>();+ }+};++TEST_P(GGUFMatMulRmsFusion, FusesMatMulRmsNorm) {}++INSTANTIATE_TEST_SUITE_P(GGUFActivationShapes,+ GGUFMatMulRmsFusion,+ testing::Values(MatMulRmsFusionParams{true, true, {-1, 1, 8}},+ MatMulRmsFusionParams{true, true, {2, 1, 8}},+ MatMulRmsFusionParams{false, false, {2, 1, 8}},+ MatMulRmsFusionParams{false, true, {-1, 1, 8}}),+ GGUFMatMulRmsFusion::getTestCaseName);++std::shared_ptr<ov::Model> rotary_model(bool compact,+ int64_t split_axis,+ int64_t concat_axis,+ bool split_input = false,+ bool split_cos = false) {+ const bool split_last = split_axis == -1 || split_axis == 3;+ const auto x_shape = split_cos ? ov::PartialShape{2, 1, 2, 8}+ : split_last ? ov::PartialShape{2, 1, -1, 8}+ : ov::PartialShape{2, 1, 8, 4};+ const auto table_shape = split_cos ? ov::PartialShape{2, 1, 2, 4}+ : split_last ? ov::PartialShape{2, 1, -1, 4}+ : ov::PartialShape{2, 1, 4, 4};+ const auto input =+ std::make_shared<v0::Parameter>(ov::element::f32, split_input ? ov::PartialShape{2, 2, -1, 8} : x_shape);+ ov::Output<ov::Node> x = input;+ if (split_input) {+ x = std::make_shared<v1::VariadicSplit>(input,+ v0::Constant::create(ov::element::i64, {}, {1}),+ v0::Constant::create(ov::element::i64, {2}, {1, 1}))+ ->output(0);+ }+ const auto cos =+ std::make_shared<v0::Parameter>(ov::element::f32, split_cos ? ov::PartialShape{2, 1, 4, 4} : table_shape);+ const auto sin = std::make_shared<v0::Parameter>(ov::element::f32, table_shape);+ const auto split = std::make_shared<v1::VariadicSplit>(x,+ v0::Constant::create(ov::element::i64, {}, {split_axis}),+ v0::Constant::create(ov::element::i64, {2}, {4, 4}));+ const auto axis = v0::Constant::create(ov::element::i64, {1}, {1});+ ov::Output<ov::Node> first = split->output(0);+ ov::Output<ov::Node> second = split->output(1);+ ov::Output<ov::Node> cos_value = cos;+ ov::Output<ov::Node> sin_value = sin;+ if (split_cos) {+ cos_value = std::make_shared<v1::VariadicSplit>(cos,+ v0::Constant::create(ov::element::i64, {}, {2}),+ v0::Constant::create(ov::element::i64, {2}, {2, 2}))+ ->output(0);+ }+ if (compact) {+ first = std::make_shared<v0::Squeeze>(first, axis);+ second = std::make_shared<v0::Squeeze>(second, axis);+ cos_value = std::make_shared<v0::Squeeze>(cos_value, axis);+ sin_value = std::make_shared<v0::Squeeze>(sin_value, axis);+ }+ const auto first_cos =+ split_cos ? std::make_shared<v1::Multiply>(cos_value, first) : std::make_shared<v1::Multiply>(first, cos_value);+ const auto second_sin = std::make_shared<v1::Multiply>(second, sin_value);+ const auto negative =+ std::make_shared<v1::Multiply>(second_sin, v0::Constant::create(ov::element::f32, {}, {-1.f}));+ ov::Output<ov::Node> result_first = std::make_shared<v1::Add>(first_cos, negative);+ const auto second_cos = split_cos ? std::make_shared<v1::Multiply>(cos_value, second)+ : std::make_shared<v1::Multiply>(second, cos_value);+ const auto first_sin = std::make_shared<v1::Multiply>(first, sin_value);+ ov::Output<ov::Node> result_second = std::make_shared<v1::Add>(second_cos, first_sin);+ if (compact) {+ result_first = std::make_shared<v0::Unsqueeze>(result_first, axis);+ result_second = std::make_shared<v0::Unsqueeze>(result_second, axis);+ }+ const auto output = std::make_shared<v0::Concat>(ov::OutputVector{result_first, result_second}, concat_axis);+ return std::make_shared<ov::Model>(ov::OutputVector{output}, ov::ParameterVector{input, cos, sin});+}++std::shared_ptr<ov::Model> rotary_model_ref(bool split_input = false, bool split_cos = false) {+ const auto input = std::make_shared<v0::Parameter>(ov::element::f32,+ split_input ? ov::PartialShape{2, 2, -1, 8}+ : split_cos ? ov::PartialShape{2, 1, 2, 8}+ : ov::PartialShape{2, 1, -1, 8});+ ov::Output<ov::Node> x = input;+ if (split_input) {+ x = std::make_shared<v1::VariadicSplit>(input,+ v0::Constant::create(ov::element::i64, {}, {1}),+ v0::Constant::create(ov::element::i64, {2}, {1, 1}))+ ->output(0);+ }+ const auto cos =+ std::make_shared<v0::Parameter>(ov::element::f32,+ split_cos ? ov::PartialShape{2, 1, 4, 4} : ov::PartialShape{2, 1, -1, 4});+ const auto sin =+ std::make_shared<v0::Parameter>(ov::element::f32,+ split_cos ? ov::PartialShape{2, 1, 2, 4} : ov::PartialShape{2, 1, -1, 4});+ ov::Output<ov::Node> cos_value = cos;+ if (split_cos) {+ cos_value = std::make_shared<v1::VariadicSplit>(cos,+ v0::Constant::create(ov::element::i64, {}, {2}),+ v0::Constant::create(ov::element::i64, {2}, {2, 2}))+ ->output(0);+ }+ ov::op::internal::RoPE::Config config;+ config.rotary_ndims = 8;+ config.cos_sin_ndims = 4;+ const auto rope = std::make_shared<ov::op::internal::RoPE>(ov::OutputVector{x, cos_value, sin}, config);+ return std::make_shared<ov::Model>(ov::OutputVector{rope}, ov::ParameterVector{input, cos, sin});+}++using SingletonHeadRoPEParams = std::tuple<int64_t, int64_t, bool, bool>;++class SingletonHeadRoPEFusionTests : public GGUFActivationShapes,+ public testing::WithParamInterface<SingletonHeadRoPEParams> {+protected:+ void SetUp() override {+ GGUFActivationShapes::SetUp();+ const auto [split_axis, concat_axis, split_input, split_cos] = GetParam();+ model = rotary_model(false, split_axis, concat_axis, split_input, split_cos);+ model_ref = rotary_model_ref(split_input, split_cos);+ manager.register_pass<ov::pass::RoPEFusion>();+ comparator.disable(FunctionsComparator::ACCURACY);+ disable_rt_info_check();+ }+};++TEST_P(SingletonHeadRoPEFusionTests, Fuses) {}++std::string singleton_head_rope_test_name(const testing::TestParamInfo<SingletonHeadRoPEParams>& info) {+ switch (info.index) {+ case 0:+ return "NegativeAxes";+ case 1:+ return "PositiveAxes";+ case 2:+ return "SplitInput";+ case 3:+ return "SplitCosine";+ default:+ return "Unknown";+ }+}++INSTANTIATE_TEST_SUITE_P(smoke,+ SingletonHeadRoPEFusionTests,+ testing::Values(SingletonHeadRoPEParams{-1, -1, false, false},+ SingletonHeadRoPEParams{3, 3, false, false},+ SingletonHeadRoPEParams{-1, -1, true, false},+ SingletonHeadRoPEParams{-1, -1, false, true}),+ singleton_head_rope_test_name);++TEST_F(GGUFActivationShapes, SimplifiesRotaryArithmeticWithNonLastConcatAxis) {+ model = rotary_model(false, -1, 2);+ model_ref = rotary_model(true, -1, 2);+}++TEST_F(GGUFActivationShapes, SimplifiesRotaryArithmeticWithNonLastSplitAxis) {+ model = rotary_model(false, 2, -1);+ model_ref = rotary_model(true, 2, -1);+}++TEST_F(GGUFActivationShapes, KeepsUnrelatedMatMulElementwiseConsumersAtRankFour) {+ const auto x = std::make_shared<v0::Parameter>(ov::element::f32, ov::Shape{2, 1, 3, 8});+ const auto weights = v0::Constant::create(ov::element::f32, {8, 8}, {0.25f});+ const auto fc = std::make_shared<v0::MatMul>(x, weights, false, true);+ const auto scale = v0::Constant::create(ov::element::f32, {}, {0.5f});+ const auto exponent = v0::Constant::create(ov::element::f32, {}, {2.0f});+ model = std::make_shared<ov::Model>(+ ov::OutputVector{std::make_shared<v1::Multiply>(fc, scale), std::make_shared<v1::Power>(fc, exponent)},+ ov::ParameterVector{x});+}+TEST_F(GGUFActivationShapes, PreservesOtherOutputsOfReshapeProducer) {const auto make_model = [](bool compact) {const auto x = std::make_shared<v0::Parameter>(ov::element::f32, ov::Shape{1, 5, 8});