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
[NPUW][MoE] GatherTo2DGather: share indices-transform across sibling Gathers, drop rt_info (#38174)
Guoliang Shifdb825ff9880
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/gather_to_2d_gather.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/gather_to_2d_gather.cppindex e920186e9c5..94dec7a780d 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/gather_to_2d_gather.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/gather_to_2d_gather.cpp@@ -4,8 +4,11 @@#include "gather_to_2d_gather.hpp"+#include <limits>+#include <map>#include <numeric>#include <optional>+#include <unordered_map>#include "../logging.hpp"#include "openvino/core/rt_info.hpp"@@ -63,6 +66,7 @@ std::optional<GatherInfo> validate_gather_for_transform(const std::shared_ptr<ovreturn std::nullopt;}+ int64_t N = data_shape[0].get_length();int64_t M = data_shape[1].get_length();int64_t K = data_shape[2].get_length();@@ -71,6 +75,13 @@ std::optional<GatherInfo> validate_gather_for_transform(const std::shared_ptr<ovreturn std::nullopt;}+ // Flattened indices are computed as (index * M + [0, M)) in i32; skip the rewrite if N*M+ // can't be represented in i32 to avoid silently wrong results from overflow.+ constexpr int64_t kInt32Max = std::numeric_limits<int32_t>::max();+ if (M != 0 && N > kInt32Max / M) {+ return std::nullopt;+ }+// Check indices shape: should be 1D [I] with static dimensionauto indices_shape = indices_input.get_partial_shape();if (!indices_shape.rank().is_static() || indices_shape.rank().get_length() != 1) {@@ -80,89 +91,221 @@ std::optional<GatherInfo> validate_gather_for_transform(const std::shared_ptr<ovreturn std::nullopt;}+ // Only i32/i64 indices are supported; i64 gets canonicalized to i32 in build_shared_new_indices.+ auto indices_et = indices_input.get_element_type();+ if (indices_et != ov::element::i32 && indices_et != ov::element::i64) {+ return std::nullopt;+ }+// Valid gather - return info- return GatherInfo{gather, data_shape[0].get_length(), M, K, indices_shape[0].get_length()};+ return GatherInfo{gather, N, M, K, indices_shape[0].get_length()};}-// Transform a single 3D Gather to 2D Gather sequence-void transform_gather_to_2d(const GatherInfo& info) {- auto gather = info.gather_node;- auto data_input = gather->input_value(0);- auto indices_input = gather->input_value(1);+// Sibling Gathers that read the same indices tensor share an identical indices-transform+// prefix, so it should be built once per group instead of once per Gather. This is the common+// case in MoE experts, where the same selected-expert indices feed several sibling Gathers+// (e.g. gate_proj/up_proj/down_proj).- std::string gather_name = gather->get_friendly_name();+// Groups Gathers by indices source: same source Output -> same group. Preserves topological+// order both across groups (order first encountered) and within a group.+//+// Key: the indices Output itself (producer node + output index) identifies the source+// directly, since it already supports ordering comparison -- no custom key/hash type needed.+std::vector<std::vector<GatherInfo>> group_by_indices_source(const std::vector<GatherInfo>& gathers) {+ std::vector<std::vector<GatherInfo>> groups;+ std::map<ov::Output<ov::Node>, size_t> indices_to_group;++ for (const auto& info : gathers) {+ auto indices_input = info.gather_node->input_value(1);+ auto it = indices_to_group.find(indices_input);+ if (it == indices_to_group.end()) {+ indices_to_group[indices_input] = groups.size();+ groups.push_back({info});+ } else {+ groups[it->second].push_back(info);+ }+ }+ return groups;+}- // Step 1: Reshape indices [I] -> [I, 1]- std::vector<int64_t> indices_reshape_data = {static_cast<int64_t>(info.I), 1};+// Build the indices-transform prefix (steps 0-4) once for a group of Gathers that all read the+// same indices tensor, then attribute every node created here to every Gather in the group via+// copy_runtime_info. Members are deduplicated by M:+// - Same M (including a singleton group): every member reuses one scalar Multiply/Add, byte-+// for-byte identical to the original per-Gather construction.+// - Different M: one combined Multiply/Add is computed over per-branch M/range values+// concatenated at pass-build time (plain std::vector, not a runtime Concat), then routed to+// each branch via VariadicSplit.+//+// Returns: one Output per member of `group` (same order) -- the [I, M_i] tensor that member+// should flatten and gather with.+std::vector<ov::Output<ov::Node>> build_shared_new_indices(const std::vector<GatherInfo>& group) {+ OPENVINO_ASSERT(!group.empty());+ auto indices_input = group.front().gather_node->input_value(1);+ int64_t I = group.front().I;++ // Name new nodes after the shared indices source (siblings have no single owning Gather);+ // a singleton group falls back to the Gather's own name, matching the pre-sharing naming.+ std::string base_name = group.size() == 1 ? group.front().gather_node->get_friendly_name()+ : indices_input.get_node()->get_friendly_name() + "/shared_experts";++ ov::NodeVector created;++ // Step 0: canonicalize indices to i32 once (NPU lacks efficient native i64 execution).+ ov::Output<ov::Node> indices_i32 = indices_input;+ if (indices_input.get_element_type() != ov::element::i32) {+ auto convert = std::make_shared<ov::op::v0::Convert>(indices_input, ov::element::i32);+ convert->set_friendly_name(base_name + "/indices_to_i32");+ created.push_back(convert);+ indices_i32 = convert->output(0);+ }++ // Step 1: Reshape indices [I] -> [I, 1] -- shared by every member since I is identical+ // across the whole group (they all read the very same indices tensor).auto indices_reshape_shape =- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, indices_reshape_data.data());- auto reshaped_indices = std::make_shared<ov::op::v1::Reshape>(indices_input, indices_reshape_shape, false);- reshaped_indices->set_friendly_name(gather_name + "/indices_reshaped");-- // Step 2: Multiply by M to get expert starting positions [I, 1]- std::vector<int64_t> m_data = {static_cast<int64_t>(info.M)};- auto m_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1, 1}, m_data.data());- auto experts_start = std::make_shared<ov::op::v1::Multiply>(reshaped_indices, m_const);- experts_start->set_friendly_name(gather_name + "/experts_start");-- // Step 3: Create range [0, 1, 2, ..., M-1] and tile to [I, M]- std::vector<int64_t> range_values(info.M);- std::iota(range_values.begin(), range_values.end(), 0);- auto range_m =- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1, static_cast<size_t>(info.M)}, range_values);- // Mark this constant to be preserved in function body during partitioning- range_m->get_rt_info()["npuw_moe_gather_indices"] = true;-- // Tile range to [I, M]- std::vector<int64_t> tile_repeats_data = {static_cast<int64_t>(info.I), 1};- auto tile_repeats = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, tile_repeats_data.data());- auto range_m_tiled = std::make_shared<ov::op::v0::Tile>(range_m, tile_repeats);- range_m_tiled->set_friendly_name(gather_name + "/range_tiled");-- // Step 4: Add experts_start + range to get final indices [I, M]- auto new_indices = std::make_shared<ov::op::v1::Add>(experts_start, range_m_tiled);- new_indices->set_friendly_name(gather_name + "/new_indices");+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{I, 1});+ auto reshaped_indices = std::make_shared<ov::op::v1::Reshape>(indices_i32, indices_reshape_shape, false);+ reshaped_indices->set_friendly_name(base_name + "/indices_reshaped");+ created.push_back(reshaped_indices);++ // Deduplicate by M, preserving first-seen order.+ std::vector<int64_t> distinct_m;+ std::unordered_map<int64_t, size_t> m_to_slot;+ std::vector<size_t> branch_slot(group.size());+ for (size_t i = 0; i < group.size(); ++i) {+ int64_t M = group[i].M;+ auto it = m_to_slot.find(M);+ if (it == m_to_slot.end()) {+ branch_slot[i] = distinct_m.size();+ m_to_slot[M] = branch_slot[i];+ distinct_m.push_back(M);+ } else {+ branch_slot[i] = it->second;+ }+ }++ std::vector<ov::Output<ov::Node>> new_indices_per_branch(group.size());++ if (distinct_m.size() == 1) {+ // Same M for every member (also the only case a singleton group hits):+ // 1. experts_start = indices[I,1] * M (Multiply, scalar M)+ // 2. new_indices = experts_start + range[0..M) (Add)+ // new_indices is [I, M] and is reused as-is by every branch -- no Split needed.+ int64_t M = distinct_m.front();+ auto m_const = ov::op::v0::Constant::create(ov::element::i32,+ ov::Shape{1, 1},+ std::vector<int32_t>{static_cast<int32_t>(M)});+ auto experts_start = std::make_shared<ov::op::v1::Multiply>(reshaped_indices, m_const);+ experts_start->set_friendly_name(base_name + "/experts_start");+ created.push_back(experts_start);++ std::vector<int32_t> range_values(static_cast<size_t>(M));+ std::iota(range_values.begin(), range_values.end(), 0);+ auto range_m =+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1, static_cast<size_t>(M)}, range_values);++ auto new_indices = std::make_shared<ov::op::v1::Add>(experts_start, range_m);+ new_indices->set_friendly_name(base_name + "/new_indices");+ created.push_back(new_indices);++ for (size_t i = 0; i < group.size(); ++i) {+ new_indices_per_branch[i] = new_indices->output(0);+ }+ } else {+ // Mixed M values: compute every branch's formula side by side in one wide tensor, then+ // split it back into one chunk per distinct M.+ // m_vec[j] = M of the block column j belongs to (per-column Multiply factor)+ // range_vec[j] = local offset of column j in its block (0..M-1)+ //+ // 1. experts_start = indices[I,1] * m_vec (Multiply)+ // 2. new_indices_combined = experts_start + range_vec (Add) -> [I, sum(distinct_m)]+ // 3. per-branch chunks = VariadicSplit(new_indices_combined, by distinct_m)+ std::vector<int32_t> m_vec_data;+ std::vector<int32_t> range_vec_data;+ for (int64_t M : distinct_m) {+ m_vec_data.insert(m_vec_data.end(), static_cast<size_t>(M), static_cast<int32_t>(M));+ for (int64_t j = 0; j < M; ++j) {+ range_vec_data.push_back(static_cast<int32_t>(j));+ }+ }+ size_t combined_len = m_vec_data.size();++ auto m_vec_const = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1, combined_len}, m_vec_data);+ auto experts_start = std::make_shared<ov::op::v1::Multiply>(reshaped_indices, m_vec_const);+ experts_start->set_friendly_name(base_name + "/experts_start");+ created.push_back(experts_start);++ auto range_vec_const =+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1, combined_len}, range_vec_data);+ auto new_indices_combined = std::make_shared<ov::op::v1::Add>(experts_start, range_vec_const);+ new_indices_combined->set_friendly_name(base_name + "/new_indices");+ created.push_back(new_indices_combined);++ std::vector<int64_t> split_lengths(distinct_m.begin(), distinct_m.end());+ auto split_lengths_const =+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{split_lengths.size()}, split_lengths);+ auto split_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, std::vector<int64_t>{1});+ auto split = std::make_shared<ov::op::v1::VariadicSplit>(new_indices_combined, split_axis, split_lengths_const);+ split->set_friendly_name(base_name + "/split_by_m");+ created.push_back(split);++ for (size_t i = 0; i < group.size(); ++i) {+ new_indices_per_branch[i] = split->output(branch_slot[i]);+ }+ }++ ov::NodeVector group_gathers;+ group_gathers.reserve(group.size());+ for (const auto& info : group) {+ group_gathers.push_back(info.gather_node);+ }+ ov::copy_runtime_info(group_gathers, created);++ return new_indices_per_branch;+}++// Build one branch's Gather itself (steps 5-8: flatten indices/weights, 2D Gather, reshape+// back to [I, M, K]), given the new_indices this branch was assigned by the shared prefix.+void build_gather_suffix(const GatherInfo& info, const ov::Output<ov::Node>& new_indices) {+ auto gather = info.gather_node;+ auto data_input = gather->input_value(0);+ std::string gather_name = gather->get_friendly_name();// Step 5: Flatten indices [I, M] -> [I*M]- std::vector<int64_t> flat_indices_shape_data = {static_cast<int64_t>(info.I * info.M)};auto flat_indices_shape =- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, flat_indices_shape_data.data());+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{info.I * info.M});auto flat_indices = std::make_shared<ov::op::v1::Reshape>(new_indices, flat_indices_shape, false);flat_indices->set_friendly_name(gather_name + "/flat_indices");// Step 6: Flatten weights [N, M, K] -> [N*M, K]- std::vector<int64_t> flat_weights_shape_data = {static_cast<int64_t>(info.N * info.M),- static_cast<int64_t>(info.K)};auto flat_weights_shape =- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, flat_weights_shape_data.data());+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{info.N * info.M, info.K});auto flat_weights = std::make_shared<ov::op::v1::Reshape>(data_input, flat_weights_shape, false);flat_weights->set_friendly_name(gather_name + "/flat_weights");// Step 7: Perform 2D Gather [I*M, K]- std::vector<int64_t> gather_axis_data = {0};- auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, gather_axis_data.data());+ auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, std::vector<int64_t>{0});auto gathered_flat = std::make_shared<ov::op::v8::Gather>(flat_weights, flat_indices, gather_axis);gathered_flat->set_friendly_name(gather_name + "/gathered_flat");// Step 8: Reshape to final output [I, M, K]- std::vector<int64_t> output_shape_data = {static_cast<int64_t>(info.I),- static_cast<int64_t>(info.M),- static_cast<int64_t>(info.K)};- auto output_shape = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, output_shape_data.data());+ auto output_shape =+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{info.I, info.M, info.K});auto final_output = std::make_shared<ov::op::v1::Reshape>(gathered_flat, output_shape, false);final_output->set_friendly_name(gather_name + "/output");// Replace the original Gather with the final Reshapeov::replace_node(gather, final_output);- ov::copy_runtime_info(gather,- {reshaped_indices,- experts_start,- range_m_tiled,- new_indices,- flat_indices,- flat_weights,- gathered_flat,- final_output});+ ov::copy_runtime_info(gather, {flat_indices, flat_weights, gathered_flat, final_output});+}++// Transform a whole group of Gathers that share the same indices source: build the shared+// prefix once, then let every member build its own suffix off the slice it was assigned.+void transform_gather_group(const std::vector<GatherInfo>& group) {+ auto new_indices_per_branch = build_shared_new_indices(group);+ for (size_t i = 0; i < group.size(); ++i) {+ build_gather_suffix(group[i], new_indices_per_branch[i]);+ }}} // anonymous namespace@@ -186,13 +329,15 @@ bool GatherTo2DGather::run_on_model(const std::shared_ptr<ov::Model>& model) {}}- // Transform each valid Gather- for (const auto& info : gathers_to_transform) {- transform_gather_to_2d(info);+ // Transform each group of Gathers sharing the same indices source+ auto groups = group_by_indices_source(gathers_to_transform);+ for (const auto& group : groups) {+ transform_gather_group(group);}if (!gathers_to_transform.empty()) {- LOG_INFO("GatherTo2DGather: Transformed " << gathers_to_transform.size() << " Gather nodes");+ LOG_INFO("GatherTo2DGather: Transformed " << gathers_to_transform.size() << " Gather node(s) across "+ << groups.size() << " shared indices group(s)");}return !gathers_to_transform.empty();diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/gather_to_2d_gather.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/gather_to_2d_gather.hppindex 1ae1c2b9a2d..80ab184ec41 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/gather_to_2d_gather.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/gather_to_2d_gather.hpp@@ -18,11 +18,12 @@ namespace pass {* Gather(weights[N, M, K], indices[I]) -> output[I, M, K]** Into equivalent sequence:- * 1. reshaped_indices = Reshape(indices[I]) -> [I, 1]+ * 0. indices_i32 = Convert(indices[I]) -> [I] (i32) -- only inserted when the source+ * indices are not already i32 (e.g. i64)+ * 1. reshaped_indices = Reshape(indices_i32) -> [I, 1]* 2. experts_start = Multiply(reshaped_indices, M) -> [I, 1]* 3. range_m = Constant([0, 1, ..., M-1]) -> [1, M]- * range_m_tiled = Tile(range_m, [I, 1]) -> [I, M]- * 4. new_indices = Add(experts_start, range_m_tiled) -> [I, M]+ * 4. new_indices = Add(experts_start, range_m) -> [I, M]* 5. flat_indices = Reshape(new_indices) -> [I*M]* 6. flat_weights = Reshape(weights) -> [N*M, K]* 7. gathered_flat = Gather(flat_weights, flat_indices, axis=0) -> [I*M, K]@@ -30,6 +31,12 @@ namespace pass {** This transformation enables better hardware support for Gather operations* by converting multi-dimensional gather into flattened 2D gather.+ *+ * Gathers that read the exact same indices tensor share steps 0-4 -- built once per group+ * instead of once per Gather: members with equal M reuse the identical [I, M] tensor directly,+ * members with different M each get their own slice out of a single combined Multiply/Add via+ * VariadicSplit. A Gather with no siblings sharing its indices degenerates to exactly the+ * single-Gather sequence above.*/class GatherTo2DGather : public ov::pass::ModelPass {public:diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cppindex 33d9f57b98a..bbb6774f76e 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp@@ -1535,11 +1535,6 @@ void Partitioner::saveRepeatedConstants(const std::string& func_name) {}return false;};- // Helper to check if a constant is MoE Gather indices (marked by GatherTo2DGather pass)- auto is_moe_gather_const = [](const CTPtr& const_node) -> bool {- const auto& rt_info = const_node->get_rt_info();- return rt_info.count("npuw_moe_gather_indices") > 0;- };auto check_and_mark = [&](const ov::npuw::RepeatedBlock::MatchedLayers& bank) {std::unordered_set<CTPtr> instances;@@ -1553,9 +1548,8 @@ void Partitioner::saveRepeatedConstants(const std::string& func_name) {LOG_BLOCK();bool is_tiny = ov::npuw::partitioning::traits::is_tiny_shape(proto_shape);- bool is_moe_gather = is_moe_gather_const(proto_node);- if (!is_tiny && !is_moe_gather) {- LOG_DEBUG("[CUT ] Not tiny shape and not MoE Gather indices - will be cut-off from the function");+ if (!is_tiny) {+ LOG_DEBUG("[CUT ] Not tiny shape - will be cut-off from the function");return;}@@ -1574,11 +1568,7 @@ void Partitioner::saveRepeatedConstants(const std::string& func_name) {return;}- if (is_moe_gather) {- LOG_DEBUG("[KEEP] MoE Gather indices constant - identical across all repeats");- } else {- LOG_DEBUG("[KEEP] Tiny shape constant - safe to keep in function");- }+ LOG_DEBUG("[KEEP] Tiny shape constant - safe to keep in function");for (auto&& const_node : instances) {func_group.consts_to_keep.insert(const_node);}diff --git a/src/plugins/intel_npu/tests/unit/npuw/gather_to_2d_gather_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/gather_to_2d_gather_test.cppindex f32f96a3d41..08896187b79 100644--- a/src/plugins/intel_npu/tests/unit/npuw/gather_to_2d_gather_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/gather_to_2d_gather_test.cpp@@ -1,9 +1,10 @@-// Copyright (C) 2026 Intel Corporation+// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0//#include "moe_transformations/gather_to_2d_gather.hpp"+#include <gmock/gmock.h>#include <gtest/gtest.h>#include <common_test_utils/test_common.hpp>@@ -21,6 +22,13 @@* - Negative2DData: Ensure transformation skips for 1D/2D data* - NegativeSingleDimension: Ensure transformation skips when M=1 or K=1* - LargeDimensions: Stress test with realistic MoE sizes+ * - IndicesI64InsertsConvertToI32: i64 indices get canonicalized via exactly 1 Convert+ * - IndicesI32NoConvertInserted: i32 indices are left as-is, no Convert added+ * - SharedIndicesSameM_SingleSharedMultiplyAdd: sibling Gathers sharing indices + same M share+ * one Multiply/Add (no VariadicSplit)+ * - SharedIndicesDifferentM_VariadicSplitIntroduced: sibling Gathers sharing indices with+ * different M share one combined Multiply/Add, routed via VariadicSplit+ * - IndependentIndices_NoSharingNoVariadicSplit: Gathers with unrelated indices are never merged*/// Uncomment to save debug XML files during test execution@@ -62,13 +70,25 @@ protected:return count;}+ // Helper: Find the (single) Gather left in the model after the rewrite+ std::shared_ptr<op::v8::Gather> find_gather(const std::shared_ptr<Model>& model) {+ for (const auto& node : model->get_ordered_ops()) {+ if (auto gather = std::dynamic_pointer_cast<op::v8::Gather>(node)) {+ return gather;+ }+ }+ return nullptr;+ }+// Helper: Validate transformation resultsvoid validate_transformation(const std::shared_ptr<Model>& model, int64_t I, int64_t M, int64_t K) {// Verify node countsEXPECT_EQ(count_nodes<op::v8::Gather>(model), 1) << "Should have 1 Gather after transformation";- EXPECT_EQ(count_nodes<op::v0::Tile>(model), 1) << "Should have 1 Tile";+ EXPECT_EQ(count_nodes<op::v0::Tile>(model), 0) << "Should have no Tile (Add broadcasts implicitly)";EXPECT_EQ(count_nodes<op::v1::Multiply>(model), 1) << "Should have 1 Multiply";EXPECT_EQ(count_nodes<op::v1::Add>(model), 1) << "Should have 1 Add";+ EXPECT_EQ(count_nodes<op::v1::VariadicSplit>(model), 0)+ << "A standalone Gather (no siblings sharing its indices) must never produce a VariadicSplit";// Verify Multiply constant is Mbool found_multiply_constant = false;@@ -97,12 +117,7 @@ protected:for (size_t i = 0; i < 2; ++i) {auto input = add->input_value(i).get_node_shared_ptr();- auto tile = std::dynamic_pointer_cast<op::v0::Tile>(input);- if (!tile)- continue;-- auto range_input = tile->input_value(0).get_node_shared_ptr();- auto constant = std::dynamic_pointer_cast<op::v0::Constant>(range_input);+ auto constant = std::dynamic_pointer_cast<op::v0::Constant>(input);if (!constant)continue;@@ -147,11 +162,13 @@ protected:// Create a simple 3D Gather graph// data: [N, M, K], indices: [I], axis: 0 -> output: [I, M, K]+// indices_et lets callers exercise both the i64 (Convert-inserted) and i32 (no Convert) paths.std::shared_ptr<Model> create_3d_gather_graph(int64_t N,int64_t M,int64_t K,int64_t I,- const std::string& name_prefix = "gather") {+ const std::string& name_prefix = "gather",+ const element::Type& indices_et = element::i64) {// Data input [N, M, K]auto data = op::v0::Constant::create(element::f32,Shape{static_cast<size_t>(N), static_cast<size_t>(M), static_cast<size_t>(K)},@@ -159,11 +176,20 @@ std::shared_ptr<Model> create_3d_gather_graph(int64_t N,data->set_friendly_name(name_prefix + "_data");// Indices [I]- std::vector<int64_t> indices_data(I);- for (int64_t i = 0; i < I; ++i) {- indices_data[i] = i % N; // Valid indices within [0, N)+ std::shared_ptr<op::v0::Constant> indices;+ if (indices_et == element::i32) {+ std::vector<int32_t> indices_data(I);+ for (int64_t i = 0; i < I; ++i) {+ indices_data[i] = static_cast<int32_t>(i % N); // Valid indices within [0, N)+ }+ indices = op::v0::Constant::create(element::i32, Shape{static_cast<size_t>(I)}, indices_data);+ } else {+ std::vector<int64_t> indices_data(I);+ for (int64_t i = 0; i < I; ++i) {+ indices_data[i] = i % N; // Valid indices within [0, N)+ }+ indices = op::v0::Constant::create(element::i64, Shape{static_cast<size_t>(I)}, indices_data);}- auto indices = op::v0::Constant::create(element::i64, Shape{static_cast<size_t>(I)}, indices_data);indices->set_friendly_name(name_prefix + "_indices");// Axis = 0@@ -219,6 +245,44 @@ std::shared_ptr<Model> create_gather_with_single_m() {return std::make_shared<Model>(ResultVector{result}, ParameterVector{});}+// Describes one sibling Gather's data shape [N, M, K] for the shared-indices graph builder below.+struct GatherBranchSpec {+ int64_t N;+ int64_t M;+ int64_t K;+};++// Create `branches.size()` Gathers that all read the SAME indices tensor (as MoE gate_proj /+// up_proj / down_proj weight lookups typically do), each with its own data shape/branch M.+std::shared_ptr<Model> create_shared_indices_multi_gather_graph(const std::vector<GatherBranchSpec>& branches,+ int64_t I,+ const std::string& name_prefix = "moe") {+ auto indices = op::v0::Constant::create(element::i64,+ Shape{static_cast<size_t>(I)},+ std::vector<int64_t>(static_cast<size_t>(I), 0));+ indices->set_friendly_name(name_prefix + "_shared_indices");+ auto axis = op::v0::Constant::create(element::i64, Shape{}, std::vector<int64_t>{0});++ ResultVector results;+ for (size_t b = 0; b < branches.size(); ++b) {+ const auto& spec = branches[b];+ auto data = op::v0::Constant::create(+ element::f32,+ Shape{static_cast<size_t>(spec.N), static_cast<size_t>(spec.M), static_cast<size_t>(spec.K)},+ std::vector<float>(spec.N * spec.M * spec.K, 1.0f));+ data->set_friendly_name(name_prefix + "_data_" + std::to_string(b));++ auto gather = std::make_shared<op::v8::Gather>(data, indices, axis);+ gather->set_friendly_name(name_prefix + "_gather_" + std::to_string(b));++ auto result = std::make_shared<op::v0::Result>(gather);+ result->set_friendly_name(name_prefix + "_output_" + std::to_string(b));+ results.push_back(result);+ }++ return std::make_shared<Model>(results, ParameterVector{});+}+// ============================================================================// Unit Tests// ============================================================================@@ -311,4 +375,157 @@ TEST_F(GatherTo2DGatherTest, LargeDimensions) {validate_transformation(model, I, M, K);}+// Test 6: i64 indices must be canonicalized to i32 through exactly one Convert (NPU has no+// efficient native i64 execution support), and the rewritten Gather must consume i32 indices.+TEST_F(GatherTo2DGatherTest, IndicesI64InsertsConvertToI32) {+ constexpr int64_t N = 8, M = 16, K = 32, I = 4;+ auto model = create_3d_gather_graph(N, M, K, I, "gather", element::i64);++ ov::pass::Manager manager;+ manager.register_pass<GatherTo2DGather>();+ bool changed = manager.run_passes(model);++ ASSERT_TRUE(changed);+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());++ ASSERT_EQ(count_nodes<op::v0::Convert>(model), 1) << "Should insert exactly 1 Convert for i64 indices";+ for (const auto& node : model->get_ordered_ops()) {+ if (auto convert = std::dynamic_pointer_cast<op::v0::Convert>(node)) {+ EXPECT_EQ(convert->get_input_element_type(0), element::i64);+ EXPECT_EQ(convert->get_output_element_type(0), element::i32);+ }+ }++ auto gather = find_gather(model);+ ASSERT_NE(gather, nullptr);+ EXPECT_EQ(gather->get_input_element_type(1), element::i32) << "Rewritten Gather should be fed i32 indices";+}++// Test 7: i32 indices need no Convert -- the rewrite must not add one unconditionally.+TEST_F(GatherTo2DGatherTest, IndicesI32NoConvertInserted) {+ constexpr int64_t N = 8, M = 16, K = 32, I = 4;+ auto model = create_3d_gather_graph(N, M, K, I, "gather", element::i32);++ ov::pass::Manager manager;+ manager.register_pass<GatherTo2DGather>();+ bool changed = manager.run_passes(model);++ ASSERT_TRUE(changed);+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());++ EXPECT_EQ(count_nodes<op::v0::Convert>(model), 0) << "No Convert should be inserted when indices are already i32";++ auto gather = find_gather(model);+ ASSERT_NE(gather, nullptr);+ EXPECT_EQ(gather->get_input_element_type(1), element::i32);+}++// Test 8: Two sibling Gathers reading the same indices tensor with the SAME M must share a+// single Multiply/Add (indices-transform prefix built once), with no VariadicSplit involved.+TEST_F(GatherTo2DGatherTest, SharedIndicesSameM_SingleSharedMultiplyAdd) {+ constexpr int64_t I = 4, M = 16, K = 32;+ auto model = create_shared_indices_multi_gather_graph({{8, M, K}, {8, M, K}}, I, "moe_same_m");+ save_model(model, "gather_to_2d_shared_same_m_before");++ ov::pass::Manager manager;+ manager.register_pass<GatherTo2DGather>();+ bool changed = manager.run_passes(model);++ ASSERT_TRUE(changed);+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());++ EXPECT_EQ(count_nodes<op::v8::Gather>(model), 2) << "Both branches should still produce their own 2D Gather";+ EXPECT_EQ(count_nodes<op::v1::Multiply>(model), 1)+ << "Both branches share the same M, so exactly 1 Multiply should be built (not 1 per branch)";+ EXPECT_EQ(count_nodes<op::v1::Add>(model), 1)+ << "Both branches share the same M, so exactly 1 Add should be built (not 1 per branch)";+ EXPECT_EQ(count_nodes<op::v1::VariadicSplit>(model), 0) << "Same-M sharing never needs a VariadicSplit";++ // The single shared Add must fan out directly to both branches' downstream flatten-Reshape.+ for (const auto& node : model->get_ordered_ops()) {+ if (auto add = std::dynamic_pointer_cast<op::v1::Add>(node)) {+ EXPECT_EQ(add->output(0).get_target_inputs().size(), 2u)+ << "The shared Add should feed exactly the 2 sibling branches";+ }+ }+}++// Test 9: Two sibling Gathers reading the same indices tensor with DIFFERENT M must still share a+// single combined Multiply/Add, but require a VariadicSplit to route each branch its own slice.+TEST_F(GatherTo2DGatherTest, SharedIndicesDifferentM_VariadicSplitIntroduced) {+ constexpr int64_t I = 4, M1 = 16, M2 = 8, K = 32;+ auto model = create_shared_indices_multi_gather_graph({{8, M1, K}, {8, M2, K}}, I, "moe_diff_m");+ save_model(model, "gather_to_2d_shared_diff_m_before");++ ov::pass::Manager manager;+ manager.register_pass<GatherTo2DGather>();+ bool changed = manager.run_passes(model);++ ASSERT_TRUE(changed);+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());++ EXPECT_EQ(count_nodes<op::v8::Gather>(model), 2);+ EXPECT_EQ(count_nodes<op::v1::Multiply>(model), 1)+ << "Different-M branches still share ONE combined Multiply over the concatenated columns";+ EXPECT_EQ(count_nodes<op::v1::Add>(model), 1)+ << "Different-M branches still share ONE combined Add over the concatenated columns";+ ASSERT_EQ(count_nodes<op::v1::VariadicSplit>(model), 1)+ << "Different-M branches need a VariadicSplit to route their own slice";++ // The VariadicSplit's split_lengths must be exactly the 2 distinct M values (order depends on+ // topological traversal order of the group's Gathers, not on construction order), and each of+ // its 2 outputs must feed exactly 1 downstream consumer (one per branch).+ for (const auto& node : model->get_ordered_ops()) {+ auto split = std::dynamic_pointer_cast<op::v1::VariadicSplit>(node);+ if (!split)+ continue;++ auto split_lengths_const =+ std::dynamic_pointer_cast<op::v0::Constant>(split->input_value(2).get_node_shared_ptr());+ ASSERT_NE(split_lengths_const, nullptr);+ auto split_lengths = split_lengths_const->cast_vector<int64_t>();+ ASSERT_EQ(split_lengths.size(), 2u);+ EXPECT_THAT(split_lengths, ::testing::UnorderedElementsAre(M1, M2));++ ASSERT_EQ(split->get_output_size(), 2u);+ EXPECT_EQ(split->output(0).get_target_inputs().size(), 1u);+ EXPECT_EQ(split->output(1).get_target_inputs().size(), 1u);+ }++ // Output shapes must still reflect each branch's own M.+ auto results = model->get_results();+ ASSERT_EQ(results.size(), 2u);+ EXPECT_EQ(results[0]->get_output_shape(0), Shape({I, M1, K}));+ EXPECT_EQ(results[1]->get_output_shape(0), Shape({I, M2, K}));+}++// Test 10: Two Gathers reading DIFFERENT (unrelated) indices tensors must be treated as two+// independent singleton groups -- each gets its own Multiply/Add, and no VariadicSplit at all.+TEST_F(GatherTo2DGatherTest, IndependentIndices_NoSharingNoVariadicSplit) {+ constexpr int64_t N = 8, M = 16, K = 32, I = 4;+ auto model1 = create_3d_gather_graph(N, M, K, I, "gather_a");+ auto model2 = create_3d_gather_graph(N, M, K, I, "gather_b");++ // Merge into a single model with two independent Gathers (distinct indices Constants).+ ResultVector results;+ for (const auto& r : model1->get_results())+ results.push_back(r);+ for (const auto& r : model2->get_results())+ results.push_back(r);+ auto model = std::make_shared<Model>(results, ParameterVector{});++ ov::pass::Manager manager;+ manager.register_pass<GatherTo2DGather>();+ bool changed = manager.run_passes(model);++ ASSERT_TRUE(changed);+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());++ EXPECT_EQ(count_nodes<op::v8::Gather>(model), 2);+ EXPECT_EQ(count_nodes<op::v1::Multiply>(model), 2) << "Unrelated indices must not be merged into 1 Multiply";+ EXPECT_EQ(count_nodes<op::v1::Add>(model), 2) << "Unrelated indices must not be merged into 1 Add";+ EXPECT_EQ(count_nodes<op::v1::VariadicSplit>(model), 0)+ << "Independent (non-shared) indices should never introduce a VariadicSplit";+}+} // namespace