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] Support Gemma4 26B A4B MoE Pattern (#36861)
Guoliang Shi9c60fedc7589
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.cppindex 373bf8d5900..b8aedaf8f37 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@@ -342,10 +342,11 @@ std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> register_patternov::npuw::v1::subgraphs::PatternRegistry& registry,const std::size_t moe_chunk_size) {std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> registrations;- registrations.reserve(5);+ registrations.reserve(7);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::Gemma4Router>().scoped());registrations.emplace_back(registry.on<ov::npuw::patterns::moe::GPTOSSExpert>()@@ -369,6 +370,17 @@ std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> register_pattern}).scoped());+ registrations.emplace_back(+ registry.on<ov::npuw::patterns::moe::Gemma4Expert>()+ .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/npuw_transformations/reshape_to_static.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cppindex 49d285f7f63..97cbd588ee7 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp@@ -90,18 +90,19 @@ void reshape_to_static(std::shared_ptr<ov::Model> model,} else if (ov::npuw::util::matchLoRAMatMulBString(input_name)) {new_shape = ov::PartialShape({input.get_partial_shape()[0], lora_rank});} else if (input_name.find("per_layer_inputs") != std::string::npos) {- // NB: Gemma4 per-layer embedding feature.- // Shape is [batch, seq_len, num_layers, projection_dim].- // seq_len (dim 1) should match input_size (tokens being processed),- // while num_layers (dim 2) and projection_dim (dim 3) are model constants.- // These may be dynamic in the parameter's partial_shape itself, so fall back to- // reading them from the sibling input of the Add node that consumes this parameter- // (the other branch always carries a fully static shape, e.g. f32[1,S,42,256]).+ // NB: Gemma4 Per-Layer Embeddings (PLE): shape is [batch, seq_len, num_layers, proj_dim].+ // MoE models (e.g. 26B A4B) have proj_dim==0 and no PLE — parameter is dangling.+ // Dense models (E2B/E4B) may have dynamic num_layers/proj_dim in the partial_shape;+ // resolve them from the static sibling of the Add node that consumes this input.const auto& partial_shape = input.get_partial_shape();NPUW_ASSERT(partial_shape.size() == 4u);ov::Dimension num_layers = partial_shape[2];ov::Dimension proj_dim = partial_shape[3];- if (!num_layers.is_static() || !proj_dim.is_static()) {+ if (proj_dim.is_static() && proj_dim.get_length() == 0) {+ // NB: MoE models (e.g. Gemma4 26B A4B) have projection_dim==0 and no PLE;+ // the parameter is dangling, so assign a zero-sized static shape directly.+ new_shape = ov::PartialShape({1, input_size, 0, 0});+ } else {for (const auto& target : input.get_target_inputs()) {const auto* node = target.get_node();if (!ov::is_type<ov::op::v1::Add>(node)) {@@ -126,10 +127,10 @@ void reshape_to_static(std::shared_ptr<ov::Model> model,break;}}+ NPUW_ASSERT(num_layers.is_static()); // num_layers must be resolved+ NPUW_ASSERT(proj_dim.is_static()); // projection_dim must be resolved+ new_shape = ov::PartialShape({1, input_size, num_layers, proj_dim});}- NPUW_ASSERT(num_layers.is_static()); // num_layers must be resolved- NPUW_ASSERT(proj_dim.is_static()); // projection_dim must be resolved- new_shape = ov::PartialShape({1, input_size, num_layers, proj_dim});} else if (ov::npuw::util::matchLinCacheString(input_name)) {const auto& partial_shape = input.get_partial_shape();new_shape = partial_shape;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.cppindex 24bba59df0a..67ae14b88f3 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@@ -765,6 +765,8 @@ void Snapshot::earlyRegroup() {HNDL_MOE(GPTOSSRouter);HNDL_MOE(Qwen3Expert);HNDL_MOE(Qwen3Router);+ HNDL_MOE(Gemma4Expert);+ HNDL_MOE(Gemma4Router);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.hppindex 940f3523725..14e744f3874 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@@ -109,7 +109,8 @@ static const std::map<std::string, std::string> ISOL_PRESETS = {"P:QuantizedSDPAWithGlobalMask/attn,P:GQA/attn,P:SDPACompressed/attn"},{"MOE","P:GPTOSSExpert/expert,P:GPTOSSRouter/router,"- "P:Qwen3Expert/expert,P:Qwen3Router/router"}};+ "P:Qwen3Expert/expert,P:Qwen3Router/router,"+ "P:Gemma4Expert/expert,P:Gemma4Router/router"}};} // namespace util} // namespace onlinediff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.cppindex 6b3f7567adf..63832e7e142 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@@ -4,7 +4,9 @@#include "moe.hpp"+#include <functional>#include <optional>+#include <utility>#include "../../logging.hpp"#include "openvino/op/ops.hpp"@@ -78,7 +80,7 @@ void isolate_reduce_sum_after(const std::shared_ptr<ov::Node>& output_multiply,// Extract K from a TopK node's constant second input and write it to rt_info// under the RT_INFO_MOE_K key so that PartitioningCallbacks::find_node_with_rt_info// can retrieve it during the partition stage. Returns true on success.-// Both GPTOSSRouter and Qwen3Router call this after validating the TopK node.+// Shared across all Router MatcherPass implementations for consistency checking:// expected_k is updated on first call and checked for consistency on subsequent calls;// OPENVINO_THROW is raised if two matched layers carry different K values.bool tag_topk_k(const std::shared_ptr<ov::Node>& topk_node, std::optional<size_t>& expected_k) {@@ -107,6 +109,147 @@ bool tag_topk_k(const std::shared_ptr<ov::Node>& topk_node, std::optional<size_treturn true;}+// Shared callback factory for all Router MatcherPass implementations.+// Validates the matched TopK node and tags it with RT_INFO_MOE_K for K-value propagation.+// An optional guard predicate may reject the match by returning false.+// The only difference between Router implementations is the pattern graph structure;+// all use this helper for TopK validation and K-tagging logic.+std::function<bool(ov::pass::pattern::Matcher&)> make_router_k_callback(+ const std::shared_ptr<ov::Node>& topk_pattern,+ const char* class_name,+ std::function<bool(const std::shared_ptr<ov::Node>&)> guard = {}) {+ auto expected_k = std::make_shared<std::optional<size_t>>();+ return [topk_pattern, class_name, guard, expected_k](ov::pass::pattern::Matcher& m) -> bool {+ auto& node_to_output = m.get_pattern_value_map();+ auto matched_topk = node_to_output.at(topk_pattern).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;+ }+ if (guard && !guard(matched_topk)) {+ return false;+ }+ if (!tag_topk_k(matched_topk, *expected_k)) {+ LOG_WARN(class_name << ": failed to extract K from TopK '" << matched_topk->get_friendly_name()+ << "'; MoE transformation will be skipped");+ }+ return false;+ };+}++// Shared data structure for router score pattern nodes (from MatMul to Divide).+struct RouterScorePattern {+ std::shared_ptr<ov::Node> matmul;+ std::shared_ptr<ov::Node> topk;+ std::shared_ptr<ov::Node> reduce_sum;+ std::shared_ptr<ov::Node> divide;+};++// Builds the shared router score computation pattern (MatMul -> Softmax -> TopK -> ReduceSum -> Divide).+// MatMul inputs are unconstrained (any_input) to support both quantized and non-quantized weight paths.+// Returned pattern nodes can be used by different Router implementations (Qwen3, Gemma4, etc.).+RouterScorePattern build_shared_router_score_pattern() {+ auto matmul = opp::wrap_type<ov::op::v0::MatMul>({opp::any_input(), opp::any_input()});+ auto softmax = opp::wrap_type<ov::op::v8::Softmax>({matmul});+ auto topk = opp::wrap_type<ov::op::v11::TopK>({softmax, opp::any_input()});+ 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});+ return {matmul, topk, reduce_sum, divide};+}++// Builds the shared router tail pattern (Scatter -> Transpose -> Reshape -> Unsqueeze).+// Pattern root is Unsqueeze; this helper encapsulates the tail logic common to all Router implementations.+std::shared_ptr<ov::Node> build_shared_router_tail(const std::shared_ptr<ov::Node>& scatter_input) {+ auto transpose = opp::wrap_type<ov::op::v1::Transpose>({scatter_input, 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()});+ return unsqueeze;+}++// Builds the pattern graph and callback for a SwiGLU-style expert layer with a+// parameterised gate activation operator (template parameter ActivationOp).+// Returns (Matcher, callback) so the caller can invoke its own register_matcher().+//+// Pattern structure (parameterised by activation operator):+// Tile -> Reshape1+// Reshape1 -> MatMul_gate (dequant: Multiply->Convert) -> ActivationOp+// Reshape1 -> MatMul_up (dequant: Multiply->Convert)+// ActivationOp * MatMul_up -> MatMul_down (dequant: Multiply->Convert) -> Reshape2+// Reshape2 * router_score -> output_multiply [pattern root]+//+// Isolation strategy (applied in callback):+// - Prefill (token_count > 1): Isolate up to output_multiply; ReduceSum stays in downstream+// - Decoding (token_count == 1): Isolate including ReduceSum (self-contained expert subgraph)+template <typename ActivationOp>+std::pair<std::shared_ptr<opp::Matcher>, std::function<bool(opp::Matcher&)>> make_swiglu_expert_matcher(+ const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot,+ const std::string& isol_tag,+ const char* expert_name) {+ 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: dequantized weights -> MatMul -> activation+ auto gate_w_mul = opp::wrap_type<ov::op::v1::Multiply>({opp::any_input(), opp::any_input()});+ auto gate_w_cvt = opp::wrap_type<ov::op::v0::Convert>({gate_w_mul});+ auto matmul_gate = opp::wrap_type<ov::op::v0::MatMul>({reshape1, gate_w_cvt});+ auto activation = opp::wrap_type<ActivationOp>({matmul_gate});++ // Up projection: dequantized weights -> MatMul+ auto up_w_mul = opp::wrap_type<ov::op::v1::Multiply>({opp::any_input(), opp::any_input()});+ auto up_w_cvt = opp::wrap_type<ov::op::v0::Convert>({up_w_mul});+ auto matmul_up = opp::wrap_type<ov::op::v0::MatMul>({reshape1, up_w_cvt});++ // SwiGLU merge: activation(gate) * up+ auto merge = opp::wrap_type<ov::op::v1::Multiply>({activation, matmul_up});++ // Down projection: dequantized weights -> MatMul -> Reshape+ auto down_w_mul = opp::wrap_type<ov::op::v1::Multiply>({opp::any_input(), opp::any_input()});+ auto down_w_cvt = opp::wrap_type<ov::op::v0::Convert>({down_w_mul});+ auto matmul_down = opp::wrap_type<ov::op::v0::MatMul>({merge, down_w_cvt});+ auto reshape2 = opp::wrap_type<ov::op::v1::Reshape>({matmul_down, opp::any_input()});++ // Pattern root: expert output * scattered router scores+ 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_output_multiply = node_to_output.at(output_multiply).get_node_shared_ptr();+ const bool is_decoding = is_decoding_stage(matched_output_multiply);+ LOG_DEBUG(expert_name << " 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_w_mul);+ isolate(gate_w_cvt);+ isolate(matmul_gate);+ isolate(activation);+ isolate(up_w_mul);+ isolate(up_w_cvt);+ isolate(matmul_up);+ isolate(merge);+ isolate(down_w_mul);+ isolate(down_w_cvt);+ isolate(matmul_down);+ isolate(reshape2);+ isolate_node(matched_output_multiply, isol_tag, node_to_gptr);++ if (is_decoding) {+ isolate_reduce_sum_after(matched_output_multiply, isol_tag, node_to_gptr);+ }++ return false;+ };++ return {std::make_shared<opp::Matcher>(output_multiply, std::string("Tag") + expert_name + "Expert"),+ std::move(callback)};+}+} // namespace/*@@ -288,37 +431,12 @@ GPTOSSRouter::GPTOSSRouter([[maybe_unused]] const std::shared_ptr<ov::npuw::onli{opp::any_input(), opp::any_input(), slice, opp::any_input()});// Shared across layers to detect inconsistent K values.- auto expected_k = std::make_shared<std::optional<size_t>>();- auto callback = [=](ov::pass::pattern::Matcher& m) {- auto& node_to_output = m.get_pattern_value_map();-- // Validate TopK mode (MAX) and Router keywords- 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;- }-- std::string topk_name = matched_topk->get_friendly_name();- // Check if node name contains MoE router/expert patterns- bool is_router = (topk_name.find(MLP_ROUTER_NAME) != std::string::npos ||- topk_name.find(MLP_EXPERT_NAME) != std::string::npos);- if (!is_router) {- return false;- }-- // Extract K from the TopK constant input and tag the node so that- // PartitioningCallbacks::find_node_with_rt_info can retrieve it later.- if (!tag_topk_k(matched_topk, *expected_k)) {- LOG_WARN("GPTOSSRouter: failed to extract K from TopK '" << matched_topk->get_friendly_name()- << "'; MoE transformation will be skipped");- }-- // Router stays in the upstream subgraph — no isolation.- return false;- };-- register_matcher(std::make_shared<opp::Matcher>(scatter, "TagGPTOSSRouter"), std::move(callback));+ register_matcher(std::make_shared<opp::Matcher>(scatter, "TagGPTOSSRouter"),+ make_router_k_callback(topk, "GPTOSSRouter", [](const std::shared_ptr<ov::Node>& node) {+ const auto& name = node->get_friendly_name();+ return name.find(MLP_ROUTER_NAME) != std::string::npos ||+ name.find(MLP_EXPERT_NAME) != std::string::npos;+ }));}/*@@ -349,157 +467,117 @@ GPTOSSRouter::GPTOSSRouter([[maybe_unused]] const std::shared_ptr<ov::npuw::onli*/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);+ auto [matcher, callback] = make_swiglu_expert_matcher<ov::op::v4::Swish>(snapshot, isol_tag, "Qwen3");+ register_matcher(std::move(matcher), std::move(callback));+}- // 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();+/*+ Qwen3 Router Pattern:- 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();+ Shared score computation (MatMul -> Softmax -> TopK -> ReduceSum -> Divide):+ MatMul inputs may be quantized or non-quantized; pattern uses any_input() for flexibility- LOG_DEBUG("Qwen3Expert pattern matched: " << matched_tile->get_friendly_name());+ Qwen3-specific scores path:+ optional<Convert>({topk}) -> TopK indices may pass through Convert+ optional<Slice>({divide}) -> Divide output may pass through Slice before scatter- 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)");+ Scatter to full expert dimension:+ ScatterElementsUpdate -> Transpose -> Reshape -> Unsqueeze <-- pattern root- 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);- };+ Key difference from GPT-OSS: Softmax is BEFORE TopK (not after).+*/+Qwen3Router::Qwen3Router([[maybe_unused]] const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot,+ [[maybe_unused]] const std::string& isol_tag) {+ LOG_DEBUG("Qwen3Router pattern matcher registered (K-extraction only, no isolation)");- 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);+ // Use shared score computation: MatMul -> Softmax -> TopK -> ReduceSum -> Divide+ auto score_nodes = build_shared_router_score_pattern();- 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);- }+ // Qwen3-specific: optional Convert on TopK indices and optional Slice on Divide+ auto topk_to_scatter = opp::optional<ov::op::v0::Convert>({score_nodes.topk});+ auto divide_to_scatter = opp::optional<ov::op::v8::Slice>(+ {score_nodes.divide, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});- return false;- };+ // Scatter inputs: any_input() for zero_broadcast, topk_to_scatter for indices, divide_to_scatter for scores+ auto scatter_input = opp::wrap_type<ov::op::v12::ScatterElementsUpdate>(+ {opp::any_input(), topk_to_scatter, divide_to_scatter, opp::any_input()});+ auto unsqueeze = build_shared_router_tail(scatter_input);- register_matcher(std::make_shared<opp::Matcher>(output_multiply, "TagQwen3Expert"), std::move(callback));+ // Shared K-value extraction and validation callback.+ register_matcher(std::make_shared<opp::Matcher>(unsqueeze, "TagQwen3Router"),+ make_router_k_callback(score_nodes.topk, "Qwen3Router"));}/*- Qwen3 Router Pattern:-- Router weights (quantized, dequantized via weight chain):- Convert(weight) -> Multiply(weight, scale) -> Convert -> MatMul(input, weight)+ Gemma4 Expert Pattern:- Score computation:- MatMul -> Softmax -> TopK(values, indices)+ Input:+ Tile -> Reshape1- Score normalization:- TopK(values) -> ReduceSum -> Divide(values, sum) [renormalize over K selected]+ Gate projection (with weights Convert1) -> Gelu:+ Reshape1 -> MatMul1 (Multiply -> Convert) -> Gelu- Scatter to full expert dimension:- TopK(indices) + Divide(scores) -> ScatterElementsUpdate(zero_broadcast, indices, scores)+ Up projection (with weights Convert2):+ Reshape1 -> MatMul2 (Multiply -> Convert)- Shape to [num_experts, token_count, 1, 1] for expert broadcast:- ScatterElementsUpdate -> Transpose -> Reshape -> Unsqueeze <-- pattern root+ SwiGLU merge:+ Gelu + MatMul2 -> Multiply1- Key difference from GPT-OSS: Softmax is BEFORE TopK (not after).-*/-Qwen3Router::Qwen3Router([[maybe_unused]] const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot,- [[maybe_unused]] const std::string& isol_tag) {- LOG_DEBUG("Qwen3Router pattern matcher registered (K-extraction only, no isolation)");+ Down projection (with weights Convert3) -> Reshape2:+ Multiply1 -> MatMul3 (Multiply -> Convert) -> Reshape2- // 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});+ Output:+ Reshape2 -> Multiply2 (with scattered router scores) <-- pattern root- // 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()});+ Isolation strategy:+ - Prefill (token_count > 1): Isolate up to Multiply2; ReduceSum stays in downstream+ - Decoding (token_count == 1): Isolate including ReduceSum- // 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});+ Key differences from Qwen3Expert:+ - Gate activation is Gelu (Qwen3Expert uses Swish)+*/+Gemma4Expert::Gemma4Expert(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag) {+ auto [matcher, callback] = make_swiglu_expert_matcher<ov::op::v7::Gelu>(snapshot, isol_tag, "Gemma4");+ register_matcher(std::move(matcher), std::move(callback));+}- auto topk_to_scatter = opp::optional<ov::op::v0::Convert>({topk});- auto divide_to_scatter = opp::optional<ov::op::v8::Slice>(- {divide, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});+/*+ Gemma4 Router Pattern:- // Scatter to full expert shape (pattern root = Unsqueeze)- auto scatter = opp::wrap_type<ov::op::v12::ScatterElementsUpdate>(- {opp::any_input(), topk_to_scatter, divide_to_scatter, 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()});+ Shared score computation (MatMul -> Softmax -> TopK -> ReduceSum -> Divide):+ MatMul inputs may be quantized or non-quantized; pattern uses any_input() for flexibility- // Shared across layers to detect inconsistent K values.- auto expected_k = std::make_shared<std::optional<size_t>>();- auto callback = [=](ov::pass::pattern::Matcher& m) {- auto& node_to_output = m.get_pattern_value_map();+ Gemma4-specific scores path (per-expert learned scale):+ Gather(per_expert_scale, topk_indices) -> Multiply(Divide, Gather) -> Slice+ per-expert scale is combined with renormalized scores before scatter- // 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;- }+ Scatter to full expert dimension:+ ScatterElementsUpdate -> Transpose -> Reshape -> Unsqueeze <-- pattern root- // Extract K from the TopK constant input and tag the node so that- // PartitioningCallbacks::find_node_with_rt_info can retrieve it later.- if (!tag_topk_k(matched_topk, *expected_k)) {- LOG_WARN("Qwen3Router: failed to extract K from TopK '" << matched_topk->get_friendly_name()- << "'; MoE transformation will be skipped");- }+ Key difference from Qwen3Router:+ - Per-expert learned scale applied via Gather+Multiply before scatter (mandatory in Gemma4)+*/+Gemma4Router::Gemma4Router([[maybe_unused]] const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot,+ [[maybe_unused]] const std::string& isol_tag) {+ // Use shared score computation: MatMul -> Softmax -> TopK -> ReduceSum -> Divide+ auto score_nodes = build_shared_router_score_pattern();++ // Gemma4-specific: Per-expert learned scale via Gather, then Multiply and Slice+ // TopK output(1) (indices) goes through Convert before Gather port 1;+ // wrap_type can only express output(0), so both use any_input().+ auto gather = opp::wrap_type<ov::op::v8::Gather>({opp::any_input(), opp::any_input(), opp::any_input()});+ auto scores_multiply = opp::wrap_type<ov::op::v1::Multiply>({score_nodes.divide, gather});+ auto slice = opp::wrap_type<ov::op::v8::Slice>(+ {scores_multiply, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});- // Router stays in the upstream subgraph — no isolation.- return false;- };+ // Scatter inputs: any_input() for indices and zero_broadcast, slice for scores+ auto scatter_input = opp::wrap_type<ov::op::v12::ScatterElementsUpdate>(+ {opp::any_input(), opp::any_input(), slice, opp::any_input()});+ auto unsqueeze = build_shared_router_tail(scatter_input);- register_matcher(std::make_shared<opp::Matcher>(unsqueeze, "TagQwen3Router"), std::move(callback));+ // Shared K-value extraction and validation callback.+ register_matcher(std::make_shared<opp::Matcher>(unsqueeze, "TagGemma4Router"),+ make_router_k_callback(score_nodes.topk, "Gemma4Router"));}} // namespace moediff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hppindex 6d2aaab548f..7f95907af8c 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@@ -23,84 +23,76 @@ constexpr const char* ROUTER_TAG = "router";constexpr const char* EXPERT_TAG = "expert";// MoE layer name patterns for model detection-constexpr const char* MLP_ROUTER_NAME = ".mlp.router";-constexpr const char* MLP_EXPERT_NAME = ".mlp.expert";+constexpr const char* MLP_ROUTER_NAME = ".router";+constexpr const char* MLP_EXPERT_NAME = ".expert";// RT info key used to propagate the Router's K value from pattern-matching// callbacks to the partition stage (written by Router matchers, read by// PartitioningCallbacks::find_node_with_rt_info).constexpr const char* RT_INFO_MOE_K = "npuw_moe_k";+// Boilerplate macros for MoE MatcherPass classes.+//+// Each MoE pass class requires four identical declarations: RTTI, pattern_name(),+// isolation_tag(), and group_name(). These macros centralise that boilerplate so+// that adding a new model variant requires only a constructor declaration in this+// header and a corresponding definition in moe.cpp.+//+// MOE_EXPERT_STATIC_INFO — for Expert passes that isolate matched subgraph nodes.+// MOE_ROUTER_STATIC_INFO — for Router passes that only extract K via RT_INFO_MOE_K+// and do NOT isolate any nodes. The isol_tag constructor+// argument is accepted for call-site uniformity but is+// intentionally unused in all Router implementations.+// clang-format off+#define MOE_EXPERT_STATIC_INFO(ClassName) \+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::moe::" #ClassName); \+ static constexpr const char* pattern_name() { return #ClassName; } \+ static constexpr const char* isolation_tag() { return EXPERT_TAG; } \+ static constexpr const char* group_name() { return "moe"; }++#define MOE_ROUTER_STATIC_INFO(ClassName) \+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::moe::" #ClassName); \+ static constexpr const char* pattern_name() { return #ClassName; } \+ static constexpr const char* isolation_tag() { return ROUTER_TAG; } \+ static constexpr const char* group_name() { return "moe"; }+// clang-format on+class GPTOSSExpert : public ov::pass::MatcherPass {public:- OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::moe::GPTOSSExpert");- static constexpr const char* pattern_name() {- return "GPTOSSExpert";- }- static constexpr const char* isolation_tag() {- return EXPERT_TAG;- }- static constexpr const char* group_name() {- return "moe";- }+ MOE_EXPERT_STATIC_INFO(GPTOSSExpert)GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);};class GPTOSSRouter : public ov::pass::MatcherPass {public:- OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::moe::GPTOSSRouter");- static constexpr const char* pattern_name() {- return "GPTOSSRouter";- }- // NOTE: GPTOSSRouter does NOT isolate any nodes. It only tags the matched- // TopK with RT_INFO_MOE_K. This tag is the ISOL_PRESETS lookup key used by- // the pattern registry ("P:GPTOSSRouter/router") — not an isolation target.- static constexpr const char* isolation_tag() {- return ROUTER_TAG;- }- static constexpr const char* group_name() {- return "moe";- }- // NOTE: isol_tag is accepted for macro-call uniformity but is intentionally unused- // (Router nodes are not isolated; only K is extracted via RT_INFO_MOE_K).+ MOE_ROUTER_STATIC_INFO(GPTOSSRouter)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";- }+ MOE_EXPERT_STATIC_INFO(Qwen3Expert)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";- }- // NOTE: Qwen3Router does NOT isolate any nodes. It only tags the matched- // TopK with RT_INFO_MOE_K. This tag is the ISOL_PRESETS lookup key used by- // the pattern registry ("P:Qwen3Router/router") — not an isolation target.- static constexpr const char* isolation_tag() {- return ROUTER_TAG;- }- static constexpr const char* group_name() {- return "moe";- }- // NOTE: isol_tag is accepted for macro-call uniformity but is intentionally unused- // (Router nodes are not isolated; only K is extracted via RT_INFO_MOE_K).+ MOE_ROUTER_STATIC_INFO(Qwen3Router)Qwen3Router(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);};+class Gemma4Expert : public ov::pass::MatcherPass {+public:+ MOE_EXPERT_STATIC_INFO(Gemma4Expert)+ Gemma4Expert(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);+};++class Gemma4Router : public ov::pass::MatcherPass {+public:+ MOE_ROUTER_STATIC_INFO(Gemma4Router)+ Gemma4Router(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);+};+} // namespace moe} // namespace patterns} // namespace npuwdiff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.cppindex b96b1481e4a..3e8bb654f48 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.cpp@@ -292,8 +292,7 @@ ov::Output<ov::Node> Qwen3MoEFFN::operator()(const ov::Output<ov::Node>& input,// Scatter the renormalized scores back to the full expert dimension. The TopK indices// (output(1)) feed the scatter directly — no intermediate Convert — matching Qwen3Router.auto zeros = router_zeros(r_mm, name + ".expert.router.shapeof", name + ".expert.router.zeros");- auto scatter =- std::make_shared<ov::op::v12::ScatterElementsUpdate>(zeros, topk->output(1), divide, scatter_axis);+ auto scatter = std::make_shared<ov::op::v12::ScatterElementsUpdate>(zeros, topk->output(1), divide, scatter_axis);scatter->set_friendly_name(name + ".expert.router.scatter");auto router_scores = broadcast_router_scores(scatter, name);@@ -302,9 +301,8 @@ ov::Output<ov::Node> Qwen3MoEFFN::operator()(const ov::Output<ov::Node>& input,auto expert_3d = tile_to_experts(input_2d, name);// Gate projection -> Swish.- auto gate_w = weight_fn(name + ".expert.gate_proj.weight",- ov::Shape{num_experts, intermediate_size, hidden_size},- prec);+ auto gate_w =+ weight_fn(name + ".expert.gate_proj.weight", ov::Shape{num_experts, intermediate_size, hidden_size}, prec);auto gate_mm = std::make_shared<ov::opset11::MatMul>(expert_3d, gate_w, false, true);gate_mm->set_friendly_name(name + ".expert.gate_matmul");// Single-input Swish (no beta) — matches real Qwen3 aten::silu and the Qwen3Expert@@ -331,6 +329,119 @@ ov::Output<ov::Node> Qwen3MoEFFN::operator()(const ov::Output<ov::Node>& input,return weighted_expert_sum(dn_mm, router_scores, original_shape, name);}+Gemma4MoEFFN::Gemma4MoEFFN(size_t hs, size_t is, size_t ne, size_t k, ov::element::Type prec, WeightFn wf)+ // const_shape: literal Const reshape shapes, same requirement as Qwen3MoEFFN.+ : BatchedMoEFFN(hs, is, ne, k, prec, std::move(wf), const_shape) {+ // Router renormalization sums the K selected scores (last router axis), keepdims.+ reduce_axis_k = ov::opset11::Constant::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{1});+ // Uniform per-expert scale (all ones); real Gemma4 learns this from training data.+ per_expert_scale_const =+ ov::opset11::Constant::create(ov::element::f32, ov::Shape{ne}, std::vector<float>(ne, 1.0f));+}++ov::Output<ov::Node> Gemma4MoEFFN::operator()(const ov::Output<ov::Node>& input, const std::string& name) const {+ // Gemma4-style batched MoE matching NPUW's Gemma4Expert + Gemma4Router patterns.+ //+ // Router (FP32 weights, per-expert scale, extra Slice before scatter):+ // input_2d -> MatMul(FP32 weight) -> Softmax -> TopK(MAX)+ // -> ReduceSum(values) -> Divide(values, sum) = renormalized+ // -> Gather(per_expert_scale, topk_indices) -> Multiply(renormalized, scale)+ // -> Slice -> ScatterElementsUpdate(zeros, indices, slice)+ // -> Transpose -> Reshape([N,1,-1]) -> Unsqueeze(axis 3) = router_scores+ //+ // Expert (gate/up share the same Reshape; activation is Gelu):+ // input_2d -> Tile -> Reshape([N,-1,H]) = expert_3d+ // gate: expert_3d -> MatMul(gate_w) -> Gelu+ // up: expert_3d -> MatMul(up_w)+ // merge: Gelu * up -> Multiply+ // down: Multiply -> MatMul(down_w)+ // -> weighted_expert_sum (Reshape -> Multiply(router_scores) -> ReduceSum -> Reshape)+ const auto prec = precision;+ const int32_t k_i = static_cast<int32_t>(num_experts_per_tok);++ auto [original_shape, input_2d] = flatten_input(input, name);++ // --- Router ---+ // Plain FP32 weight (Gemma4 does not quantize the router).+ auto rw = ov::opset11::Constant::create(ov::element::f32,+ ov::Shape{num_experts, hidden_size},+ std::vector<float>(num_experts * hidden_size, 1.0f));+ rw->set_friendly_name(name + ".router.weight");+ auto r_mm = std::make_shared<ov::opset11::MatMul>(input_2d, rw, false, true);+ r_mm->set_friendly_name(name + ".router.matmul");++ auto softmax = std::make_shared<ov::op::v8::Softmax>(r_mm, 1);+ softmax->set_friendly_name(name + ".router.softmax");+ auto topk = std::make_shared<ov::opset11::TopK>(softmax, topk_k_const, 1, "max", "value", ov::element::i64);+ topk->set_friendly_name(name + ".router.topk");++ // Renormalize over the K selected experts.+ auto reduce_router = std::make_shared<ov::opset11::ReduceSum>(topk->output(0), reduce_axis_k, true);+ reduce_router->set_friendly_name(name + ".router.reduce");+ auto divide = std::make_shared<ov::opset11::Divide>(topk->output(0), reduce_router);+ divide->set_friendly_name(name + ".router.divide");++ // Per-expert learned scale: Gather(per_expert_scale, Convert(topk_indices), axis=0).+ // Gemma4Router's Gather uses all any_input() ports, so any Gather here will bind.+ auto gather_axis = ov::opset11::Constant::create(ov::element::i64, ov::Shape{}, {0LL});+ auto topk_idx_cast = std::make_shared<ov::opset11::Convert>(topk->output(1), ov::element::i64);+ topk_idx_cast->set_friendly_name(name + ".router.topk_idx_cast");+ auto gather = std::make_shared<ov::op::v8::Gather>(per_expert_scale_const, topk_idx_cast, gather_axis);+ gather->set_friendly_name(name + ".router.per_expert_scale_gather");++ // Combine renormalized scores with per-expert scale.+ auto scores_multiply = std::make_shared<ov::opset11::Multiply>(divide, gather);+ scores_multiply->set_friendly_name(name + ".router.scores_multiply");++ // Slice(scores_multiply, start=0, stop=k, step=1, axis=1) — Gemma4-specific.+ auto sl_begin = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {0LL});+ auto sl_end = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{k_i});+ auto sl_step = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {1LL});+ auto sl_axes = ov::opset11::Constant::create(ov::element::i64, ov::Shape{1}, {1LL});+ auto slice = std::make_shared<ov::op::v8::Slice>(scores_multiply, sl_begin, sl_end, sl_step, sl_axes);+ slice->set_friendly_name(name + ".router.slice");++ // Scatter selected scores back to the full expert dimension.+ auto zeros = router_zeros(r_mm, name + ".router.shapeof", name + ".router.zeros");+ auto scatter_indices_cast = std::make_shared<ov::opset11::Convert>(topk->output(1), ov::element::i64);+ scatter_indices_cast->set_friendly_name(name + ".router.scatter_idx_cast");+ auto scatter =+ std::make_shared<ov::op::v12::ScatterElementsUpdate>(zeros, scatter_indices_cast, slice, scatter_axis);+ scatter->set_friendly_name(name + ".router.scatter");++ auto router_scores = broadcast_router_scores(scatter, name);++ // --- Expert ---+ // Gate and up projections both use the same Tile → Reshape3D (expert_3d).+ auto expert_3d = tile_to_experts(input_2d, name);++ // Gate projection -> Gelu.+ auto gate_w =+ weight_fn(name + ".expert.gate_proj.weight", ov::Shape{num_experts, intermediate_size, hidden_size}, prec);+ auto gate_mm = std::make_shared<ov::opset11::MatMul>(expert_3d, gate_w, false, true);+ gate_mm->set_friendly_name(name + ".expert.gate_matmul");+ auto gelu = std::make_shared<ov::op::v7::Gelu>(gate_mm);+ gelu->set_friendly_name(name + ".expert.gelu");++ // Up projection (shares expert_3d input, matching Gemma4Expert's pattern).+ auto up_w =+ weight_fn(name + ".expert.up_proj.weight", ov::Shape{num_experts, intermediate_size, hidden_size}, prec);+ auto up_mm = std::make_shared<ov::opset11::MatMul>(expert_3d, up_w, false, true);+ up_mm->set_friendly_name(name + ".expert.up_matmul");++ // SwiGLU merge: Gelu(gate) * up.+ auto merged = std::make_shared<ov::opset11::Multiply>(gelu, up_mm);+ merged->set_friendly_name(name + ".expert.merge");++ // Down projection.+ auto dn_w =+ weight_fn(name + ".expert.down_proj.weight", ov::Shape{num_experts, hidden_size, intermediate_size}, prec);+ auto dn_mm = std::make_shared<ov::opset11::MatMul>(merged, dn_w, false, true);+ dn_mm->set_friendly_name(name + ".expert.down_matmul");++ return weighted_expert_sum(dn_mm, router_scores, original_shape, name);+}+} // namespace npuw} // namespace test} // namespace ovdiff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.hppindex 84516b12a2e..18a7147bba3 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.hpp@@ -62,8 +62,7 @@ protected:/// Scattered per-expert scores [N,ne] -> [ne,1,N,1] for broadcasting over the expert/// outputs: Transpose -> Reshape -> Unsqueeze (the Qwen3Router/GPTOSSRouter tail).- ov::Output<ov::Node> broadcast_router_scores(const ov::Output<ov::Node>& scattered,- const std::string& name) const;+ ov::Output<ov::Node> broadcast_router_scores(const ov::Output<ov::Node>& scattered, const std::string& name) const;/// 2D input [N,H] -> all-expert batch [ne,N,H]: Tile -> Reshape.ov::Output<ov::Node> tile_to_experts(const ov::Output<ov::Node>& input_2d, const std::string& name) const;@@ -124,6 +123,29 @@ inline FFNFn make_qwen3_moe_ffn(size_t hs, size_t is, size_t ne, size_t k, ov::ereturn Qwen3MoEFFN(hs, is, ne, k, prec);}+/// Gemma4 style batched MoE FFN matching NPUW's Gemma4Expert + Gemma4Router patterns (real Gemma4-26B-A4B).+/// Differences from Qwen3MoEFFN:+/// - Expert: gate/up share the same Reshape input (no separate Tile per branch); activation+/// is Gelu (not Swish);+/// - Router: plain FP32 weight (no dequant chain); per-expert learned scale via Gather;+/// extra Slice before ScatterElementsUpdate; Gemma4Router pattern root is Unsqueeze.+/// Select via LLMConfig::moe_factory = make_gemma4_moe_ffn.+struct Gemma4MoEFFN : BatchedMoEFFN {+ /// Default weight_fn: CompressedWeight{i4, 0, SYMM_NO_ZP}.+ Gemma4MoEFFN(size_t hs, size_t is, size_t ne, size_t k, ov::element::Type prec, WeightFn wf = {});++ ov::Output<ov::Node> operator()(const ov::Output<ov::Node>& input, const std::string& name) const;++private:+ std::shared_ptr<ov::Node> reduce_axis_k; ///< router renormalization axis (over K)+ std::shared_ptr<ov::Node> per_expert_scale_const; ///< learned per-expert scale [num_experts]+};++/// MoEFactoryFn for the Gemma4 topology. Assign to LLMConfig::moe_factory to select it.+inline FFNFn make_gemma4_moe_ffn(size_t hs, size_t is, size_t ne, size_t k, ov::element::Type prec) {+ return Gemma4MoEFFN(hs, is, ne, k, prec);+}+} // namespace npuw} // namespace test} // namespace ovdiff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hppindex 48ce2997a6e..387b0b83701 100644--- a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp@@ -207,6 +207,19 @@ inline std::shared_ptr<ov::Model> build_qwen3_moe_llm_test_model() {return mb.build_llm(cfg);}+/// Gemma4-style MoE: separate gate/up expert MatMuls (GeLU activation) and a+/// Softmax->TopK router with ReduceSum->Divide renormalization plus per-expert+/// learned scale (Gather) and an extra Slice before scatter, matching NPUW's+/// Gemma4Expert + Gemma4Router patterns (real Gemma4-26B-A4B).+inline std::shared_ptr<ov::Model> build_gemma4_moe_llm_test_model() {+ ModelBuilder mb;+ auto cfg = make_test_model_config();+ cfg.num_experts = 8;+ cfg.num_experts_per_tok = 2;+ cfg.moe_factory = make_gemma4_moe_ffn;+ return mb.build_llm(cfg);+}+inline std::shared_ptr<ov::Model> build_sliding_window_test_model(size_t window_size = 512,size_t sliding_to_full_ratio = 0,const SlidingMaskFn& sliding_mask_fn = {},diff --git a/src/plugins/intel_npu/tests/unit/npuw/moe_k_tag_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/moe_k_tag_test.cppindex cdeedbdf2fa..edf2c07d397 100644--- a/src/plugins/intel_npu/tests/unit/npuw/moe_k_tag_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/moe_k_tag_test.cpp@@ -386,4 +386,176 @@ TEST_F(Qwen3RouterTest, RouterNodesNotIsolated_WithConvertAndSlice) {}}+// ============================================================================+// Gemma4 Router graph helpers+// ============================================================================++// Build one Gemma4 Router layer attached to router_input and return its+// Unsqueeze output (the pattern root).+// Gemma4 differences vs Qwen3:+// - FP32 plain-weight MatMul (no dequantisation chain)+// - Per-expert learned scale via Gather before scatter+// - Extra Slice between scores and ScatterElementsUpdate+std::shared_ptr<Node> build_gemma4_router_layer(const std::shared_ptr<op::v0::Parameter>& router_input,+ int64_t k_value,+ int layer_idx,+ size_t num_experts) {+ const size_t hidden_dim = router_input->get_shape()[1];+ const std::string prefix = "__module.model.layer" + std::to_string(layer_idx) + ".router/";++ // FP32 plain weight (Gemma4 router weights are not quantized)+ auto w_fp32 = op::v0::Constant::create(element::f32,+ Shape{num_experts, hidden_dim},+ std::vector<float>(num_experts * hidden_dim, 1.0f));+ auto matmul = std::make_shared<op::v0::MatMul>(router_input, w_fp32, false, true);+ matmul->set_friendly_name(prefix + "MatMul");++ auto softmax = std::make_shared<op::v8::Softmax>(matmul, 1);+ softmax->set_friendly_name(prefix + "Softmax");++ auto k_const = op::v0::Constant::create(element::i64, Shape{}, std::vector<int64_t>{k_value});+ auto topk =+ std::make_shared<op::v11::TopK>(softmax, k_const, -1, op::v11::TopK::Mode::MAX, op::v11::TopK::SortType::NONE);+ topk->set_friendly_name(prefix + "TopK");++ // Renormalise over K selected experts: ReduceSum -> Divide+ auto reduce_axes = op::v0::Constant::create(element::i64, Shape{1}, {1LL});+ auto reduce_sum = std::make_shared<op::v1::ReduceSum>(topk->output(0), reduce_axes, /*keep_dims=*/true);+ auto divide = std::make_shared<op::v1::Divide>(topk->output(0), reduce_sum);++ // Per-expert learned scale: Gather(per_expert_scale, Convert(topk_indices), axis=0)+ auto per_expert_scale =+ op::v0::Constant::create(element::f32, Shape{num_experts}, std::vector<float>(num_experts, 1.0f));+ auto topk_indices_convert = std::make_shared<op::v0::Convert>(topk->output(1), element::i64);+ auto gather_axis = op::v0::Constant::create(element::i64, Shape{}, {0LL});+ auto gather = std::make_shared<op::v8::Gather>(per_expert_scale, topk_indices_convert, gather_axis);++ // Combine renormalised scores with per-expert scale+ auto scores_multiply = std::make_shared<op::v1::Multiply>(divide, gather);++ // Slice(scores_multiply, 0, k_value, step=1, axis=1) — Gemma4-specific trim+ auto sl_begin = op::v0::Constant::create(element::i64, Shape{1}, {0LL});+ auto sl_end = op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{k_value});+ auto sl_step = op::v0::Constant::create(element::i64, Shape{1}, {1LL});+ auto sl_axes = op::v0::Constant::create(element::i64, Shape{1}, {1LL});+ auto slice = std::make_shared<op::v8::Slice>(scores_multiply, sl_begin, sl_end, sl_step, sl_axes);++ // Scatter selected scores to full-expert dimension+ auto zero_base =+ op::v0::Constant::create(element::f32, Shape{1, num_experts}, std::vector<float>(num_experts, 0.0f));+ auto scatter_axis = op::v0::Constant::create(element::i64, Shape{}, {1LL});+ auto scatter_indices = std::make_shared<op::v0::Convert>(topk->output(1), element::i64);+ auto scatter = std::make_shared<op::v12::ScatterElementsUpdate>(zero_base, scatter_indices, slice, scatter_axis);++ // Tail: Transpose -> Reshape -> Unsqueeze (pattern root)+ auto t_order = op::v0::Constant::create(element::i32, Shape{2}, std::vector<int32_t>{1, 0});+ auto transpose = std::make_shared<op::v1::Transpose>(scatter, t_order);++ auto reshape_shape =+ op::v0::Constant::create(element::i64, Shape{3}, std::vector<int64_t>{static_cast<int64_t>(num_experts), 1, 1});+ auto reshape = std::make_shared<op::v1::Reshape>(transpose, reshape_shape, false);++ auto unsqueeze_axis = op::v0::Constant::create(element::i64, Shape{}, {3LL});+ return std::make_shared<op::v0::Unsqueeze>(reshape, unsqueeze_axis);+}++std::shared_ptr<Model> build_gemma4_router_graph(int64_t k_value, size_t hidden_dim = 16, size_t num_experts = 8) {+ auto router_input = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, hidden_dim});+ router_input->set_friendly_name("router_input");+ auto out = build_gemma4_router_layer(router_input, k_value, 0, num_experts);+ return std::make_shared<Model>(ResultVector{std::make_shared<op::v0::Result>(out)}, ParameterVector{router_input});+}++std::shared_ptr<Model> build_two_gemma4_router_model(int64_t k0,+ int64_t k1,+ size_t hidden_dim = 16,+ size_t num_experts = 8) {+ auto router_input = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, hidden_dim});+ router_input->set_friendly_name("router_input");+ ResultVector results;+ for (int i = 0; i < 2; ++i) {+ auto out = build_gemma4_router_layer(router_input, i == 0 ? k0 : k1, i, num_experts);+ results.push_back(std::make_shared<op::v0::Result>(out));+ }+ return std::make_shared<Model>(results, ParameterVector{router_input});+}++// ============================================================================+// Test fixture — Gemma4Router+// ============================================================================++class Gemma4RouterTest : public ::testing::Test {+protected:+ void run_pass(const std::shared_ptr<Model>& model) {+ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(model);+ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::moe::Gemma4Router>(snapshot, "router");+ rewr.run_on_model(model);+ }+};++// ============================================================================+// Gemma4Router tests+// ============================================================================++TEST_F(Gemma4RouterTest, TagsTopKWithCorrectK) {+ constexpr int64_t K = 4;+ auto model = build_gemma4_router_graph(K);+ run_pass(model);++ auto topks = find_all_topk(model);+ ASSERT_EQ(topks.size(), 1u);+ const auto& rt = topks[0]->get_rt_info();+ ASSERT_NE(rt.find(ov::npuw::patterns::moe::RT_INFO_MOE_K), rt.end());+ EXPECT_EQ(rt.at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), static_cast<size_t>(K));+}++TEST_F(Gemma4RouterTest, ZeroKNotTagged) {+ // K=0 is invalid; tag_topk_k() must return false without tagging.+ auto model = build_gemma4_router_graph(/*k_value=*/0);+ run_pass(model);++ auto topks = find_all_topk(model);+ ASSERT_EQ(topks.size(), 1u);+ EXPECT_EQ(topks[0]->get_rt_info().find(ov::npuw::patterns::moe::RT_INFO_MOE_K), topks[0]->get_rt_info().end())+ << "rt_info K must NOT be set when K=0";+}++TEST_F(Gemma4RouterTest, RouterNodesNotIsolated) {+ // Callback must return false without isolating any node.+ constexpr int64_t K = 4;+ auto model = build_gemma4_router_graph(K);+ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(model);+ snapshot->buildGraph();++ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::moe::Gemma4Router>(snapshot, "router");+ rewr.run_on_model(model);++ for (const auto& [node, group] : *snapshot->getNodeToGroupMap()) {+ EXPECT_NE(group->isolatedTag(), "router")+ << "Node \"" << node->get_friendly_name() << "\" was unexpectedly isolated";+ }+}++TEST_F(Gemma4RouterTest, ConsistentKAcrossLayersTagsBothNodes) {+ constexpr int64_t K = 4;+ auto model = build_two_gemma4_router_model(K, K);+ ASSERT_NO_THROW(run_pass(model));++ auto topks = find_all_topk(model);+ ASSERT_EQ(topks.size(), 2u);+ for (const auto& topk : topks) {+ const auto& rt = topk->get_rt_info();+ ASSERT_NE(rt.find(ov::npuw::patterns::moe::RT_INFO_MOE_K), rt.end())+ << "TopK \"" << topk->get_friendly_name() << "\" was not tagged";+ EXPECT_EQ(rt.at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), static_cast<size_t>(K));+ }+}++TEST_F(Gemma4RouterTest, InconsistentKAcrossLayersThrows) {+ auto model = build_two_gemma4_router_model(/*k0=*/2, /*k1=*/4);+ EXPECT_THROW(run_pass(model), ov::Exception) << "Inconsistent K values across MoE layers must throw";+}+} // namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cppindex 8b525cb52b6..95b3b6b3e8c 100644--- a/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cpp@@ -7,9 +7,8 @@#include <gtest/gtest.h>#include <algorithm>-#include <map>-#include <common_test_utils/test_common.hpp>+#include <map>#include "intel_npu/config/config.hpp"#include "intel_npu/config/npuw.hpp"@@ -17,11 +16,14 @@#include "model_builder.hpp"#include "moe_transformations/apply_moe_device_routed_transforms.hpp"#include "openvino/op/ops.hpp"+#include "openvino/pass/graph_rewrite.hpp"#include "openvino/pass/manager.hpp"#include "openvino/pass/serialize.hpp"#include "openvino/pass/stateful_to_stateless.hpp"#include "partitioning/online/compiler.hpp"+#include "partitioning/online/snapshot.hpp"#include "partitioning/partitioning.hpp"+#include "partitioning/patterns/moe.hpp"/** Test suite for MoE Expert Transformation@@ -662,6 +664,61 @@ TEST_F(MoETransformationTest, BuildQwen3MoELLM_HasExpertAndRouterNodes) {EXPECT_EQ(router_divide_count, 2u) << "One router Divide (renormalization) per layer";}+// Gemma4 MoE topology: separate gate/up MatMuls with Gelu (not Swish), a+// Softmax->TopK router with ReduceSum->Divide + per-expert scale Gather, and an+// extra Slice before ScatterElementsUpdate. Matches NPUW's Gemma4Expert + Gemma4Router.+TEST_F(MoETransformationTest, BuildGemma4MoELLM_HasExpertAndRouterNodes) {+ auto model = ov::test::npuw::build_gemma4_moe_llm_test_model();+ ASSERT_NE(model, nullptr);++ bool has_tile = false, has_topk = false, has_softmax = false, has_gelu = false;+ size_t topk_router_count = 0, softmax_router_count = 0, scatter_count = 0;+ size_t router_reduce_count = 0, router_divide_count = 0, router_gather_count = 0;++ for (const auto& op : model->get_ordered_ops()) {+ const auto& fname = op->get_friendly_name();+ const bool is_router = fname.find(".router") != std::string::npos;+ if (std::dynamic_pointer_cast<ov::op::v0::Tile>(op))+ has_tile = true;+ if (std::dynamic_pointer_cast<ov::op::v7::Gelu>(op))+ has_gelu = true;+ if (auto topk = std::dynamic_pointer_cast<ov::op::v11::TopK>(op)) {+ has_topk = true;+ if (is_router) {+ EXPECT_EQ(topk->get_mode(), ov::op::v11::TopK::Mode::MAX);+ topk_router_count++;+ }+ }+ if (std::dynamic_pointer_cast<ov::op::v8::Softmax>(op)) {+ has_softmax = true;+ if (is_router)+ softmax_router_count++;+ }+ if (std::dynamic_pointer_cast<ov::op::v3::ScatterElementsUpdate>(op) ||+ std::dynamic_pointer_cast<ov::op::v12::ScatterElementsUpdate>(op))+ scatter_count++;+ if (is_router && std::dynamic_pointer_cast<ov::op::v1::ReduceSum>(op))+ router_reduce_count++;+ if (is_router && std::dynamic_pointer_cast<ov::op::v1::Divide>(op))+ router_divide_count++;+ if (is_router && std::dynamic_pointer_cast<ov::op::v8::Gather>(op))+ router_gather_count++;+ }++ EXPECT_TRUE(has_tile) << "Missing Tile (expert input broadcast)";+ EXPECT_TRUE(has_topk) << "Missing TopK (router)";+ EXPECT_TRUE(has_softmax) << "Missing Softmax (router)";+ // Gemma4 expert activation is Gelu, not Swish.+ EXPECT_TRUE(has_gelu) << "Missing Gelu (expert gate activation)";+ EXPECT_EQ(topk_router_count, 2u) << "One router TopK per layer";+ EXPECT_EQ(softmax_router_count, 2u) << "One router Softmax per layer";+ EXPECT_EQ(scatter_count, 2u) << "One ScatterElementsUpdate per layer";+ // Gemma4-specific renormalization and per-expert scale.+ EXPECT_EQ(router_reduce_count, 2u) << "One router ReduceSum (renormalization) per layer";+ EXPECT_EQ(router_divide_count, 2u) << "One router Divide (renormalization) per layer";+ EXPECT_EQ(router_gather_count, 2u) << "One router Gather (per-expert scale) per layer";+}+// Minimal Qwen3 MoE config: num_experts + moe_factory, everything else defaulted.TEST_F(MoETransformationTest, Qwen3MoE_MinimalConfigBuildsFromFactory) {ov::test::npuw::ModelBuilder mb;@@ -696,10 +753,9 @@ inline ::intel_npu::Config make_moe_isolate_cfg() {}inline size_t count_groups_with_tag(const ov::npuw::Ensemble& ens, const std::string& tag) {- return static_cast<size_t>(- std::count_if(ens.groups.begin(), ens.groups.end(), [&tag](const ov::npuw::Group& g) {- return g.gettag() == tag;- }));+ return static_cast<size_t>(std::count_if(ens.groups.begin(), ens.groups.end(), [&tag](const ov::npuw::Group& g) {+ return g.gettag() == tag;+ }));}// The builder model is stateful (KV cache) like a real LLM; the partitioner and the@@ -795,5 +851,193 @@ TEST_F(MoETransformationTest, Qwen3MoE_DeviceRoutedTransformRewritesBuilderOutpuEXPECT_GT(checked_tiles, 0u) << "no expert Tile found to verify";}+// ============================================================================+// Gemma4Expert pattern tests+// ============================================================================++// Build a Gemma4-style expert subgraph that matches NPUW's Gemma4Expert pattern:+// Tile -> Reshape1+// gate: Reshape1 -> MatMul1(DQ_gate) -> Gelu+// up: Reshape1 -> MatMul2(DQ_up)+// merge: Gelu * MatMul2 -> Multiply1+// down: Multiply1 -> MatMul3(DQ_down) -> Reshape2+// Pattern root: Reshape2 * router_scores -> output_multiply+//+// If with_reduce_sum is true a ReduceSum consumer is appended (simulates the downstream+// ReduceSum that exists in the full MoE graph, which is isolated into the expert group+// only in the decoding stage).+static std::shared_ptr<Model> create_gemma4_expert_graph(size_t num_experts,+ size_t hidden_dim = 64,+ size_t intermediate_dim = 128,+ size_t token_count = 1,+ bool with_reduce_sum = false) {+ ov::ParameterVector params;++ // Expert input: [token_count, hidden_dim]+ auto expert_input = std::make_shared<op::v0::Parameter>(element::f32, Shape{token_count, hidden_dim});+ expert_input->set_friendly_name("expert_input");+ params.push_back(expert_input);++ // Tile: [token_count, hidden_dim] -> [num_experts * token_count, hidden_dim]+ auto repeats =+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{static_cast<int64_t>(num_experts), 1});+ auto tile = std::make_shared<op::v0::Tile>(expert_input, repeats);+ tile->set_friendly_name("expert_tile");++ // Reshape1: [num_experts, token_count, hidden_dim]+ auto reshape_shape1 = op::v0::Constant::create(element::i64,+ Shape{3},+ std::vector<int64_t>{static_cast<int64_t>(num_experts),+ static_cast<int64_t>(token_count),+ static_cast<int64_t>(hidden_dim)});+ auto reshape1 = std::make_shared<op::v1::Reshape>(tile, reshape_shape1, false);+ reshape1->set_friendly_name("expert_reshape1");++ // Helper lambda: build a DQ chain (nf4 -> fp16 -> Multiply(scale) -> fp32)+ auto make_dq_weight = [&](const std::string& name, const Shape& weight_shape) -> std::shared_ptr<Node> {+ auto w_nf4 = std::make_shared<op::v0::Parameter>(element::nf4, weight_shape);+ w_nf4->set_friendly_name(name + "_nf4");+ params.push_back(w_nf4);+ auto w_fp16 = std::make_shared<op::v0::Convert>(w_nf4, element::f16);+ w_fp16->set_friendly_name(name + "_fp16");+ Shape scale_shape{weight_shape[0], weight_shape[1], 1};+ auto scale = std::make_shared<op::v0::Parameter>(element::f16, scale_shape);+ scale->set_friendly_name(name + "_scale");+ params.push_back(scale);+ auto w_scaled = std::make_shared<op::v1::Multiply>(w_fp16, scale);+ w_scaled->set_friendly_name(name + "_multiply");+ auto w_fp32 = std::make_shared<op::v0::Convert>(w_scaled, element::f32);+ w_fp32->set_friendly_name(name + "_fp32");+ return w_fp32;+ };++ // Gate projection: MatMul1(reshape1, DQ_gate) -> Gelu+ auto gate_dq = make_dq_weight("gate_weights", Shape{num_experts, intermediate_dim, hidden_dim});+ auto matmul1 = std::make_shared<op::v0::MatMul>(reshape1, gate_dq, false, true);+ matmul1->set_friendly_name("expert_matmul1_gate");+ auto gelu = std::make_shared<op::v7::Gelu>(matmul1);+ gelu->set_friendly_name("expert_gelu");++ // Up projection: MatMul2(reshape1, DQ_up)+ auto up_dq = make_dq_weight("up_weights", Shape{num_experts, intermediate_dim, hidden_dim});+ auto matmul2 = std::make_shared<op::v0::MatMul>(reshape1, up_dq, false, true);+ matmul2->set_friendly_name("expert_matmul2_up");++ // SwiGLU merge: Gelu(gate) * up+ auto multiply1 = std::make_shared<op::v1::Multiply>(gelu, matmul2);+ multiply1->set_friendly_name("expert_multiply1_swiglu");++ // Down projection: MatMul3(merge, DQ_down) -> Reshape2+ auto down_dq = make_dq_weight("down_weights", Shape{num_experts, hidden_dim, intermediate_dim});+ auto matmul3 = std::make_shared<op::v0::MatMul>(multiply1, down_dq, false, true);+ matmul3->set_friendly_name("expert_matmul3_down");+ auto reshape_shape2 = op::v0::Constant::create(element::i64,+ Shape{3},+ std::vector<int64_t>{static_cast<int64_t>(num_experts),+ static_cast<int64_t>(token_count),+ static_cast<int64_t>(hidden_dim)});+ auto reshape2 = std::make_shared<op::v1::Reshape>(matmul3, reshape_shape2, false);+ reshape2->set_friendly_name("expert_reshape2");++ // Pattern root: Reshape2 * scattered_router_scores+ auto router_scores = std::make_shared<op::v0::Parameter>(element::f32, Shape{num_experts, token_count, 1});+ router_scores->set_friendly_name("router_scores");+ params.push_back(router_scores);+ auto output_multiply = std::make_shared<op::v1::Multiply>(reshape2, router_scores);+ output_multiply->set_friendly_name("output_multiply");++ Output<Node> result_input = output_multiply->output(0);++ if (with_reduce_sum) {+ // Downstream ReduceSum: aggregates over expert dim (axis 0)+ auto reduce_axis = op::v0::Constant::create(element::i64, Shape{1}, {0LL});+ auto reduce_sum = std::make_shared<op::v1::ReduceSum>(output_multiply, reduce_axis, false);+ reduce_sum->set_friendly_name("expert_downstream_reduce_sum");+ result_input = reduce_sum->output(0);+ }++ auto result = std::make_shared<op::v0::Result>(result_input);+ auto model = std::make_shared<Model>(ResultVector{result}, params);+ model->set_friendly_name("gemma4_expert_" + std::to_string(num_experts));+ return model;+}++// Verify that Gemma4Expert isolates all matched nodes with the "expert" tag.+TEST_F(MoETransformationTest, Gemma4Expert_IsolatesNodes) {+ constexpr size_t num_experts = 8;+ auto model = create_gemma4_expert_graph(num_experts,+ /*hidden_dim=*/64,+ /*intermediate_dim=*/128,+ /*token_count=*/1);++ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(model);+ snapshot->buildGraph();++ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::moe::Gemma4Expert>(snapshot, "expert");+ ASSERT_NO_THROW(rewr.run_on_model(model));++ // At least the core compute nodes (Tile, Reshape, MatMuls, Gelu, Multiply) must be isolated.+ const auto& node_map = *snapshot->getNodeToGroupMap();+ size_t isolated_count = 0;+ for (const auto& [node, group] : node_map) {+ if (group->isolatedTag() == "expert")+ ++isolated_count;+ }+ EXPECT_GT(isolated_count, 0u) << "Gemma4Expert did not isolate any node";+}++// In decoding mode (token_count == 1, middle shape dim == 1) the downstream ReduceSum+// must also be isolated into the expert group.+TEST_F(MoETransformationTest, Gemma4Expert_DecodingIsolatesReduceSum) {+ constexpr size_t num_experts = 8;+ auto model = create_gemma4_expert_graph(num_experts,+ /*hidden_dim=*/64,+ /*intermediate_dim=*/128,+ /*token_count=*/1,+ /*with_reduce_sum=*/true);++ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(model);+ snapshot->buildGraph();++ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::moe::Gemma4Expert>(snapshot, "expert");+ rewr.run_on_model(model);++ // The downstream ReduceSum must be tagged "expert" (decoding path).+ bool reduce_sum_isolated = false;+ for (const auto& [node, group] : *snapshot->getNodeToGroupMap()) {+ if (group->isolatedTag() == "expert" && std::dynamic_pointer_cast<op::v1::ReduceSum>(node)) {+ reduce_sum_isolated = true;+ break;+ }+ }+ EXPECT_TRUE(reduce_sum_isolated) << "Downstream ReduceSum must be isolated into the expert group in decoding mode";+}++// In prefill mode (token_count > 1) the downstream ReduceSum must NOT be isolated.+TEST_F(MoETransformationTest, Gemma4Expert_PrefillDoesNotIsolateReduceSum) {+ constexpr size_t num_experts = 8;+ constexpr size_t prefill_tokens = 16;+ auto model = create_gemma4_expert_graph(num_experts,+ /*hidden_dim=*/64,+ /*intermediate_dim=*/128,+ /*token_count=*/prefill_tokens,+ /*with_reduce_sum=*/true);++ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(model);+ snapshot->buildGraph();++ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::moe::Gemma4Expert>(snapshot, "expert");+ rewr.run_on_model(model);++ for (const auto& [node, group] : *snapshot->getNodeToGroupMap()) {+ if (std::dynamic_pointer_cast<op::v1::ReduceSum>(node) &&+ node->get_friendly_name() == "expert_downstream_reduce_sum") {+ EXPECT_NE(group->isolatedTag(), "expert") << "Downstream ReduceSum must NOT be isolated in prefill mode";+ }+ }+}} // namespace