Skip to content

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

[NPUW][MoE Scaling]Qwen3-30B-A3B support on NPU. (#36269)

intelgaoxiongc88e94a57c33
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
index f94629bc8c5..0a5d0801333 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
@@ -1085,18 +1085,16 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
// online partitioning runs pattern matching (e.g. GPTOSSRouter). Must run after
// ReshapeToStatic has made all shapes static so that ShapeOf bounds are resolvable.
ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(prefill_model);
- if (generate_moe_hint == ::intel_npu::npuw::llm::MoEHint::HOST_ROUTED) {
- for (auto&& model_variant : generate_model_variants) {
- ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(model_variant);
- }
- } else if (generate_moe_hint == ::intel_npu::npuw::llm::MoEHint::DEVICE_ROUTED) {
+ for (auto&& model_variant : generate_model_variants) {
+ ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(model_variant);
+ }
+
+ if (generate_moe_hint == ::intel_npu::npuw::llm::MoEHint::DEVICE_ROUTED) {
// Apply model transformations only to GENERATE stage (PREFILL doesn't support DEVICE_ROUTED
// transformations)
for (auto&& model_variant : generate_model_variants) {
ov::npuw::ApplyMoEDeviceRoutedTransforms().run_on_model(model_variant);
}
- } else {
- OPENVINO_THROW("Unsupported MoE hint: " + std::to_string(static_cast<int>(generate_moe_hint)));
}
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.cpp
index a041bbee05a..4b80df840c7 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.cpp
@@ -336,9 +336,10 @@ std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> register_pattern
ov::npuw::v1::subgraphs::PatternRegistry& registry,
const std::size_t moe_chunk_size) {
std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> registrations;
- registrations.reserve(3);
+ registrations.reserve(5);
registrations.emplace_back(registry.on<ov::npuw::patterns::moe::GPTOSSRouter>().scoped());
+ registrations.emplace_back(registry.on<ov::npuw::patterns::moe::Qwen3Router>().scoped());
registrations.emplace_back(
registry.on<ov::npuw::patterns::moe::GPTOSSExpert>()
@@ -351,6 +352,17 @@ std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> register_pattern
})
.scoped());
+ registrations.emplace_back(
+ registry.on<ov::npuw::patterns::moe::Qwen3Expert>()
+ .at_partition([moe_chunk_size](ov::npuw::Function& function, ov::npuw::v1::subgraphs::Context& ctx) {
+ transform_experts(function, ctx, moe_chunk_size);
+ })
+ .at_compile([](ov::npuw::v1::subgraphs::CompiledPipeline& compiled_pipeline,
+ ov::npuw::v1::subgraphs::Context& compiled_context) {
+ configure_expert_compile(compiled_pipeline, compiled_context);
+ })
+ .scoped());
+
ov::npuw::v1::subgraphs::PatternRegistration downstream_registration;
downstream_registration.partition_stage = [](ov::npuw::Function& function, ov::npuw::v1::subgraphs::Context& ctx) {
transform_downstream(function, ctx);
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/device_routed_moe_transform.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/device_routed_moe_transform.cpp
index 3f467f914d7..1f91cc23cf7 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/device_routed_moe_transform.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/device_routed_moe_transform.cpp
@@ -4,8 +4,12 @@
#include "device_routed_moe_transform.hpp"
+#include <optional>
+#include <queue>
+#include <unordered_set>
+
#include "../logging.hpp"
-#include "../partitioning/patterns/moe.hpp"
+#include "moe_transformation_utils.hpp"
#include "openvino/core/rt_info.hpp"
#include "openvino/op/ops.hpp"
@@ -13,8 +17,6 @@ namespace ov {
namespace npuw {
namespace pass {
-namespace opp = ov::pass::pattern;
-
namespace {
// ============================================================================
@@ -39,9 +41,10 @@ struct LayerNodes {
struct RouterInfo {
std::shared_ptr<ov::op::v11::TopK> topk_node;
ov::Output<ov::Node> topk_indices_raw;
- ov::Output<ov::Node> topk_softmax_scores;
+ ov::Output<ov::Node> router_scores; // scores from Scatter.input(2), replaces Scatter->Transpose
int64_t k_value;
- std::string layer_id;
+ std::shared_ptr<ov::op::v1::Transpose> scatter_transpose; // the Scatter -> Transpose node
+ std::shared_ptr<ov::op::v1::Multiply> output_multiply; // expert x scores Multiply
};
// ============================================================================
@@ -57,28 +60,10 @@ inline ov::Output<ov::Node> get_weight_source(const ov::Output<ov::Node>& input)
return input;
}
-// Extract layer ID from node name (e.g., "layers.0." from full name)
-std::string extract_layer_id(const std::string& topk_name) {
- size_t layers_pos = topk_name.find("layers.");
- if (layers_pos == std::string::npos) {
- return "";
- }
-
- size_t start = layers_pos;
- size_t end = topk_name.find(".", start + 7);
- if (end == std::string::npos) {
- end = topk_name.find("/", start);
- }
-
- return (end != std::string::npos) ? topk_name.substr(start, end - start + 1) : "";
-}
-
-// Check if node name belongs to the specified layer
-inline bool belongs_to_layer(const std::string& node_name, const std::string& layer_id) {
- return node_name.find(layer_id) != std::string::npos;
-}
-
-// Check if a reshape operation is unsqueeze-like (only inserts dimensions with size 1)
+// Check if a reshape operation is unsqueeze-like (only inserts dimensions with size 1).
+// Used in collect_from_expert_output to detect activation-path Reshapes whose shape
+// is not a Constant node (e.g. driven by ShapeOf chains) but are safe to replace with
+// an Unsqueeze of the data input.
bool is_unsqueeze_like_reshape(const std::shared_ptr<ov::op::v1::Reshape>& reshape) {
auto input_shape = reshape->input_value(0).get_partial_shape();
auto output_shape = reshape->get_output_partial_shape(0);
@@ -109,216 +94,296 @@ bool is_unsqueeze_like_reshape(const std::shared_ptr<ov::op::v1::Reshape>& resha
}
// ============================================================================
-// Router processing
+// Router detection by topology
// ============================================================================
-std::optional<RouterInfo> process_router_topk(const std::shared_ptr<ov::op::v11::TopK>& topk_node) {
- if (!topk_node || topk_node->get_mode() != ov::op::v11::TopK::Mode::MAX) {
- return std::nullopt;
+// Detects a MoE router pattern starting from a ScatterElementsUpdate node.
+// Expected downstream chain: Scatter -> Transpose -> [Reshape/Unsqueeze]* -> Multiply -> ReduceSum
+// The Scatter.input(1) must trace back to a TopK (router top-k selection).
+// This approach is name-independent and works for both GPT-OSS and Qwen3.
+std::optional<RouterInfo> detect_router_by_topology(const std::shared_ptr<ov::Node>& scatter) {
+ // 1. Find Transpose as a direct consumer of Scatter.output(0)
+ std::shared_ptr<ov::op::v1::Transpose> transpose;
+ for (const auto& ti : scatter->output(0).get_target_inputs()) {
+ if (auto t = std::dynamic_pointer_cast<ov::op::v1::Transpose>(ti.get_node()->shared_from_this())) {
+ transpose = t;
+ break;
+ }
}
-
- std::string topk_name = topk_node->get_friendly_name();
- if (topk_name.find(ov::npuw::patterns::moe::MLP_ROUTER_NAME) == std::string::npos) {
+ if (!transpose)
return std::nullopt;
- }
- // Validate TopK indices shape (batch dimension should be 1, indicates it is model for decoding)
- auto topk_indices_raw = topk_node->output(1);
- auto indices_shape = topk_indices_raw.get_partial_shape();
- if (indices_shape.rank().is_static() && indices_shape.rank().get_length() == 2) {
- if (indices_shape[0].is_static() && indices_shape[0].get_length() != 1) {
- LOG_WARN(" TopK indices batch dimension is not 1, skipping");
+ // 2. Walk downstream: Transpose -> [Reshape/Unsqueeze]* -> Multiply
+ // Follow single-consumer chain to find the output_multiply (expert x scores)
+ auto follow_single = [](const std::shared_ptr<ov::Node>& n) -> std::shared_ptr<ov::Node> {
+ const auto targets = n->output(0).get_target_inputs();
+ if (targets.size() != 1)
+ return nullptr;
+ return targets.begin()->get_node()->shared_from_this();
+ };
+
+ std::shared_ptr<ov::op::v1::Multiply> output_multiply;
+ auto cur = follow_single(transpose);
+ for (int hops = 0; hops < 4 && cur; ++hops) {
+ if (auto mul = std::dynamic_pointer_cast<ov::op::v1::Multiply>(cur)) {
+ output_multiply = mul;
+ break;
+ }
+ if (!std::dynamic_pointer_cast<ov::op::v1::Reshape>(cur) &&
+ !std::dynamic_pointer_cast<ov::op::v0::Unsqueeze>(cur)) {
return std::nullopt;
}
+ cur = follow_single(cur);
}
+ if (!output_multiply)
+ return std::nullopt;
- // Extract K value
- auto k_input = topk_node->input_value(1);
- auto k_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(k_input.get_node_shared_ptr());
- if (!k_const) {
- LOG_WARN(" TopK K value is not a constant, skipping");
+ // 3. Verify ReduceSum as the single consumer of output_multiply
+ if (!std::dynamic_pointer_cast<ov::op::v1::ReduceSum>(follow_single(output_multiply)))
return std::nullopt;
- }
- int64_t k_value = k_const->cast_vector<int64_t>()[0];
- // Extract layer ID
- std::string layer_id = extract_layer_id(topk_name);
- if (layer_id.empty()) {
- LOG_WARN(" Cannot extract layer ID from: " << topk_name);
+ // 4. Trace Scatter.input(1) back to TopK (indices, possibly through Convert)
+ auto indices_node = scatter->input_value(1).get_node_shared_ptr();
+ if (auto conv = std::dynamic_pointer_cast<ov::op::v0::Convert>(indices_node)) {
+ indices_node = conv->input_value(0).get_node_shared_ptr();
+ }
+ auto topk_node = std::dynamic_pointer_cast<ov::op::v11::TopK>(indices_node);
+ if (!topk_node || topk_node->get_mode() != ov::op::v11::TopK::Mode::MAX) {
return std::nullopt;
}
- // Find Softmax for router scores
- auto topk_values = topk_node->output(0);
- std::shared_ptr<ov::Node> topk_softmax = nullptr;
- for (const auto& target : topk_values.get_target_inputs()) {
- auto consumer = target.get_node()->shared_from_this();
- if (auto softmax = std::dynamic_pointer_cast<ov::op::v8::Softmax>(consumer)) {
- topk_softmax = softmax;
- break;
+ // 5. Validate TopK indices shape: batch dimension must be 1 (decoding stage only)
+ auto topk_indices_raw = topk_node->output(1);
+ auto indices_shape = topk_indices_raw.get_partial_shape();
+ if (indices_shape.rank().is_static() && indices_shape.rank().get_length() >= 1) {
+ if (indices_shape[0].is_static() && indices_shape[0].get_length() != 1) {
+ return std::nullopt;
}
}
- if (!topk_softmax) {
- LOG_WARN(" No Softmax found for TopK values");
+ // 6. Extract K value from TopK's constant K input
+ auto k_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(topk_node->input_value(1).get_node_shared_ptr());
+ if (!k_const)
return std::nullopt;
- }
+ int64_t k_value = k_const->cast_vector<int64_t>()[0];
+
+ // 7. Router scores = Scatter.input(2): the k scores that were scattered into position
+ // GPT-OSS: Slice(Softmax(TopK.out(0))) Qwen3: Divide(TopK.out(0), ReduceSum(...))
+ auto router_scores = scatter->input_value(2);
- LOG_INFO("DeviceRoutedMoE: Processing router TopK: " << topk_name << " (K=" << k_value << ")");
+ LOG_INFO("DeviceRoutedMoE: Detected MoE router by topology, K=" << k_value);
- return RouterInfo{topk_node, topk_indices_raw, topk_softmax->output(0), k_value, layer_id};
+ return RouterInfo{topk_node, topk_indices_raw, router_scores, k_value, transpose, output_multiply};
}
// ============================================================================
-// Node collection per layer
+// Expert node collection by backward BFS from expert output
// ============================================================================
-LayerNodes collect_layer_nodes(const std::shared_ptr<ov::Model>& model, const RouterInfo& router) {
+// Collects expert subgraph nodes by tracing backward from the expert computation output.
+// output_multiply has two inputs: expert computation output (BFS entry) and router scores (skip).
+// This approach is name-independent and works for both GPT-OSS and Qwen3.
+LayerNodes collect_from_expert_output(const RouterInfo& router) {
LayerNodes nodes;
- const std::string& layer_id = router.layer_id;
- int64_t k_value = router.k_value;
+ nodes.transpose = router.scatter_transpose;
+
+ // Identify which input of output_multiply is the expert computation output.
+ // The other input comes from the Scatter->Transpose chain (router broadcast path).
+ auto is_from_scatter_transpose = [&](const std::shared_ptr<ov::Node>& n) -> bool {
+ std::shared_ptr<ov::Node> cur = n;
+ for (int hops = 0; hops < 5 && cur; ++hops) {
+ if (cur == router.scatter_transpose)
+ return true;
+ // Follow input(0) through shape ops (Reshape has data at input 0, Unsqueeze too)
+ if (std::dynamic_pointer_cast<ov::op::v1::Reshape>(cur) ||
+ std::dynamic_pointer_cast<ov::op::v0::Unsqueeze>(cur)) {
+ cur = cur->input_value(0).get_node_shared_ptr();
+ } else {
+ break;
+ }
+ }
+ return false;
+ };
+
+ ov::Output<ov::Node> expert_output;
+ bool found = false;
+ for (size_t i = 0; i < 2 && !found; ++i) {
+ auto inp = router.output_multiply->input_value(i);
+ if (!is_from_scatter_transpose(inp.get_node_shared_ptr())) {
+ expert_output = inp;
+ found = true;
+ }
+ }
+ if (!found) {
+ LOG_WARN("collect_from_expert_output: cannot identify expert output in output_multiply");
+ return nodes;
+ }
- // Single pass through all nodes to collect relevant operations
- for (const auto& n : model->get_ordered_ops()) {
- std::string node_name = n->get_friendly_name();
+ // Phase 1: BFS backward from expert_output, collecting all activation-path nodes.
+ // Constant-derived inputs (weights, scales, biases) are skipped in BFS but collected in phase 3.
+ std::queue<std::shared_ptr<ov::Node>> queue;
+ std::unordered_set<std::shared_ptr<ov::Node>> visited;
- // Skip nodes not belonging to this layer or not MoE expert nodes
- if (node_name.find(ov::npuw::patterns::moe::MLP_EXPERT_NAME) == std::string::npos ||
- !belongs_to_layer(node_name, layer_id)) {
- continue;
- }
+ auto start = expert_output.get_node_shared_ptr();
+ queue.push(start);
+ visited.insert(start);
+
+ std::vector<std::shared_ptr<ov::op::v0::Tile>> all_tiles;
+ std::vector<std::shared_ptr<ov::op::v1::Reshape>> all_const_reshapes;
+ std::vector<std::shared_ptr<ov::op::v1::Reshape>> all_dyn_reshapes;
+ std::vector<std::shared_ptr<ov::op::v0::MatMul>> all_matmuls;
+ std::vector<std::shared_ptr<ov::op::v1::Add>> all_adds;
+ std::vector<std::shared_ptr<ov::op::v1::Multiply>> all_multiplies;
+
+ while (!queue.empty()) {
+ auto n = queue.front();
+ queue.pop();
- // Collect Tile nodes
if (auto tile = std::dynamic_pointer_cast<ov::op::v0::Tile>(n)) {
- auto repeats_const =
- std::dynamic_pointer_cast<ov::op::v0::Constant>(tile->input_value(1).get_node_shared_ptr());
- if (repeats_const) {
- auto repeats_data = repeats_const->cast_vector<int64_t>();
- if (!repeats_data.empty() && repeats_data[0] > k_value) {
- if (nodes.num_experts == 0) {
- nodes.num_experts = static_cast<size_t>(repeats_data[0]);
- }
- nodes.tiles.push_back(tile);
- }
- }
- continue;
+ all_tiles.push_back(tile);
+ continue; // Tile is the boundary; don't BFS further into shared hidden state
}
-
- // Collect Reshape nodes
if (auto reshape = std::dynamic_pointer_cast<ov::op::v1::Reshape>(n)) {
- auto shape_const =
- std::dynamic_pointer_cast<ov::op::v0::Constant>(reshape->input_value(1).get_node_shared_ptr());
-
- if (!shape_const) {
- // Dynamic reshape - check if it's unsqueeze-like
- if (is_unsqueeze_like_reshape(reshape)) {
- nodes.dynamic_reshapes.push_back(reshape);
- }
- } else {
- // Constant reshape - check if dim 0 is expert dimension
- auto shape_data = shape_const->cast_vector<int64_t>();
- if (nodes.num_experts > 0 && !shape_data.empty() &&
- shape_data[0] == static_cast<int64_t>(nodes.num_experts)) {
- nodes.constant_reshapes.push_back(reshape);
- }
+ auto shape_src = reshape->input_value(1).get_node_shared_ptr();
+ if (std::dynamic_pointer_cast<ov::op::v0::Constant>(shape_src)) {
+ all_const_reshapes.push_back(reshape);
+ } else if (is_unsqueeze_like_reshape(reshape)) {
+ all_dyn_reshapes.push_back(reshape);
}
- continue;
+ } else if (auto matmul = std::dynamic_pointer_cast<ov::op::v0::MatMul>(n)) {
+ all_matmuls.push_back(matmul);
+ } else if (auto add = std::dynamic_pointer_cast<ov::op::v1::Add>(n)) {
+ all_adds.push_back(add);
+ } else if (auto mul = std::dynamic_pointer_cast<ov::op::v1::Multiply>(n)) {
+ all_multiplies.push_back(mul);
}
- // Collect MatMul nodes
- if (auto matmul = std::dynamic_pointer_cast<ov::op::v0::MatMul>(n)) {
- auto weight_source = get_weight_source(matmul->input_value(1));
- auto weight_node = weight_source.get_node_shared_ptr();
-
- // Check if quantized weight comes from Multiply with expert-dimension constant
- if (auto multiply = std::dynamic_pointer_cast<ov::op::v1::Multiply>(weight_node)) {
- for (size_t i = 0; i < 2; ++i) {
- auto mul_input = multiply->get_input_node_shared_ptr(i);
- if (auto const_node = std::dynamic_pointer_cast<ov::op::v0::Constant>(mul_input)) {
- auto shape = const_node->get_shape();
- if (nodes.num_experts > 0 && shape.size() >= 2 && shape[0] == nodes.num_experts) {
- nodes.matmuls.push_back(matmul);
- break;
- }
- }
- }
- }
+ // Enqueue non-constant-derived inputs (activation paths only)
+ for (size_t i = 0; i < n->get_input_size(); ++i) {
+ auto inp_node = n->input_value(i).get_node_shared_ptr();
+ if (visited.count(inp_node))
+ continue;
+ if (moe_utils::is_constant_derived(inp_node))
+ continue;
+ if (std::dynamic_pointer_cast<ov::op::v0::Parameter>(inp_node))
+ continue;
+ visited.insert(inp_node);
+ queue.push(inp_node);
+ }
+ }
+
+ // Phase 2: Determine num_experts from Tile repeats[0] > k_value
+ for (auto& tile : all_tiles) {
+ auto repeats_const =
+ std::dynamic_pointer_cast<ov::op::v0::Constant>(tile->input_value(1).get_node_shared_ptr());
+ if (!repeats_const)
continue;
+ auto rdata = repeats_const->cast_vector<int64_t>();
+ if (!rdata.empty() && rdata[0] > router.k_value) {
+ if (nodes.num_experts == 0) {
+ nodes.num_experts = static_cast<size_t>(rdata[0]);
+ }
+ nodes.tiles.push_back(tile);
}
+ }
- // Collect Add nodes
- if (auto add = std::dynamic_pointer_cast<ov::op::v1::Add>(n)) {
- // Check both inputs for expert-dimension bias constant
- for (size_t input_idx = 0; input_idx < 2; ++input_idx) {
- auto bias_source = get_weight_source(add->input_value(input_idx));
- auto const_node = std::dynamic_pointer_cast<ov::op::v0::Constant>(bias_source.get_node_shared_ptr());
+ if (nodes.num_experts == 0) {
+ LOG_WARN("collect_from_expert_output: no Tile with repeats[0] > k_value found");
+ return nodes;
+ }
- if (const_node) {
- auto shape = const_node->get_shape();
- if (nodes.num_experts > 0 && shape.size() >= 1 && shape[0] == nodes.num_experts) {
- nodes.adds.push_back(add);
- break;
- }
- }
- }
- continue;
+ // Phase 3: Filter collected nodes — keep only those whose weight/shape uses the expert dimension
+ for (auto& reshape : all_const_reshapes) {
+ auto shape_const =
+ std::dynamic_pointer_cast<ov::op::v0::Constant>(reshape->input_value(1).get_node_shared_ptr());
+ auto shape_data = shape_const->cast_vector<int64_t>();
+ if (!shape_data.empty() && shape_data[0] == static_cast<int64_t>(nodes.num_experts)) {
+ nodes.constant_reshapes.push_back(reshape);
}
+ }
- // Collect Multiply nodes, e.g. AWQ multiply (one input from constant, other input is not constant/convert, and
- // user is not MatMul)
- if (auto multiply = std::dynamic_pointer_cast<ov::op::v1::Multiply>(n)) {
- // Skip if this Multiply is used by MatMul (it's MatMul weights multiply, which has been processed by
- // transform_matmuls)
- bool used_by_matmul = false;
- for (const auto& output : multiply->outputs()) {
- for (const auto& target : output.get_target_inputs()) {
- auto user = target.get_node()->shared_from_this();
- if (std::dynamic_pointer_cast<ov::op::v0::MatMul>(user)) {
- used_by_matmul = true;
- break;
- }
- }
- if (used_by_matmul)
- break;
- }
- if (used_by_matmul) {
- continue;
- }
+ nodes.dynamic_reshapes = std::move(all_dyn_reshapes);
- // Check both inputs: one should be constant with expert dimension, other should not be constant/convert
- for (size_t const_idx = 0; const_idx < 2; ++const_idx) {
- size_t other_idx = 1 - const_idx;
+ // Returns true if a constant somewhere in the weight chain has shape[0] == expert_dim.
+ // Recursively peels Convert and both inputs of Multiply (the two recognized chain patterns).
+ // Returns false for any unrecognized node type, signalling an unknown weight chain.
+ std::function<bool(const ov::Output<ov::Node>&, size_t, bool&)> weight_has_expert_dim;
+ weight_has_expert_dim = [&](const ov::Output<ov::Node>& input, size_t expert_dim, bool& chain_recognized) -> bool {
+ auto node = input.get_node_shared_ptr();
+ if (auto c = std::dynamic_pointer_cast<ov::op::v0::Constant>(node)) {
+ return !c->get_shape().empty() && c->get_shape()[0] == expert_dim;
+ }
+ if (auto conv = std::dynamic_pointer_cast<ov::op::v0::Convert>(node)) {
+ return weight_has_expert_dim(conv->input_value(0), expert_dim, chain_recognized);
+ }
+ if (auto mul = std::dynamic_pointer_cast<ov::op::v1::Multiply>(node)) {
+ return weight_has_expert_dim(mul->input_value(0), expert_dim, chain_recognized) ||
+ weight_has_expert_dim(mul->input_value(1), expert_dim, chain_recognized);
+ }
+ // Unrecognized node in weight chain (e.g. Reshape, Gather, custom op).
+ chain_recognized = false;
+ return false;
+ };
- auto const_source = get_weight_source(multiply->input_value(const_idx));
- auto const_node = std::dynamic_pointer_cast<ov::op::v0::Constant>(const_source.get_node_shared_ptr());
+ for (auto& matmul : all_matmuls) {
+ bool chain_recognized = true;
+ bool has_expert_dim = weight_has_expert_dim(matmul->input_value(1), nodes.num_experts, chain_recognized);
+ if (!has_expert_dim) {
+ continue; // weight doesn't use expert dimension — not an expert MatMul
+ }
+ if (!chain_recognized) {
+ // Weight has the expert dimension but through an unrecognized chain: we cannot safely
+ // insert a Gather into it. Transforming other nodes (Tile, Reshape) without transforming
+ // this MatMul's weight would produce a shape mismatch at inference time.
+ LOG_WARN("collect_from_expert_output: MatMul '" << matmul->get_friendly_name()
+ << "' has expert-dim weight through an unrecognized chain; "
+ "skipping transformation for this layer");
+ nodes.matmuls.clear();
+ return nodes;
+ }
+ nodes.matmuls.push_back(matmul);
+ }
- if (const_node) {
- auto shape = const_node->get_shape();
- if (nodes.num_experts > 0 && shape.size() >= 1 && shape[0] == nodes.num_experts) {
- // Check if other input is not constant/convert
- auto other_input = multiply->input_value(other_idx);
- auto other_source = get_weight_source(other_input);
- auto other_node = other_source.get_node_shared_ptr();
-
- if (!std::dynamic_pointer_cast<ov::op::v0::Constant>(other_node)) {
- nodes.multiplies.push_back(multiply);
- break;
- }
- }
+ for (auto& add : all_adds) {
+ for (size_t i = 0; i < 2; ++i) {
+ auto bias_source = get_weight_source(add->input_value(i));
+ if (auto c = std::dynamic_pointer_cast<ov::op::v0::Constant>(bias_source.get_node_shared_ptr())) {
+ if (!c->get_shape().empty() && c->get_shape()[0] == nodes.num_experts) {
+ nodes.adds.push_back(add);
+ break;
}
}
- continue;
}
+ }
- // Collect Transpose node
- if (auto transpose = std::dynamic_pointer_cast<ov::op::v1::Transpose>(n)) {
- auto input_node = transpose->input_value(0).get_node_shared_ptr();
- if (std::dynamic_pointer_cast<ov::op::v3::ScatterElementsUpdate>(input_node) ||
- std::dynamic_pointer_cast<ov::op::v12::ScatterElementsUpdate>(input_node)) {
- nodes.transpose = transpose;
- // Don't break - continue collecting other nodes
+ for (auto& mul : all_multiplies) {
+ // Skip if used as MatMul weight input (quantized weight chain, handled by transform_matmuls)
+ bool used_by_matmul = false;
+ for (const auto& out : mul->outputs()) {
+ for (const auto& ti : out.get_target_inputs()) {
+ if (std::dynamic_pointer_cast<ov::op::v0::MatMul>(ti.get_node()->shared_from_this())) {
+ used_by_matmul = true;
+ break;
+ }
}
+ if (used_by_matmul)
+ break;
+ }
+ if (used_by_matmul)
continue;
+
+ // Keep only activation-scale multiplies (one constant input with expert dim, one activation input)
+ for (size_t i = 0; i < 2; ++i) {
+ auto const_src = get_weight_source(mul->input_value(i));
+ if (auto c = std::dynamic_pointer_cast<ov::op::v0::Constant>(const_src.get_node_shared_ptr())) {
+ if (!c->get_shape().empty() && c->get_shape()[0] == nodes.num_experts) {
+ auto other_src = get_weight_source(mul->input_value(1 - i));
+ if (!std::dynamic_pointer_cast<ov::op::v0::Constant>(other_src.get_node_shared_ptr())) {
+ nodes.multiplies.push_back(mul);
+ break;
+ }
+ }
+ }
}
}
@@ -482,13 +547,46 @@ void transform_multiplies(LayerNodes& nodes, const std::shared_ptr<ov::op::v1::R
}
}
-void transform_transpose(LayerNodes& nodes, const ov::Output<ov::Node>& topk_softmax_scores) {
+void transform_transpose(LayerNodes& nodes, const ov::Output<ov::Node>& router_scores) {
if (nodes.transpose) {
auto transpose_input = nodes.transpose->input_value(0);
auto input_node = transpose_input.get_node_shared_ptr();
- nodes.transpose->input(0).replace_source_output(topk_softmax_scores);
- ov::copy_runtime_info(input_node, topk_softmax_scores.get_node_shared_ptr());
+ nodes.transpose->input(0).replace_source_output(router_scores);
+ ov::copy_runtime_info(input_node, router_scores.get_node_shared_ptr());
+ }
+}
+
+// After transform_transpose, the router broadcast chain (Transpose → Reshape → Unsqueeze → Multiply)
+// still has Reshape shape constants with dim-0 = num_experts. Update them to k_value.
+void transform_router_broadcast_chain(const RouterInfo& router, size_t num_experts) {
+ if (!router.scatter_transpose)
+ return;
+ auto cur = router.scatter_transpose->shared_from_this();
+ // Walk forward until we reach output_multiply (at most a few hops)
+ for (int hops = 0; hops < 6 && cur && cur != router.output_multiply; ++hops) {
+ if (auto reshape = std::dynamic_pointer_cast<ov::op::v1::Reshape>(cur)) {
+ auto shape_const =
+ std::dynamic_pointer_cast<ov::op::v0::Constant>(reshape->input_value(1).get_node_shared_ptr());
+ if (shape_const) {
+ auto shape_data = shape_const->cast_vector<int64_t>();
+ if (!shape_data.empty() && shape_data[0] == static_cast<int64_t>(num_experts)) {
+ shape_data[0] = router.k_value;
+ auto new_shape = ov::op::v0::Constant::create(shape_const->get_element_type(),
+ shape_const->get_shape(),
+ shape_data);
+ reshape->input(1).replace_source_output(new_shape);
+ ov::copy_runtime_info(shape_const, new_shape);
+ LOG_DEBUG(" Updated router broadcast Reshape shape[0] from " << num_experts << " to "
+ << router.k_value);
+ }
+ }
+ }
+ // Advance to the single consumer
+ const auto targets = cur->output(0).get_target_inputs();
+ if (targets.size() != 1)
+ break;
+ cur = targets.begin()->get_node()->shared_from_this();
}
}
@@ -496,9 +594,9 @@ bool apply_layer_transformation(const RouterInfo& router, LayerNodes& nodes) {
// Validate we have required nodes
if (!nodes.has_required_nodes()) {
if (nodes.constant_reshapes.empty() && nodes.dynamic_reshapes.empty()) {
- LOG_WARN(" Skipping layer " << router.layer_id << ": No Reshape nodes found");
+ LOG_WARN(" Skipping layer: No Reshape nodes found");
} else {
- LOG_WARN(" Skipping layer " << router.layer_id << ": No MatMul/Add nodes found");
+ LOG_WARN(" Skipping layer: No MatMul/Add nodes found");
}
return false;
}
@@ -515,9 +613,10 @@ bool apply_layer_transformation(const RouterInfo& router, LayerNodes& nodes) {
transform_matmuls(nodes, topk_indices);
transform_adds(nodes, topk_indices);
transform_multiplies(nodes, topk_indices);
- transform_transpose(nodes, router.topk_softmax_scores);
+ transform_transpose(nodes, router.router_scores);
+ transform_router_broadcast_chain(router, nodes.num_experts);
- LOG_INFO("DeviceRoutedMoE transformation successful for " << router.layer_id);
+ LOG_INFO("DeviceRoutedMoE transformation successful");
LOG_INFO(" Tiles: " << nodes.tiles.size() << ", ConstReshapes: " << nodes.constant_reshapes.size()
<< ", DynReshapes: " << nodes.dynamic_reshapes.size() << ", MatMuls: " << nodes.matmuls.size()
<< ", Adds: " << nodes.adds.size() << ", Multiplies: " << nodes.multiplies.size()
@@ -537,18 +636,20 @@ bool DeviceRoutedMoETransform::run_on_model(const std::shared_ptr<ov::Model>& mo
bool model_changed = false;
- // Process each Router TopK node (one per MoE layer)
+ // Process each ScatterElementsUpdate node; validate each as a MoE router by topology
for (const auto& node : model->get_ordered_ops()) {
- auto topk_node = std::dynamic_pointer_cast<ov::op::v11::TopK>(node);
+ const bool is_scatter = std::dynamic_pointer_cast<ov::op::v3::ScatterElementsUpdate>(node) != nullptr ||
+ std::dynamic_pointer_cast<ov::op::v12::ScatterElementsUpdate>(node) != nullptr;
+ if (!is_scatter)
+ continue;
- // Step 1: Process and validate router
- auto router = process_router_topk(topk_node);
- if (!router.has_value()) {
+ // Step 1: Detect router by topology (name-independent, works for GPT-OSS and Qwen3)
+ auto router = detect_router_by_topology(node);
+ if (!router.has_value())
continue;
- }
- // Step 2: Collect all nodes for this layer
- auto layer_nodes = collect_layer_nodes(model, router.value());
+ // Step 2: Collect expert nodes via backward BFS from output_multiply
+ auto layer_nodes = collect_from_expert_output(router.value());
// Step 3: Transform collected nodes (all-or-nothing)
if (apply_layer_transformation(router.value(), layer_nodes)) {
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation_utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation_utils.hpp
new file mode 100644
index 00000000000..d00b51b98eb
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation_utils.hpp
@@ -0,0 +1,37 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/multiply.hpp"
+
+namespace ov {
+namespace npuw {
+namespace moe_utils {
+
+// Returns true if the node's output is entirely determined by constants
+// (no data-dependent values from Parameters flow through it).
+// Recognizes: Constant, Convert(constant), Multiply(constant, constant).
+inline bool is_constant_derived(const std::shared_ptr<ov::Node>& n) {
+ if (!n)
+ return false;
+ if (std::dynamic_pointer_cast<ov::op::v0::Constant>(n))
+ return true;
+ if (auto conv = std::dynamic_pointer_cast<ov::op::v0::Convert>(n)) {
+ return is_constant_derived(conv->input_value(0).get_node_shared_ptr());
+ }
+ if (auto mul = std::dynamic_pointer_cast<ov::op::v1::Multiply>(n)) {
+ return is_constant_derived(mul->input_value(0).get_node_shared_ptr()) &&
+ is_constant_derived(mul->input_value(1).get_node_shared_ptr());
+ }
+ return false;
+}
+
+} // namespace moe_utils
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp
index 977ea691e32..459050b89a3 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp
@@ -762,6 +762,8 @@ void Snapshot::earlyRegroup() {
HNDL(VariadicSplit);
HNDL_MOE(GPTOSSExpert);
HNDL_MOE(GPTOSSRouter);
+ HNDL_MOE(Qwen3Expert);
+ HNDL_MOE(Qwen3Router);
HNDL_FAKE(FakeConvert);
HNDL_FAKE(FakeQuantize);
HNDL_ATTN(SDPA);
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp
index e68b96ba32e..9f27e94f261 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp
@@ -102,7 +102,9 @@ static const std::map<std::string, std::string> ISOL_PRESETS = {{"COMPUTE",
"P:VariadicSplit/compute"},
{"FAKE", "P:FakeConvert/fake,P:FakeQuantize/fake"},
{"ATTN", "P:SDPA/attn,P:SDPADecomposed/attn"},
- {"MOE", "P:GPTOSSExpert/expert,P:GPTOSSRouter/router"}};
+ {"MOE",
+ "P:GPTOSSExpert/expert,P:GPTOSSRouter/router,"
+ "P:Qwen3Expert/expert,P:Qwen3Router/router"}};
} // namespace util
} // namespace online
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.cpp
index 33488f09ced..7b5d4e8d664 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.cpp
@@ -17,6 +17,78 @@ namespace moe {
namespace opp = ov::pass::pattern;
+namespace {
+
+using NodeToGroupMapPtr = ov::npuw::online::detail::OVNodeToGroupMapPtr;
+
+void isolate_node(const std::shared_ptr<ov::Node>& node,
+ const std::string& isol_tag,
+ const NodeToGroupMapPtr& node_to_gptr) {
+ if (node && node_to_gptr->count(node)) {
+ node_to_gptr->at(node)->isolate(isol_tag);
+ }
+}
+
+// Scan output_multiply's middle dimensions (all dims except dim-0=num_experts and last=hidden).
+// If any middle dim > 1 it is the token count (prefill). If all are 1, it is decoding.
+// Shape layouts: GPT-OSS [N, token, 1, H] / Qwen3 [N, 1, token, H]
+bool is_decoding_stage(const std::shared_ptr<ov::Node>& output_multiply) {
+ const auto shape = output_multiply->get_output_partial_shape(0);
+ if (!shape.rank().is_static()) {
+ return false;
+ }
+ const auto rank = shape.rank().get_length();
+ for (int64_t i = 1; i < rank - 1; ++i) {
+ const auto& d = shape[i];
+ if (d.is_static() && d.get_length() != 1) {
+ return false; // prefill: found token dim > 1
+ }
+ }
+ return true; // all middle dims are 1 → decoding
+}
+
+// Find the first consumer of `node` satisfying `pred`. Returns nullptr if not found.
+template <typename Pred>
+std::shared_ptr<ov::Node> find_consumer_by_type(const std::shared_ptr<ov::Node>& node, Pred&& pred) {
+ for (auto& output : node->outputs()) {
+ for (auto& input : output.get_target_inputs()) {
+ auto consumer = input.get_node()->shared_from_this();
+ if (pred(consumer)) {
+ return consumer;
+ }
+ }
+ }
+ return nullptr;
+}
+
+// After output_multiply, find the first ReduceSum consumer and isolate it.
+void isolate_reduce_sum_after(const std::shared_ptr<ov::Node>& output_multiply,
+ const std::string& isol_tag,
+ const NodeToGroupMapPtr& node_to_gptr) {
+ std::shared_ptr<ov::Node> reduce_sum;
+ for (auto& out : output_multiply->outputs()) {
+ for (auto& in : out.get_target_inputs()) {
+ auto consumer = in.get_node()->shared_from_this();
+ if (std::dynamic_pointer_cast<ov::op::v1::ReduceSum>(consumer)) {
+ reduce_sum = consumer;
+ break;
+ }
+ }
+ if (reduce_sum)
+ break;
+ }
+ if (reduce_sum && node_to_gptr->count(reduce_sum)) {
+ node_to_gptr->at(reduce_sum)->isolate(isol_tag);
+ LOG_DEBUG(" ReduceSum successfully isolated");
+ } else if (reduce_sum) {
+ LOG_WARN(" ReduceSum found but not in node_to_gptr map");
+ } else {
+ LOG_WARN(" No ReduceSum found after Multiply (unexpected for decoding stage)");
+ }
+}
+
+} // namespace
+
/*
GPT-OSS Expert Pattern:
@@ -98,17 +170,8 @@ GPTOSSExpert::GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
auto callback = [=](ov::pass::pattern::Matcher& m) {
auto& node_to_output = m.get_pattern_value_map();
- auto matched_tile = node_to_output.at(tile).get_node_shared_ptr();
- auto matched_reshape1 = node_to_output.at(reshape1).get_node_shared_ptr();
- auto matched_weights_multiply1 = node_to_output.at(weights_multiply1).get_node_shared_ptr();
- auto matched_weights_convert1 = node_to_output.at(weights_convert1).get_node_shared_ptr();
- auto matched_matmul1 = node_to_output.at(matmul1).get_node_shared_ptr();
- auto matched_add1 = node_to_output.at(add1).get_node_shared_ptr();
- auto matched_slice = node_to_output.at(slice).get_node_shared_ptr();
- auto matched_minimum = node_to_output.at(minimum).get_node_shared_ptr();
- auto matched_swish = node_to_output.at(swish).get_node_shared_ptr();
-
// Check if optional AWQ multiply was matched
+ auto matched_swish = node_to_output.at(swish).get_node_shared_ptr();
std::shared_ptr<ov::Node> matched_awq_multiply = nullptr;
if (node_to_output.count(awq_multiply) > 0) {
auto awq_multiply_value = node_to_output.at(awq_multiply);
@@ -121,115 +184,46 @@ GPTOSSExpert::GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
LOG_DEBUG("Normal model: No AWQ multiply after Swish");
}
- auto matched_other_slice = node_to_output.at(other_slice).get_node_shared_ptr();
- auto matched_clamp = node_to_output.at(clamp).get_node_shared_ptr();
- auto matched_add2 = node_to_output.at(add2).get_node_shared_ptr();
- auto matched_multiply1 = node_to_output.at(multiply1).get_node_shared_ptr();
- auto matched_weights_multiply2 = node_to_output.at(weights_multiply2).get_node_shared_ptr();
- auto matched_weights_convert2 = node_to_output.at(weights_convert2).get_node_shared_ptr();
- auto matched_matmul2 = node_to_output.at(matmul2).get_node_shared_ptr();
- auto matched_add3 = node_to_output.at(add3).get_node_shared_ptr();
- auto matched_reshape2 = node_to_output.at(reshape2).get_node_shared_ptr();
auto matched_output_multiply = node_to_output.at(output_multiply).get_node_shared_ptr();
- // Check if this is decoding stage by scanning the middle dimensions of
- // output_multiply for a non-1 token count. The shape is always rank-4
- // [num_experts, ..., hidden] with exactly one "token" dim and one singleton
- // among dims 1..rank-2.
- //
- // GPT-OSS: [N, token, 1, H] - prefill: token > 1; decoding: token = 1
- // Qwen: [N, 1, token, H] - same semantics, different layout
- //
- // Strategy: scan dims 1..rank-2 for the first non-1 value.
- // - Found non-1 value → that is the token count; if > 1 it's prefill.
- // - No non-1 found → all middle dims are 1 (decoding, token_count == 1).
- // Note: a token_count of exactly 1 always falls into the "not found" case
- // since both middle dims are 1, and the fallback correctly sets is_decoding.
- auto output_shape = matched_output_multiply->get_output_partial_shape(0);
- LOG_DEBUG("Expert Multiply output_shape: " << output_shape);
- bool is_decoding = false;
-
- if (output_shape.rank().is_static()) {
- const auto rank = output_shape.rank().get_length();
- // Scan middle dims (skip dim 0 = num_experts, skip last = hidden_dim)
- bool found_token_dim = false;
- for (int64_t i = 1; i < rank - 1; ++i) {
- const auto& d = output_shape[i];
- if (!d.is_static()) {
- continue;
- }
- const auto val = d.get_length();
- if (val != 1) {
- // This is the token dimension and val > 1: prefill stage.
- // (val == 1 never reaches here; that case is handled by fallback.)
- is_decoding = false;
- LOG_DEBUG("GPT-OSS Expert pattern matched (Prefill stage): token_count=" << val);
- found_token_dim = true;
- break;
- }
- // val == 1: singleton layout dim, keep scanning
- }
- if (!found_token_dim) {
- // All middle dims are 1 (token_count == 1): decoding stage.
- is_decoding = true;
- LOG_DEBUG("GPT-OSS Expert pattern matched (Decoding stage): single token");
- }
- }
+ LOG_DEBUG("Expert Multiply output_shape: " << matched_output_multiply->get_output_partial_shape(0));
+ const bool is_decoding = is_decoding_stage(matched_output_multiply);
+ LOG_DEBUG("GPT-OSS Expert pattern matched (" << (is_decoding ? "Decoding" : "Prefill") << " stage)");
+
+ auto isolate = [&](const std::shared_ptr<ov::Node>& pattern_node) {
+ isolate_node(node_to_output.at(pattern_node).get_node_shared_ptr(), isol_tag, node_to_gptr);
+ };
- // Isolate all common expert nodes
- node_to_gptr->at(matched_tile)->isolate(isol_tag);
- node_to_gptr->at(matched_reshape1)->isolate(isol_tag);
- node_to_gptr->at(matched_weights_multiply1)->isolate(isol_tag);
- node_to_gptr->at(matched_weights_convert1)->isolate(isol_tag);
- node_to_gptr->at(matched_matmul1)->isolate(isol_tag);
- node_to_gptr->at(matched_add1)->isolate(isol_tag);
- node_to_gptr->at(matched_slice)->isolate(isol_tag);
- node_to_gptr->at(matched_minimum)->isolate(isol_tag);
- node_to_gptr->at(matched_swish)->isolate(isol_tag);
+ isolate(tile);
+ isolate(reshape1);
+ isolate(weights_multiply1);
+ isolate(weights_convert1);
+ isolate(matmul1);
+ isolate(add1);
+ isolate(slice);
+ isolate(minimum);
+ isolate_node(matched_swish, isol_tag, node_to_gptr);
// Isolate AWQ multiply if it exists
- if (matched_awq_multiply && node_to_gptr->count(matched_awq_multiply)) {
- node_to_gptr->at(matched_awq_multiply)->isolate(isol_tag);
+ if (matched_awq_multiply) {
+ isolate_node(matched_awq_multiply, isol_tag, node_to_gptr);
LOG_DEBUG("AWQ multiply after Swish isolated");
}
- node_to_gptr->at(matched_other_slice)->isolate(isol_tag);
- node_to_gptr->at(matched_clamp)->isolate(isol_tag);
- node_to_gptr->at(matched_add2)->isolate(isol_tag);
- node_to_gptr->at(matched_multiply1)->isolate(isol_tag);
- node_to_gptr->at(matched_weights_multiply2)->isolate(isol_tag);
- node_to_gptr->at(matched_weights_convert2)->isolate(isol_tag);
- node_to_gptr->at(matched_matmul2)->isolate(isol_tag);
- node_to_gptr->at(matched_add3)->isolate(isol_tag);
- node_to_gptr->at(matched_reshape2)->isolate(isol_tag);
- node_to_gptr->at(matched_output_multiply)->isolate(isol_tag);
-
- // If decoding stage, find and isolate ReduceSum after Multiply
+ isolate(other_slice);
+ isolate(clamp);
+ isolate(add2);
+ isolate(multiply1);
+ isolate(weights_multiply2);
+ isolate(weights_convert2);
+ isolate(matmul2);
+ isolate(add3);
+ isolate(reshape2);
+ isolate_node(matched_output_multiply, isol_tag, node_to_gptr);
+
if (is_decoding) {
LOG_DEBUG("Decoding stage detected, searching for ReduceSum to isolate...");
- std::shared_ptr<ov::Node> matched_reduce_sum = nullptr;
-
- for (auto& output : matched_output_multiply->outputs()) {
- for (auto& input : output.get_target_inputs()) {
- auto consumer = input.get_node()->shared_from_this();
- if (auto reduce_sum = std::dynamic_pointer_cast<ov::op::v1::ReduceSum>(consumer)) {
- matched_reduce_sum = reduce_sum;
- LOG_DEBUG(" Found ReduceSum after Multiply, isolating for decoding stage");
- break;
- }
- }
- if (matched_reduce_sum)
- break;
- }
-
- if (matched_reduce_sum && node_to_gptr->count(matched_reduce_sum)) {
- node_to_gptr->at(matched_reduce_sum)->isolate(isol_tag);
- LOG_DEBUG(" ReduceSum successfully isolated");
- } else if (matched_reduce_sum) {
- LOG_WARN(" ReduceSum found but not in node_to_gptr map");
- } else {
- LOG_WARN(" No ReduceSum found after Multiply (unexpected for decoding stage)");
- }
+ isolate_reduce_sum_after(matched_output_multiply, isol_tag, node_to_gptr);
}
return false;
@@ -295,12 +289,7 @@ GPTOSSRouter::GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
LOG_DEBUG("GPT-OSS Router pattern matched: " << topk_name);
- // Get pattern-matched nodes
- auto matched_weights_multiply = node_to_output.at(weights_multiply).get_node_shared_ptr();
- auto matched_weights_convert2 = node_to_output.at(weights_convert2).get_node_shared_ptr();
- auto matched_matmul = node_to_output.at(matmul).get_node_shared_ptr();
- auto matched_add = node_to_output.at(add).get_node_shared_ptr();
- auto matched_softmax = node_to_output.at(softmax).get_node_shared_ptr();
+ // Get pattern-matched nodes needed for manual retrieval
auto matched_slice = node_to_output.at(slice).get_node_shared_ptr();
// topk_convert: Convert on TopK indices output (output(1)). Not in the formal
@@ -315,20 +304,6 @@ GPTOSSRouter::GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
}
// Manual retrieval (7 nodes): helper function
- auto find_consumer_by_type =
- [](const std::shared_ptr<ov::Node>& node,
- const std::function<bool(const std::shared_ptr<ov::Node>&)>& pred) -> std::shared_ptr<ov::Node> {
- for (auto& output : node->outputs()) {
- for (auto& input : output.get_target_inputs()) {
- auto consumer = input.get_node()->shared_from_this();
- if (pred(consumer)) {
- return consumer;
- }
- }
- }
- return nullptr;
- };
-
auto matched_scatter = find_consumer_by_type(matched_slice, [](const std::shared_ptr<ov::Node>& n) {
return std::dynamic_pointer_cast<ov::op::v3::ScatterElementsUpdate>(n) ||
std::dynamic_pointer_cast<ov::op::v12::ScatterElementsUpdate>(n);
@@ -372,25 +347,23 @@ GPTOSSRouter::GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
}
// Isolate all 16 nodes
- auto isolate_if_exists = [&](const std::shared_ptr<ov::Node>& node) {
- if (node && node_to_gptr->count(node)) {
- node_to_gptr->at(node)->isolate(isol_tag);
- }
+ auto isolate = [&](const std::shared_ptr<ov::Node>& pattern_node) {
+ isolate_node(node_to_output.at(pattern_node).get_node_shared_ptr(), isol_tag, node_to_gptr);
};
- isolate_if_exists(matched_weights_multiply);
- isolate_if_exists(matched_weights_convert2);
- isolate_if_exists(matched_matmul);
- isolate_if_exists(matched_add);
- isolate_if_exists(matched_topk);
- isolate_if_exists(matched_softmax);
- isolate_if_exists(matched_topk_convert);
- isolate_if_exists(matched_slice);
- isolate_if_exists(matched_broadcast);
- isolate_if_exists(matched_scatter);
- isolate_if_exists(matched_transpose);
- isolate_if_exists(matched_reshape);
- isolate_if_exists(matched_unsqueeze);
+ isolate(weights_multiply);
+ isolate(weights_convert2);
+ isolate(matmul);
+ isolate(add);
+ isolate_node(matched_topk, isol_tag, node_to_gptr);
+ isolate(softmax);
+ isolate_node(matched_topk_convert, isol_tag, node_to_gptr);
+ isolate_node(matched_slice, isol_tag, node_to_gptr);
+ isolate_node(matched_broadcast, isol_tag, node_to_gptr);
+ isolate_node(matched_scatter, isol_tag, node_to_gptr);
+ isolate_node(matched_transpose, isol_tag, node_to_gptr);
+ isolate_node(matched_reshape, isol_tag, node_to_gptr);
+ isolate_node(matched_unsqueeze, isol_tag, node_to_gptr);
LOG_DEBUG("Router pattern isolated");
return false;
@@ -399,6 +372,204 @@ GPTOSSRouter::GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
register_matcher(std::make_shared<opp::Matcher>(slice, "TagGPTOSSRouter"), std::move(callback));
}
+/*
+ Qwen3 Expert Pattern:
+
+ Input preparation:
+ Tile -> Reshape1
+
+ Gate projection (SwiGLU gate branch):
+ Reshape1 -> MatMul_gate (with weights: Multiply -> Convert) -> Swish
+
+ Up projection (SwiGLU up branch):
+ Reshape1 -> MatMul_up (with weights: Multiply -> Convert)
+
+ SwiGLU merge:
+ Swish + MatMul_up -> Multiply_swiglu
+
+ Down projection:
+ Multiply_swiglu -> MatMul_down (with weights: Multiply -> Convert) -> Reshape2
+
+ Output (scaled by router scores):
+ Reshape2 * router_score -> Multiply_output <-- pattern root
+ (router_score = opp::any_input(), produced entirely by Qwen3Router)
+
+ Isolation boundary:
+ - Expert claims: Tile, Reshape1, gate/up/down MatMuls+weights, SwiGLU Multiply, Reshape2, output Multiply
+ - Router claims: Softmax, TopK, ReduceSum, Divide, ScatterElementsUpdate, Transpose, Reshape_score, Unsqueeze_score
+ - Shared shape-compute nodes (ShapeOf->Gather->Unsqueeze->Concat chains) stay outside both,
+ becoming parameter inputs at subgraph boundaries.
+*/
+Qwen3Expert::Qwen3Expert(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag) {
+ LOG_DEBUG("Qwen3Expert pattern matcher registered with tag: " << isol_tag);
+
+ // Input preparation: Tile -> Reshape
+ auto tile = opp::wrap_type<ov::op::v0::Tile>({opp::any_input(), opp::any_input()});
+ auto reshape1 = opp::wrap_type<ov::op::v1::Reshape>({tile, opp::any_input()});
+
+ // Gate projection weights: Multiply(quantized weight, scale) -> Convert
+ auto gate_weights_multiply = opp::wrap_type<ov::op::v1::Multiply>({opp::any_input(), opp::any_input()});
+ auto gate_weights_convert = opp::wrap_type<ov::op::v0::Convert>({gate_weights_multiply});
+ // Gate MatMul + Swish activation
+ auto matmul_gate = opp::wrap_type<ov::op::v0::MatMul>({reshape1, gate_weights_convert});
+ auto swish = opp::wrap_type<ov::op::v4::Swish>({matmul_gate});
+
+ // Up projection weights: Multiply(quantized weight, scale) -> Convert
+ auto up_weights_multiply = opp::wrap_type<ov::op::v1::Multiply>({opp::any_input(), opp::any_input()});
+ auto up_weights_convert = opp::wrap_type<ov::op::v0::Convert>({up_weights_multiply});
+ // Up MatMul
+ auto matmul_up = opp::wrap_type<ov::op::v0::MatMul>({reshape1, up_weights_convert});
+
+ // SwiGLU: gate * up
+ auto multiply_swiglu = opp::wrap_type<ov::op::v1::Multiply>({swish, matmul_up});
+
+ // Down projection weights: Multiply(quantized weight, scale) -> Convert
+ auto down_weights_multiply = opp::wrap_type<ov::op::v1::Multiply>({opp::any_input(), opp::any_input()});
+ auto down_weights_convert = opp::wrap_type<ov::op::v0::Convert>({down_weights_multiply});
+ // Down MatMul -> Reshape
+ auto matmul_down = opp::wrap_type<ov::op::v0::MatMul>({multiply_swiglu, down_weights_convert});
+ auto reshape2 = opp::wrap_type<ov::op::v1::Reshape>({matmul_down, opp::any_input()});
+
+ // Pattern root: expert_output * router_score
+ // The router score (Unsqueeze output) is produced entirely by Qwen3Router and flows
+ // in as opp::any_input() here to avoid double-claiming shared nodes.
+ auto output_multiply = opp::wrap_type<ov::op::v1::Multiply>({reshape2, opp::any_input()});
+
+ auto node_to_gptr = snapshot->getNodeToGroupMap();
+
+ auto callback = [=](ov::pass::pattern::Matcher& m) {
+ auto& node_to_output = m.get_pattern_value_map();
+
+ auto matched_tile = node_to_output.at(tile).get_node_shared_ptr();
+ auto matched_output_multiply = node_to_output.at(output_multiply).get_node_shared_ptr();
+
+ LOG_DEBUG("Qwen3Expert pattern matched: " << matched_tile->get_friendly_name());
+
+ LOG_DEBUG("Qwen3 Expert Multiply output_shape: " << matched_output_multiply->get_output_partial_shape(0));
+ const bool is_decoding = is_decoding_stage(matched_output_multiply);
+ LOG_DEBUG("Qwen3 Expert pattern matched (" << (is_decoding ? "Decoding" : "Prefill") << " stage)");
+
+ auto isolate = [&](const std::shared_ptr<ov::Node>& pattern_node) {
+ isolate_node(node_to_output.at(pattern_node).get_node_shared_ptr(), isol_tag, node_to_gptr);
+ };
+
+ isolate(tile);
+ isolate(reshape1);
+ isolate(gate_weights_multiply);
+ isolate(gate_weights_convert);
+ isolate(matmul_gate);
+ isolate(swish);
+ isolate(up_weights_multiply);
+ isolate(up_weights_convert);
+ isolate(matmul_up);
+ isolate(multiply_swiglu);
+ isolate(down_weights_multiply);
+ isolate(down_weights_convert);
+ isolate(matmul_down);
+ isolate(reshape2);
+ isolate_node(matched_output_multiply, isol_tag, node_to_gptr);
+
+ if (is_decoding) {
+ LOG_DEBUG("Decoding stage detected, searching for ReduceSum to isolate...");
+ isolate_reduce_sum_after(matched_output_multiply, isol_tag, node_to_gptr);
+ }
+
+ return false;
+ };
+
+ register_matcher(std::make_shared<opp::Matcher>(output_multiply, "TagQwen3Expert"), std::move(callback));
+}
+
+/*
+ Qwen3 Router Pattern:
+
+ Router weights (quantized, dequantized via weight chain):
+ Convert(weight) -> Multiply(weight, scale) -> Convert -> MatMul(input, weight)
+
+ Score computation:
+ MatMul -> Softmax -> TopK(values, indices)
+
+ Score normalization:
+ TopK(values) -> ReduceSum -> Divide(values, sum) [renormalize over K selected]
+
+ Scatter to full expert dimension:
+ TopK(indices) + Divide(scores) -> ScatterElementsUpdate(zero_broadcast, indices, scores)
+
+ Shape to [num_experts, token_count, 1, 1] for expert broadcast:
+ ScatterElementsUpdate -> Transpose -> Reshape -> Unsqueeze <-- pattern root
+
+ Note: The Unsqueeze output is consumed by Qwen3Expert's Multiply_output node.
+ Key difference from GPT-OSS: Softmax is BEFORE TopK (not after),
+ requiring explicit renormalization via ReduceSum->Divide.
+*/
+Qwen3Router::Qwen3Router(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag) {
+ LOG_DEBUG("Qwen3Router pattern matcher registered with tag: " << isol_tag);
+
+ // Router weights: Convert(weight) -> Multiply(weight, scale) -> Convert -> MatMul
+ auto weights_convert_in = opp::wrap_type<ov::op::v0::Convert>({opp::any_input()});
+ auto weights_multiply = opp::wrap_type<ov::op::v1::Multiply>({weights_convert_in, opp::any_input()});
+ auto weights_convert_out = opp::wrap_type<ov::op::v0::Convert>({weights_multiply});
+ auto matmul = opp::wrap_type<ov::op::v0::MatMul>({opp::any_input(), weights_convert_out});
+
+ // Score: Softmax -> TopK
+ auto softmax = opp::wrap_type<ov::op::v8::Softmax>({matmul});
+ auto topk = opp::wrap_type<ov::op::v11::TopK>({softmax, opp::any_input()});
+
+ // Renormalization: TopK(values)->ReduceSum, TopK(values)/ReduceSum = Divide
+ auto reduce_sum = opp::wrap_type<ov::op::v1::ReduceSum>({topk, opp::any_input()});
+ auto divide = opp::wrap_type<ov::op::v1::Divide>({topk, reduce_sum});
+
+ // Scatter to full expert shape (pattern root = Unsqueeze)
+ auto scatter =
+ opp::wrap_type<ov::op::v12::ScatterElementsUpdate>({opp::any_input(), topk, divide, opp::any_input()});
+ auto transpose = opp::wrap_type<ov::op::v1::Transpose>({scatter, opp::any_input()});
+ auto reshape = opp::wrap_type<ov::op::v1::Reshape>({transpose, opp::any_input()});
+ auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({reshape, opp::any_input()});
+
+ auto node_to_gptr = snapshot->getNodeToGroupMap();
+
+ auto callback = [=](ov::pass::pattern::Matcher& m) {
+ auto& node_to_output = m.get_pattern_value_map();
+
+ // Validate: TopK should be MAX mode (selecting top-K experts)
+ auto matched_topk = node_to_output.at(topk).get_node_shared_ptr();
+ auto topk_node = std::dynamic_pointer_cast<ov::op::v11::TopK>(matched_topk);
+ if (!topk_node || topk_node->get_mode() != ov::op::v11::TopK::Mode::MAX) {
+ return false;
+ }
+
+ LOG_DEBUG("Qwen3Router pattern matched: " << matched_topk->get_friendly_name());
+
+ auto matched_scatter = node_to_output.at(scatter).get_node_shared_ptr();
+
+ // Also isolate Broadcast node that provides zero-filled base for ScatterElementsUpdate
+ auto broadcast_node = matched_scatter->input_value(0).get_node_shared_ptr();
+ auto matched_broadcast = std::dynamic_pointer_cast<ov::op::v3::Broadcast>(broadcast_node);
+
+ auto isolate = [&](const std::shared_ptr<ov::Node>& pattern_node) {
+ isolate_node(node_to_output.at(pattern_node).get_node_shared_ptr(), isol_tag, node_to_gptr);
+ };
+
+ isolate(weights_convert_in);
+ isolate(weights_multiply);
+ isolate(weights_convert_out);
+ isolate(matmul);
+ isolate(softmax);
+ isolate_node(matched_topk, isol_tag, node_to_gptr);
+ isolate(reduce_sum);
+ isolate(divide);
+ isolate_node(matched_broadcast, isol_tag, node_to_gptr);
+ isolate_node(matched_scatter, isol_tag, node_to_gptr);
+ isolate(transpose);
+ isolate(reshape);
+ isolate(unsqueeze);
+
+ return false;
+ };
+
+ register_matcher(std::make_shared<opp::Matcher>(unsqueeze, "TagQwen3Router"), std::move(callback));
+}
+
} // namespace moe
} // namespace patterns
} // namespace npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hpp
index df0a55881c5..8c369075966 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hpp
@@ -56,6 +56,36 @@ public:
GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);
};
+class Qwen3Expert : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::moe::Qwen3Expert");
+ static constexpr const char* pattern_name() {
+ return "Qwen3Expert";
+ }
+ static constexpr const char* isolation_tag() {
+ return EXPERT_TAG;
+ }
+ static constexpr const char* group_name() {
+ return "moe";
+ }
+ Qwen3Expert(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);
+};
+
+class Qwen3Router : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::moe::Qwen3Router");
+ static constexpr const char* pattern_name() {
+ return "Qwen3Router";
+ }
+ static constexpr const char* isolation_tag() {
+ return ROUTER_TAG;
+ }
+ static constexpr const char* group_name() {
+ return "moe";
+ }
+ Qwen3Router(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);
+};
+
} // namespace moe
} // namespace patterns
} // namespace npuw
diff --git a/src/plugins/intel_npu/tests/unit/npuw/device_routed_moe_transform_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/device_routed_moe_transform_test.cpp
index 6b254878186..b71d5d6680f 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/device_routed_moe_transform_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/device_routed_moe_transform_test.cpp
@@ -1,4 +1,4 @@
-// Copyright (C) 2026 Intel Corporation
+// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
@@ -15,10 +15,15 @@
/*
* Test suite for Device-Routed MoE Transformation
*
- * Testing Strategy:
- * - BasicTransformation: Verify Gather insertion in quantized weights and shape updates
- * - MultiLayerMoE: Test independent transformation of multiple layers
- * - AWQActivationMultiply: Test AWQ activation scaling support
+ * GPT-OSS tests (create_complete_moe_graph):
+ * - BasicTransformation: Gather insertion in quantized weights; shape updates
+ * - MultiLayerMoE: Independent transformation of multiple layers
+ * - AWQActivationMultiply: AWQ activation-scale Multiply support
+ * - NegativeNoSoftmax: Transformation skipped when Softmax is absent
+ *
+ * Qwen3 tests (create_qwen3_moe_graph):
+ * - Qwen3BasicTransformation: Gather insertion for Qwen3 SwiGLU expert
+ * - RouterBroadcastChainShapeUpdate: Reshape shape[0] updated after transpose replacement
*/
// Uncomment to save debug XML files during test execution
@@ -283,8 +288,12 @@ std::shared_ptr<Model> create_complete_moe_graph(size_t num_experts = 32,
auto output_multiply = std::make_shared<op::v1::Multiply>(reshape2, router_scores_output);
output_multiply->set_friendly_name("__module.model." + layer_id + "mlp.experts/aten::mul/Multiply");
- // Result
- auto result = std::make_shared<op::v0::Result>(output_multiply);
+ // ReduceSum over expert dim — required by detect_router_by_topology step 3.
+ auto reduce_axis = op::v0::Constant::create(element::i64, Shape{1}, {0});
+ auto reduce_sum = std::make_shared<op::v1::ReduceSum>(output_multiply, reduce_axis);
+ reduce_sum->set_friendly_name("__module.model." + layer_id + "mlp.experts/aten::sum/ReduceSum");
+
+ auto result = std::make_shared<op::v0::Result>(reduce_sum);
result->set_friendly_name(layer_id + "output");
return std::make_shared<Model>(ResultVector{result}, ParameterVector{shared_input});
@@ -539,4 +548,221 @@ TEST_F(DeviceRoutedMoETransformTest, NegativeNoSoftmax) {
EXPECT_EQ(repeats_data[0], num_experts) << "Tile repeats should remain unchanged";
}
+// ============================================================================
+// Qwen3 graph builder
+// ============================================================================
+
+// Qwen3-style MoE graph (decoding stage, token_count=1).
+// Router: Input -> MatMul -> Softmax -> TopK -> ReduceSum -> Divide
+// -> Scatter -> Transpose -> Reshape([N,1,1]) -> Unsqueeze -> [N,1,1,1]
+// Expert: Input -> Tile -> Reshape([N,1,H]) -> gate/up/down MatMuls (SwiGLU)
+// -> Reshape([N,1,1,H]) -> Multiply(router) -> ReduceSum
+// Weights: Const(i4) -> Convert(f16) -> Multiply(scale) -> Convert(f32) -> MatMul
+// 2 Gathers per MatMul (weight + scale) x 3 MatMuls = 6 total.
+std::shared_ptr<Model> create_qwen3_moe_graph(size_t num_experts = 4,
+ int64_t k_value = 2,
+ size_t hidden_dim = 8,
+ size_t intermediate_dim = 4) {
+ auto input = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, hidden_dim});
+ input->set_friendly_name("qwen3_input");
+
+ // --- Router ---
+ // NF4 weight chain: i4 [N,H] -> f16 -> Multiply(scale[N,1]) -> f32 -> MatMul
+ auto rw = op::v0::Constant::create(element::i4,
+ Shape{num_experts, hidden_dim},
+ std::vector<int8_t>(num_experts * hidden_dim, 1));
+ auto rw_f16 = std::make_shared<op::v0::Convert>(rw, element::f16);
+ auto rs = op::v0::Constant::create(element::f16, Shape{num_experts, 1}, std::vector<float>(num_experts, 1.0f));
+ auto rw_scaled = std::make_shared<op::v1::Multiply>(rw_f16, rs);
+ auto rw_f32 = std::make_shared<op::v0::Convert>(rw_scaled, element::f32);
+ auto router_mm = std::make_shared<op::v0::MatMul>(input, rw_f32, false, true);
+
+ // Softmax -> TopK (Softmax BEFORE TopK, Qwen3 style)
+ auto softmax = std::make_shared<op::v8::Softmax>(router_mm, 1);
+ auto k_c = op::v0::Constant::create(element::i64, Shape{}, {k_value});
+ auto topk =
+ std::make_shared<op::v11::TopK>(softmax, k_c, -1, op::v11::TopK::Mode::MAX, op::v11::TopK::SortType::NONE);
+
+ // Renormalize: ReduceSum(values) -> Divide
+ auto rs_ax = op::v0::Constant::create(element::i64, Shape{1}, {1});
+ auto reduce_router = std::make_shared<op::v1::ReduceSum>(topk->output(0), rs_ax, true);
+ auto divide = std::make_shared<op::v1::Divide>(topk->output(0), reduce_router);
+
+ // Scatter back to full expert dimension
+ auto zero = op::v0::Constant::create(element::f32, Shape{}, {0.0f});
+ auto bcast_shp = op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{1LL, (int64_t)num_experts});
+ auto broadcast = std::make_shared<op::v3::Broadcast>(zero, bcast_shp);
+ auto sc_ax = op::v0::Constant::create(element::i64, Shape{1}, {1});
+ auto scatter = std::make_shared<op::v12::ScatterElementsUpdate>(broadcast, topk->output(1), divide, sc_ax);
+
+ // Transpose [1,N] -> [N,1]
+ auto tp_ord = op::v0::Constant::create(element::i32, Shape{2}, {1, 0});
+ auto transpose = std::make_shared<op::v1::Transpose>(scatter, tp_ord);
+
+ // Reshape [N,1] -> [N,1,1] (shape[0] = num_experts, fixed by transform_router_broadcast_chain)
+ auto r_shp = op::v0::Constant::create(element::i64, Shape{3}, std::vector<int64_t>{(int64_t)num_experts, 1LL, 1LL});
+ auto router_reshape = std::make_shared<op::v1::Reshape>(transpose, r_shp, false);
+
+ // Unsqueeze dim 3: [N,1,1] -> [N,1,1,1]
+ auto us_ax = op::v0::Constant::create(element::i64, Shape{1}, {3});
+ auto unsqueeze = std::make_shared<op::v0::Unsqueeze>(router_reshape, us_ax);
+
+ // --- Expert ---
+ // Helper: build INT4 weight dequantization chain: Const(i4,[d0,d1,d2])->f16->Multiply(scale)->f32
+ auto make_weight = [](size_t d0, size_t d1, size_t d2) {
+ auto w = op::v0::Constant::create(element::i4, Shape{d0, d1, d2}, std::vector<int8_t>(d0 * d1 * d2, 1));
+ auto wf = std::make_shared<op::v0::Convert>(w, element::f16);
+ auto sc = op::v0::Constant::create(element::f16, Shape{d0, d1, 1}, std::vector<float>(d0 * d1, 1.0f));
+ auto ws = std::make_shared<op::v1::Multiply>(wf, sc);
+ return std::make_shared<op::v0::Convert>(ws, element::f32);
+ };
+
+ // Tile [1,H] -> [N,H]
+ auto tile_rep = op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{(int64_t)num_experts, 1LL});
+ auto tile = std::make_shared<op::v0::Tile>(input, tile_rep);
+
+ // Reshape [N,H] -> [N,1,H] (shape[0] = num_experts)
+ auto rs1_shp = op::v0::Constant::create(element::i64,
+ Shape{3},
+ std::vector<int64_t>{(int64_t)num_experts, 1LL, (int64_t)hidden_dim});
+ auto reshape1 = std::make_shared<op::v1::Reshape>(tile, rs1_shp, false);
+
+ // Gate: [N,I,H] weights -> [N,1,H] x [N,I,H]^T -> [N,1,I] -> Swish
+ auto gate_w = make_weight(num_experts, intermediate_dim, hidden_dim);
+ auto matmul_gate = std::make_shared<op::v0::MatMul>(reshape1, gate_w, false, true);
+ auto swish = std::make_shared<op::v4::Swish>(matmul_gate);
+
+ // Up: [N,I,H] weights -> [N,1,H] x [N,I,H]^T -> [N,1,I]
+ auto up_w = make_weight(num_experts, intermediate_dim, hidden_dim);
+ auto matmul_up = std::make_shared<op::v0::MatMul>(reshape1, up_w, false, true);
+
+ // SwiGLU
+ auto swiglu = std::make_shared<op::v1::Multiply>(swish, matmul_up);
+
+ // Down: [N,H,I] weights -> [N,1,I] x [N,H,I]^T -> [N,1,H]
+ auto down_w = make_weight(num_experts, hidden_dim, intermediate_dim);
+ auto matmul_down = std::make_shared<op::v0::MatMul>(swiglu, down_w, false, true);
+
+ // Reshape [N,1,H] -> [N,1,1,H] (shape[0] = num_experts)
+ auto rs2_shp = op::v0::Constant::create(element::i64,
+ Shape{4},
+ std::vector<int64_t>{(int64_t)num_experts, 1LL, 1LL, (int64_t)hidden_dim});
+ auto reshape2 = std::make_shared<op::v1::Reshape>(matmul_down, rs2_shp, false);
+
+ // Output multiply: [N,1,1,H] * [N,1,1,1] -> [N,1,1,H]
+ auto output_multiply = std::make_shared<op::v1::Multiply>(reshape2, unsqueeze);
+
+ // ReduceSum over expert dim — required by detect_router_by_topology step 3.
+ auto final_ax = op::v0::Constant::create(element::i64, Shape{1}, {0});
+ auto final_reduce = std::make_shared<op::v1::ReduceSum>(output_multiply, final_ax);
+
+ auto result = std::make_shared<op::v0::Result>(final_reduce);
+ return std::make_shared<Model>(ResultVector{result}, ParameterVector{input});
+}
+
+// ============================================================================
+// Qwen3 tests
+// ============================================================================
+
+// Test 5: Qwen3 basic transformation
+// Verifies 6 Gather nodes inserted, Tile repeats[0] and Reshape dim[0] updated to k_value.
+TEST_F(DeviceRoutedMoETransformTest, Qwen3BasicTransformation) {
+ constexpr size_t num_experts = 4;
+ constexpr int64_t k_value = 2;
+ constexpr size_t hidden_dim = 8;
+ constexpr size_t intermediate_dim = 4;
+
+ auto model = create_qwen3_moe_graph(num_experts, k_value, hidden_dim, intermediate_dim);
+ save_model(model, "qwen3_moe_basic_before");
+
+ EXPECT_EQ(count_nodes<op::v8::Gather>(model), 0u) << "No Gather before transformation";
+ EXPECT_EQ(count_nodes<op::v0::Tile>(model), 1u) << "One Tile before transformation";
+
+ ov::pass::Manager manager;
+ manager.register_pass<DeviceRoutedMoETransform>();
+ manager.run_passes(model);
+
+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());
+ save_model(model, "qwen3_moe_basic_after");
+
+ // 2 Gathers per MatMul (weight + scale) x 3 MatMuls = 6
+ auto gathers = find_gather_nodes(model);
+ EXPECT_EQ(gathers.size(), 6u) << "Expected 6 Gather nodes (weight+scale per gate/up/down MatMul)";
+
+ // Tile repeats[0] must be updated to k_value
+ for (const auto& node : model->get_ordered_ops()) {
+ if (auto tile = std::dynamic_pointer_cast<op::v0::Tile>(node)) {
+ auto rep = std::dynamic_pointer_cast<op::v0::Constant>(tile->input_value(1).get_node_shared_ptr());
+ ASSERT_NE(rep, nullptr);
+ EXPECT_EQ(rep->cast_vector<int64_t>()[0], k_value) << "Tile repeats[0] should be updated to k=" << k_value;
+ }
+ }
+
+ // All Reshape shape constants where dim[0] > 1 must be updated to k_value
+ for (const auto& node : model->get_ordered_ops()) {
+ if (auto reshape = std::dynamic_pointer_cast<op::v1::Reshape>(node)) {
+ auto shp = std::dynamic_pointer_cast<op::v0::Constant>(reshape->input_value(1).get_node_shared_ptr());
+ if (!shp)
+ continue;
+ auto d = shp->cast_vector<int64_t>();
+ if (!d.empty() && d[0] > 1) {
+ EXPECT_EQ(d[0], k_value) << "Reshape expert dim should be updated to k=" << k_value;
+ }
+ }
+ }
+}
+
+// Test 6: Router broadcast chain Reshape shape fix (Qwen3-specific)
+// After transform_transpose replaces Scatter->Transpose with router_scores [1,k],
+// transform_router_broadcast_chain must update Reshape shape[0] from num_experts to k_value.
+TEST_F(DeviceRoutedMoETransformTest, RouterBroadcastChainShapeUpdate) {
+ constexpr size_t num_experts = 4;
+ constexpr int64_t k_value = 2;
+ constexpr size_t hidden_dim = 8;
+ constexpr size_t intermediate_dim = 4;
+
+ auto model = create_qwen3_moe_graph(num_experts, k_value, hidden_dim, intermediate_dim);
+
+ // Before: locate the 3-element Reshape [num_experts, 1, 1] in the router broadcast chain
+ auto find_router_reshape_shape = [&]() -> std::shared_ptr<op::v0::Constant> {
+ for (const auto& node : model->get_ordered_ops()) {
+ if (auto reshape = std::dynamic_pointer_cast<op::v1::Reshape>(node)) {
+ auto shp = std::dynamic_pointer_cast<op::v0::Constant>(reshape->input_value(1).get_node_shared_ptr());
+ if (!shp)
+ continue;
+ auto d = shp->cast_vector<int64_t>();
+ if (d.size() == 3 && d[0] == (int64_t)num_experts && d[1] == 1 && d[2] == 1)
+ return shp;
+ }
+ }
+ return nullptr;
+ };
+
+ auto before_shp = find_router_reshape_shape();
+ ASSERT_NE(before_shp, nullptr) << "Router broadcast Reshape [N,1,1] should exist before transform";
+ EXPECT_EQ(before_shp->cast_vector<int64_t>()[0], (int64_t)num_experts);
+
+ ov::pass::Manager manager;
+ manager.register_pass<DeviceRoutedMoETransform>();
+ manager.run_passes(model);
+
+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());
+
+ // After: the Reshape in the chain must now have shape [k_value, 1, 1]
+ bool found = false;
+ for (const auto& node : model->get_ordered_ops()) {
+ if (auto reshape = std::dynamic_pointer_cast<op::v1::Reshape>(node)) {
+ auto shp = std::dynamic_pointer_cast<op::v0::Constant>(reshape->input_value(1).get_node_shared_ptr());
+ if (!shp)
+ continue;
+ auto d = shp->cast_vector<int64_t>();
+ if (d.size() == 3 && d[0] == k_value && d[1] == 1 && d[2] == 1) {
+ found = true;
+ }
+ }
+ }
+ EXPECT_TRUE(found) << "Router broadcast Reshape shape[0] must be updated from " << num_experts
+ << " to k=" << k_value;
+}
+
} // namespace
diff --git a/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_utils_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_utils_test.cpp
new file mode 100644
index 00000000000..59b6a2963dd
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_utils_test.cpp
@@ -0,0 +1,113 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_transformations/moe_transformation_utils.hpp"
+
+#include <gtest/gtest.h>
+
+#include "openvino/op/ops.hpp"
+
+/*
+ * Unit tests for ov::npuw::moe_utils::is_constant_derived()
+ *
+ * Covered cases:
+ * Positive:
+ * - Bare Constant node
+ * - Convert(Constant)
+ * - Multiply(Constant, Constant)
+ * - Convert(Multiply(Constant, Constant)) -- nested chain
+ * Negative:
+ * - nullptr input
+ * - Parameter (data-dependent)
+ * - Convert(Parameter)
+ * - Multiply(Constant, Parameter)
+ * - Multiply(Parameter, Constant) -- symmetric check
+ * - Add(Constant, Constant) -- unrecognized op type
+ */
+
+namespace {
+
+using ov::npuw::moe_utils::is_constant_derived;
+
+// ── helpers ──────────────────────────────────────────────────────────────────
+
+static std::shared_ptr<ov::op::v0::Constant> make_const_f32(ov::Shape shape) {
+ std::vector<float> data(ov::shape_size(shape), 1.0f);
+ return ov::op::v0::Constant::create(ov::element::f32, shape, data);
+}
+
+static std::shared_ptr<ov::op::v0::Parameter> make_param_f32(ov::PartialShape shape) {
+ return std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape);
+}
+
+// ── Positive cases ────────────────────────────────────────────────────────────
+
+TEST(IsconstantDerivedTest, BareConstant) {
+ auto c = make_const_f32({4, 16});
+ EXPECT_TRUE(is_constant_derived(c));
+}
+
+TEST(IsconstantDerivedTest, ConvertOfConstant) {
+ auto c = make_const_f32({4, 16});
+ auto conv = std::make_shared<ov::op::v0::Convert>(c, ov::element::f16);
+ EXPECT_TRUE(is_constant_derived(conv));
+}
+
+TEST(IsconstantDerivedTest, MultiplyTwoConstants) {
+ auto c0 = make_const_f32({4, 16});
+ auto c1 = make_const_f32({4, 1});
+ auto mul = std::make_shared<ov::op::v1::Multiply>(c0, c1);
+ EXPECT_TRUE(is_constant_derived(mul));
+}
+
+TEST(IsconstantDerivedTest, NestedConvertMultiplyConstants) {
+ // Convert(Multiply(Constant, Constant)) — typical NF4 weight dequant chain
+ auto c0 = make_const_f32({4, 16});
+ auto c1 = make_const_f32({4, 1});
+ auto mul = std::make_shared<ov::op::v1::Multiply>(c0, c1);
+ auto conv = std::make_shared<ov::op::v0::Convert>(mul, ov::element::f16);
+ EXPECT_TRUE(is_constant_derived(conv));
+}
+
+// ── Negative cases ────────────────────────────────────────────────────────────
+
+TEST(IsconstantDerivedTest, NullInput) {
+ EXPECT_FALSE(is_constant_derived(nullptr));
+}
+
+TEST(IsconstantDerivedTest, BareParameter) {
+ auto p = make_param_f32({1, 16});
+ EXPECT_FALSE(is_constant_derived(p));
+}
+
+TEST(IsconstantDerivedTest, ConvertOfParameter) {
+ auto p = make_param_f32({1, 16});
+ auto conv = std::make_shared<ov::op::v0::Convert>(p, ov::element::f16);
+ EXPECT_FALSE(is_constant_derived(conv));
+}
+
+TEST(IsconstantDerivedTest, MultiplyConstantAndParameter) {
+ auto c = make_const_f32({4, 1});
+ auto p = make_param_f32({4, 16});
+ auto mul = std::make_shared<ov::op::v1::Multiply>(c, p);
+ EXPECT_FALSE(is_constant_derived(mul));
+}
+
+TEST(IsconstantDerivedTest, MultiplyParameterAndConstant) {
+ // Symmetric: swapped operand order must also return false
+ auto p = make_param_f32({4, 16});
+ auto c = make_const_f32({4, 1});
+ auto mul = std::make_shared<ov::op::v1::Multiply>(p, c);
+ EXPECT_FALSE(is_constant_derived(mul));
+}
+
+TEST(IsconstantDerivedTest, UnrecognizedOpType) {
+ // Add is not handled by is_constant_derived — must return false
+ auto c0 = make_const_f32({4});
+ auto c1 = make_const_f32({4});
+ auto add = std::make_shared<ov::op::v1::Add>(c0, c1);
+ EXPECT_FALSE(is_constant_derived(add));
+}
+
+} // namespace