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
[GPU] Preserve special-zero reshape semantics in MoE fusion (#39306)
Sungeun Kim313eee5a3de4
diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cppindex d6acb543c20..5403388d7d0 100644--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp@@ -255,6 +255,12 @@#include "openvino/util/log.hpp"#include "intel_gpu/primitives/scaled_dot_product_attention.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/equal.hpp"+#include "openvino/op/logical_and.hpp"+#include "openvino/op/logical_or.hpp"+#include "openvino/op/select.hpp"+#include "openvino/op/shape_of.hpp"namespace {template<typename T>static bool disable_reduce_decomposition(const std::shared_ptr<const ov::Node> node) {@@ -473,6 +479,131 @@ extern bool check_cm_jit_support(cldnn::engine& e, const cldnn::ExecutionConfig&namespace ov::intel_gpu {+class NormalizeMoEOutputReshape : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("NormalizeMoEOutputReshape");++ NormalizeMoEOutputReshape() {+ using namespace ov::pass::pattern;++ auto product = wrap_type<ov::op::v1::Multiply>();+ auto reduction = wrap_type<ov::op::v1::ReduceSum>({product, any_input()});+ auto reshape = wrap_type<ov::op::v1::Reshape>({reduction, any_input()});++ ov::matcher_pass_callback callback = [this](ov::pass::pattern::Matcher& m) {+ const auto root = ov::as_type_ptr<ov::op::v1::Reshape>(m.get_match_root());+ if (transformation_callback(root) || !root->get_special_zero()) {+ return false;+ }+ const auto reduce = root->input_value(0).get_node_shared_ptr();+ const auto multiply = reduce->input_value(0).get_node_shared_ptr();+ ov::Output<ov::Node> gemm;+ ov::Output<ov::Node> routing;+ for (const auto& input : multiply->input_values()) {+ const auto node = input.get_node_shared_ptr();+ if (ov::is_type<ov::op::internal::GatherMatmul>(node) || ov::is_type<ov::op::internal::GatherMatmulCompressed>(node)) {+ gemm = input;+ } else {+ routing = input;+ }+ }+ const auto& shape = root->get_input_partial_shape(0);+ if (gemm.get_node() == nullptr || routing.get_node() == nullptr || shape.rank() != 2) {+ return false;+ }+ const auto target = ov::util::get_constant_from_source(root->input_value(1));+ const auto& target_shape = root->get_input_partial_shape(1);+ if (target_shape.rank() != 1 || !target_shape[0].is_static() || target_shape[0].get_length() != 2) {+ return false;+ }+ if (target) {+ const auto values = target->cast_vector<int64_t>();+ if (std::find(values.begin(), values.end(), 0) == values.end()) {+ return false;+ }+ if (shape[1].is_static() && shape[1].get_length() > 0 &&+ ((values[0] == 0 && (values[1] == 0 || values[1] == shape[1].get_length() || values[1] == -1)) ||+ (values[0] == -1 && values[1] == 0))) {+ const auto new_target = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{-1, shape[1].get_length()});+ ov::copy_runtime_info(target, new_target);+ root->input(1).replace_source_output(new_target);+ root->set_special_zero(false);+ root->validate_and_infer_types();+ return true;+ }+ }++ const auto reduction_op = ov::as_type_ptr<ov::op::v1::ReduceSum>(reduce);+ const auto multiply_op = ov::as_type_ptr<ov::op::v1::Multiply>(multiply);+ const auto axes = ov::util::get_constant_from_source(reduction_op->input_value(1));+ const auto routing_rank = routing.get_partial_shape().rank();+ if (reduction_op->get_keep_dims() || !axes ||+ (axes->cast_vector<int64_t>() != std::vector<int64_t>{0} && axes->cast_vector<int64_t>() != std::vector<int64_t>{-3}) ||+ multiply_op->get_autob().m_type != ov::op::AutoBroadcastType::NUMPY || routing_rank.is_dynamic() || routing_rank.get_length() > 3) {+ return false;+ }++ // Derive the original reduced shape without retaining the unfused expert computation.+ const auto type = ov::element::i64;+ ov::NodeVector new_nodes;+ ov::Output<ov::Node> target_values = root->input_value(1);+ if (target_values.get_element_type() != type) {+ target_values = std::make_shared<ov::op::v0::Convert>(target_values, type);+ new_nodes.push_back(target_values.get_node_shared_ptr());+ }+ const auto axis = ov::op::v0::Constant::create(type, ov::Shape{}, {0});+ const auto indices_shape = std::make_shared<ov::op::v3::ShapeOf>(gemm.get_node()->input_value(2), type);+ const auto token_dim = std::make_shared<ov::op::v8::Gather>(indices_shape, ov::op::v0::Constant::create(type, ov::Shape{1}, {0}), axis);+ const auto weights_shape = std::make_shared<ov::op::v3::ShapeOf>(gemm.get_node()->input_value(1), type);+ const auto hidden_dim = std::make_shared<ov::op::v8::Gather>(weights_shape, ov::op::v0::Constant::create(type, ov::Shape{1}, {1}), axis);+ const auto gemm_shape = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{token_dim, hidden_dim}, 0);+ const auto routing_shape = std::make_shared<ov::op::v3::ShapeOf>(routing, type);+ const auto padded_routing_shape = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{ov::op::v0::Constant::create(type, ov::Shape{static_cast<size_t>(3 - routing_rank.get_length())}, {1}), routing_shape},+ 0);+ const auto routing_tail =+ std::make_shared<ov::op::v8::Gather>(padded_routing_shape, ov::op::v0::Constant::create(type, ov::Shape{2}, {1, 2}), axis);+ const auto one = ov::op::v0::Constant::create(type, ov::Shape{}, {1});+ const auto original_shape = std::make_shared<ov::op::v1::Select>(std::make_shared<ov::op::v1::Equal>(gemm_shape, one), routing_tail, gemm_shape);+ const auto zero = ov::op::v0::Constant::create(type, ov::Shape{}, {0});+ const auto is_zero = std::make_shared<ov::op::v1::Equal>(target_values, zero);+ // With an axis copy, special_zero infers -1 from the remaining original dimension, also for empty tensors.+ const auto other_is_zero = std::make_shared<ov::op::v8::Gather>(is_zero, ov::op::v0::Constant::create(type, ov::Shape{2}, {1, 0}), axis);+ const auto minus_one = ov::op::v0::Constant::create(type, ov::Shape{}, {-1});+ const auto is_minus_one = std::make_shared<ov::op::v1::Equal>(target_values, minus_one);+ const auto copied_minus_one = std::make_shared<ov::op::v1::LogicalAnd>(is_minus_one, other_is_zero);+ const auto use_original = std::make_shared<ov::op::v1::LogicalOr>(is_zero, copied_minus_one);+ const auto new_target = std::make_shared<ov::op::v1::Select>(use_original, original_shape, target_values);+ new_nodes.insert(new_nodes.end(),+ {axis,+ indices_shape,+ token_dim,+ weights_shape,+ hidden_dim,+ gemm_shape,+ routing_shape,+ padded_routing_shape,+ routing_tail,+ one,+ original_shape,+ zero,+ is_zero,+ other_is_zero,+ minus_one,+ is_minus_one,+ copied_minus_one,+ use_original,+ new_target});+ ov::copy_runtime_info(root, new_nodes);+ root->input(1).replace_source_output(new_target);+ root->set_special_zero(false);+ root->validate_and_infer_types();+ return true;+ };+ register_matcher(std::make_shared<ov::pass::pattern::Matcher>(reshape, "NormalizeMoEOutputReshape"), callback);+ }+};+namespace {// Detect whether the model contains a linear-attention (Mamba2 / Gated DeltaNet)// block. Such hybrid-attention models have an SSM gated output whose activation@@ -742,6 +873,7 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {// oneDNN, which requires an in-order OCL queue. If oneDNN is// disabled (e.g. via OV_GPU_USE_ONEDNN=0 on an IMMAD GPU), the// queue stays out-of-order and the oneDNN stream creation may assert.+ manager.register_pass<ov::intel_gpu::NormalizeMoEOutputReshape>();manager.register_pass<ov::pass::MoeOpFusion>();manager.register_pass<ov::intel_gpu::FuseMoERouterScale>();manager.register_pass<ov::intel_gpu::FuseMOESharedExpert>();diff --git a/src/plugins/intel_gpu/tests/unit/transformations/xattention_kv_cache_transform_test.cpp b/src/plugins/intel_gpu/tests/unit/transformations/xattention_kv_cache_transform_test.cppindex 9d8e8d40a99..ddb5f50367c 100644--- a/src/plugins/intel_gpu/tests/unit/transformations/xattention_kv_cache_transform_test.cpp+++ b/src/plugins/intel_gpu/tests/unit/transformations/xattention_kv_cache_transform_test.cpp@@ -4,9 +4,12 @@#include <gtest/gtest.h>+#include <algorithm>#include <memory>+#include <optional>#include <string>#include <tuple>+#include <utility>#include <vector>#include "intel_gpu/op/fully_connected_compressed.hpp"@@ -20,6 +23,8 @@#include "openvino/op/constant.hpp"#include "openvino/op/paged_attention.hpp"#include "openvino/op/parameter.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/pass/manager.hpp"#include "openvino/runtime/internal_properties.hpp"#include "openvino/runtime/intel_gpu/properties.hpp"#include "openvino/runtime/properties.hpp"@@ -252,4 +257,180 @@ TEST(XAttentionTransformPipelineTest, NormalizesByTokenFp16RtInfoToCompressedCacEXPECT_EQ(value_shape[3].get_length(), 68);}+static std::optional<ov::Shape> infer_reshape(const ov::Shape& data_shape, const std::vector<int64_t>& target, bool special_zero) {+ try {+ const auto data = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, data_shape);+ const auto pattern = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{target.size()}, target);+ return std::make_shared<ov::op::v1::Reshape>(data, pattern, special_zero)->get_output_shape(0);+ } catch (const ov::Exception&) {+ return std::nullopt;+ }+}++class NormalizeMoEOutputReshapeTest : public testing::TestWithParam<std::tuple<bool, bool, int>> {};++TEST_P(NormalizeMoEOutputReshapeTest, ResolvesAxisCopies) {+ const auto [compressed, swapped, target_kind] = GetParam();+ const auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, -1, 8});+ const auto indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1, 2});+ const auto weights = ov::op::v0::Constant::create(compressed ? ov::element::u8 : ov::element::f16, ov::Shape{3, 8, 8}, {1});+ std::shared_ptr<ov::Node> gemm;+ if (compressed) {+ gemm = std::make_shared<ov::op::internal::GatherMatmulCompressed>(input,+ weights,+ indices,+ ov::op::v0::Constant::create(ov::element::f16, ov::Shape{0}, std::vector<float>{}),+ ov::op::v0::Constant::create(ov::element::f16, ov::Shape{3, 8, 1}, {1}),+ ov::op::v0::Constant::create(ov::element::u8, ov::Shape{3, 8, 1}, {0}));+ } else {+ gemm = std::make_shared<ov::op::internal::GatherMatmul>(input, weights, indices);+ }+ const auto routing = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{2, -1, 1});+ auto product = std::make_shared<ov::op::v1::Multiply>(swapped ? routing : gemm, swapped ? gemm : routing);+ if (target_kind == 7) {+ product = std::make_shared<ov::op::v1::Multiply>(routing, input);+ }+ const auto reduction = std::make_shared<ov::op::v1::ReduceSum>(product, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}), false);+ ov::ParameterVector parameters{input, indices, routing};+ ov::Output<ov::Node> target = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, 8});+ if (target_kind == 1) {+ target = std::make_shared<ov::op::v8::Slice>(ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {3, 0, 8}),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {3}),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}));+ } else if (target_kind == 2) {+ const auto shape_parameter = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{2});+ target = shape_parameter;+ parameters.push_back(shape_parameter);+ } else if (target_kind >= 3 && target_kind <= 5) {+ const int64_t second = target_kind == 3 ? -1 : target_kind == 4 ? 0 : 4;+ target = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, second});+ } else if (target_kind == 8) {+ target = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {-1, 0});+ } else if (target_kind == 9) {+ target = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {-1, 8});+ }+ const auto reshape = std::make_shared<ov::op::v1::Reshape>(reduction, target, target_kind != 6);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{reshape}, parameters);+ const auto original_shape = reshape->get_output_partial_shape(0);+ ov::pass::Manager manager;+ manager.register_pass<ov::intel_gpu::NormalizeMoEOutputReshape>();+ manager.run_passes(model);+ const bool normalized = target_kind <= 5 || target_kind == 8;+ EXPECT_EQ(reshape->get_special_zero(), normalized ? false : target_kind != 6);+ if (target_kind == 0 || target_kind == 1 || target_kind == 3 || target_kind == 4 || target_kind == 8) {+ const auto value = ov::as_type_ptr<ov::op::v0::Constant>(reshape->get_input_node_shared_ptr(1));+ ASSERT_NE(value, nullptr);+ EXPECT_EQ(value->cast_vector<int64_t>(), (std::vector<int64_t>{-1, 8}));+ EXPECT_EQ(reshape->get_output_partial_shape(0), original_shape);+ } else if (normalized) {+ const auto select = ov::as_type_ptr<ov::op::v1::Select>(reshape->get_input_node_shared_ptr(1));+ ASSERT_NE(select, nullptr);+ EXPECT_EQ(select->input_value(2), target);+ ov::ParameterVector shape_parameters{indices, routing};+ ov::TensorVector inputs{ov::Tensor(ov::element::i32, {4, 2}), ov::Tensor(ov::element::f16, {2, 4, 1})};+ if (target_kind == 2) {+ shape_parameters.push_back(parameters.back());+ inputs.emplace_back(ov::element::i64, ov::Shape{2});+ inputs.back().data<int64_t>()[0] = 0;+ inputs.back().data<int64_t>()[1] = 8;+ }+ const auto shape_model = std::make_shared<ov::Model>(ov::OutputVector{select}, shape_parameters);+ for (const auto& node : shape_model->get_ordered_ops()) {+ EXPECT_FALSE(ov::is_type<ov::op::internal::GatherMatmul>(node));+ EXPECT_FALSE(ov::is_type<ov::op::internal::GatherMatmulCompressed>(node));+ }+ ov::TensorVector outputs{ov::Tensor(ov::element::i64, {2})};+ ASSERT_TRUE(shape_model->evaluate(outputs, inputs));+ EXPECT_EQ(outputs[0].data<int64_t>()[0], 4);+ EXPECT_EQ(outputs[0].data<int64_t>()[1], target_kind == 5 ? 4 : 8);+ } else {+ EXPECT_EQ(reshape->input_value(1), target);+ }+}++INSTANTIATE_TEST_SUITE_P(smoke, NormalizeMoEOutputReshapeTest, testing::Combine(testing::Bool(), testing::Bool(), testing::Range(0, 10)));++TEST(NormalizeMoEOutputReshapeTest, ResolvesDynamicHiddenSizeAndTarget) {+ const auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, -1, 8});+ const auto indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1, 2});+ const auto weights = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{3, -1, 8});+ const auto gemm = std::make_shared<ov::op::internal::GatherMatmul>(input, weights, indices);+ const auto routing = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{2, -1, 1});+ const auto product = std::make_shared<ov::op::v1::Multiply>(gemm, routing);+ const auto reduction = std::make_shared<ov::op::v1::ReduceSum>(product, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}), false);+ const auto target = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{2});+ const auto reshape = std::make_shared<ov::op::v1::Reshape>(reduction, target, true);+ const auto model = std::make_shared<ov::Model>(ov::OutputVector{reshape}, ov::ParameterVector{input, weights, indices, routing, target});+ ov::pass::Manager manager;+ manager.register_pass<ov::intel_gpu::NormalizeMoEOutputReshape>();+ manager.run_passes(model);+ EXPECT_FALSE(reshape->get_special_zero());+ const auto shape_model = std::make_shared<ov::Model>(ov::OutputVector{reshape->input_value(1)}, ov::ParameterVector{weights, indices, routing, target});+ for (const auto& node : shape_model->get_ordered_ops()) {+ EXPECT_FALSE(ov::is_type<ov::op::internal::GatherMatmul>(node));+ }+ for (const auto& [tokens, routing_tokens, hidden] : std::vector<std::tuple<size_t, size_t, size_t>>{{4, 4, 8}, {1, 4, 8}, {4, 1, 8}, {0, 1, 8}, {1, 0, 8}, {4, 4, 0}}) {+ for (const auto& values : std::vector<std::vector<int32_t>>{{0, 0}, {-1, 0}, {0, -1}, {2, 16}}) {+ ov::TensorVector inputs{ov::Tensor(ov::element::f16, {3, hidden, 8}),+ ov::Tensor(ov::element::i32, {tokens, 2}),+ ov::Tensor(ov::element::f16, {2, routing_tokens, 1}),+ ov::Tensor(ov::element::i32, {2})};+ std::copy(values.begin(), values.end(), inputs.back().data<int32_t>());+ ov::TensorVector outputs{ov::Tensor(shape_model->get_output_element_type(0), {2})};+ ASSERT_TRUE(shape_model->evaluate(outputs, inputs));+ const ov::Shape original_shape{tokens == 1 ? routing_tokens : tokens, hidden};+ const auto resolved = ov::op::v0::Constant(outputs[0]).cast_vector<int64_t>();+ EXPECT_EQ(infer_reshape(original_shape, resolved, false),+ infer_reshape(original_shape, {values[0], values[1]}, true));+ }+ }+}++class NormalizeMoEOutputReshapeTargetTypeTest : public testing::TestWithParam<ov::element::Type> {};++TEST_P(NormalizeMoEOutputReshapeTargetTypeTest, SupportsIntegralTargetTypes) {+ const auto type = GetParam();+ for (const bool constant_target : {true, false}) {+ const auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{1, -1, 8});+ const auto indices = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1, 2});+ const auto weights = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{3, 8, 8}, {1});+ const auto gemm = std::make_shared<ov::op::internal::GatherMatmul>(input, weights, indices);+ const auto routing = std::make_shared<ov::op::v0::Parameter>(ov::element::f16, ov::PartialShape{2, -1, 1});+ const auto product = std::make_shared<ov::op::v1::Multiply>(gemm, routing);+ const auto reduction = std::make_shared<ov::op::v1::ReduceSum>(product, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}), false);+ ov::ParameterVector parameters{input, indices, routing};+ ov::Output<ov::Node> target = ov::op::v0::Constant::create(type, ov::Shape{2}, {0, 8});+ if (!constant_target) {+ const auto shape_parameter = std::make_shared<ov::op::v0::Parameter>(type, ov::Shape{2});+ target = shape_parameter;+ parameters.push_back(shape_parameter);+ }+ const auto reshape = std::make_shared<ov::op::v1::Reshape>(reduction, target, true);+ const auto original_shape = reshape->get_output_partial_shape(0);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{reshape}, parameters);+ ov::pass::Manager manager;+ manager.register_pass<ov::intel_gpu::NormalizeMoEOutputReshape>();+ ASSERT_NO_THROW(manager.run_passes(model));+ EXPECT_FALSE(reshape->get_special_zero());+ EXPECT_EQ(reshape->get_output_partial_shape(0), original_shape);+ ov::ParameterVector shape_parameters{indices, routing};+ ov::TensorVector inputs{ov::Tensor(ov::element::i32, {4, 2}), ov::Tensor(ov::element::f16, {2, 4, 1})};+ const auto target_value = ov::op::v0::Constant::create(type, ov::Shape{2}, {0, 8});+ if (!constant_target) {+ shape_parameters.push_back(parameters.back());+ inputs.push_back(target_value->get_tensor_view());+ }+ const auto shape_model = std::make_shared<ov::Model>(ov::OutputVector{reshape->input_value(1)}, shape_parameters);+ ov::TensorVector outputs{ov::Tensor(shape_model->get_output_element_type(0), {2})};+ ASSERT_TRUE(shape_model->evaluate(outputs, inputs));+ const auto resolved = ov::op::v0::Constant(outputs[0]).cast_vector<int64_t>();+ EXPECT_EQ(infer_reshape(ov::Shape{4, 8}, resolved, false), (std::optional<ov::Shape>{ov::Shape{4, 8}}));+ }+}++INSTANTIATE_TEST_SUITE_P(smoke,+ NormalizeMoEOutputReshapeTargetTypeTest,+ testing::Values(ov::element::i8, ov::element::i16, ov::element::i32, ov::element::i64, ov::element::u8, ov::element::u32));+} // namespace ov::test::intel_gpu