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] Share batched MoE matching and sparse lowering (#38124)
Rajath Ravib61c7e8cc135
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cppindex 2ff379294f7..7fe9ea33750 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp@@ -742,9 +742,7 @@ void MoEExecutor::unpack_single_expert_closure(std::size_t idx, RqPtr request, sauto& iport = func_desc.compiled_model->inputs()[closure_param_id];- // Check if this weight needs slicing (has num_experts in first dimension)- auto closure_shape = closure.get_shape();- bool needs_slicing = !closure_shape.empty() && closure_shape[0] == num_experts;+ const bool needs_slicing = ov::npuw::moe::requires_expert_slice(closure, iport.get_shape(), num_experts);if (needs_slicing) {// Slice expert weight using view (no copy) - returns ov::Tensor object@@ -830,26 +828,21 @@ void MoEExecutor::unpack_multiple_experts_closure(std::size_t idx,const size_t original_param_idx = comp_model_desc.param_base + closure_idx;auto& batched_closure = desc_closure[closure_idx];- const auto& closure_shape = batched_closure.get_shape();// Check if this parameter has unrolled variants (is in param_mapping)auto mapping_it = param_mapping.find(original_param_idx);- if (mapping_it == param_mapping.end()) {- // If the closure is batched [num_experts,...] but has no param_mapping entry, the- // expert-dimension unrolling (UnrollMoEMatMul) failed to fire for this weight.- // This is a transformation bug — assert to surface it early.- const bool is_batched_nounroll = !closure_shape.empty() && closure_shape[0] == num_experts;- NPUW_ASSERT(!is_batched_nounroll &&- "Batched closure has no param_mapping entry — UnrollMoEMatMul did not fire");- continue; // Non-batched shared param not in mapping — skip silently- }+ OPENVINO_ASSERT(mapping_it != param_mapping.end(),+ "MoE: closure parameter is missing from the transformed input mapping: ",+ original_param_idx);const auto& unrolled_indices = mapping_it->second;NPUW_ASSERT(unrolled_indices.size() == K);- // Verify this is a batched parameter [num_experts, ...]- const bool is_batched = !closure_shape.empty() && closure_shape[0] == num_experts;- if (!is_batched) {+ const bool needs_slicing =+ ov::npuw::moe::requires_expert_slice(batched_closure,+ compiled_inputs.at(unrolled_indices.front()).get_shape(),+ num_experts);+ if (!needs_slicing) {// Shared parameter path - all K unrolled parameters share same weightconst bool do_copy = m_accessor.needs_copy_closure(idx, closure_idx);auto batched_impl = ov::get_tensor_impl(batched_closure);diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cppindex 8e30842af5b..85e90ba39fb 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp@@ -4,6 +4,7 @@#include "moe_infer_utils.hpp"+#include <algorithm>#include <cstring>#include <iomanip>#include <iostream>@@ -100,6 +101,17 @@ ov::Tensor slice_expert_weight(const ov::Tensor& batched_weight, size_t expert_ireturn view_tensor;}+bool requires_expert_slice(const ov::Tensor& source, const ov::Shape& target_shape, size_t num_experts) {+ const auto& source_shape = source.get_shape();+ if (source_shape == target_shape)+ return false;+ OPENVINO_ASSERT(!source_shape.empty() && source_shape.size() == target_shape.size() &&+ source_shape[0] == num_experts && target_shape[0] == 1 &&+ std::equal(source_shape.begin() + 1, source_shape.end(), target_shape.begin() + 1),+ "MoE: closure shape does not match its transformed input");+ return true;+}+namespace {// Returns the token-count dimension from a router output shape.// All supported layouts have a trailing singleton dim:diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.hppindex 7cf09cd2b59..33e91f70b47 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.hpp@@ -88,6 +88,8 @@ inline bool is_nonzero(T v) {*/ov::Tensor slice_expert_weight(const ov::Tensor& batched_weight, size_t expert_id, size_t num_experts);+bool requires_expert_slice(const ov::Tensor& source, const ov::Shape& target_shape, size_t num_experts);+/*** @brief Parse selected experts from router output tensor.*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 30528da29bb..1384e89212a 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@@ -125,14 +125,15 @@ void transform_experts(ov::npuw::Function& function,ov::npuw::v1::subgraphs::Context& ctx,const std::size_t moe_chunk_size) {auto k_value = find_moe_k_value(ctx);- if (!k_value.has_value()) {- LOG_WARN("MoE K value not found in context; skipping expert transformation");- return;- }+ OPENVINO_ASSERT(k_value.has_value(),+ "NPUW sparse expert partition is missing its top-k metadata. "+ "Refusing to execute an expert partition densely.");auto experts = ov::npuw::function::MoEExperts::from(function._model, k_value.value(), moe_chunk_size);- if (experts.has_value()) {- ctx.put<ov::npuw::function::MoEExperts>(std::move(experts.value()));- }+ OPENVINO_ASSERT(experts.has_value(),+ "NPUW could not lower the isolated expert partition to sparse execution: ",+ function._model->get_friendly_name(),+ ". Check the expert weight layout and export representation.");+ ctx.put<ov::npuw::function::MoEExperts>(std::move(experts.value()));}void compile_transformed_expert_models(const CompiledExpertsState& runtime_experts,@@ -361,14 +362,10 @@ 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(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.reserve(8);registrations.emplace_back(- registry.on<ov::npuw::patterns::moe::GPTOSSExpert>()+ registry.on<ov::npuw::patterns::moe::BatchedExpert>().at_partition([moe_chunk_size](ov::npuw::Function& function, ov::npuw::v1::subgraphs::Context& ctx) {transform_experts(function, ctx, moe_chunk_size);})@@ -378,27 +375,16 @@ 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());+ 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::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());+ // Keep explicit legacy matcher names, but attach the expert-tag pipeline+ // only once. Registering identical callbacks for each matcher transforms+ // the same function repeatedly, even when only one topology matched.+ registrations.emplace_back(registry.on<ov::npuw::patterns::moe::GPTOSSExpert>().scoped());+ registrations.emplace_back(registry.on<ov::npuw::patterns::moe::Qwen3Expert>().scoped());+ registrations.emplace_back(registry.on<ov::npuw::patterns::moe::Gemma4Expert>().scoped());ov::npuw::v1::subgraphs::PatternRegistration downstream_registration;downstream_registration.partition_stage = [](ov::npuw::Function& function, ov::npuw::v1::subgraphs::Context& ctx) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/apply_moe_device_routed_transforms.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/apply_moe_device_routed_transforms.cppindex be2918ee7ca..a1ee1ef7ea9 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/apply_moe_device_routed_transforms.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/apply_moe_device_routed_transforms.cpp@@ -15,7 +15,11 @@ void apply_moe_device_routed_transforms(const std::shared_ptr<ov::Model>& model)ov::npuw::pass::DeviceRoutedMoETransform moe_transform;ov::npuw::pass::GatherTo2DGather gather_transform;- moe_transform.run_on_model(model);+ OPENVINO_ASSERT(moe_transform.run_on_model(model),+ "NPUW DEVICE_ROUTED was requested but no supported batched MoE was lowered. "+ "DEVICE_ROUTED requires static single-token decode; use HOST_ROUTED for prefill. "+ "Re-export with explicit top-k indices, mixing scores, and expert-major weights, "+ "or select a supported HOST_ROUTED path explicitly.");LOG_DEBUG(" Applied DEVICE_ROUTED transformations to model variant");// Apply Gather to 2D Gather transformation for HW optimizationdiff --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.cppindex 1f91cc23cf7..b447aead47b 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,662 +4,30 @@#include "device_routed_moe_transform.hpp"-#include <optional>-#include <queue>-#include <unordered_set>-#include "../logging.hpp"-#include "moe_transformation_utils.hpp"-#include "openvino/core/rt_info.hpp"-#include "openvino/op/ops.hpp"--namespace ov {-namespace npuw {-namespace pass {--namespace {--// ============================================================================-// Helper structures for organizing transformation data-// ============================================================================--struct LayerNodes {- std::vector<std::shared_ptr<ov::op::v0::Tile>> tiles;- std::vector<std::shared_ptr<ov::op::v1::Reshape>> constant_reshapes;- std::vector<std::shared_ptr<ov::op::v1::Reshape>> dynamic_reshapes;- std::vector<std::shared_ptr<ov::op::v0::MatMul>> matmuls;- std::vector<std::shared_ptr<ov::op::v1::Add>> adds;- std::vector<std::shared_ptr<ov::op::v1::Multiply>> multiplies;- std::shared_ptr<ov::op::v1::Transpose> transpose;- size_t num_experts = 0;-- bool has_required_nodes() const {- return (!constant_reshapes.empty() || !dynamic_reshapes.empty()) && (!matmuls.empty() || !adds.empty());- }-};--struct RouterInfo {- std::shared_ptr<ov::op::v11::TopK> topk_node;- ov::Output<ov::Node> topk_indices_raw;- ov::Output<ov::Node> router_scores; // scores from Scatter.input(2), replaces Scatter->Transpose- int64_t k_value;- 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-};--// ============================================================================-// Helper functions-// ============================================================================--// Trace back through Convert to find actual weight/bias source-inline ov::Output<ov::Node> get_weight_source(const ov::Output<ov::Node>& input) {- auto node = input.get_node_shared_ptr();- if (auto convert = std::dynamic_pointer_cast<ov::op::v0::Convert>(node)) {- return convert->input_value(0);- }- return input;-}--// 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);-- // Must have static ranks and output rank must be greater than input rank- if (!input_shape.rank().is_static() || !output_shape.rank().is_static() ||- output_shape.rank().get_length() <= input_shape.rank().get_length()) {- return false;- }-- // Verify all output dims are either from input or newly inserted with size 1- int64_t in_idx = 0;- for (int64_t out_idx = 0; out_idx < output_shape.rank().get_length(); ++out_idx) {- if (in_idx < input_shape.rank().get_length() &&- (!input_shape[in_idx].is_static() || !output_shape[out_idx].is_static() ||- input_shape[in_idx].get_length() == output_shape[out_idx].get_length())) {- // This dimension matches input dimension- ++in_idx;- } else if (!output_shape[out_idx].is_static() || output_shape[out_idx].get_length() != 1) {- // Not a size-1 inserted dimension - not unsqueeze-like- return false;- }- // else: this is a newly inserted dimension with size 1, continue- }-- // Valid unsqueeze if all input dimensions were matched- return in_idx == input_shape.rank().get_length();-}--// ============================================================================-// Router detection by topology-// ============================================================================--// 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;- }- }- if (!transpose)- return std::nullopt;-- // 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;-- // 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;-- // 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;- }-- // 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;- }- }-- // 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: Detected MoE router by topology, K=" << k_value);-- return RouterInfo{topk_node, topk_indices_raw, router_scores, k_value, transpose, output_multiply};-}--// ============================================================================-// Expert node collection by backward BFS from expert output-// ============================================================================--// 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;- 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;- }-- // 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;-- 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();-- if (auto tile = std::dynamic_pointer_cast<ov::op::v0::Tile>(n)) {- all_tiles.push_back(tile);- continue; // Tile is the boundary; don't BFS further into shared hidden state- }- if (auto reshape = std::dynamic_pointer_cast<ov::op::v1::Reshape>(n)) {- 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);- }- } 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);- }-- // 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);- }- }-- if (nodes.num_experts == 0) {- LOG_WARN("collect_from_expert_output: no Tile with repeats[0] > k_value found");- return nodes;- }-- // 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);- }- }-- nodes.dynamic_reshapes = std::move(all_dyn_reshapes);-- // 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;- };-- 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);- }-- 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;- }- }- }- }+#include "moe_topology.hpp"+#include "openvino/core/graph_util.hpp"- 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;- }- }- }- }- }-- return nodes;-}--// ============================================================================-// Node transformation-// ============================================================================--void transform_tiles(LayerNodes& nodes, int64_t k_value) {- for (auto& tile : nodes.tiles) {- auto repeats_const =- std::dynamic_pointer_cast<ov::op::v0::Constant>(tile->input_value(1).get_node_shared_ptr());- auto repeats_data = repeats_const->cast_vector<int64_t>();- repeats_data[0] = k_value;-- auto new_repeats =- ov::op::v0::Constant::create(repeats_const->get_element_type(), repeats_const->get_shape(), repeats_data);-- tile->input(1).replace_source_output(new_repeats);- ov::copy_runtime_info(repeats_const, new_repeats);- }-}--void transform_constant_reshapes(LayerNodes& nodes, int64_t k_value) {- for (auto& reshape : nodes.constant_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>();-- // Replace dim 0 (expert dimension) with K- shape_data[0] = 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);- }-}--void transform_dynamic_reshapes(LayerNodes& nodes) {- // Replace dynamic reshapes with Unsqueeze at dimension 1- for (auto& reshape : nodes.dynamic_reshapes) {- auto data_input = reshape->input_value(0);- auto unsqueeze_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});- auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(data_input, unsqueeze_axis);- unsqueeze->set_friendly_name(reshape->get_friendly_name() + "/unsqueeze_dim1");-- ov::replace_node(reshape, unsqueeze);- ov::copy_runtime_info(reshape, unsqueeze);- }-}--void transform_matmuls(LayerNodes& nodes, const std::shared_ptr<ov::op::v1::Reshape>& topk_indices) {- for (auto& matmul : nodes.matmuls) {- auto weight_input = matmul->input_value(1);- auto weight_source = get_weight_source(weight_input);- auto weight_node = weight_source.get_node_shared_ptr();-- bool transformed = false;- // Handle Multiply case: insert Gather before Multiply on expert-dimension inputs- 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->input_value(i);- auto mul_source = get_weight_source(mul_input);- auto mul_source_node = mul_source.get_node_shared_ptr();-- if (auto const_node = std::dynamic_pointer_cast<ov::op::v0::Constant>(mul_source_node)) {- auto shape = const_node->get_shape();- if (shape.size() >= 2 && shape[0] == nodes.num_experts) {- // Insert Gather on constant source- auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});- auto gathered = std::make_shared<ov::op::v8::Gather>(mul_source, topk_indices, gather_axis);- gathered->set_friendly_name(mul_source_node->get_friendly_name() + "/gathered");-- // Recreate Convert if present- auto mul_input_node = mul_input.get_node_shared_ptr();- if (auto convert = std::dynamic_pointer_cast<ov::op::v0::Convert>(mul_input_node)) {- auto new_convert =- std::make_shared<ov::op::v0::Convert>(gathered, convert->get_destination_type());- new_convert->set_friendly_name(convert->get_friendly_name() + "/regathered");- multiply->input(i).replace_source_output(new_convert);- ov::copy_runtime_info({mul_source_node, convert}, {gathered, new_convert});- } else {- multiply->input(i).replace_source_output(gathered);- ov::copy_runtime_info(mul_source_node, gathered);- }- transformed = true;- }- }- }- } else {- // Direct weight case: insert Gather on weight input- auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});- auto gathered = std::make_shared<ov::op::v8::Gather>(weight_input, topk_indices, gather_axis);- gathered->set_friendly_name(weight_input.get_node()->get_friendly_name() + "/gathered");-- matmul->input(1).replace_source_output(gathered);- ov::copy_runtime_info(weight_input.get_node_shared_ptr(), gathered);- transformed = true;- }- OPENVINO_ASSERT(transformed, "Failed to transform MatMul weights for node: ", matmul->get_friendly_name());- }-}--void transform_adds(LayerNodes& nodes, const std::shared_ptr<ov::op::v1::Reshape>& topk_indices) {- for (auto& add : nodes.adds) {- bool transformed = false;- for (size_t input_idx = 0; input_idx < 2; ++input_idx) {- auto bias_input = add->input_value(input_idx);- auto bias_source = get_weight_source(bias_input);- auto const_node = std::dynamic_pointer_cast<ov::op::v0::Constant>(bias_source.get_node_shared_ptr());-- if (const_node) {- auto shape = const_node->get_shape();- if (nodes.num_experts > 0 && shape.size() >= 1 && shape[0] == nodes.num_experts) {- auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});- auto gathered = std::make_shared<ov::op::v8::Gather>(bias_input, topk_indices, gather_axis);- gathered->set_friendly_name(bias_input.get_node()->get_friendly_name() + "/gathered");-- add->input(input_idx).replace_source_output(gathered);- ov::copy_runtime_info(bias_input.get_node_shared_ptr(), gathered);-- transformed = true;- break;- }- }- }- OPENVINO_ASSERT(transformed, "Failed to transform Add biases for node: ", add->get_friendly_name());- }-}--void transform_multiplies(LayerNodes& nodes, const std::shared_ptr<ov::op::v1::Reshape>& topk_indices) {- for (auto& multiply : nodes.multiplies) {- bool transformed = false;- for (size_t input_idx = 0; input_idx < 2; ++input_idx) {- auto const_input = multiply->input_value(input_idx);- auto const_source = get_weight_source(const_input);- auto const_node = std::dynamic_pointer_cast<ov::op::v0::Constant>(const_source.get_node_shared_ptr());-- if (const_node) {- auto shape = const_node->get_shape();- if (nodes.num_experts > 0 && shape.size() >= 1 && shape[0] == nodes.num_experts) {- auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});- auto gathered = std::make_shared<ov::op::v8::Gather>(const_input, topk_indices, gather_axis);- gathered->set_friendly_name(const_input.get_node()->get_friendly_name() + "/gathered");-- multiply->input(input_idx).replace_source_output(gathered);- ov::copy_runtime_info(const_input.get_node_shared_ptr(), gathered);-- transformed = true;- break;- }- }- }- OPENVINO_ASSERT(transformed,- "Failed to transform Multiply constants for node: ",- multiply->get_friendly_name());- }-}--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(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();- }-}--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: No Reshape nodes found");- } else {- LOG_WARN(" Skipping layer: No MatMul/Add nodes found");- }- return false;- }-- // Create reshaped TopK indices [1, K] -> [K]- auto new_shape = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {router.k_value});- auto topk_indices = std::make_shared<ov::op::v1::Reshape>(router.topk_indices_raw, new_shape, false);- topk_indices->set_friendly_name(router.topk_node->get_friendly_name() + "/indices_reshaped");-- // Apply all transformations- transform_tiles(nodes, router.k_value);- transform_constant_reshapes(nodes, router.k_value);- transform_dynamic_reshapes(nodes);- transform_matmuls(nodes, topk_indices);- transform_adds(nodes, topk_indices);- transform_multiplies(nodes, topk_indices);- transform_transpose(nodes, router.router_scores);- transform_router_broadcast_chain(router, nodes.num_experts);-- 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()- << ", K=" << router.k_value);-- return true;-}--} // anonymous namespace--// ============================================================================-// Main transformation entry point-// ============================================================================+namespace ov::npuw::pass {bool DeviceRoutedMoETransform::run_on_model(const std::shared_ptr<ov::Model>& model) {- LOG_DEBUG("DeviceRoutedMoETransform: Starting transformation");-- bool model_changed = false;-- // Process each ScatterElementsUpdate node; validate each as a MoE router by topology+ bool changed = false;+ const ov::npuw::moe::BatchedMoEPattern pattern;for (const auto& node : model->get_ordered_ops()) {- 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)+ const auto topology = pattern.match(node);+ if (!topology)continue;-- // 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())+ // Build first, replace last: an unsupported expression must never leave+ // a partially rewritten layer or mutate a shared weight/score producer.+ auto replacement = ov::npuw::moe::build_device_routed_moe(*topology);+ if (!replacement)continue;-- // 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)) {- model_changed = true;- }+ ov::replace_node(topology->reduction, replacement);+ LOG_INFO("DeviceRoutedMoE: selected " << topology->num_selected << "/" << topology->num_experts+ << " experts for " << replacement->get_friendly_name());+ changed = true;}-- return model_changed;+ return changed;}-} // namespace pass-} // namespace npuw-} // namespace ov+} // namespace ov::npuw::passdiff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/device_routed_moe_transform.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/device_routed_moe_transform.hppindex 11a7eda9980..ee6f3ef79cd 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/device_routed_moe_transform.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/device_routed_moe_transform.hpp@@ -7,8 +7,9 @@* @brief Device-routed MoE transformation using Gather-based expert selection** This transformation implements DEVICE_ROUTED mode for MoE models, where expert- * selection is performed dynamically on the device using Gather operations driven- * by Router's TopK outputs, avoiding graph splitting and reducing host-device overhead.+ * selection is performed on the device using Gather operations driven by TopK+ * indices. The original scatter updates supply mixing scores without changing+ * their normalization, activation, or learned scales. Single-token decode only.** Key Features:* - Uses TopK indices from router to dynamically gather expert weights and biases@@ -19,7 +20,7 @@* Transformation Strategy (Two-Phase Approach):* Phase 1 - Collection:* 1. Locate Router's TopK node (selecting K active experts per token)- * 2. Extract TopK indices and Softmax scores+ * 2. Extract TopK indices and the original mixing scores (not necessarily softmax)* 3. Collect all expert nodes for the layer:* - Tile nodes (expert dimension expansion)* - Reshape nodes (constant or dynamic/unsqueeze-like)@@ -33,10 +34,11 @@* 3. Replace dynamic reshapes with Unsqueeze operations* 4. Insert Gather on expert weights/scales (for MatMul inputs)* 5. Insert Gather on expert biases (for Add inputs)- * 6. Replace routing scores with TopK Softmax outputs+ * 6. Replace scatter/broadcast with the original selected mixing scores+ * All replacements are constructed before updating the original graph.** Quantization Support:- * - Detects Multiply nodes in weight path (quantized_weight * scale)+ * - Supports conversion, dequantization arithmetic, and expert-preserving group reshapes* - Inserts Gather on both quantized weights and per-expert scales* - Preserves Convert nodes for data type handling*/@@ -54,8 +56,8 @@ namespace pass {** Pattern to match:* Router:- * Input → MatMul(router_weights) → Add(router_bias) → TopK(K=num_active_experts)- * TopK.output(0): top-K scores → Softmax → routing weights+ * Selection expression → TopK(K=num_active_experts)+ * Original score expression → routing weights (may differ from selection logits)* TopK.output(1): top-K indices → used for Gather operations** Experts (batched execution for all num_experts):@@ -67,7 +69,7 @@ namespace pass {* Transformation:* Router:* TopK.output(1) → Reshape([K]) → used as Gather indices- * TopK.output(0) → Softmax → replaces ScatterElementsUpdate routing scores+ * ScatterElementsUpdate.input(2) → preserves original selected routing scores** Experts (dynamic execution for K active experts):* - Tile(repeat=[K, 1, ...]) // reduced from num_experts to Kdiff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_topology.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_topology.cppnew file mode 100644index 00000000000..756d8bd5eaf--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_topology.cpp@@ -0,0 +1,440 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "moe_topology.hpp"++#include <algorithm>+#include <functional>+#include <unordered_map>+#include <unordered_set>++#include "moe_transformation_utils.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/op/ops.hpp"+#include "openvino/op/util/binary_elementwise_arithmetic.hpp"+#include "openvino/op/util/unary_elementwise_arithmetic.hpp"+#include "openvino/pass/pattern/matcher.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"++namespace ov::npuw::moe {+namespace {++// Preserve the original limit: at most seven score views between Transpose+// and Multiply. TopK index conversions are checked separately without a limit.+constexpr size_t max_score_views = 7;++std::optional<std::vector<int64_t>> integers(const ov::Output<ov::Node>& value) {+ const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(value.get_node_shared_ptr());+ if (!constant || !constant->get_element_type().is_integral_number())+ return std::nullopt;+ return constant->cast_vector<int64_t>();+}++bool is_axis(const ov::Output<ov::Node>& value, int64_t axis, int64_t rank) {+ const auto data = integers(value);+ return data && data->size() == 1 && (data->front() == axis || data->front() == axis - rank);+}++bool is_zero(const ov::Output<ov::Node>& value) {+ const auto node = value.get_node_shared_ptr();+ if (auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node)) {+ const auto data = constant->cast_vector<float>();+ return !data.empty() && std::all_of(data.begin(), data.end(), [](float x) {+ return x == 0.0f;+ });+ }+ if (ov::is_type<ov::op::v0::Convert>(node) || ov::is_type<ov::op::v3::Broadcast>(node) ||+ ov::is_type<ov::op::v1::Broadcast>(node))+ return is_zero(node->input_value(0));+ return false;+}++std::shared_ptr<ov::Node> only_consumer(const ov::Output<ov::Node>& value) {+ const auto users = value.get_target_inputs();+ return users.size() == 1 ? users.begin()->get_node()->shared_from_this() : nullptr;+}++bool has_expert_axis(const ov::PartialShape& shape, size_t experts) {+ return shape.rank().is_static() && shape.rank().get_length() > 0 && shape[0].is_static() &&+ shape[0].get_length() == static_cast<int64_t>(experts);+}++bool has_token_layout(const ov::PartialShape& shape, const BatchedMoE& moe) {+ if (!has_expert_axis(shape, moe.num_experts))+ return false;+ const auto tokens = moe.indices.get_partial_shape()[0];+ if (shape.rank() == ov::Rank(3))+ return shape[1].compatible(tokens);+ if (shape.rank() == ov::Rank(4))+ return (shape[1] == ov::Dimension(1) && shape[2].compatible(tokens)) ||+ (shape[2] == ov::Dimension(1) && shape[1].compatible(tokens));+ return false;+}++bool has_supported_broadcast(const std::shared_ptr<ov::Node>& node) {+ const auto arithmetic = ov::as_type_ptr<ov::op::util::BinaryElementwiseArithmetic>(node);+ if (!arithmetic)+ return true;+ // Selection below assumes right-aligned NumPy axes or equal-rank operands.+ // PDPD can put a lower-rank scale on the expert axis; leaving it ungathered+ // silently changes expert order even when K == E and shapes still validate.+ const auto mode = arithmetic->get_autob().m_type;+ return mode == ov::op::AutoBroadcastType::NUMPY || mode == ov::op::AutoBroadcastType::NONE;+}++// Gathering must commute with the dequantization/view chain. In particular,+// never treat a feature dimension that happens to equal E as an expert axis.+bool can_gather_weight(const ov::Output<ov::Node>& value, size_t experts) {+ const auto node = value.get_node_shared_ptr();+ const auto shape = value.get_partial_shape();+ if (!shape.is_static() || !has_expert_axis(shape, experts) || !has_supported_broadcast(node))+ return false;+ if (ov::is_type<ov::op::v0::Constant>(node))+ return true;+ if (ov::is_type<ov::op::v0::Convert>(node))+ return can_gather_weight(node->input_value(0), experts);+ if (ov::is_type<ov::op::v1::Reshape>(node))+ return integers(node->input_value(1)).has_value() && can_gather_weight(node->input_value(0), experts);+ if (ov::is_type<ov::op::v1::Multiply>(node) || ov::is_type<ov::op::v1::Subtract>(node) ||+ ov::is_type<ov::op::v1::Add>(node)) {+ for (const auto& input : node->input_values()) {+ if (!moe_utils::is_constant_derived(input.get_node_shared_ptr()))+ return false;+ if (input.get_partial_shape().rank() == shape.rank() &&+ has_expert_axis(input.get_partial_shape(), experts) && !can_gather_weight(input, experts))+ return false;+ }+ return true;+ }+ return false;+}++// Walk only the expert arm, stopping at Tile and constant leaves. Routing and+// the rest of the model are outside this validation boundary.+bool collect_experts(BatchedMoE& moe) {+ std::unordered_set<std::shared_ptr<ov::Node>> seen;+ size_t matmuls = 0;+ std::function<bool(const ov::Output<ov::Node>&)> visit = [&](const ov::Output<ov::Node>& value) {+ const auto node = value.get_node_shared_ptr();+ if (!seen.insert(node).second)+ return true;+ if (ov::is_type<ov::op::v0::Constant>(node))+ return true;+ if (!has_supported_broadcast(node))+ return false;+ if (moe_utils::is_constant_derived(node)) {+ for (const auto& input : node->input_values()) {+ if (!visit(input))+ return false;+ }+ moe.expert_nodes.push_back(node);+ return true;+ }+ if (auto tile = ov::as_type_ptr<ov::op::v0::Tile>(node)) {+ const auto repeats = integers(tile->input_value(1));+ const auto input_shape = tile->input_value(0).get_partial_shape();+ if (!repeats || *repeats != std::vector<int64_t>{static_cast<int64_t>(moe.num_experts), 1} ||+ input_shape.rank() != ov::Rank(2) || !input_shape[0].compatible(moe.indices.get_partial_shape()[0]) ||+ (moe.tile && moe.tile != tile))+ return false;+ moe.tile = tile;+ moe.expert_nodes.push_back(node);+ return true;+ }+ const auto shape = value.get_partial_shape();+ if (!has_token_layout(shape, moe))+ return false;+ if (auto matmul = ov::as_type_ptr<ov::op::v0::MatMul>(node)) {+ const auto weight_rank = matmul->input_value(1).get_partial_shape().rank();+ if (matmul->get_transpose_a() || !weight_rank.is_static() || weight_rank.get_length() < 3 ||+ !can_gather_weight(matmul->input_value(1), moe.num_experts))+ return false;+ ++matmuls;+ } else if (ov::is_type<ov::op::v1::Reshape>(node)) {+ // Never merge token and feature axes: host prefill dispatches tokens+ // independently. Only the initial Tile separates the expert axis;+ // later activation views may insert/move singleton dimensions.+ const auto input_shape = node->input_value(0).get_partial_shape();+ if (!input_shape.rank().is_static() || input_shape.rank().get_length() < 2 ||+ !input_shape[input_shape.rank().get_length() - 1].compatible(shape[shape.rank().get_length() - 1]) ||+ (!ov::is_type<ov::op::v0::Tile>(node->input_value(0).get_node()) &&+ !has_token_layout(input_shape, moe)))+ return false;+ } else if (ov::is_type<ov::op::v8::Slice>(node)) {+ if (node->get_input_size() != 5 ||+ !is_axis(node->input_value(4), shape.rank().get_length() - 1, shape.rank().get_length()))+ return false;+ } else if (ov::is_type<ov::op::v1::Split>(node) || ov::is_type<ov::op::v1::VariadicSplit>(node)) {+ if (!is_axis(node->input_value(1), shape.rank().get_length() - 1, shape.rank().get_length()))+ return false;+ } else if (!ov::is_type<ov::op::v0::Convert>(node) && !ov::is_type<ov::op::v4::Swish>(node) &&+ !ov::is_type<ov::op::util::UnaryElementwiseArithmetic>(node) &&+ !ov::is_type<ov::op::util::BinaryElementwiseArithmetic>(node)) {+ return false;+ }+ // Shape inputs are metadata, not part of the expert dataflow.+ const size_t count = ov::is_type<ov::op::v1::Reshape>(node) || ov::is_type<ov::op::v8::Slice>(node) ||+ ov::is_type<ov::op::v1::Split>(node) ||+ ov::is_type<ov::op::v1::VariadicSplit>(node)+ ? 1+ : node->get_input_size();+ for (size_t i = 0; i < count; ++i) {+ if (!visit(node->input_value(i)))+ return false;+ }+ moe.expert_nodes.push_back(node);+ return true;+ };+ if (!visit(moe.expert_output) || !moe.tile || matmuls < 2)+ return false;+ auto expert_input = moe.tile->output(0);+ if (auto reshape = ov::as_type_ptr<ov::op::v1::Reshape>(only_consumer(expert_input)))+ expert_input = reshape->output(0);+ for (const auto& target_input : expert_input.get_target_inputs()) {+ if (target_input.get_index() != 0 || !ov::is_type<ov::op::v0::MatMul>(target_input.get_node()))+ return false;+ }+ // Host partitioning must not steal an intermediate used by another branch.+ for (const auto& node : moe.expert_nodes) {+ for (const auto& output : node->outputs()) {+ for (const auto& input : output.get_target_inputs()) {+ if (!seen.count(input.get_node()->shared_from_this()) && input.get_node() != moe.weighted_output.get())+ return false;+ }+ }+ }+ return true;+}++} // namespace++BatchedMoEPattern::BatchedMoEPattern() {+ namespace opp = ov::pass::pattern;++ auto k = opp::any_input([](const ov::Output<ov::Node>& value) {+ const auto data = integers(value);+ return data && data->size() == 1 && data->front() > 0;+ });+ m_topk =+ opp::wrap_type_strict_index<ov::op::v11::TopK>({opp::any_input(), k}, [](const ov::Output<ov::Node>& value) {+ const auto topk = ov::as_type_ptr<ov::op::v11::TopK>(value.get_node_shared_ptr());+ const auto axis = topk->get_provided_axis();+ return topk->get_mode() == ov::op::v11::TopK::Mode::MAX && (axis == 1 || axis == -1);+ });++ // Indices may have arbitrary i32/i64 Convert chains. Match their unwrapped+ // source against m_topk in extract(); the score expression stays independent.+ auto zero = opp::any_input(is_zero);+ auto expert_axis = opp::any_input([](const ov::Output<ov::Node>& value) {+ return is_axis(value, 1, 2);+ });+ m_scatter = opp::wrap_type<ov::op::v3::ScatterElementsUpdate, ov::op::v12::ScatterElementsUpdate>(+ {zero, opp::any_input(), opp::any_input(), expert_axis},+ opp::consumers_count(1) && [](const ov::Output<ov::Node>& value) {+ const auto scatter = ov::as_type_ptr<ov::op::v12::ScatterElementsUpdate>(value.get_node_shared_ptr());+ return !scatter || scatter->get_reduction() == ov::op::v12::ScatterElementsUpdate::Reduction::NONE;+ });+ auto permutation = opp::any_input([](const ov::Output<ov::Node>& value) {+ return integers(value) == std::optional<std::vector<int64_t>>{{1, 0}};+ });+ m_score_transpose = opp::wrap_type<ov::op::v1::Transpose>({m_scatter, permutation}, opp::consumers_count(1));+ auto scores = m_score_transpose;+ for (size_t i = 0; i < max_score_views; ++i) {+ scores = opp::optional<ov::op::v1::Reshape, ov::op::v0::Unsqueeze>({scores, opp::any_input()},+ opp::consumers_count(1));+ }+ m_expert_output = opp::any_input();+ m_weighted_output = opp::wrap_type<ov::op::v1::Multiply>({m_expert_output, scores},+ opp::consumers_count(1) && has_supported_broadcast);+ m_reduction = opp::wrap_type<ov::op::v1::ReduceSum>({m_weighted_output, opp::any_input()});+}++std::optional<BatchedMoE> BatchedMoEPattern::extract(ov::pass::pattern::Matcher& matcher) const {+ const auto& matched = matcher.get_pattern_value_map();+ const auto scatter = matched.at(m_scatter).get_node_shared_ptr();+ auto indices = scatter->input_value(1);+ while (auto convert = ov::as_type_ptr<ov::op::v0::Convert>(indices.get_node_shared_ptr())) {+ if (convert->get_destination_type() != ov::element::i32 && convert->get_destination_type() != ov::element::i64)+ return std::nullopt;+ indices = convert->input_value(0);+ }+ auto selection_output = m_topk->output(1);+ ov::pass::pattern::Matcher selection(selection_output, "BatchedMoESelection");+ if (!selection.match(indices))+ return std::nullopt;+ const auto topk = ov::as_type_ptr<ov::op::v11::TopK>(indices.get_node_shared_ptr());+ const auto data_shape = scatter->input_value(0).get_partial_shape();+ const auto indices_shape = indices.get_partial_shape();+ const auto selection_shape = topk->input_value(0).get_partial_shape();+ const auto k = integers(topk->input_value(1));+ if (data_shape.rank() != ov::Rank(2) || indices_shape.rank() != ov::Rank(2) ||+ selection_shape.rank() != ov::Rank(2) || !selection_shape.compatible(data_shape) ||+ !selection_shape[1].is_static() || selection_shape[1] != data_shape[1] || !data_shape[1].is_static() || !k ||+ k->front() > data_shape[1].get_length() ||+ !scatter->input_value(2).get_partial_shape().compatible(indices_shape))+ return std::nullopt;+ BatchedMoE moe;+ moe.topk = topk;+ moe.indices = indices;+ moe.scores = scatter->input_value(2);+ moe.num_experts = static_cast<size_t>(data_shape[1].get_length());+ moe.num_selected = static_cast<size_t>(k->front());+ moe.score_transpose = ov::as_type_ptr<ov::op::v1::Transpose>(matched.at(m_score_transpose).get_node_shared_ptr());+ moe.expert_output = matched.at(m_expert_output);+ moe.weighted_output = ov::as_type_ptr<ov::op::v1::Multiply>(matched.at(m_weighted_output).get_node_shared_ptr());+ moe.broadcast_scores =+ moe.weighted_output->input_value(moe.weighted_output->input_value(0) == moe.expert_output ? 1 : 0);+ moe.reduction = ov::as_type_ptr<ov::op::v1::ReduceSum>(matched.at(m_reduction).get_node_shared_ptr());+ const auto expert_shape = moe.expert_output.get_partial_shape();+ const auto score_shape = moe.broadcast_scores.get_partial_shape();+ if (!moe.reduction || !has_expert_axis(expert_shape, moe.num_experts) ||+ !has_expert_axis(score_shape, moe.num_experts) || expert_shape.rank() != score_shape.rank() ||+ score_shape.rank().get_length() < 3 || score_shape.rank().get_length() > 4 ||+ score_shape[score_shape.rank().get_length() - 1] != ov::Dimension(1) ||+ !is_axis(moe.reduction->input_value(1), 0, expert_shape.rank().get_length()))+ return std::nullopt;+ const auto rank = score_shape.rank().get_length();+ if (rank == 4 && score_shape[1] != ov::Dimension(1) && score_shape[2] != ov::Dimension(1))+ return std::nullopt;+ const size_t token_axis = rank == 4 && score_shape[1] == ov::Dimension(1) ? 2 : 1;+ if (!score_shape[token_axis].compatible(indices_shape[0]))+ return std::nullopt;+ for (int64_t axis = 1; axis < rank - 1; ++axis) {+ if (!expert_shape[axis].compatible(score_shape[axis]))+ return std::nullopt;+ }+ if (!collect_experts(moe))+ return std::nullopt;+ return moe;+}++std::optional<BatchedMoE> BatchedMoEPattern::match(const std::shared_ptr<ov::Node>& reduction) const {+ if (!ov::is_type<ov::op::v1::ReduceSum>(reduction))+ return std::nullopt;+ ov::pass::pattern::Matcher matcher(m_reduction, "BatchedMoEBoundary");+ return matcher.match(reduction) ? extract(matcher) : std::nullopt;+}++std::optional<BatchedMoE> match_batched_moe(const std::shared_ptr<ov::Node>& scatter) {+ if (!ov::is_type<ov::op::v3::ScatterElementsUpdate>(scatter) &&+ !ov::is_type<ov::op::v12::ScatterElementsUpdate>(scatter))+ return std::nullopt;+ // Legacy router callbacks are anchored upstream of the shared pattern.+ // Locate a candidate only; all topology checks belong to BatchedMoEPattern.+ auto node = scatter;+ for (size_t hop = 0; hop < max_score_views + 3; ++hop) {+ node = only_consumer(node->output(0));+ if (!node)+ return std::nullopt;+ if (ov::is_type<ov::op::v1::ReduceSum>(node)) {+ const auto moe = BatchedMoEPattern().match(node);+ return moe && moe->score_transpose->input_value(0).get_node_shared_ptr() == scatter ? moe : std::nullopt;+ }+ }+ return std::nullopt;+}++bool can_device_route(const BatchedMoE& moe) {+ const auto index_shape = moe.indices.get_partial_shape();+ if (!index_shape.is_static() || index_shape[0] != ov::Dimension(1) ||+ !moe.broadcast_scores.get_partial_shape().is_static())+ return false;+ for (const auto& node : moe.expert_nodes) {+ for (const auto& output : node->outputs()) {+ if (!output.get_partial_shape().is_static())+ return false;+ }+ }+ return true;+}++std::shared_ptr<ov::Node> build_device_routed_moe(const BatchedMoE& moe) {+ if (!can_device_route(moe))+ return nullptr;+ auto indices = std::make_shared<ov::op::v1::Reshape>(+ moe.indices,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {moe.num_selected}),+ false);+ indices->set_friendly_name(moe.topk->get_friendly_name() + "/indices_reshaped");+ const auto axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});+ std::unordered_map<std::shared_ptr<ov::Node>, std::shared_ptr<ov::Node>> gathered;+ std::function<ov::Output<ov::Node>(const ov::Output<ov::Node>&)> select_weight =+ [&](const ov::Output<ov::Node>& value) -> ov::Output<ov::Node> {+ const auto node = value.get_node_shared_ptr();+ if (const auto it = gathered.find(node); it != gathered.end())+ return it->second->output(value.get_index());+ std::shared_ptr<ov::Node> selected;+ if (ov::is_type<ov::op::v0::Constant>(node)) {+ selected = std::make_shared<ov::op::v8::Gather>(value, indices, axis);+ } else if (ov::is_type<ov::op::v1::Reshape>(node)) {+ auto shape = value.get_shape();+ shape[0] = moe.num_selected;+ selected = std::make_shared<ov::op::v1::Reshape>(+ select_weight(node->input_value(0)),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{shape.size()}, shape),+ false);+ } else {+ auto inputs = node->input_values();+ for (auto& input : inputs) {+ if (input.get_partial_shape().rank() == value.get_partial_shape().rank() &&+ has_expert_axis(input.get_partial_shape(), moe.num_experts))+ input = select_weight(input);+ }+ selected = node->clone_with_new_inputs(inputs);+ }+ selected->set_friendly_name(node->get_friendly_name() + "/gathered");+ ov::copy_runtime_info(node, selected);+ gathered.emplace(node, selected);+ return selected->output(value.get_index());+ };+ std::unordered_map<std::shared_ptr<ov::Node>, std::shared_ptr<ov::Node>> clones;+ for (const auto& node : moe.expert_nodes) {+ if (moe_utils::is_constant_derived(node))+ continue;+ auto inputs = node->input_values();+ if (node == moe.tile) {+ inputs[1] =+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<size_t>{moe.num_selected, 1});+ } else {+ for (size_t i = 0; i < inputs.size(); ++i) {+ auto input = inputs[i];+ if (const auto it = clones.find(input.get_node_shared_ptr()); it != clones.end()) {+ inputs[i] = it->second->output(input.get_index());+ } else if ((ov::is_type<ov::op::v0::MatMul>(node) && i == 1) ||+ (input.get_partial_shape().rank() == node->get_output_partial_shape(0).rank() &&+ has_expert_axis(input.get_partial_shape(), moe.num_experts))) {+ if (!can_gather_weight(input, moe.num_experts))+ return nullptr;+ inputs[i] = select_weight(input);+ }+ }+ if (ov::is_type<ov::op::v1::Reshape>(node)) {+ auto shape = node->get_output_shape(0);+ shape[0] = moe.num_selected;+ inputs[1] = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{shape.size()}, shape);+ }+ }+ auto clone = node->clone_with_new_inputs(inputs);+ clone->set_friendly_name(node->get_friendly_name());+ ov::copy_runtime_info(node, clone);+ clones.emplace(node, clone);+ }+ auto scores = std::make_shared<ov::op::v1::Transpose>(moe.scores, moe.score_transpose->input_value(1));+ auto score_shape = moe.broadcast_scores.get_shape();+ score_shape[0] = moe.num_selected;+ auto broadcast_scores = std::make_shared<ov::op::v1::Reshape>(+ scores,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{score_shape.size()}, score_shape),+ false);+ auto expert_output = clones.at(moe.expert_output.get_node_shared_ptr())->output(moe.expert_output.get_index());+ auto weighted =+ std::make_shared<ov::op::v1::Multiply>(expert_output, broadcast_scores, moe.weighted_output->get_autob());+ auto result = moe.reduction->clone_with_new_inputs({weighted, moe.reduction->input_value(1)});+ result->set_friendly_name(moe.reduction->get_friendly_name());+ ov::copy_runtime_info(moe.reduction, result);+ return result;+}++} // namespace ov::npuw::moediff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_topology.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_topology.hppnew file mode 100644index 00000000000..5f5ee60e083--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_topology.hpp@@ -0,0 +1,76 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <optional>++#include "openvino/core/node.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/tile.hpp"+#include "openvino/op/topk.hpp"+#include "openvino/op/transpose.hpp"++namespace ov::pass::pattern {+class Matcher;+}++namespace ov::npuw::moe {++// The semantic boundary between routing and expert execution. Selection and+// mixing are deliberately separate: selection logits may include a bias that+// must NOT be applied to the mixture weights (e.g. sigmoid/bias routers).+struct BatchedMoE {+ std::shared_ptr<ov::op::v11::TopK> topk;+ ov::Output<ov::Node> indices;+ ov::Output<ov::Node> scores;+ std::shared_ptr<ov::op::v1::Transpose> score_transpose;+ ov::Output<ov::Node> broadcast_scores;+ ov::Output<ov::Node> expert_output;+ std::shared_ptr<ov::op::v1::Multiply> weighted_output;+ std::shared_ptr<ov::op::v1::ReduceSum> reduction;+ std::shared_ptr<ov::op::v0::Tile> tile;+ ov::NodeVector expert_nodes;+ size_t num_experts = 0;+ size_t num_selected = 0;+};++// Shared declarative router/mixing/reduction boundary. Callbacks validate only+// cross-node semantics and the bounded expert body between Tile and Multiply.+// The pattern owns no matched graph state, so pure queries cannot retain a model.+class BatchedMoEPattern {+public:+ BatchedMoEPattern();++ const std::shared_ptr<ov::Node>& root() const {+ return m_reduction;+ }++ std::optional<BatchedMoE> extract(ov::pass::pattern::Matcher& matcher) const;+ std::optional<BatchedMoE> match(const std::shared_ptr<ov::Node>& reduction) const;++private:+ std::shared_ptr<ov::Node> m_topk;+ std::shared_ptr<ov::Node> m_scatter;+ std::shared_ptr<ov::Node> m_score_transpose;+ std::shared_ptr<ov::Node> m_expert_output;+ std::shared_ptr<ov::Node> m_weighted_output;+ std::shared_ptr<ov::Node> m_reduction;+};++// Compatibility lookup for legacy router callbacks anchored at Scatter. Only+// locates the reduction; recognition uses the same declarative boundary above.+std::optional<BatchedMoE> match_batched_moe(const std::shared_ptr<ov::Node>& scatter);++// Pure eligibility check shared by automatic strategy selection and lowering.+// Device routing currently requires static single-token expert computation.+bool can_device_route(const BatchedMoE& moe);++// Rebuild only the selected expert branches. Original constants/dequantization+// expressions are not modified, including when other graph users share them.+// The caller replaces the reduction only after construction succeeds.+std::shared_ptr<ov::Node> build_device_routed_moe(const BatchedMoE& moe);++} // namespace ov::npuw::moediff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.cppindex 2f7abb5eccf..6cb63ff87b5 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.cpp@@ -4,6 +4,8 @@#include "moe_transformation.hpp"+#include <functional>+#include "moe_unroll_patterns.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/ops.hpp"@@ -40,10 +42,12 @@ static std::optional<size_t> resolve_compiled_idx(const std::shared_ptr<ov::Modereturn original_idx;}-// Helper function to build parameter mapping from RTInfo metadata-static std::map<size_t, std::vector<size_t>> build_parameter_mapping_from_rtinfo(+// Build the closure mapping for both unrolled experts and top-one decode.+static std::map<size_t, std::vector<size_t>> build_parameter_mapping(const std::shared_ptr<ov::Model>& original_model,- const std::shared_ptr<ov::Model>& transformed_model) {+ const std::shared_ptr<ov::Model>& transformed_model,+ const MoEStructureInfo& structure_info,+ size_t num_active_experts) {std::map<size_t, std::vector<size_t>> param_mapping;LOG_DEBUG("Building parameter mapping from RTInfo...");@@ -85,6 +89,21 @@ static std::map<size_t, std::vector<size_t>> build_parameter_mapping_from_rtinfo}}+ if (structure_info.is_expert_batch_mode()) {+ for (size_t original_idx = 0; original_idx < original_params.size(); ++original_idx) {+ if (structure_info.expert_input_param_idx == original_idx || param_mapping.count(original_idx) ||+ (num_active_experts > 1 && structure_info.expert_parameters.count(original_idx)))+ continue;+ for (size_t compiled_idx = 0; compiled_idx < transformed_params.size(); ++compiled_idx) {+ if (transformed_params[compiled_idx]->get_friendly_name() ==+ original_params[original_idx]->get_friendly_name()) {+ param_mapping[original_idx] = std::vector<size_t>(num_active_experts, compiled_idx);+ break;+ }+ }+ }+ }+LOG_INFO("Parameter mapping built: " << param_mapping.size() << " original parameters unrolled");for (const auto& entry : param_mapping) {LOG_DEBUG(" Original param[" << entry.first << "] -> " << entry.second.size() << " unrolled params");@@ -93,6 +112,59 @@ static std::map<size_t, std::vector<size_t>> build_parameter_mapping_from_rtinforeturn param_mapping;}+static std::optional<std::set<const ov::Node*>> find_expert_axis_nodes(+ const std::shared_ptr<ov::op::v1::Multiply>& output,+ const std::shared_ptr<ov::op::v0::Tile>& tile,+ size_t num_experts) {+ std::map<const ov::Node*, bool> decisions;+ std::set<const ov::Node*> expert_nodes;+ std::function<bool(const ov::Output<ov::Node>&, bool)> visit = [&](const ov::Output<ov::Node>& value,+ bool expert_axis) {+ const auto node = value.get_node_shared_ptr();+ const auto inserted = decisions.emplace(node.get(), expert_axis);+ if (!inserted.second)+ return inserted.first->second == expert_axis;+ const auto shape = value.get_partial_shape();+ if (!shape.is_static())+ return false;+ if (expert_axis) {+ if (shape.size() == 0 || shape[0] != ov::Dimension(num_experts))+ return false;+ expert_nodes.insert(node.get());+ }+ if (ov::is_type<ov::op::v0::Constant>(node) || ov::is_type<ov::op::v0::Parameter>(node))+ return true;+ if (node == tile)+ return visit(node->input_value(0), false);+ const bool reshape = ov::is_type<ov::op::v1::Reshape>(node);+ for (size_t input_idx = 0; input_idx < (reshape ? 1 : node->get_input_size()); ++input_idx) {+ const auto input = node->input_value(input_idx);+ const auto input_shape = input.get_partial_shape();+ bool input_expert_axis = false;+ if (expert_axis) {+ if (!input_shape.is_static())+ return false;+ if (reshape && input.get_node_shared_ptr() == tile) {+ input_expert_axis = false;+ } else if (reshape) {+ if (input_shape.size() == 0 || input_shape[0] != ov::Dimension(num_experts))+ return false;+ input_expert_axis = true;+ } else {+ input_expert_axis = input_shape.rank() == shape.rank() && input_shape.size() != 0 &&+ input_shape[0] == ov::Dimension(num_experts);+ }+ }+ if (!visit(input, input_expert_axis))+ return false;+ }+ return true;+ };+ if (!visit(output->output(0), true))+ return std::nullopt;+ return expert_nodes;+}+// Helper: Trace back from a node to find the source Parameterstatic std::optional<size_t> trace_to_parameter(const std::shared_ptr<ov::Node>& start_node,const std::shared_ptr<ov::Model>& model) {@@ -139,7 +211,9 @@ static bool find_tile_and_extract_config(const std::shared_ptr<ov::Model>& modelcontinue;auto repeats_data = repeats_const->cast_vector<int64_t>();- if (repeats_data.empty() || repeats_data[0] <= 1)+ const auto input_shape = tile->input_value(0).get_partial_shape();+ if (repeats_data.size() != 2 || repeats_data[0] <= 1 || repeats_data[1] != 1 || !input_shape.is_static() ||+ input_shape.rank() != ov::Rank(2))continue;// Found valid Tile node@@ -242,6 +316,25 @@ std::optional<MoEStructureInfo> analyze_moe_structure(const std::shared_ptr<ov::return std::nullopt;}+ const auto router_shape = model->get_parameters().at(info.router_scores_idx.value())->get_partial_shape();+ if (!router_shape.is_static())+ return std::nullopt;+ const auto scores = router_shape.to_shape();+ const bool supported_scores = scores == ov::Shape{info.num_experts, info.input_token_count, 1} ||+ scores == ov::Shape{info.num_experts, 1, info.input_token_count, 1} ||+ scores == ov::Shape{info.num_experts, info.input_token_count, 1, 1};+ if (!supported_scores)+ return std::nullopt;+ const auto expert_nodes =+ find_expert_axis_nodes(info.router_scores_multiply_node, info.expert_input_tile_node, info.num_experts);+ if (!expert_nodes)+ return std::nullopt;+ const auto& parameters = model->get_parameters();+ for (size_t param_idx = 0; param_idx < parameters.size(); ++param_idx) {+ if (expert_nodes->count(parameters[param_idx].get()))+ info.expert_parameters.insert(param_idx);+ }+// Step 3: Infer processing mode based on input_token_count// EXPERT_BATCH: token_count == 1 (single token, K experts in parallel)// EXPERT_ITERATIVE: token_count > 1 (multiple tokens, iterate through experts)@@ -610,7 +703,8 @@ void MoEModelTransformer::ensure_tensor_names(const std::shared_ptr<ov::Model>&void MoEModelTransformer::fix_parameters_with_num_experts(const std::shared_ptr<ov::Model>& model,size_t num_experts,- size_t num_target_experts) const {+ size_t num_target_experts,+ const std::set<const ov::Node*>& expert_axis_nodes) const {LOG_DEBUG("Fixing Parameter nodes with num_experts in shape to " << num_target_experts << " experts...");const auto& all_params = model->get_parameters();@@ -630,15 +724,10 @@ void MoEModelTransformer::fix_parameters_with_num_experts(const std::shared_ptr<bool needs_fix = false;size_t fix_dim = 0;- for (size_t i = 0; i < shape.size(); ++i) {- if (shape[i] == num_experts) {- needs_fix = true;- fix_dim = i;- break;- }- }+ needs_fix = expert_axis_nodes.count(param.get()) != 0;if (needs_fix) {+ OPENVINO_ASSERT(!shape.empty() && shape[0] == num_experts, "MoE: inconsistent expert-axis parameter");LOG_DEBUG(" Found Parameter '" << param->get_friendly_name() << "' with shape[" << fix_dim<< "]=" << num_experts);@@ -656,7 +745,7 @@ void MoEModelTransformer::fix_parameters_with_num_experts(const std::shared_ptr<LOG_DEBUG("Fixing Reshape nodes with num_experts in shape...");for (const auto& node : model->get_ordered_ops()) {auto reshape_node = std::dynamic_pointer_cast<ov::op::v1::Reshape>(node);- if (!reshape_node) {+ if (!reshape_node || !expert_axis_nodes.count(node.get())) {continue;}@@ -672,7 +761,7 @@ void MoEModelTransformer::fix_token_count_for_expert_iterative(size_t chunk_size,const std::shared_ptr<ov::op::v0::Tile>& expert_input_tile_op,const std::shared_ptr<ov::op::v1::Multiply>& router_scores_multiply_op) const {- if (num_target_experts != 1) {+ if (!m_structure_info.is_expert_iterative_mode()) {return; // Only apply to EXPERT_ITERATIVE mode (single expert)}@@ -684,41 +773,15 @@ void MoEModelTransformer::fix_token_count_for_expert_iterative(return;}- // Trace back from Tile input to find Parameters+ // The structure analysis already identified the two token-bearing inputs.+ // Traversing all inputs of the final Multiply mistakes expert weights for+ // token inputs when its expert arm is Convert(Reshape(...)) instead of a+ // direct Reshape. Cloning preserves the original parameter order here.std::set<std::shared_ptr<ov::op::v0::Parameter>> params_to_fix;- std::function<void(const ov::Output<ov::Node>&)> trace_to_params;- trace_to_params = [&](const ov::Output<ov::Node>& output) {- auto node = output.get_node_shared_ptr();-- if (auto param = std::dynamic_pointer_cast<ov::op::v0::Parameter>(node)) {- params_to_fix.insert(param);- return;- }-- // Skip Convert nodes during tracing- if (auto convert = std::dynamic_pointer_cast<ov::op::v0::Convert>(node)) {- LOG_DEBUG(" Skipping Convert node during trace: " << convert->get_friendly_name());- }-- // Recursively trace inputs- for (size_t i = 0; i < node->get_input_size(); ++i) {- trace_to_params(node->input_value(i));- }- };-- trace_to_params(expert_input_tile_op->input_value(0));-- // Also find router parameter from the Multiply node- LOG_DEBUG("Tracing router parameter from Multiply node");- for (size_t i = 0; i < 2; ++i) {- auto multiply_input = router_scores_multiply_op->input_value(i).get_node_shared_ptr();-- // Skip Reshape input (that's the expert output)- if (std::dynamic_pointer_cast<ov::op::v1::Reshape>(multiply_input)) {- continue;- }-- trace_to_params(router_scores_multiply_op->input_value(i));+ for (const auto index : {m_structure_info.expert_input_param_idx, m_structure_info.router_scores_idx}) {+ OPENVINO_ASSERT(index.has_value() && index.value() < model->get_parameters().size(),+ "MoE: token-bearing parameter was not identified");+ params_to_fix.insert(model->get_parameters().at(index.value()));}// Fix Parameter shapes@@ -728,14 +791,18 @@ void MoEModelTransformer::fix_token_count_for_expert_iterative(if (param_shape.rank().is_static() && param_shape.rank().get_length() >= 2) {auto shape = param_shape.to_shape();- // Find dimension with original token count- for (size_t i = 0; i < shape.size(); ++i) {- if (shape[i] == original_token_count) {- LOG_DEBUG(" Updating Parameter '" << param->get_friendly_name() << "' shape[" << i << "] from "- << original_token_count << " to " << chunk_size);- shape[i] = chunk_size;- }- }+ // Activation input: [tokens, hidden]. Router input: [E,tokens,1]+ // or [E,1,tokens,1]/[E,tokens,1,1]. Never change the hidden/expert+ // dimension just because its numerical size equals the token count.+ size_t token_axis = 0;+ if (shape.size() == 3)+ token_axis = 1;+ else if (shape.size() == 4)+ token_axis = shape[1] == 1 ? 2 : 1;+ OPENVINO_ASSERT(shape[token_axis] == original_token_count,+ "MoE: unexpected token axis for ",+ param->get_friendly_name());+ shape[token_axis] = chunk_size;param->set_partial_shape(ov::PartialShape(shape));param->validate_and_infer_types();@@ -746,9 +813,15 @@ void MoEModelTransformer::fix_token_count_for_expert_iterative(// Scan dims 1..n-2 (skip dim 0 = num_experts and last dim = hidden_dim) and replace any// dimension whose value equals original_token_count with chunk_size.LOG_DEBUG("Fixing Reshape nodes with token_count in shape...");+ std::set<const ov::Node*> token_dependent{expert_input_tile_op.get()};for (const auto& node : model->get_ordered_ops()) {+ const auto inputs = node->input_values();+ if (std::any_of(inputs.begin(), inputs.end(), [&](const auto& input) {+ return token_dependent.count(input.get_node()) != 0;+ }))+ token_dependent.insert(node.get());auto reshape_node = std::dynamic_pointer_cast<ov::op::v1::Reshape>(node);- if (!reshape_node) {+ if (!reshape_node || !token_dependent.count(node.get())) {continue;}// Scan middle dims (1..n-2), skip dim 0 (num_experts) and last dim (hidden_dim).@@ -825,6 +898,10 @@ std::shared_ptr<ov::Model> MoEModelTransformer::apply_expert_transformation(return nullptr;}+ const auto expert_axis_nodes = find_expert_axis_nodes(router_scores_multiply_op, expert_input_tile_op, num_experts);+ if (!expert_axis_nodes)+ return nullptr;+// Main transformation flowauto tile_input = expert_input_tile_op->input_value(0);auto tile_output = expert_input_tile_op->output(0);@@ -845,7 +922,7 @@ std::shared_ptr<ov::Model> MoEModelTransformer::apply_expert_transformation(node_before_matmul,expert_input_tile_op->get_friendly_name(),num_target_experts);- fix_parameters_with_num_experts(model, num_experts, num_target_experts);+ fix_parameters_with_num_experts(model, num_experts, num_target_experts, *expert_axis_nodes);ensure_tensor_names(model);model->validate_nodes_and_infer_types();@@ -938,19 +1015,15 @@ std::optional<MoEExperts> MoEExperts::from(const std::shared_ptr<ov::Model>& mod// Step 5: Build parameter mapping from any transformed model (all have same mapping)// Note: For EXPERT_ITERATIVE mode (single expert), no unrolling happens, so mapping will be empty// For EXPERT_BATCH mode (K experts), unrolling creates the same mapping structure- auto param_mapping = build_parameter_mapping_from_rtinfo(model, transformed_models.begin()->second);+ auto param_mapping = build_parameter_mapping(model, first_transformed_model, *structure_info, k_value);- // Step 6: EXPERT_BATCH guard — every param with shape[0]==num_experts must appear in+ // Step 6: EXPERT_BATCH guard — every expert-specific parameter must appear in// param_mapping with exactly K entries; a missing entry means UnrollMoEMatMul did not// recognise the weight chain and inference would produce silently wrong results.if (structure_info->is_expert_batch_mode()) {const auto& orig_params = model->get_parameters();- for (size_t pi = 0; pi < orig_params.size(); ++pi) {+ for (const size_t pi : structure_info->expert_parameters) {const auto& pshape = orig_params[pi]->get_partial_shape();- if (!pshape.rank().is_static() || !pshape[0].is_static())- continue;- if (static_cast<size_t>(pshape[0].get_length()) != structure_info->num_experts)- continue;// This parameter is batched over the expert dimension and must be unrolled.auto it = param_mapping.find(pi);if (it == param_mapping.end()) {@@ -960,7 +1033,7 @@ std::optional<MoEExperts> MoEExperts::from(const std::shared_ptr<ov::Model>& modpi,", shape=",pshape,- ") has shape[0]==num_experts but was not unrolled. "+ ") has an expert axis but was not unrolled. ""UnrollMoEMatMul did not recognise its weight chain. ""Inspect the weight graph topology and add the missing chain variant.");}diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.hppindex 3b981146ec2..0a18efc7784 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.hpp@@ -6,6 +6,7 @@#include <map>#include <optional>+#include <set>#include <vector>#include "../logging.hpp"@@ -53,6 +54,7 @@ struct MoEStructureInfo {// Parameter indices (detected once during analysis)std::optional<size_t> expert_input_param_idx; // Parameter index for expert's input (token embeddings)std::optional<size_t> router_scores_idx; // Parameter index for router scores (from Multiply in output path)+ std::set<size_t> expert_parameters;// Processing mode (inferred from input_token_count)moe::MoEProcessingMode processing_mode = moe::MoEProcessingMode::EXPERT_ITERATIVE;@@ -150,7 +152,8 @@ private:void fix_parameters_with_num_experts(const std::shared_ptr<ov::Model>& model,size_t num_experts,- size_t num_target_experts) const;+ size_t num_target_experts,+ const std::set<const ov::Node*>& expert_axis_nodes) const;void fix_token_count_for_expert_iterative(const std::shared_ptr<ov::Model>& model,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.hppindex d00b51b98eb..f9dba043820 100644--- 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@@ -6,9 +6,12 @@#include <memory>+#include "openvino/op/add.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"#include "openvino/op/multiply.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/subtract.hpp"namespace ov {namespace npuw {@@ -16,7 +19,8 @@ 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).+// Recognizes decompression arithmetic and group-quantized weight views without+// folding or materializing the (potentially very large) floating-point weights.inline bool is_constant_derived(const std::shared_ptr<ov::Node>& n) {if (!n)return false;@@ -25,9 +29,10 @@ inline bool is_constant_derived(const std::shared_ptr<ov::Node>& n) {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());+ if (ov::is_type<ov::op::v1::Multiply>(n) || ov::is_type<ov::op::v1::Subtract>(n) ||+ ov::is_type<ov::op::v1::Add>(n) || ov::is_type<ov::op::v1::Reshape>(n)) {+ return is_constant_derived(n->input_value(0).get_node_shared_ptr()) &&+ is_constant_derived(n->input_value(1).get_node_shared_ptr());}return false;}diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.cppindex 3bece991c8d..0906e82a2ce 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.cpp@@ -5,7 +5,9 @@#include "moe_unroll_patterns.hpp"#include <cstddef>+#include <map>#include <memory>+#include <unordered_map>#include <vector>#include "../logging.hpp"@@ -13,6 +15,7 @@#include "openvino/core/rt_info.hpp"#include "openvino/op/parameter.hpp"#include "openvino/op/swish.hpp"+#include "openvino/op/util/binary_elementwise_arithmetic.hpp"#include "openvino/opsets/opset1.hpp"#include "openvino/pass/pattern/matcher.hpp"#include "openvino/pass/pattern/op/label.hpp"@@ -40,21 +43,6 @@ inline ov::Output<ov::Node> skip_convert(ov::Output<ov::Node> out) {return out;}-/**- * @brief Calculate total number of elements in a shape- */-inline size_t calc_total_size(const ov::PartialShape& shape) {- if (!shape.rank().is_static())- return 0;- size_t total = 1;- for (int64_t i = 0; i < shape.rank().get_length(); ++i) {- if (shape[i].is_static()) {- total *= shape[i].get_length();- }- }- return total;-}-/*** @brief Extract Parameter node from output, skipping intermediate Convert if present*/@@ -63,92 +51,116 @@ inline std::shared_ptr<ov::op::v0::Parameter> get_param_node(ov::Output<ov::Nodereturn std::dynamic_pointer_cast<ov::op::v0::Parameter>(skipped.get_node_shared_ptr());}-/**- * @brief Context for creating expert branch with scale and weights parameters- */-struct ExpertBranchContext {- size_t expert_idx;- std::shared_ptr<ov::op::v0::Parameter> scale_param;- std::shared_ptr<ov::op::v0::Parameter> weights_param;- ov::Output<ov::Node> scale_param_source;- ov::Output<ov::Node> weights_param_source;- std::shared_ptr<ov::opset1::Multiply> multiply_node;- std::shared_ptr<ov::opset1::Convert> convert_after_multiply;- std::shared_ptr<ov::opset1::MatMul> matmul;- ov::Shape scale_new_shape;- ov::Shape weights_new_shape;+struct WeightBranchCopies {+ bool sliced;+ ov::OutputVector values;};-/**- * @brief Create expert branch: parameters → convert → multiply → convert → weights output- *- * This helper function encapsulates the common logic for creating per-expert parameters- * and weight computation chain used in UnrollMoEMatMul for all input patterns.- *- * @param ctx Context containing all necessary information for creating the branch- * @param new_params Output vector to collect newly created parameters- * @return Processed weights ready for MatMul operation- */-inline ov::Output<ov::Node> create_expert_branch_weights(const ExpertBranchContext& ctx,- ov::ParameterVector& new_params) {- // 1. Create new scale parameter- auto new_scale_param = std::make_shared<ov::op::v0::Parameter>(ctx.scale_param->get_element_type(),- ov::PartialShape(ctx.scale_new_shape));- new_scale_param->set_friendly_name(ctx.scale_param->get_friendly_name() + "/expert_" +- std::to_string(ctx.expert_idx));- new_scale_param->get_rt_info()["moe_original_param"] = ctx.scale_param->get_friendly_name();- new_scale_param->get_rt_info()["moe_expert_index"] = static_cast<int64_t>(ctx.expert_idx);- new_params.push_back(new_scale_param);-- // 2. Create new weights parameter- auto new_weights_param = std::make_shared<ov::op::v0::Parameter>(ctx.weights_param->get_element_type(),- ov::PartialShape(ctx.weights_new_shape));- new_weights_param->set_friendly_name(ctx.weights_param->get_friendly_name() + "/expert_" +- std::to_string(ctx.expert_idx));- new_weights_param->get_rt_info()["moe_original_param"] = ctx.weights_param->get_friendly_name();- new_weights_param->get_rt_info()["moe_expert_index"] = static_cast<int64_t>(ctx.expert_idx);- new_params.push_back(new_weights_param);-- // 3. Apply Convert to weights if needed- ov::Output<ov::Node> weights_for_multiply;- if (auto weights_convert =- std::dynamic_pointer_cast<ov::opset1::Convert>(ctx.weights_param_source.get_node_shared_ptr())) {- auto new_weights_convert =- std::make_shared<ov::opset1::Convert>(new_weights_param, weights_convert->get_destination_type());- new_weights_convert->set_friendly_name(weights_convert->get_friendly_name() + "/expert_" +- std::to_string(ctx.expert_idx));- weights_for_multiply = new_weights_convert->output(0);- } else {- weights_for_multiply = new_weights_param->output(0);- }-- // 4. Apply Convert to scale if needed- ov::Output<ov::Node> scale_for_multiply;- if (auto scale_convert =- std::dynamic_pointer_cast<ov::opset1::Convert>(ctx.scale_param_source.get_node_shared_ptr())) {- auto new_scale_convert =- std::make_shared<ov::opset1::Convert>(new_scale_param, scale_convert->get_destination_type());- new_scale_convert->set_friendly_name(scale_convert->get_friendly_name() + "/expert_" +- std::to_string(ctx.expert_idx));- scale_for_multiply = new_scale_convert->output(0);- } else {- scale_for_multiply = new_scale_param->output(0);+// Weak keys preserve node identity without retaining the replaced weight DAG:+// keeping its old consumers alive would prevent RemoveUnusedParameters cleanup.+using WeightBranchCache =+ std::map<std::weak_ptr<ov::Node>, WeightBranchCopies, std::owner_less<std::weak_ptr<ov::Node>>>;+using WeightSelection = std::unordered_map<std::shared_ptr<ov::Node>, bool>;++// Validate the entire closure expression before changing the model. Selection+// commutes with these dequantization operations only when the leading expert+// axis survives views and NumPy/NONE broadcasting. Lower-rank operands are shared.+bool plan_weight_branches(const ov::Output<ov::Node>& value,+ size_t num_experts,+ bool sliced,+ const WeightBranchCache& cache,+ WeightSelection& selection,+ ov::NodeVector& order) {+ const auto node = value.get_node_shared_ptr();+ const auto shape = value.get_partial_shape();+ if (value.get_index() != 0 || !shape.is_static() ||+ (sliced && (shape.size() == 0 || shape[0].get_length() != static_cast<int64_t>(num_experts))))+ return false;+ if (const auto it = cache.find(node); it != cache.end())+ return it->second.sliced == sliced && it->second.values.size() == num_experts;+ const auto inserted = selection.emplace(node, sliced);+ if (!inserted.second)+ return inserted.first->second == sliced;++ if (ov::is_type<ov::op::v0::Constant>(node)) {+ // Expert-specific data must arrive as a closure Parameter so the+ // executor can bind the selected expert, not a fixed compile-time slice.+ if (sliced)+ return false;+ } else if (!ov::is_type<ov::op::v0::Parameter>(node)) {+ const bool reshape = ov::is_type<ov::op::v1::Reshape>(node);+ const bool arithmetic = ov::is_type<ov::op::v1::Add>(node) || ov::is_type<ov::op::v1::Subtract>(node) ||+ ov::is_type<ov::op::v1::Multiply>(node);+ if (!reshape && !arithmetic && !ov::is_type<ov::op::v0::Convert>(node))+ return false;+ if (reshape && !ov::is_type<ov::op::v0::Constant>(node->input_value(1).get_node()))+ return false;+ if (arithmetic) {+ const auto mode = ov::as_type_ptr<ov::op::util::BinaryElementwiseArithmetic>(node)->get_autob().m_type;+ if (mode != ov::op::AutoBroadcastType::NUMPY && mode != ov::op::AutoBroadcastType::NONE)+ return false;+ }+ for (size_t i = 0; i < (reshape ? 1 : node->get_input_size()); ++i) {+ const auto input = node->input_value(i);+ const auto input_shape = input.get_partial_shape();+ const bool slice_input =+ sliced && (!arithmetic || (input_shape.rank() == shape.rank() && input_shape[0] == shape[0]));+ if (!plan_weight_branches(input, num_experts, slice_input, cache, selection, order))+ return false;+ }}+ order.push_back(node);+ return true;+}- // 5. Multiply: scale * weights- auto new_multiply = std::make_shared<ov::opset1::Multiply>(scale_for_multiply, weights_for_multiply);- new_multiply->set_friendly_name(ctx.multiply_node->get_friendly_name() + "/expert_" +- std::to_string(ctx.expert_idx));-- // 6. Convert after Multiply if needed- if (ctx.convert_after_multiply) {- auto new_convert_after_multiply =- std::make_shared<ov::opset1::Convert>(new_multiply, ctx.convert_after_multiply->get_destination_type());- new_convert_after_multiply->set_friendly_name(ctx.convert_after_multiply->get_friendly_name() + "/expert_" +- std::to_string(ctx.expert_idx));- return new_convert_after_multiply->output(0);+void build_weight_branches(const ov::NodeVector& order,+ const WeightSelection& selection,+ size_t num_experts,+ WeightBranchCache& cache,+ ov::ParameterVector& parameters) {+ for (const auto& node : order) {+ const bool sliced = selection.at(node);+ ov::OutputVector copies;+ for (size_t slot = 0; slot < num_experts; ++slot) {+ if (ov::is_type<ov::op::v0::Constant>(node)) {+ copies.push_back(node);+ continue;+ }+ std::shared_ptr<ov::Node> copy;+ if (ov::is_type<ov::op::v0::Parameter>(node)) {+ auto shape = node->get_output_shape(0);+ if (sliced)+ shape[0] = 1;+ auto parameter = std::make_shared<ov::op::v0::Parameter>(node->get_output_element_type(0), shape);+ ov::copy_runtime_info(node, parameter);+ parameter->get_rt_info()["moe_original_param"] = node->get_friendly_name();+ parameter->get_rt_info()["moe_expert_index"] = static_cast<int64_t>(slot);+ parameters.push_back(parameter);+ copy = parameter;+ } else {+ auto inputs = node->input_values();+ const bool reshape = ov::is_type<ov::op::v1::Reshape>(node);+ for (size_t i = 0; i < (reshape ? 1 : inputs.size()); ++i)+ inputs[i] = cache.at(inputs[i].get_node_shared_ptr()).values.at(slot);+ if (reshape && sliced) {+ auto shape = node->get_output_shape(0);+ shape[0] = 1;+ copy = std::make_shared<ov::op::v1::Reshape>(+ inputs[0],+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{shape.size()}, shape),+ false);+ } else {+ // Preserve Subtract operand order, conversion precision and+ // broadcast attributes rather than reconstructing a formula.+ copy = node->clone_with_new_inputs(inputs);+ }+ ov::copy_runtime_info(node, copy);+ }+ copy->set_friendly_name(node->get_friendly_name() + "/expert_" + std::to_string(slot));+ copies.push_back(copy);+ }+ cache.emplace(node, WeightBranchCopies{sliced, std::move(copies)});}- return new_multiply->output(0);}/**@@ -243,7 +255,8 @@ inline ov::OutputVector prepare_input_branches(ov::Output<ov::Node> matmul_input// Pattern 1 (Batched): input_param → convert → tile → reshape → MatMul// Pattern 2 (Concat): Concat([a,b,c,d]) → MatMul// Pattern 3 (Sliceable): AnyInput[N,...] → (auto-sliced) → MatMul-// All patterns share: scale_param + weights_param → multiply → convert → MatMul (input1)+// The weight input is a closure expression containing Convert, Add, Subtract,+// Multiply and constant-shape Reshape, or a plain weight Parameter.//// Transforms to N expert branches with individual parameters and Concat output@@ -252,7 +265,10 @@ UnrollMoEMatMul::UnrollMoEMatMul(std::shared_ptr<ov::Model> model) : model_(modeauto matmul_pattern = ov::pass::pattern::wrap_type<ov::opset1::MatMul>();- auto callback = [this](ov::pass::pattern::Matcher& m) {+ // Reuse each closure's K bindings across all MatMuls, including tied gate/up+ // projections and metadata reused at multiple points in a weight expression.+ auto weight_cache = std::make_shared<WeightBranchCache>();+ auto callback = [this, weight_cache](ov::pass::pattern::Matcher& m) {auto matmul = std::dynamic_pointer_cast<ov::opset1::MatMul>(m.get_match_root());if (!matmul)return false;@@ -263,74 +279,14 @@ UnrollMoEMatMul::UnrollMoEMatMul(std::shared_ptr<ov::Model> model) : model_(modeauto matmul_input1 = matmul->input_value(1);// ========== Step 1: Check input1 (weights path - common to all patterns) ==========- auto input1_node = matmul_input1.get_node_shared_ptr();- std::shared_ptr<ov::opset1::Convert> convert_after_multiply;- std::shared_ptr<ov::opset1::Multiply> multiply_node;-- if (auto conv = std::dynamic_pointer_cast<ov::opset1::Convert>(input1_node)) {- convert_after_multiply = conv;- multiply_node = std::dynamic_pointer_cast<ov::opset1::Multiply>(conv->input_value(0).get_node_shared_ptr());- } else {- multiply_node = std::dynamic_pointer_cast<ov::opset1::Multiply>(input1_node);- }-- if (!multiply_node) {- LOG_DEBUG(" Input1 is not Multiply, skipping");+ const auto weight_shape = matmul_input1.get_partial_shape();+ if (!weight_shape.is_static() || weight_shape.size() < 3 || weight_shape[0].get_length() <= 1)return false;- }-- auto multiply_input0 = multiply_node->input_value(0);- auto multiply_input1 = multiply_node->input_value(1);-- auto mult_in0_skip_convert = skip_convert(multiply_input0);- auto mult_in1_skip_convert = skip_convert(multiply_input1);-- size_t size0 = calc_total_size(mult_in0_skip_convert.get_partial_shape());- size_t size1 = calc_total_size(mult_in1_skip_convert.get_partial_shape());-- // Determine scale vs weights by total size (larger = weights)- ov::Output<ov::Node> scale_param_source, weights_param_source;- if (size0 > size1) {- weights_param_source = multiply_input0;- scale_param_source = multiply_input1;- } else {- weights_param_source = multiply_input1;- scale_param_source = multiply_input0;- }-- auto scale_param = get_param_node(scale_param_source);- auto weights_param = get_param_node(weights_param_source);-- if (!scale_param || !weights_param) {- LOG_DEBUG(" Could not find scale or weights parameter nodes");+ const auto num_experts = static_cast<size_t>(weight_shape[0].get_length());+ WeightSelection selection;+ ov::NodeVector weight_order;+ if (!plan_weight_branches(matmul_input1, num_experts, true, *weight_cache, selection, weight_order))return false;- }-- // Get parameter shapes to determine num_experts- auto scale_orig_shape = scale_param->get_partial_shape();- auto weights_orig_shape = weights_param->get_partial_shape();-- if (!scale_orig_shape.rank().is_static() || !weights_orig_shape.rank().is_static()) {- LOG_DEBUG(" Parameter shapes are not static, skipping");- return false;- }-- if (!scale_orig_shape[0].is_static() || !weights_orig_shape[0].is_static()) {- LOG_DEBUG(" First dimension is not static, skipping");- return false;- }-- size_t scale_num_experts = scale_orig_shape[0].get_length();- size_t weights_num_experts = weights_orig_shape[0].get_length();-- if (scale_num_experts != weights_num_experts) {- LOG_DEBUG(" Number of experts mismatch: scale=" << scale_num_experts- << ", weights=" << weights_num_experts);- return false;- }-- // Auto-detect num_experts from parameter shapes- size_t num_experts = scale_num_experts;LOG_INFO(" Found MoE MatMul pattern with " << num_experts << " experts (auto-detected)");@@ -348,42 +304,19 @@ UnrollMoEMatMul::UnrollMoEMatMul(std::shared_ptr<ov::Model> model) : model_(modereturn false;}- // ========== Step 3: Create per-expert parameters ==========- auto scale_shape_vec = scale_orig_shape.to_shape();- auto weights_shape_vec = weights_orig_shape.to_shape();-- ov::Shape scale_new_shape = scale_shape_vec;- ov::Shape weights_new_shape = weights_shape_vec;- scale_new_shape[0] = 1;- weights_new_shape[0] = 1;-- LOG_INFO(" Scale: " << scale_shape_vec << " → " << scale_new_shape);- LOG_INFO(" Weights: " << weights_shape_vec << " → " << weights_new_shape);-+ // ========== Step 3: Rebuild the complete weight expression per slot ==========ov::NodeVector expert_outputs;ov::ParameterVector new_params;+ build_weight_branches(weight_order, selection, num_experts, *weight_cache, new_params);+ const auto& weights = weight_cache->at(matmul_input1.get_node_shared_ptr()).values;// ========== Step 4: Create expert branches ==========for (size_t expert_idx = 0; expert_idx < num_experts; ++expert_idx) {auto input0_branch = input0_branches[expert_idx];- // Create expert branch weights using helper function- ExpertBranchContext ctx{expert_idx,- scale_param,- weights_param,- scale_param_source,- weights_param_source,- multiply_node,- convert_after_multiply,- matmul,- scale_new_shape,- weights_new_shape};-- auto weights_for_matmul = create_expert_branch_weights(ctx, new_params);-// MatMul: input0_branch × weightsauto new_matmul = std::make_shared<ov::opset1::MatMul>(input0_branch,- weights_for_matmul,+ weights[expert_idx],matmul->get_transpose_a(),matmul->get_transpose_b());new_matmul->set_friendly_name(matmul->get_friendly_name() + "/expert_" + std::to_string(expert_idx));diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.hppindex efa92181faf..807d5d00df5 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.hpp@@ -39,7 +39,10 @@ namespace pass {* Pattern 3 (Sliceable): AnyInput[N,...] ───────────────────────┐ (auto-sliced)* scale + weights → multiply ─────────────┤ MatMul*- * Number of experts is automatically detected from scale/weights parameter shapes.+ * Weight inputs may be plain Parameters or closure expressions built from Convert,+ * Add, Subtract, Multiply and constant-shape Reshape. Expert-major operands are+ * sliced before dequantization; shared operands retain their broadcast layout.+ * Number of experts is automatically detected from the weight expression shape.* Transforms to: N expert branches with individual parameters, concatenated output** @param model Model to register new parameters withdiff --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 cdd4a1640f7..d8f7135c234 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@@ -767,6 +767,7 @@ void Snapshot::earlyRegroup() {HNDL_MOE(Qwen3Router);HNDL_MOE(Gemma4Expert);HNDL_MOE(Gemma4Router);+ HNDL_MOE(BatchedExpert);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 14e744f3874..4589359e947 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@@ -108,9 +108,8 @@ static const std::map<std::string, std::string> ISOL_PRESETS = {"P:SDPA/attn,P:SDPADecomposed/attn,""P:QuantizedSDPAWithGlobalMask/attn,P:GQA/attn,P:SDPACompressed/attn"},{"MOE",- "P:GPTOSSExpert/expert,P:GPTOSSRouter/router,"- "P:Qwen3Expert/expert,P:Qwen3Router/router,"- "P:Gemma4Expert/expert,P:Gemma4Router/router"}};+ "P:BatchedExpert/expert,P:GPTOSSExpert/expert,P:GPTOSSRouter/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 14aa7ecbbe5..01ce811f385 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@@ -9,6 +9,7 @@#include <utility>#include "../../logging.hpp"+#include "../../moe_transformations/moe_topology.hpp"#include "openvino/op/ops.hpp"#include "openvino/pass/pattern/op/optional.hpp"#include "openvino/pass/pattern/op/or.hpp"@@ -130,6 +131,16 @@ std::function<bool(ov::pass::pattern::Matcher&)> make_router_k_callback(if (guard && !guard(matched_topk)) {return false;}+ // Legacy patterns locate TopK through the score expression. A generic+ // router may compute those scores with a different TopK than the one+ // selecting expert IDs. Prefer the explicit selection contract whenever+ // available, independent of matcher registration/traversal order.+ for (const auto& entry : node_to_output) {+ if (const auto topology = ov::npuw::moe::match_batched_moe(entry.second.get_node_shared_ptr())) {+ matched_topk = topology->topk;+ break;+ }+ }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");@@ -274,6 +285,31 @@ std::pair<std::shared_ptr<opp::Matcher>, std::function<bool(opp::Matcher&)>> mak} // namespace+BatchedExpert::BatchedExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag) {+ auto pattern = std::make_shared<ov::npuw::moe::BatchedMoEPattern>();+ auto expected_k = std::make_shared<std::optional<size_t>>();+ const auto node_to_gptr = snapshot->getNodeToGroupMap();+ auto callback = [=](opp::Matcher& matcher) {+ const auto topology = pattern->extract(matcher);+ if (!topology || !tag_topk_k(topology->topk, *expected_k))+ return false;+ // Keep the semantic contract with the expert boundary itself. The+ // router need not be folded into a function, so searching only folded+ // router nodes can otherwise lose K and silently leave experts dense.+ topology->weighted_output->get_rt_info()[RT_INFO_MOE_K] = topology->num_selected;+ topology->reduction->get_rt_info()[RT_INFO_MOE_K] = topology->num_selected;+ for (const auto& node : topology->expert_nodes)+ isolate_node(node, isol_tag, node_to_gptr);+ isolate_node(topology->weighted_output, isol_tag, node_to_gptr);+ if (is_decoding_stage(topology->weighted_output))+ isolate_node(topology->reduction, isol_tag, node_to_gptr);+ LOG_INFO("BatchedExpert: isolated " << topology->num_selected << "/" << topology->num_experts+ << " routed experts for " << topology->reduction->get_friendly_name());+ return false;+ };+ register_matcher(std::make_shared<opp::Matcher>(pattern->root(), "TagBatchedExpert"), std::move(callback));+}+/*GPT-OSS Expert Pattern: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.hppindex 7f95907af8c..15925d9d30b 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@@ -63,6 +63,14 @@ public:GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);};+// Structural expert isolation shared by all supported batched FFN layouts.+// Router activation/normalization and model/node names are not part of the match.+class BatchedExpert : public ov::pass::MatcherPass {+public:+ MOE_EXPERT_STATIC_INFO(BatchedExpert)+ BatchedExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);+};+class GPTOSSRouter : public ov::pass::MatcherPass {public:MOE_ROUTER_STATIC_INFO(GPTOSSRouter)diff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmakeindex e0d3310e655..2c8717059e7 100644--- a/src/plugins/intel_npu/src/plugin/sources.cmake+++ b/src/plugins/intel_npu/src/plugin/sources.cmake@@ -116,6 +116,8 @@ set(NPUW_SOURCES${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_transformations/moe_transformation.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_transformations/moe_transformation.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_transformations/moe_transformation_utils.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_transformations/moe_topology.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_transformations/moe_topology.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_transformations/moe_unroll_patterns.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_transformations/moe_unroll_patterns.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/add_position_ids_param.cppdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex d6c873943da..f616a0402a4 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -104,6 +104,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_topology.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/device_routed_moe_transform.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/gather_to_2d_gather.cpp@@ -225,4 +226,5 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_executor_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_infer_utils_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/make_tensor_slice_bounds_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_topology_test.cpp)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.cppindex b71d5d6680f..a8950cf1b78 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@@ -277,9 +277,10 @@ std::shared_ptr<Model> create_complete_moe_graph(size_t num_experts = 32,// Output reshapeauto reshape_shape2 = op::v0::Constant::create(element::i64,- Shape{3},+ Shape{4},std::vector<int64_t>{static_cast<int64_t>(num_experts),static_cast<int64_t>(token_count),+ 1,static_cast<int64_t>(hidden_dim)});auto reshape2 = std::make_shared<op::v1::Reshape>(add3, reshape_shape2, false);reshape2->set_friendly_name("__module.model." + layer_id + "mlp.experts/Reshape_out");@@ -748,7 +749,8 @@ TEST_F(DeviceRoutedMoETransformTest, RouterBroadcastChainShapeUpdate) {EXPECT_NO_THROW(model->validate_nodes_and_infer_types());- // After: the Reshape in the chain must now have shape [k_value, 1, 1]+ // The transactional builder collapses Reshape+Unsqueeze to one Reshape.+ // Its final broadcast layout must contain only the K selected experts.bool found = false;for (const auto& node : model->get_ordered_ops()) {if (auto reshape = std::dynamic_pointer_cast<op::v1::Reshape>(node)) {@@ -756,7 +758,7 @@ TEST_F(DeviceRoutedMoETransformTest, RouterBroadcastChainShapeUpdate) {if (!shp)continue;auto d = shp->cast_vector<int64_t>();- if (d.size() == 3 && d[0] == k_value && d[1] == 1 && d[2] == 1) {+ if (d.size() == 4 && d[0] == k_value && d[1] == 1 && d[2] == 1 && d[3] == 1) {found = true;}}diff --git a/src/plugins/intel_npu/tests/unit/npuw/moe_executor_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/moe_executor_test.cppindex 56b4f826676..32b02b3a4e9 100644--- a/src/plugins/intel_npu/tests/unit/npuw/moe_executor_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/moe_executor_test.cpp@@ -147,10 +147,16 @@ class ExecutorHarness final : public ov::npuw::ISubrequestAccessor {public:static constexpr size_t experts = 4, selected = 2, hidden = 4, chunk = 3;- ExecutorHarness(size_t tokens, const ov::element::Type& score_type, size_t pool)+ ExecutorHarness(size_t tokens,+ const ov::element::Type& score_type,+ size_t pool,+ bool with_shared_scale = false,+ size_t active_experts = selected): token_count(tokens),+ active_expert_count(active_experts),scores(score_type, ov::Shape{experts, tokens, 1}),weights(ov::element::f32, ov::Shape{experts, 1, hidden}),+ shared_scale(ov::element::f32, ov::Shape{hidden}),log(std::make_shared<ExecutionLog>()) {const bool decode = tokens == 1;auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{decode ? 1 : chunk, hidden});@@ -158,25 +164,33 @@ public:ov::OutputVector contributions;auto state = std::make_shared<ov::npuw::compiled::MoEExperts>();state->num_experts = experts;- state->num_active_experts = selected;+ state->num_active_experts = active_experts;state->expert_hidden_dim = hidden;state->input_token_count = tokens;state->_expert_input = {0, 0};state->_router_scores = {1, 1};- for (size_t slot = 0; slot < (decode ? selected : 1); ++slot) {+ for (size_t slot = 0; slot < (decode ? active_experts : 1); ++slot) {auto score = std::make_shared<ov::op::v0::Parameter>(score_type, ov::Shape{1, decode ? 1 : chunk, 1});auto weight = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 1, hidden});state->_param_mapping[1].push_back(params.size());params.push_back(score);state->_param_mapping[2].push_back(params.size());params.push_back(weight);- contributions.push_back(+ ov::Output<ov::Node> contribution =std::make_shared<ov::op::v1::Multiply>(std::make_shared<ov::op::v1::Multiply>(x, weight),- std::make_shared<ov::op::v0::Convert>(score, ov::element::f32)));+ std::make_shared<ov::op::v0::Convert>(score, ov::element::f32));+ if (with_shared_scale) {+ auto scale = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{hidden});+ state->_param_mapping[3].push_back(params.size());+ params.push_back(scale);+ contribution = std::make_shared<ov::op::v1::Multiply>(contribution, scale);+ }+ contributions.push_back(contribution);}ov::Output<ov::Node> output = contributions[0];if (decode) {- output = std::make_shared<ov::op::v1::Add>(output, contributions[1]);+ for (size_t slot = 1; slot < contributions.size(); ++slot)+ output = std::make_shared<ov::op::v1::Add>(output, contributions[slot]);output = std::make_shared<ov::op::v0::Squeeze>(output,ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}));@@ -188,6 +202,10 @@ public:desc.replaced_by = 0;desc.param_base = 2;desc.closure.get().closure = {weights};+ for (size_t feature = 0; feature < hidden; ++feature)+ shared_scale.data<float>()[feature] = with_shared_scale ? static_cast<float>(feature + 1) : 1.0f;+ if (with_shared_scale)+ desc.closure.get().closure.push_back(shared_scale);for (size_t expert = 0; expert < experts; ++expert)std::fill_n(weights.data<float>() + expert * hidden, hidden, 1024.0f * static_cast<float>(expert + 1));request = {desc.compiled_model->create_infer_request(), {}};@@ -232,11 +250,11 @@ public:float expected = 0;for (size_t expert = 0; expert < experts; ++expert)expected += input.data<float>()[token * hidden + h] * weights.data<float>()[expert * hidden + h] *- score(expert, token);+ score(expert, token) * shared_scale.data<float>()[h];float actual = output.data<float>()[h];if (token_count != 1) {actual = 0;- for (size_t slot = 0; slot < selected; ++slot)+ for (size_t slot = 0; slot < active_expert_count; ++slot)actual += accumulator.data<float>()[(slot * token_count + token) * hidden + h];}EXPECT_NEAR(actual, expected, 1e-5f);@@ -269,7 +287,8 @@ public:}size_t token_count;- ov::Tensor scores, weights, input, output, accumulator;+ size_t active_expert_count;+ ov::Tensor scores, weights, shared_scale, input, output, accumulator;std::shared_ptr<ExecutionLog> log;std::unique_ptr<ov::npuw::moe::MoEExecutor> executor;@@ -435,6 +454,25 @@ TEST_P(MoEExecutorRuntimeTest, RejectsExcessExpertsPerTokenAndRemainsReusable) {}}+TEST_P(MoEExecutorRuntimeTest, SharedFeatureWidthEqualToExpertCountIsNotSliced) {+ const auto [half_scores, tokens, pool] = GetParam();+ for (const size_t active_experts : {size_t{1}, size_t{2}}) {+ SCOPED_TRACE(active_experts);+ ExecutorHarness harness(tokens, half_scores ? ov::element::f16 : ov::element::f32, pool, true, active_experts);+ for (const size_t offset : {size_t{0}, size_t{2}, size_t{0}}) {+ SCOPED_TRACE(offset);+ std::memset(harness.scores.data(), 0, harness.scores.get_byte_size());+ for (size_t token = 0; token < tokens; ++token) {+ harness.set_score((token + offset) % ExecutorHarness::experts, token, 0.5f);+ if (active_experts > 1)+ harness.set_score((token + offset + 1) % ExecutorHarness::experts, token, -0.25f);+ }+ harness.bind(0.25f);+ harness.check();+ }+ }+}+INSTANTIATE_TEST_SUITE_P(ScoreTypesAndModes,MoEExecutorRuntimeTest,::testing::Combine(::testing::Bool(),@@ -484,4 +522,13 @@ TEST(MoEExecutorUtilitiesTest, ValidatesExpertSlicesAndPackedBoundaries) {EXPECT_THROW(ov::npuw::moe::slice_expert_weight(unaligned, 1, 4), ov::Exception);}+TEST(MoEExecutorUtilitiesTest, UsesTransformedShapeForClosureSlicing) {+ ov::Tensor shared(ov::element::f32, ov::Shape{4});+ EXPECT_FALSE(ov::npuw::moe::requires_expert_slice(shared, ov::Shape{4}, 4));+ ov::Tensor experts(ov::element::f32, ov::Shape{4, 2, 4});+ EXPECT_TRUE(ov::npuw::moe::requires_expert_slice(experts, ov::Shape{1, 2, 4}, 4));+ EXPECT_THROW(ov::npuw::moe::requires_expert_slice(experts, ov::Shape{1, 4, 2}, 4), ov::Exception);+ EXPECT_THROW(ov::npuw::moe::requires_expert_slice(shared, ov::Shape{1, 4}, 4), ov::Exception);+}+} // namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/moe_topology_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/moe_topology_test.cppnew file mode 100644index 00000000000..59d62c2f5ec--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/moe_topology_test.cpp@@ -0,0 +1,984 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "moe_transformations/moe_topology.hpp"++#include <gtest/gtest.h>++#include <cmath>+#include <cstring>+#include <limits>+#include <unordered_map>++#include "moe/moe_infer_utils.hpp"+#include "moe_transformations/apply_moe_device_routed_transforms.hpp"+#include "moe_transformations/device_routed_moe_transform.hpp"+#include "moe_transformations/moe_transformation.hpp"+#include "moe_transformations/moe_unroll_patterns.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/op/ops.hpp"+#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/runtime/make_tensor.hpp"+#include "partitioning/online/group.hpp"+#include "partitioning/online/snapshot.hpp"+#include "partitioning/patterns/moe.hpp"++namespace {++enum class Routing { SOFTMAX_TOPK, TOPK_SOFTMAX, SIGMOID_BIAS, SCALED, UNNORMALIZED };++struct Graph {+ std::shared_ptr<ov::Model> model;+ std::shared_ptr<ov::Node> scatter;+ std::shared_ptr<ov::op::v11::TopK> topk;+ std::shared_ptr<ov::op::v1::ReduceSum> reduction;+};++Graph make_moe(Routing routing, bool grouped = false, size_t tokens = 1, int64_t k = 2, bool shared = false) {+ constexpr size_t experts = 4, hidden = 8, intermediate = 16;+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{tokens, hidden});+ auto logits = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{tokens, experts});+ input->set_friendly_name("hidden");+ logits->set_friendly_name("selection_input");+ ov::Output<ov::Node> selection = logits;+ std::shared_ptr<ov::Node> probabilities;+ if (routing == Routing::SOFTMAX_TOPK || routing == Routing::SCALED) {+ probabilities = std::make_shared<ov::op::v8::Softmax>(logits, 1);+ selection = probabilities;+ } else if (routing == Routing::SIGMOID_BIAS) {+ probabilities = std::make_shared<ov::op::v0::Sigmoid>(logits);+ auto bias = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{experts}, {0.9f, -0.7f, 0.3f, 0.0f});+ selection = std::make_shared<ov::op::v1::Add>(probabilities, bias);+ }+ auto topk = std::make_shared<ov::op::v11::TopK>(selection,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {k}),+ -1,+ ov::op::v11::TopK::Mode::MAX,+ ov::op::v11::TopK::SortType::SORT_VALUES);+ ov::Output<ov::Node> scores = topk->output(0);+ if (routing == Routing::SIGMOID_BIAS)+ scores = std::make_shared<ov::op::v6::GatherElements>(probabilities, topk->output(1), 1);+ if (routing == Routing::TOPK_SOFTMAX) {+ scores = std::make_shared<ov::op::v8::Softmax>(scores, 1);+ } else if (routing != Routing::UNNORMALIZED) {+ ov::Output<ov::Node> denominator =+ std::make_shared<ov::op::v1::ReduceSum>(scores,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}),+ true);+ if (routing == Routing::SIGMOID_BIAS)+ denominator =+ std::make_shared<ov::op::v1::Add>(denominator,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {1e-6f}));+ scores = std::make_shared<ov::op::v1::Divide>(scores, denominator);+ if (routing == Routing::SCALED) {+ auto scales = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{experts}, {0.5f, 1.5f, 0.8f, 2.0f});+ auto selected_scales =+ std::make_shared<ov::op::v8::Gather>(scales,+ topk->output(1),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0}));+ scores = std::make_shared<ov::op::v1::Multiply>(scores, selected_scales);+ }+ }+ auto zero = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{tokens, experts}, {0.0f});+ auto indices = std::make_shared<ov::op::v0::Convert>(topk->output(1), ov::element::i32);+ auto scatter = std::make_shared<ov::op::v12::ScatterElementsUpdate>(+ zero,+ indices,+ scores,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {1}));+ auto transposed =+ std::make_shared<ov::op::v1::Transpose>(scatter,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {1, 0}));+ auto routing_weights = std::make_shared<ov::op::v1::Reshape>(+ transposed,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<size_t>{experts, tokens, 1}),+ false);+ auto tile = std::make_shared<ov::op::v0::Tile>(+ input,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<size_t>{experts, 1}));+ auto batched = std::make_shared<ov::op::v1::Reshape>(+ tile,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<size_t>{experts, tokens, hidden}),+ false);+ auto weight = [grouped, experts](size_t rows, size_t cols, int seed) -> ov::Output<ov::Node> {+ std::vector<int8_t> values(experts * rows * cols);+ for (size_t i = 0; i < values.size(); ++i)+ values[i] = static_cast<int8_t>((i * 3 + i / (rows * cols) + static_cast<size_t>(seed)) % 8) - 4;+ ov::Shape shape = grouped ? ov::Shape{experts, rows, cols / 4, 4} : ov::Shape{experts, rows, cols};+ auto compressed = ov::op::v0::Constant::create(ov::element::i4, shape, values);+ auto converted = std::make_shared<ov::op::v0::Convert>(compressed, ov::element::f32);+ shape.back() = 1;+ auto scales = ov::op::v0::Constant::create(ov::element::f32, shape, {0.0625f});+ ov::Output<ov::Node> result = std::make_shared<ov::op::v1::Multiply>(converted, scales);+ if (grouped)+ result = std::make_shared<ov::op::v1::Reshape>(+ result,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<size_t>{experts, rows, cols}),+ false);+ return std::make_shared<ov::op::v0::Convert>(result, ov::element::f32);+ };+ auto gate = std::make_shared<ov::op::v0::MatMul>(batched, weight(intermediate, hidden, 1), false, true);+ auto up = std::make_shared<ov::op::v0::MatMul>(batched, weight(intermediate, hidden, 2), false, true);+ auto activation = std::make_shared<ov::op::v1::Multiply>(std::make_shared<ov::op::v4::Swish>(gate), up);+ auto down = std::make_shared<ov::op::v0::MatMul>(activation, weight(hidden, intermediate, 3), false, true);+ auto expert_output = std::make_shared<ov::op::v1::Reshape>(+ down,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<size_t>{experts, tokens, hidden}),+ false);+ auto weighted = std::make_shared<ov::op::v1::Multiply>(expert_output, routing_weights);+ auto reduction =+ std::make_shared<ov::op::v1::ReduceSum>(weighted,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}),+ false);+ ov::Output<ov::Node> output = reduction;+ if (shared)+ output = std::make_shared<ov::op::v1::Add>(+ output,+ std::make_shared<ov::op::v0::MatMul>(+ input,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{hidden, hidden}, {0.125f}),+ false,+ false));+ return {std::make_shared<ov::Model>(ov::OutputVector{output}, ov::ParameterVector{input, logits}),+ scatter,+ topk,+ reduction};+}++ov::TensorVector evaluate(const std::shared_ptr<ov::Model>& original) {+ // Model::evaluate has no sub-byte Gather or GatherElements evaluator.+ // Widen storage losslessly in a REFERENCE COPY and express the 2D+ // GatherElements as batched Gather; the graph under test stays packed INT4.+ auto model = original->clone();+ for (const auto& node : model->get_ordered_ops()) {+ if (auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node)) {+ if (constant->get_element_type() == ov::element::i4)+ ov::replace_node(constant,+ ov::op::v0::Constant::create(ov::element::i8,+ constant->get_shape(),+ constant->cast_vector<int8_t>()));+ } else if (auto gather = ov::as_type_ptr<ov::op::v6::GatherElements>(node)) {+ EXPECT_EQ(gather->get_axis(), 1);+ EXPECT_EQ(gather->get_input_partial_shape(0).rank(), ov::Rank(2));+ ov::replace_node(+ gather,+ std::make_shared<ov::op::v8::Gather>(gather->input_value(0),+ gather->input_value(1),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {1}),+ 1));+ }+ }+ model->validate_nodes_and_infer_types();+ ov::TensorVector inputs;+ for (const auto& parameter : model->get_parameters()) {+ ov::Tensor tensor(ov::element::f32, parameter->get_shape());+ for (size_t i = 0; i < tensor.get_size(); ++i)+ tensor.data<float>()[i] = static_cast<float>((i * 7 + 3) % 19) / 8.0f - 1.0f;+ inputs.push_back(tensor);+ }+ ov::TensorVector outputs;+ for (const auto& output : model->outputs())+ outputs.emplace_back(output.get_element_type(), output.get_shape());+ EXPECT_TRUE(model->evaluate(outputs, inputs));+ return outputs;+}++class GenericMoETest : public ::testing::TestWithParam<std::tuple<Routing, bool, int64_t>> {};++TEST_P(GenericMoETest, DeviceRoutingPreservesScoresAndSlicesOnlySelectedExperts) {+ const auto [routing, grouped, k] = GetParam();+ auto graph = make_moe(routing, grouped, 1, k, true);+ const auto topology = ov::npuw::moe::match_batched_moe(graph.scatter);+ ASSERT_TRUE(topology);+ EXPECT_EQ(topology->num_experts, 4u);+ EXPECT_EQ(topology->num_selected, static_cast<size_t>(k));+ EXPECT_EQ(topology->scores, graph.scatter->input_value(2));+ const auto before = evaluate(graph.model);+ ASSERT_TRUE(ov::npuw::ApplyMoEDeviceRoutedTransforms().run_on_model(graph.model));+ graph.model->validate_nodes_and_infer_types();+ const auto after = evaluate(graph.model);+ ASSERT_EQ(before[0].get_shape(), after[0].get_shape());+ for (size_t i = 0; i < before[0].get_size(); ++i)+ EXPECT_NEAR(before[0].data<float>()[i], after[0].data<float>()[i], 1e-5f);+ size_t sparse_matmuls = 0;+ for (const auto& node : graph.model->get_ordered_ops()) {+ if (ov::is_type<ov::op::v0::MatMul>(node) && node->get_output_shape(0).size() == 3) {+ EXPECT_EQ(node->get_output_shape(0)[0], static_cast<size_t>(k));+ ++sparse_matmuls;+ }+ EXPECT_FALSE(ov::is_type<ov::op::v12::ScatterElementsUpdate>(node));+ }+ EXPECT_EQ(sparse_matmuls, 3u);+}++INSTANTIATE_TEST_SUITE_P(RoutingSemantics,+ GenericMoETest,+ ::testing::Combine(::testing::Values(Routing::SOFTMAX_TOPK,+ Routing::TOPK_SOFTMAX,+ Routing::SIGMOID_BIAS,+ Routing::SCALED,+ Routing::UNNORMALIZED),+ ::testing::Bool(),+ ::testing::Values(int64_t{1}, int64_t{2}, int64_t{4})));++// Exercise the complete boundary independently of the legacy Scatter lookup.+// Layout 0: [E,T,1]; layout 1: [E,1,T,1]; layout 2: [E,T,1,1].+std::shared_ptr<ov::Node> configure_score_boundary(Graph& graph,+ size_t views,+ size_t layout,+ bool reverse_multiply,+ bool scatter_v3) {+ auto weighted = ov::as_type_ptr<ov::op::v1::Multiply>(graph.reduction->input_value(0).get_node_shared_ptr());+ auto transpose = weighted->input_value(1).get_node_shared_ptr()->input_value(0).get_node_shared_ptr();+ const auto tokens = graph.topk->get_input_shape(0)[0];+ const ov::Shape score_shape =+ layout == 0 ? ov::Shape{4, tokens, 1} : (layout == 1 ? ov::Shape{4, 1, tokens, 1} : ov::Shape{4, tokens, 1, 1});+ const std::vector<int64_t> axes =+ layout == 0 ? std::vector<int64_t>{2} : (layout == 1 ? std::vector<int64_t>{1, 3} : std::vector<int64_t>{2, 3});+ ov::Output<ov::Node> scores = transpose;+ for (size_t i = 0; i < views; ++i) {+ if (i == (views == 1 ? 0 : 1)) {+ scores = std::make_shared<ov::op::v0::Unsqueeze>(+ scores,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{axes.size()}, axes));+ } else {+ const auto shape = i == 0 ? ov::Shape{4, tokens} : score_shape;+ scores = std::make_shared<ov::op::v1::Reshape>(+ scores,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{shape.size()}, shape),+ false);+ }+ }+ ov::Output<ov::Node> expert = weighted->input_value(0);+ if (layout != 0) {+ auto shape = score_shape;+ shape.back() = 8;+ expert = std::make_shared<ov::op::v1::Reshape>(+ expert,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{shape.size()}, shape),+ false);+ }+ weighted->input(0).replace_source_output(reverse_multiply ? scores : expert);+ weighted->input(1).replace_source_output(reverse_multiply ? expert : scores);+ std::shared_ptr<ov::Node> scatter = graph.scatter;+ if (scatter_v3) {+ scatter = std::make_shared<ov::op::v3::ScatterElementsUpdate>(graph.scatter->input_value(0),+ graph.scatter->input_value(1),+ graph.scatter->input_value(2),+ graph.scatter->input_value(3));+ ov::replace_node(graph.scatter, scatter);+ // Do not retain an obsolete consumer of the router outputs: Snapshot+ // expects every live consumer to belong to the model being partitioned.+ graph.scatter = scatter;+ }+ ov::Output<ov::Node> indices = graph.topk->output(1);+ for (const auto type : {ov::element::i32, ov::element::i64, ov::element::i32, ov::element::i64})+ indices = std::make_shared<ov::op::v0::Convert>(indices, type);+ scatter->input(1).replace_source_output(indices);+ graph.model->validate_nodes_and_infer_types();+ return scatter;+}++class BatchedMoEBoundaryTest : public ::testing::TestWithParam<std::tuple<size_t, size_t, bool, bool>> {};++TEST_P(BatchedMoEBoundaryTest, SharedPatternPreservesHostIsolationAndDeviceNumerics) {+ const auto [views, layout, reverse_multiply, scatter_v3] = GetParam();+ const ov::npuw::moe::BatchedMoEPattern pattern;+ for (const size_t tokens : {size_t{1}, size_t{7}}) {+ SCOPED_TRACE(tokens);+ auto graph = make_moe(Routing::SIGMOID_BIAS, true, tokens, 2, true);+ const auto scatter = configure_score_boundary(graph, views, layout, reverse_multiply, scatter_v3);+ const auto topology = pattern.match(graph.reduction);+ ASSERT_TRUE(topology);+ EXPECT_EQ(topology->topk, graph.topk);+ EXPECT_EQ(topology->indices, graph.topk->output(1));+ EXPECT_EQ(topology->scores, scatter->input_value(2));+ EXPECT_EQ(topology->num_experts, 4u);+ EXPECT_EQ(topology->num_selected, 2u);+ EXPECT_EQ(ov::npuw::moe::can_device_route(*topology), tokens == 1);++ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(graph.model);+ snapshot->buildGraph();+ ov::pass::GraphRewrite host;+ host.add_matcher<ov::npuw::patterns::moe::BatchedExpert>(snapshot, "expert");+ host.run_on_model(graph.model);+ EXPECT_EQ(graph.topk->get_rt_info().at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), 2u);+ EXPECT_EQ(snapshot->getNodeToGroupMap()->at(topology->weighted_output)->isolatedTag(), "expert");+ EXPECT_EQ(snapshot->getNodeToGroupMap()->at(graph.reduction)->isolatedTag() == "expert", tokens == 1);+ if (tokens == 1) {+ const auto expected = evaluate(graph.model);+ ASSERT_TRUE(ov::npuw::ApplyMoEDeviceRoutedTransforms().run_on_model(graph.model));+ const auto actual = evaluate(graph.model);+ ASSERT_EQ(actual[0].get_shape(), expected[0].get_shape());+ for (size_t i = 0; i < actual[0].get_size(); ++i)+ EXPECT_NEAR(actual[0].data<float>()[i], expected[0].data<float>()[i], 1e-5f);+ } else {+ const auto nodes = graph.model->get_ordered_ops();+ EXPECT_FALSE(ov::npuw::pass::DeviceRoutedMoETransform().run_on_model(graph.model));+ EXPECT_EQ(nodes, graph.model->get_ordered_ops());+ }+ }+}++INSTANTIATE_TEST_SUITE_P(ScoreViews,+ BatchedMoEBoundaryTest,+ ::testing::Combine(::testing::Values(size_t{1}, size_t{2}, size_t{7}),+ ::testing::Values(size_t{0}, size_t{1}, size_t{2}),+ ::testing::Bool(),+ ::testing::Bool()));++TEST(GenericMoETopologyTest, DeclarativeBoundaryRejectsExcessScoreViewsWithoutMutation) {+ auto graph = make_moe(Routing::TOPK_SOFTMAX);+ configure_score_boundary(graph, 8, 0, false, false);+ const auto nodes = graph.model->get_ordered_ops();+ EXPECT_FALSE(ov::npuw::moe::BatchedMoEPattern().match(graph.reduction));+ EXPECT_FALSE(ov::npuw::moe::match_batched_moe(graph.scatter));+ EXPECT_FALSE(ov::npuw::pass::DeviceRoutedMoETransform().run_on_model(graph.model));+ EXPECT_EQ(nodes, graph.model->get_ordered_ops());+}++TEST(GenericMoETopologyTest, DeclarativeBoundaryRejectsEscapingValuesWithoutMutation) {+ const ov::npuw::moe::BatchedMoEPattern pattern;+ for (size_t boundary = 0; boundary < 5; ++boundary) {+ SCOPED_TRACE(boundary);+ auto graph = make_moe(Routing::TOPK_SOFTMAX);+ const auto topology = pattern.match(graph.reduction);+ ASSERT_TRUE(topology);+ const ov::OutputVector values{graph.scatter,+ topology->score_transpose,+ topology->broadcast_scores,+ topology->expert_output,+ topology->weighted_output};+ graph.model->add_results({std::make_shared<ov::op::v0::Result>(values[boundary])});+ const auto nodes = graph.model->get_ordered_ops();+ EXPECT_FALSE(pattern.match(graph.reduction));+ EXPECT_FALSE(ov::npuw::pass::DeviceRoutedMoETransform().run_on_model(graph.model));+ EXPECT_EQ(nodes, graph.model->get_ordered_ops());+ }+}++TEST(GenericMoETopologyTest, DeclarativeBoundaryRejectsInvalidPermutationAndIndexConversions) {+ const ov::npuw::moe::BatchedMoEPattern pattern;+ for (const bool invalid_permutation : {false, true}) {+ auto graph = make_moe(Routing::TOPK_SOFTMAX, false, 4);+ const auto topology = pattern.match(graph.reduction);+ ASSERT_TRUE(topology);+ if (invalid_permutation) {+ topology->score_transpose->input(1).replace_source_output(+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1}));+ } else {+ graph.scatter->input(1).replace_source_output(std::make_shared<ov::op::v0::Convert>(+ std::make_shared<ov::op::v0::Convert>(graph.topk->output(1), ov::element::f32),+ ov::element::i64));+ }+ graph.model->validate_nodes_and_infer_types();+ EXPECT_FALSE(pattern.match(graph.reduction));+ }+}++TEST(GenericMoETopologyTest, PureBoundaryPatternDoesNotRetainModelsOrStaleMatches) {+ const ov::npuw::moe::BatchedMoEPattern pattern;+ std::weak_ptr<ov::Node> reduction;+ {+ auto graph = make_moe(Routing::TOPK_SOFTMAX);+ reduction = graph.reduction;+ ASSERT_TRUE(pattern.match(graph.reduction));+ graph.scatter->input(0).replace_source_output(+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 4}, {1.0f}));+ EXPECT_FALSE(pattern.match(graph.reduction));+ graph.scatter->input(0).replace_source_output(+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 4}, {0.0f}));+ EXPECT_TRUE(pattern.match(graph.reduction));+ }+ EXPECT_TRUE(reduction.expired());+}++TEST(GenericMoETopologyTest, SharedPatternCoversGroupedAndPlainWeightsOutsideLegacySkeletons) {+ for (const bool plain_weights : {false, true}) {+ auto graph = make_moe(Routing::SIGMOID_BIAS, true, 7);+ if (plain_weights) {+ for (const auto& node : graph.model->get_ordered_ops()) {+ if (const auto matmul = ov::as_type_ptr<ov::op::v0::MatMul>(node))+ matmul->input(1).replace_source_output(+ ov::op::v0::Constant::create(ov::element::f32, matmul->get_input_shape(1), {0.125f}));+ }+ graph.model->validate_nodes_and_infer_types();+ }+ const auto topology = ov::npuw::moe::BatchedMoEPattern().match(graph.reduction);+ ASSERT_TRUE(topology);+ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(graph.model);+ snapshot->buildGraph();+ ov::pass::GraphRewrite legacy;+ legacy.add_matcher<ov::npuw::patterns::moe::GPTOSSExpert>(snapshot, "expert");+ legacy.add_matcher<ov::npuw::patterns::moe::Qwen3Expert>(snapshot, "expert");+ legacy.add_matcher<ov::npuw::patterns::moe::Gemma4Expert>(snapshot, "expert");+ legacy.add_matcher<ov::npuw::patterns::moe::GPTOSSRouter>(snapshot, "router");+ legacy.add_matcher<ov::npuw::patterns::moe::Qwen3Router>(snapshot, "router");+ legacy.add_matcher<ov::npuw::patterns::moe::Gemma4Router>(snapshot, "router");+ legacy.run_on_model(graph.model);+ EXPECT_NE(snapshot->getNodeToGroupMap()->at(topology->weighted_output)->isolatedTag(), "expert");+ EXPECT_FALSE(graph.topk->get_rt_info().count(ov::npuw::patterns::moe::RT_INFO_MOE_K));+ ov::pass::GraphRewrite generic;+ generic.add_matcher<ov::npuw::patterns::moe::BatchedExpert>(snapshot, "expert");+ generic.run_on_model(graph.model);+ EXPECT_EQ(snapshot->getNodeToGroupMap()->at(topology->weighted_output)->isolatedTag(), "expert");+ EXPECT_EQ(graph.topk->get_rt_info().at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), 2u);+ }+}++TEST(GenericMoETopologyTest, HostMatcherTagsSigmoidBiasAndGroupedWeightsWithoutNames) {+ auto graph = make_moe(Routing::SIGMOID_BIAS, true, 7);+ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(graph.model);+ snapshot->buildGraph();+ ov::pass::GraphRewrite rewrite;+ rewrite.add_matcher<ov::npuw::patterns::moe::BatchedExpert>(snapshot, "expert");+ rewrite.run_on_model(graph.model);+ ASSERT_TRUE(graph.topk->get_rt_info().count(ov::npuw::patterns::moe::RT_INFO_MOE_K));+ EXPECT_EQ(graph.topk->get_rt_info().at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), 2u);+ auto topology = ov::npuw::moe::match_batched_moe(graph.scatter);+ ASSERT_TRUE(topology);+ EXPECT_EQ(topology->weighted_output->get_rt_info().at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), 2u);+ EXPECT_EQ(snapshot->getNodeToGroupMap()->at(topology->weighted_output)->isolatedTag(), "expert");+ EXPECT_NE(snapshot->getNodeToGroupMap()->at(topology->reduction)->isolatedTag(), "expert");+ EXPECT_FALSE(ov::npuw::pass::DeviceRoutedMoETransform().run_on_model(graph.model));+}++TEST(GenericMoETopologyTest, LegacyRouterUsesSelectionKInsteadOfAnUnrelatedScoreTopK) {+ for (const bool legacy_first : {false, true}) {+ ov::ResultVector results;+ ov::ParameterVector parameters;+ std::vector<std::shared_ptr<ov::op::v11::TopK>> selections, score_topks;+ for (const int64_t score_k : {3, 4}) {+ auto graph = make_moe(Routing::UNNORMALIZED, false, 1, 2);+ // Match GPTOSS's legacy score pattern, but keep the actual expert+ // selection TopK separate (K=2 in both layers).+ auto weight = std::make_shared<ov::op::v1::Multiply>(+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{4, 8}, {0.125f}),+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {1.0f}));+ auto matmul =+ std::make_shared<ov::op::v0::MatMul>(graph.model->get_parameters()[0],+ std::make_shared<ov::op::v0::Convert>(weight, ov::element::f32),+ false,+ true);+ auto biased =+ std::make_shared<ov::op::v1::Add>(matmul,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{4}, {0.0f}));+ auto score_topk = std::make_shared<ov::op::v11::TopK>(+ biased,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {score_k}),+ 1,+ ov::op::v11::TopK::Mode::MAX,+ ov::op::v11::TopK::SortType::SORT_VALUES);+ score_topk->set_friendly_name("layer" + std::to_string(score_k) + ".router/score_topk");+ auto softmax = std::make_shared<ov::op::v8::Softmax>(score_topk->output(0), 1);+ auto scores =+ std::make_shared<ov::op::v8::Slice>(softmax,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}));+ graph.scatter->input(2).replace_source_output(scores);+ graph.model->validate_nodes_and_infer_types();+ ASSERT_TRUE(ov::npuw::moe::match_batched_moe(graph.scatter));+ results.push_back(graph.model->get_results()[0]);+ parameters.insert(parameters.end(),+ graph.model->get_parameters().begin(),+ graph.model->get_parameters().end());+ selections.push_back(graph.topk);+ score_topks.push_back(score_topk);+ }+ auto model = std::make_shared<ov::Model>(results, parameters);+ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(model);+ snapshot->buildGraph();+ ov::pass::GraphRewrite rewrite;+ if (legacy_first)+ rewrite.add_matcher<ov::npuw::patterns::moe::GPTOSSRouter>(snapshot, "router");+ rewrite.add_matcher<ov::npuw::patterns::moe::BatchedExpert>(snapshot, "expert");+ if (!legacy_first)+ rewrite.add_matcher<ov::npuw::patterns::moe::GPTOSSRouter>(snapshot, "router");+ EXPECT_NO_THROW(rewrite.run_on_model(model));+ for (const auto& topk : selections)+ EXPECT_EQ(topk->get_rt_info().at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), 2u);+ for (const auto& topk : score_topks)+ EXPECT_FALSE(topk->get_rt_info().count(ov::npuw::patterns::moe::RT_INFO_MOE_K));+ }+}++TEST(GenericMoETopologyTest, RejectsNonzeroScatterBaseWithoutMutation) {+ auto graph = make_moe(Routing::TOPK_SOFTMAX);+ graph.scatter->input(0).replace_source_output(+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 4}, {1.0f}));+ const auto original = graph.model->get_ordered_ops();+ EXPECT_FALSE(ov::npuw::pass::DeviceRoutedMoETransform().run_on_model(graph.model));+ EXPECT_EQ(original, graph.model->get_ordered_ops());+}++TEST(GenericMoETopologyTest, RejectsTopKValuesUsedAsIndices) {+ auto graph = make_moe(Routing::TOPK_SOFTMAX);+ graph.scatter->input(1).replace_source_output(+ std::make_shared<ov::op::v0::Convert>(graph.topk->output(0), ov::element::i32));+ EXPECT_FALSE(ov::npuw::moe::match_batched_moe(graph.scatter));+}++TEST(GenericMoETopologyTest, AcceptsExpertAxisAndRejectsTokenAxis) {+ for (const int64_t axis : {1, -1, 0, -2}) {+ SCOPED_TRACE(axis);+ auto graph = make_moe(Routing::TOPK_SOFTMAX, false, 4, 4);+ graph.topk->set_axis(axis);+ graph.model->validate_nodes_and_infer_types();+ EXPECT_EQ(ov::npuw::moe::match_batched_moe(graph.scatter).has_value(), axis == 1 || axis == -1);+ }+}++TEST(GenericMoETopologyTest, RejectsReductionScatter) {+ auto graph = make_moe(Routing::TOPK_SOFTMAX);+ ov::as_type_ptr<ov::op::v12::ScatterElementsUpdate>(graph.scatter)+ ->set_reduction(ov::op::v12::ScatterElementsUpdate::Reduction::PROD);+ EXPECT_FALSE(ov::npuw::moe::match_batched_moe(graph.scatter));+}++TEST(GenericMoETopologyTest, FullDevicePipelineAcceptsBothTopKIndexTypes) {+ for (const auto index_type : {ov::element::i32, ov::element::i64}) {+ for (const bool grouped : {false, true}) {+ SCOPED_TRACE(index_type.get_type_name());+ auto graph = make_moe(Routing::TOPK_SOFTMAX, grouped);+ graph.topk->set_index_element_type(index_type);+ graph.model->validate_nodes_and_infer_types();+ // make_moe also inserts an i32 Convert before the scatter.+ const auto before = evaluate(graph.model);+ ASSERT_TRUE(ov::npuw::ApplyMoEDeviceRoutedTransforms().run_on_model(graph.model));+ const auto after = evaluate(graph.model);+ ASSERT_EQ(before[0].get_shape(), after[0].get_shape());+ for (size_t i = 0; i < before[0].get_size(); ++i)+ EXPECT_NEAR(before[0].data<float>()[i], after[0].data<float>()[i], 1e-5f);+ }+ }+}++TEST(GenericMoETopologyTest, RejectsPDPDExpertScalesWithoutMutationEvenWhenAllExpertsAreSelected) {+ for (const int64_t k : {2, 4}) {+ auto graph = make_moe(Routing::UNNORMALIZED, false, 1, k);+ auto topology = ov::npuw::moe::match_batched_moe(graph.scatter);+ ASSERT_TRUE(topology);+ for (const auto& node : topology->expert_nodes) {+ if (auto mm = ov::as_type_ptr<ov::op::v0::MatMul>(node)) {+ auto base = ov::op::v0::Constant::create(ov::element::f32, mm->get_input_shape(1), {1.0f});+ auto scales = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{4}, {1.0f, 2.0f, 3.0f, 4.0f});+ mm->input(1).replace_source_output(std::make_shared<ov::op::v1::Multiply>(+ base,+ scales,+ ov::op::AutoBroadcastSpec(ov::op::AutoBroadcastType::PDPD, 0)));+ break;+ }+ }+ graph.model->validate_nodes_and_infer_types();+ const auto original_nodes = graph.model->get_ordered_ops();+ EXPECT_FALSE(ov::npuw::moe::match_batched_moe(graph.scatter));+ EXPECT_FALSE(ov::npuw::pass::DeviceRoutedMoETransform().run_on_model(graph.model));+ EXPECT_EQ(original_nodes, graph.model->get_ordered_ops());+ }+}++TEST(GenericMoETopologyTest, RequestedDeviceRoutingDoesNotSilentlyRunDense) {+ auto graph = make_moe(Routing::TOPK_SOFTMAX);+ graph.scatter->input(0).replace_source_output(+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 4}, {1.0f}));+ EXPECT_THROW(ov::npuw::ApplyMoEDeviceRoutedTransforms().run_on_model(graph.model), ov::Exception);+}++TEST(GenericMoETopologyTest, RejectsSharedProjectionFeatureAxisWithoutChangingNumerics) {+ auto graph = make_moe(Routing::TOPK_SOFTMAX, false, 1, 4);+ const auto topology = ov::npuw::moe::match_batched_moe(graph.scatter);+ ASSERT_TRUE(topology);+ auto logits = graph.model->get_parameters().at(1);+ ov::replace_node(logits, ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 4}, {1.0f, 3.0f, 2.0f, 4.0f}));+ graph.model->remove_parameter(logits);+ std::vector<float> values(4 * 8);+ for (size_t index = 0; index < values.size(); ++index)+ values[index] = static_cast<float>(index / 8 + 1);+ auto shifted =+ std::make_shared<ov::op::v1::Add>(topology->expert_output,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {10.0f}));+ auto projection =+ std::make_shared<ov::op::v0::MatMul>(shifted,+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{4, 8}, values),+ false,+ true);+ topology->weighted_output->input(0).replace_source_output(projection);+ graph.model->validate_nodes_and_infer_types();+ const auto before = evaluate(graph.model);+ ASSERT_EQ(before[0].get_shape(), (ov::Shape{1, 4}));+ EXPECT_NE(before[0].data<float>()[0], before[0].data<float>()[3]);+ const auto original_nodes = graph.model->get_ordered_ops();+ EXPECT_FALSE(ov::npuw::moe::match_batched_moe(graph.scatter));+ EXPECT_FALSE(ov::npuw::pass::DeviceRoutedMoETransform().run_on_model(graph.model));+ EXPECT_EQ(original_nodes, graph.model->get_ordered_ops());+ const auto after = evaluate(graph.model);+ ASSERT_EQ(before[0].get_shape(), after[0].get_shape());+ for (size_t feature = 0; feature < before[0].get_size(); ++feature)+ EXPECT_NEAR(before[0].data<float>()[feature], after[0].data<float>()[feature], 1e-6f);+}++TEST(GenericMoETopologyTest, RejectsUnsupportedActivationPrefixBeforeHostIsolation) {+ for (const size_t tokens : {size_t{1}, size_t{7}}) {+ SCOPED_TRACE(tokens);+ auto graph = make_moe(Routing::TOPK_SOFTMAX, false, tokens);+ const auto topology = ov::npuw::moe::match_batched_moe(graph.scatter);+ ASSERT_TRUE(topology);+ const auto tile_users = topology->tile->output(0).get_target_inputs();+ ASSERT_EQ(tile_users.size(), 1u);+ auto view = ov::as_type_ptr<ov::op::v1::Reshape>(tile_users.begin()->get_node()->shared_from_this());+ ASSERT_TRUE(view);+ const auto consumers = view->output(0).get_target_inputs();+ auto relu = std::make_shared<ov::op::v0::Relu>(view);+ for (auto input : consumers)+ input.replace_source_output(relu);+ graph.model->validate_nodes_and_infer_types();+ const auto original_nodes = graph.model->get_ordered_ops();+ EXPECT_FALSE(ov::npuw::moe::match_batched_moe(graph.scatter));+ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(graph.model);+ snapshot->buildGraph();+ ov::pass::GraphRewrite rewrite;+ rewrite.add_matcher<ov::npuw::patterns::moe::BatchedExpert>(snapshot, "expert");+ rewrite.run_on_model(graph.model);+ EXPECT_FALSE(graph.topk->get_rt_info().count(ov::npuw::patterns::moe::RT_INFO_MOE_K));+ EXPECT_NE(snapshot->getNodeToGroupMap()->at(topology->weighted_output)->isolatedTag(), "expert");+ EXPECT_EQ(original_nodes, graph.model->get_ordered_ops());+ }+}++TEST(GenericMoETopologyTest, RejectsReductionAcrossHiddenInsteadOfExperts) {+ auto graph = make_moe(Routing::TOPK_SOFTMAX);+ auto topology = ov::npuw::moe::match_batched_moe(graph.scatter);+ ASSERT_TRUE(topology);+ topology->reduction->input(1).replace_source_output(+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1}));+ graph.model->validate_nodes_and_infer_types();+ EXPECT_FALSE(ov::npuw::moe::match_batched_moe(graph.scatter));+}++TEST(GenericMoETopologyTest, RejectsExpertViewsThatMixTokensAndFeatures) {+ auto graph = make_moe(Routing::TOPK_SOFTMAX, false, 2);+ const auto topology = ov::npuw::moe::match_batched_moe(graph.scatter);+ ASSERT_TRUE(topology);+ for (const auto& node : topology->expert_nodes) {+ if (ov::is_type<ov::op::v1::Reshape>(node) && node->input_value(0).get_node_shared_ptr() == topology->tile) {+ node->input(1).replace_source_output(+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {4, 1, 16}));+ } else if (ov::is_type<ov::op::v0::MatMul>(node)) {+ node->input(1).replace_source_output(+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{4, 16, 16}, {0.125f}));+ }+ }+ graph.model->validate_nodes_and_infer_types();+ EXPECT_EQ(graph.model->get_output_shape(0), (ov::Shape{2, 8}));+ EXPECT_FALSE(ov::npuw::moe::match_batched_moe(graph.scatter));+}++std::shared_ptr<ov::Model> make_host_expert_model(bool grouped, size_t tokens, bool mixed_precision = false) {+ auto graph = make_moe(Routing::SIGMOID_BIAS, grouped, tokens);+ auto topology = ov::npuw::moe::match_batched_moe(graph.scatter);+ if (!topology)+ throw std::runtime_error("Test expert topology did not match");+ if (mixed_precision) {+ // Exercise a real FP16 expert arm whose output is converted to f32+ // before the final mixture, rather than a no-op Convert.+ graph.model->get_parameters()[0]->set_element_type(ov::element::f16);+ for (const auto& node : topology->expert_nodes) {+ if (auto convert = ov::as_type_ptr<ov::op::v0::Convert>(node))+ convert->set_destination_type(ov::element::f16);+ for (auto input : node->inputs()) {+ if (auto constant =+ ov::as_type_ptr<ov::op::v0::Constant>(input.get_source_output().get_node_shared_ptr())) {+ if (constant->get_element_type() == ov::element::f32)+ input.replace_source_output(ov::op::v0::Constant::create(ov::element::f16,+ constant->get_shape(),+ constant->cast_vector<float>()));+ }+ }+ }+ topology->weighted_output->input(0).replace_source_output(+ std::make_shared<ov::op::v0::Convert>(topology->expert_output, ov::element::f32));+ graph.model->validate_nodes_and_infer_types();+ topology = ov::npuw::moe::match_batched_moe(graph.scatter);+ if (!topology)+ throw std::runtime_error("Mixed-precision expert topology did not match");+ }+ // Reproduce the partition boundary: hidden state, broadcast router scores,+ // and original compressed constants become parameters/closures.+ auto scores = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, topology->broadcast_scores.get_shape());+ scores->set_friendly_name("router_scores");+ topology->weighted_output->input(1).replace_source_output(scores);+ auto hidden = graph.model->get_parameters()[0];+ ov::ParameterVector parameters{hidden, scores};+ std::unordered_map<std::shared_ptr<ov::Node>, std::shared_ptr<ov::op::v0::Parameter>> closures;+ for (const auto& node : topology->expert_nodes) {+ for (auto input : node->inputs()) {+ auto constant = ov::as_type_ptr<ov::op::v0::Constant>(input.get_source_output().get_node_shared_ptr());+ if (!constant || constant->get_shape().size() < 3)+ continue;+ auto& parameter = closures[constant];+ if (!parameter) {+ parameter =+ std::make_shared<ov::op::v0::Parameter>(constant->get_element_type(), constant->get_shape());+ parameter->set_friendly_name(constant->get_friendly_name());+ parameters.push_back(parameter);+ }+ input.replace_source_output(parameter);+ }+ }+ ov::Output<ov::Node> output = tokens == 1 ? topology->reduction->output(0) : topology->weighted_output->output(0);+ return std::make_shared<ov::Model>(ov::OutputVector{output}, parameters);+}++TEST(GenericMoETopologyTest, HostGroupedClosuresAndTopOneDecode) {+ for (const bool grouped : {false, true}) {+ for (const size_t k : {size_t{1}, size_t{2}}) {+ auto model = make_host_expert_model(grouped, 1);+ auto experts = ov::npuw::function::MoEExperts::from(model, k, 16);+ ASSERT_TRUE(experts) << "grouped=" << grouped << " k=" << k;+ ASSERT_EQ(experts->_transformed_models.size(), 1u);+ const auto& transformed = experts->_transformed_models.begin()->second;+ EXPECT_EQ(transformed->get_output_shape(0), (ov::Shape{1, 8}));+ for (const auto& entry : experts->_param_mapping)+ EXPECT_EQ(entry.second.size(), k);+ }+ }+}++enum class WeightOffset { ADD, SUBTRACT, REVERSE_SUBTRACT };++class GenericMoEHostWeightChainTest : public ::testing::TestWithParam<std::tuple<bool, WeightOffset, bool, size_t>> {};++TEST_P(GenericMoEHostWeightChainTest, LowersClosureExpressionsAndPreservesSelectedExpertNumerics) {+ const auto [grouped, offset_op, shared_metadata, k] = GetParam();+ auto graph = make_moe(Routing::UNNORMALIZED, grouped, 1, static_cast<int64_t>(k));+ std::shared_ptr<ov::Node> shared_weight;+ for (const auto& node : graph.model->get_ordered_ops()) {+ const auto matmul = ov::as_type_ptr<ov::op::v0::MatMul>(node);+ if (!matmul)+ continue;+ const auto weight_shape = matmul->get_input_shape(1);+ // Gate/up share a complete expression. A closure reused by two MatMuls+ // must still have exactly K bindings, not two independently unrolled sets.+ if (shared_weight && shared_weight->get_output_shape(0) == weight_shape) {+ matmul->input(1).replace_source_output(shared_weight);+ continue;+ }+ auto dequant = matmul->input_value(1).get_node_shared_ptr()->input_value(0);+ if (grouped)+ dequant = dequant.get_node_shared_ptr()->input_value(0);+ const auto multiply = ov::as_type_ptr<ov::op::v1::Multiply>(dequant.get_node_shared_ptr());+ ASSERT_TRUE(multiply);+ auto metadata_shape = multiply->get_input_shape(1);+ if (shared_metadata)+ metadata_shape[0] = 1;+ std::vector<float> offsets(ov::shape_size(metadata_shape)), scales(offsets.size());+ for (size_t i = 0; i < offsets.size(); ++i) {+ offsets[i] = static_cast<float>(1 + i % 7) / 4.0f;+ scales[i] = static_cast<float>(1 + i % 5) / 32.0f;+ }+ auto zero_point = ov::op::v0::Constant::create(ov::element::f32, metadata_shape, offsets);+ auto scale = ov::op::v0::Constant::create(ov::element::f32, metadata_shape, scales);+ ov::Output<ov::Node> shifted;+ if (offset_op == WeightOffset::ADD)+ shifted = std::make_shared<ov::op::v1::Add>(multiply->input_value(0), zero_point);+ else if (offset_op == WeightOffset::SUBTRACT)+ shifted = std::make_shared<ov::op::v1::Subtract>(multiply->input_value(0), zero_point);+ else+ shifted = std::make_shared<ov::op::v1::Subtract>(zero_point, multiply->input_value(0));+ // Reuse zero_point within the expression as well as across projections.+ ov::Output<ov::Node> weight =+ std::make_shared<ov::op::v1::Add>(std::make_shared<ov::op::v1::Multiply>(shifted, scale), zero_point);+ // A lower-rank constant is shared, even when its feature size equals E+ // (group_size == E == 4). It must not be sliced as an expert operand.+ const auto width = weight.get_shape().back();+ std::vector<float> feature_scales(width);+ for (size_t i = 0; i < width; ++i)+ feature_scales[i] = static_cast<float>(i + 1) / static_cast<float>(width);+ auto feature_scale = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{width}, feature_scales);+ feature_scale->set_friendly_name("shared_feature_scale_" + matmul->get_friendly_name());+ weight = std::make_shared<ov::op::v1::Multiply>(weight, feature_scale);+ if (grouped)+ weight = std::make_shared<ov::op::v1::Reshape>(+ weight,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{weight_shape.size()}, weight_shape),+ false);+ auto converted = std::make_shared<ov::op::v0::Convert>(weight, ov::element::f32);+ matmul->input(1).replace_source_output(converted);+ if (!shared_weight)+ shared_weight = converted;+ }+ graph.model->validate_nodes_and_infer_types();+ const auto topology = ov::npuw::moe::match_batched_moe(graph.scatter);+ ASSERT_TRUE(topology) << "The host regression must exercise a supported structural contract";++ auto hidden = graph.model->get_parameters()[0];+ auto scores = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, topology->broadcast_scores.get_shape());+ scores->set_friendly_name("router_scores");+ topology->weighted_output->input(1).replace_source_output(scores);+ auto reference =+ std::make_shared<ov::Model>(ov::OutputVector{topology->reduction}, ov::ParameterVector{hidden, scores});+ auto host = reference->clone();+ ov::TensorVector inputs{ov::Tensor(ov::element::f32, hidden->get_shape()),+ ov::Tensor(ov::element::f32, scores->get_shape())};+ // Reproduce the host partition boundary: packed weights, zero points and+ // scales, including the lower-rank shared feature scale, become closures.+ for (const auto& node : host->get_ordered_ops()) {+ const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node);+ if (!constant ||+ (constant->get_shape().size() < 3 && constant->get_friendly_name().find("shared_feature_scale_") != 0))+ continue;+ auto parameter = std::make_shared<ov::op::v0::Parameter>(constant->get_element_type(), constant->get_shape());+ parameter->set_friendly_name(constant->get_friendly_name());+ host->add_parameters({parameter});+ ov::Tensor tensor(constant->get_element_type(), constant->get_shape());+ std::memcpy(tensor.data(), constant->get_data_ptr(), tensor.get_byte_size());+ inputs.push_back(tensor);+ ov::replace_node(constant, parameter);+ }+ host->validate_nodes_and_infer_types();+ const auto experts = ov::npuw::function::MoEExperts::from(host, k, 16);+ ASSERT_TRUE(experts);+ const auto& transformed = experts->_transformed_models.at(0);+ ASSERT_EQ(transformed->get_parameters().size(), 1 + k * (host->get_parameters().size() - 1));+ for (size_t pi = 1; pi < host->get_parameters().size(); ++pi) {+ ASSERT_TRUE(experts->_param_mapping.count(pi)) << host->get_parameters()[pi]->get_friendly_name();+ ASSERT_EQ(experts->_param_mapping.at(pi).size(), k);+ auto shape = host->get_parameters()[pi]->get_shape();+ if (shape.size() >= 3 && shape[0] == 4)+ shape[0] = 1;+ for (const auto index : experts->_param_mapping.at(pi)) {+ const auto& parameter = transformed->get_parameters().at(index);+ EXPECT_EQ(parameter->get_shape(), shape);+ EXPECT_EQ(parameter->get_element_type(), host->get_parameters()[pi]->get_element_type());+ }+ }++ for (const auto& selection : {std::vector<size_t>{3, 1}, std::vector<size_t>{2, 0}}) {+ for (size_t i = 0; i < inputs[0].get_size(); ++i)+ inputs[0].data<float>()[i] = static_cast<float>(static_cast<int>(i % 5) - 2) / 8.0f;+ std::fill_n(inputs[1].data<float>(), inputs[1].get_size(), 0.0f);+ for (size_t slot = 0; slot < k; ++slot)+ inputs[1].data<float>()[selection[slot]] = slot == 0 ? 0.75f : -0.25f;+ ov::TensorVector selected_inputs(transformed->get_parameters().size());+ selected_inputs.at(experts->_expert_input.compiled.value()) = inputs[0];+ for (size_t pi = 1; pi < inputs.size(); ++pi) {+ for (size_t slot = 0; slot < k; ++slot) {+ const auto& source = inputs[pi];+ auto selected = source.get_shape().size() >= 3 && source.get_shape()[0] == 4+ ? ov::npuw::moe::slice_expert_weight(source, selection[slot], 4)+ : source;+ selected_inputs.at(experts->_param_mapping.at(pi)[slot]) = selected;+ }+ }+ ov::TensorVector expected{ov::Tensor(ov::element::f32, reference->get_output_shape(0))};+ ov::TensorVector actual{ov::Tensor(ov::element::f32, transformed->get_output_shape(0))};+ ASSERT_TRUE(reference->evaluate(expected, {inputs[0], inputs[1]}));+ ASSERT_TRUE(transformed->evaluate(actual, selected_inputs));+ ASSERT_EQ(expected[0].get_shape(), actual[0].get_shape());+ for (size_t i = 0; i < actual[0].get_size(); ++i)+ EXPECT_NEAR(actual[0].data<float>()[i], expected[0].data<float>()[i], 1e-5f);+ }+}++INSTANTIATE_TEST_SUITE_P(+ HostDequantization,+ GenericMoEHostWeightChainTest,+ ::testing::Combine(::testing::Bool(),+ ::testing::Values(WeightOffset::ADD, WeightOffset::SUBTRACT, WeightOffset::REVERSE_SUBTRACT),+ ::testing::Bool(),+ ::testing::Values(size_t{1}, size_t{2})));++TEST(GenericMoETopologyTest, HostUnrollRejectsUnsupportedWeightArithmeticWithoutMutation) {+ for (const bool pdpd : {false, true}) {+ auto input = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{4, 1, 8});+ auto weights = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{4, 8, 8});+ auto scales = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{4, 8, 1});+ ov::Output<ov::Node> expression;+ if (pdpd)+ expression =+ std::make_shared<ov::op::v1::Multiply>(weights,+ scales,+ ov::op::AutoBroadcastSpec(ov::op::AutoBroadcastType::PDPD, 0));+ else+ expression = std::make_shared<ov::op::v1::Divide>(weights, scales);+ auto matmul = std::make_shared<ov::op::v0::MatMul>(input, expression, false, true);+ auto model = std::make_shared<ov::Model>(ov::OutputVector{matmul}, ov::ParameterVector{input, weights, scales});+ const auto before = model->get_ordered_ops();+ const auto parameters = model->get_parameters();+ ov::pass::GraphRewrite rewrite;+ rewrite.add_matcher<ov::npuw::pass::UnrollMoEMatMul>(model);+ EXPECT_FALSE(rewrite.run_on_model(model));+ EXPECT_EQ(before, model->get_ordered_ops());+ EXPECT_EQ(parameters, model->get_parameters());+ }+}++TEST(GenericMoETopologyTest, PrefillTokenCountEqualToHiddenSizeDoesNotReshapeHidden) {+ auto model = make_host_expert_model(true, 8);+ auto experts = ov::npuw::function::MoEExperts::from(model, 2, 3);+ ASSERT_TRUE(experts);+ const auto& transformed = experts->_transformed_models.at(3);+ EXPECT_EQ(transformed->get_output_shape(0), (ov::Shape{1, 3, 8}));+ const auto hidden = transformed->get_parameters().at(experts->_expert_input.compiled.value());+ EXPECT_EQ(hidden->get_shape(), (ov::Shape{3, 8}));+}++TEST(GenericMoETopologyTest, HostRejectsUnsupportedActivationAndRouterParameterLayouts) {+ auto activation = make_host_expert_model(false, 1);+ activation->get_parameters()[0]->set_partial_shape(ov::Shape{1, 1, 8});+ activation->validate_nodes_and_infer_types();+ EXPECT_FALSE(ov::npuw::function::MoEExperts::from(activation, 2, 3));++ auto router = make_host_expert_model(false, 1);+ router->get_parameters()[1]->set_partial_shape(ov::Shape{4, 1, 1, 1, 1});+ router->validate_nodes_and_infer_types();+ EXPECT_FALSE(ov::npuw::function::MoEExperts::from(router, 2, 3));+}++TEST(GenericMoETopologyTest, HostPrefillResizesOnlyTokensAcrossAnExpertOutputConvert) {+ for (const bool grouped : {false, true}) {+ auto model = make_host_expert_model(grouped, 7, true);+ const auto original_params = model->get_parameters();+ auto experts = ov::npuw::function::MoEExperts::from(model, 2, 3);+ ASSERT_TRUE(experts);+ const auto& transformed = experts->_transformed_models.at(3);+ EXPECT_EQ(transformed->get_output_shape(0), (ov::Shape{1, 3, 8}));+ EXPECT_EQ(transformed->get_parameters().at(experts->_expert_input.compiled.value())->get_shape(),+ (ov::Shape{3, 8}));+ ASSERT_EQ(original_params.size(), transformed->get_parameters().size());+ for (size_t i = 2; i < original_params.size(); ++i) {+ auto expected = original_params[i]->get_shape();+ expected[0] = 1;+ EXPECT_EQ(transformed->get_parameters()[i]->get_shape(), expected);+ }+ }+}++TEST(GenericMoERuntimeTest, KeepsTinySignedScoresAndSkipsOnlyExactZero) {+ ov::Tensor scores(ov::element::f32, ov::Shape{4, 1, 1});+ const std::vector<float> values{0.0f, 1e-9f, -1e-10f, 0.5f};+ std::copy(values.begin(), values.end(), scores.data<float>());+ std::map<size_t, std::vector<size_t>> tokens, experts;+ auto selected = ov::npuw::moe::parse_selected_experts_from_router(ov::get_tensor_impl(scores), 4, tokens, experts);+ EXPECT_EQ(selected, (std::vector<size_t>{1, 2, 3}));+ EXPECT_EQ(tokens.at(0), selected);+ std::fill_n(scores.data<float>(), 4, 0.0f);+ EXPECT_TRUE(+ ov::npuw::moe::parse_selected_experts_from_router(ov::get_tensor_impl(scores), 4, tokens, experts).empty());+ scores.data<float>()[0] = std::numeric_limits<float>::quiet_NaN();+ EXPECT_THROW(ov::npuw::moe::parse_selected_experts_from_router(ov::get_tensor_impl(scores), 4, tokens, experts),+ ov::Exception);+}++TEST(GenericMoERuntimeTest, ValidatesSubByteExpertBoundariesAndIndices) {+ ov::Tensor aligned(ov::element::i4, ov::Shape{4, 2, 4});+ EXPECT_EQ(ov::npuw::moe::slice_expert_weight(aligned, 3, 4).get_shape(), (ov::Shape{1, 2, 4}));+ EXPECT_THROW(ov::npuw::moe::slice_expert_weight(aligned, 4, 4), ov::Exception);+ ov::Tensor unaligned(ov::element::i4, ov::Shape{4, 3, 1});+ EXPECT_THROW(ov::npuw::moe::slice_expert_weight(unaligned, 1, 4), ov::Exception);+}++} // 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 5522808c80e..43268e2b8de 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@@ -23,6 +23,7 @@#include "partitioning/online/compiler.hpp"#include "partitioning/online/snapshot.hpp"#include "partitioning/partitioning.hpp"+#include "partitioning/patterns/fold_const.hpp"#include "partitioning/patterns/moe.hpp"/*@@ -799,6 +800,62 @@ TEST_F(MoETransformationTest, Qwen3MoE_OnlinePartitionerIsolatesExpert) {EXPECT_GE(count_groups_with_tag(ens, "expert"), 1u) << "Qwen3Expert did not isolate any expert group";}+TEST_F(MoETransformationTest, GenericPresetPreservesLegacyExpertCoverageForPrefillAndDecode) {+ const std::vector<std::pair<std::string, std::function<std::shared_ptr<ov::Model>()>>> builders{+ {"GPTOSS", ov::test::npuw::build_moe_llm_test_model},+ {"Qwen3", ov::test::npuw::build_qwen3_moe_llm_test_model},+ {"Gemma4", ov::test::npuw::build_gemma4_moe_llm_test_model}};+ const auto expert_layers = [](const ov::npuw::Ensemble& ensemble) {+ std::set<std::string> layers;+ for (const auto& group : ensemble.groups) {+ if (group.gettag() == "expert")+ layers.insert(group.all_layers.begin(), group.all_layers.end());+ }+ return layers;+ };+ for (const auto& [name, build] : builders) {+ for (const int64_t tokens : {1, 8}) {+ SCOPED_TRACE(name + "/tokens=" + std::to_string(tokens));+ auto model = build();+ ov::pass::StatefulToStateless().run_on_model(model);+ std::map<std::string, ov::PartialShape> shapes;+ for (const auto& input : model->inputs()) {+ const auto input_name = input.get_any_name();+ auto shape = input.get_partial_shape();+ shape[0] = 1;+ // Empty past keeps Gemma's token-type mask aligned with the+ // current sequence; this test compares expert isolation only.+ if (input_name.find("past_key_values") != std::string::npos)+ shape[2] = 0;+ else+ shape[1] = tokens;+ shapes[input_name] = shape;+ }+ model->reshape(shapes);+ ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(model);+ auto legacy_config = make_moe_isolate_cfg();+ legacy_config.update({{"NPUW_ONLINE_ISOLATE",+ "P:GPTOSSExpert/expert,P:GPTOSSRouter/router,P:Qwen3Expert/expert,"+ "P:Qwen3Router/router,P:Gemma4Expert/expert,P:Gemma4Router/router"}});+ const auto baseline = expert_layers(ov::npuw::online::buildPartitioning(model->clone(), legacy_config));+ ASSERT_FALSE(baseline.empty());+ auto combined_config = make_moe_isolate_cfg();+ const auto combined = expert_layers(ov::npuw::online::buildPartitioning(model, combined_config));+ for (const auto& layer : baseline)+ EXPECT_TRUE(combined.count(layer)) << "Lost legacy expert layer " << layer;+ size_t tagged = 0;+ for (const auto& node : model->get_ordered_ops()) {+ if (ov::is_type<ov::op::v11::TopK>(node)) {+ ASSERT_TRUE(node->get_rt_info().count(ov::npuw::patterns::moe::RT_INFO_MOE_K));+ EXPECT_EQ(node->get_rt_info().at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), 2u);+ ++tagged;+ }+ }+ EXPECT_EQ(tagged, 2u);+ }+ }+}+// End-to-end against the *production* MoE pipeline (not just the matchers): the full// ApplyMoEDeviceRoutedTransforms pass — DeviceRoutedMoETransform followed by GatherTo2DGather,// exactly what production runs — must accept the builder's Qwen3 MoE and rewrite it into thediff --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.cppindex 1354d38f88d..c47f5bf3171 100644--- 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@@ -24,7 +24,7 @@* - Convert(Parameter)* - Multiply(Constant, Parameter)* - Multiply(Parameter, Constant) -- symmetric check- * - Add(Constant, Constant) -- unrecognized op type+ * - Divide(Constant, Constant) -- unrecognized op type*/namespace {@@ -100,11 +100,20 @@ TEST(IsconstantDerivedTest, MultiplyParameterAndConstant) {}TEST(IsconstantDerivedTest, UnrecognizedOpType) {- // Add is not handled by is_constant_derived — must return false+ // Arbitrary constant arithmetic is not part of a recognized weight chain.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));+ auto divide = std::make_shared<ov::op::v1::Divide>(c0, c1);+ EXPECT_FALSE(is_constant_derived(divide));+}++TEST(IsconstantDerivedTest, GroupedDequantizationView) {+ auto weights = make_const_f32({4, 8, 2, 4});+ auto zero_point = make_const_f32({4, 8, 2, 1});+ auto shifted = std::make_shared<ov::op::v1::Subtract>(weights, zero_point);+ auto scaled = std::make_shared<ov::op::v1::Multiply>(shifted, zero_point);+ auto shape = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {4, 8, 8});+ EXPECT_TRUE(is_constant_derived(std::make_shared<ov::op::v1::Reshape>(scaled, shape, false)));}} // namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/online_partitioning.cpp b/src/plugins/intel_npu/tests/unit/npuw/online_partitioning.cppindex 436bb3d2939..10a9e761a42 100644--- a/src/plugins/intel_npu/tests/unit/npuw/online_partitioning.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/online_partitioning.cpp@@ -125,7 +125,6 @@ TEST(OnlinePartitioningTest, Partitioning_IsTheSame_SmallModel) {}}-TEST(OnlinePartitioningTest, Partitioning_IsTheSame_RepeatedModel) {ModelBuilder mb;auto model = mb.get_model_with_repeated_blocks();diff --git a/src/plugins/intel_npu/tests/unit/npuw/subgraph_behavior_infer_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/subgraph_behavior_infer_test.cppindex d1177bc80f6..e898f89c448 100644--- a/src/plugins/intel_npu/tests/unit/npuw/subgraph_behavior_infer_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/subgraph_behavior_infer_test.cpp@@ -6,14 +6,22 @@#include <algorithm>#include <any>+#include <array>#include <atomic>#include <cstring>#include <functional>+#include <limits>#include <map>-#include <numeric>#include <mutex>+#include <numeric>+#include <set>#include <vector>+// Parse OpenVINO's exported classes before the private-access test shim;+// changing Constant's access specifiers changes imported symbol names on MSVC.+#include "openvino/op/ops.hpp"+#include "openvino/openvino.hpp"+#define private public#include "compiled_model.hpp"#undef private@@ -22,13 +30,14 @@#include "just_sync_infer_request.hpp"#include "llm_test_helpers.hpp"#include "model_builder.hpp"+#include "moe/moe_subgraph.hpp"#include "npuw_transformations/optimize_value_tensors.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/pass/stateful_to_stateless.hpp"+#include "openvino/runtime/make_tensor.hpp"#include "partitioning/patterns/sdpa.hpp"#include "pyramid_attention.hpp"#include "unfold_sync_infer_request.hpp"-#include "openvino/op/scaled_dot_product_attention.hpp"-#include "openvino/openvino.hpp"-#include "openvino/pass/stateful_to_stateless.hpp"#include "unit_test_utils/mocks/openvino/runtime/mock_icore.hpp"namespace {@@ -43,6 +52,12 @@ struct BehaviorHits {std::vector<std::pair<std::size_t, std::size_t>> values;};+struct EvaluationLog {+ std::mutex mutex;+ std::map<const ov::ICompiledModel*, std::vector<const ov::ISyncInferRequest*>> executions;+ std::atomic<size_t> pending{0};+};+class TestPlugin final : public ov::IPlugin {public:std::shared_ptr<ov::ICompiledModel> compile_model(const std::shared_ptr<const ov::Model>&,@@ -178,11 +193,23 @@ private:class FakeSubAsyncInferRequest final : public ov::IAsyncInferRequest {public:- explicit FakeSubAsyncInferRequest(const std::shared_ptr<ov::ISyncInferRequest>& request)+ explicit FakeSubAsyncInferRequest(const std::shared_ptr<ov::ISyncInferRequest>& request,+ std::shared_ptr<EvaluationLog> evaluation = {}): ov::IAsyncInferRequest(nullptr, nullptr, nullptr),- m_request(request) {}+ m_request(request),+ m_evaluation(std::move(evaluation)) {}void start_async() override {+ if (m_evaluation) {+ OPENVINO_ASSERT(!m_pending, "Test request is still pending");+ m_pending = true;+ ++m_evaluation->pending;+ return;+ }+ complete();+ }++ void complete() {try {m_request->infer();if (m_callback) {@@ -197,9 +224,16 @@ public:}}- void wait() override {}+ void wait() override {+ if (m_pending) {+ m_pending = false;+ --m_evaluation->pending;+ complete();+ }+ }bool wait_for(const std::chrono::milliseconds&) override {+ wait();return true;}@@ -210,6 +244,7 @@ public:}void infer() override {+ OPENVINO_ASSERT(!m_pending, "Test request is still pending");m_request->infer();}@@ -222,6 +257,7 @@ public:}void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override {+ OPENVINO_ASSERT(!m_pending, "Cannot rebind a pending test request");m_request->set_tensor(port, tensor);}@@ -253,21 +289,29 @@ public:private:std::shared_ptr<ov::ISyncInferRequest> m_request;std::function<void(std::exception_ptr)> m_callback;+ std::shared_ptr<EvaluationLog> m_evaluation;+ bool m_pending = false;};- class FakeSubCompiledModel final : public ov::ICompiledModel {+class FakeSubCompiledModel final : public ov::ICompiledModel {public:FakeSubCompiledModel(const std::shared_ptr<ov::Model>& model,const std::shared_ptr<const ov::IPlugin>& plugin,- bool own_ports_only = false)+ bool own_ports_only = false,+ std::shared_ptr<EvaluationLog> evaluation = {}): ov::ICompiledModel(model, plugin, nullptr, nullptr),m_model(model),- m_own_ports_only(own_ports_only) {}+ m_own_ports_only(own_ports_only),+ m_evaluation(std::move(evaluation)) {}bool own_ports_only() const {return m_own_ports_only;}+ const std::shared_ptr<EvaluationLog>& evaluation_log() const {+ return m_evaluation;+ }+void export_model(std::ostream&) const override {}std::shared_ptr<const ov::Model> get_runtime_model() const override {return m_model;@@ -284,12 +328,13 @@ public:return std::make_shared<FakeSubInferRequest>(std::move(self));}std::shared_ptr<ov::IAsyncInferRequest> create_infer_request() const override {- return std::make_shared<FakeSubAsyncInferRequest>(create_sync_infer_request());+ return std::make_shared<FakeSubAsyncInferRequest>(create_sync_infer_request(), m_evaluation);}private:std::shared_ptr<ov::Model> m_model;bool m_own_ports_only = false;+ std::shared_ptr<EvaluationLog> m_evaluation;};// When the compiled submodels are imported from a cache, each blob gets its own I/O nodes@@ -315,12 +360,30 @@ FakeSubInferRequest::FakeSubInferRequest(std::shared_ptr<const FakeSubCompiledMoov::get_tensor_impl(ov::Tensor(input.get_element_type(), input.get_shape())));}for (const auto& output : get_compiled_model()->outputs()) {- ov::ISyncInferRequest::set_tensor(output,- ov::get_tensor_impl(ov::Tensor(output.get_element_type(), output.get_shape())));+ ov::ISyncInferRequest::set_tensor(+ output,+ ov::get_tensor_impl(ov::Tensor(output.get_element_type(), output.get_shape())));+ }+ // Sparse request pools run a warmup before bindings are populated.+ for (const auto& input : get_compiled_model()->inputs()) {+ auto tensor = ov::ISyncInferRequest::get_tensor(input);+ std::memset(tensor->data(), 0, tensor->get_byte_size());}}void FakeSubInferRequest::infer() {+ const auto compiled = std::static_pointer_cast<const FakeSubCompiledModel>(get_compiled_model());+ if (const auto& log = compiled->evaluation_log()) {+ ov::TensorVector inputs, outputs;+ for (const auto& port : compiled->inputs())+ inputs.push_back(ov::make_tensor(ov::ISyncInferRequest::get_tensor(port)));+ for (const auto& port : compiled->outputs())+ outputs.push_back(ov::make_tensor(ov::ISyncInferRequest::get_tensor(port)));+ OPENVINO_ASSERT(compiled->get_runtime_model()->evaluate(outputs, inputs), "Test model evaluation failed");+ std::lock_guard<std::mutex> lock(log->mutex);+ log->executions[compiled.get()].push_back(this);+ return;+ }for (const auto& output : get_compiled_model()->outputs()) {auto tensor = ov::ISyncInferRequest::get_tensor(output);std::memset(tensor->data(), 0, tensor->get_byte_size());@@ -350,7 +413,8 @@ protected:return props;}std::shared_ptr<testing::NiceMock<ov::MockICore>> make_core(const std::shared_ptr<const ov::IPlugin>& plugin,- bool own_ports_only = false) const {+ bool own_ports_only = false,+ std::shared_ptr<EvaluationLog> evaluation = {}) const {auto core = std::make_shared<testing::NiceMock<ov::MockICore>>();ON_CALL(*core, get_supported_property(testing::_, testing::_, testing::_))@@ -393,19 +457,238 @@ protected:compile_model(testing::Matcher<const std::shared_ptr<const ov::Model>&>(testing::_),testing::Matcher<const std::string&>(testing::StrEq("CPU")),testing::Matcher<const ov::AnyMap&>(testing::_)))- .WillByDefault([plugin, own_ports_only](const std::shared_ptr<const ov::Model>& submodel,- const std::string&,- const ov::AnyMap&) {+ .WillByDefault([plugin, own_ports_only, evaluation](const std::shared_ptr<const ov::Model>& submodel,+ const std::string&,+ const ov::AnyMap&) {return ov::SoPtr<ov::ICompiledModel>{std::make_shared<FakeSubCompiledModel>(std::const_pointer_cast<ov::Model>(submodel),plugin,- own_ports_only)};+ own_ports_only,+ evaluation)};});return core;}};+std::shared_ptr<ov::Model> build_moe_dispatch_test_model(size_t tokens, bool weight_offsets = false) {+ constexpr size_t experts = 4, hidden = 8, intermediate = 16, k = 2;+ auto x = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{tokens, hidden});+ auto router = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{tokens, experts});+ auto scores = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{tokens, k});+ x->output(0).set_names({"hidden"});+ router->output(0).set_names({"logits"});+ scores->output(0).set_names({"scores"});+ auto hidden_state = std::make_shared<ov::op::v0::Tanh>(x);+ hidden_state->set_friendly_name("upstream_hidden");+ auto topk = std::make_shared<ov::op::v11::TopK>(router,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {k}),+ 1,+ ov::op::v11::TopK::Mode::MAX,+ ov::op::v11::TopK::SortType::SORT_VALUES);+ ov::OutputVector outputs;+ for (size_t layer = 0; layer < 2; ++layer) {+ auto weight = [layer, experts, weight_offsets](size_t out, size_t in, size_t seed) -> ov::Output<ov::Node> {+ std::vector<float> values(experts * out * in);+ for (size_t i = 0; i < values.size(); ++i)+ values[i] = (static_cast<float>((i + seed + layer + i / (out * in)) % 11) - 5.0f) / 16.0f;+ if (!weight_offsets)+ return ov::op::v0::Constant::create(ov::element::f32, ov::Shape{experts, out, in}, values);++ const ov::Shape grouped_shape{experts, out, in / 4, 4};+ std::vector<int8_t> packed_values(values.size());+ for (size_t i = 0; i < packed_values.size(); ++i)+ packed_values[i] = static_cast<int8_t>((i + seed + layer + i / (out * in)) % 8) - 4;+ auto packed = ov::op::v0::Constant::create(ov::element::i4, grouped_shape, packed_values);+ const ov::Shape offset_shape{1, out, in / 4, 1};+ const ov::Shape scale_shape{experts, out, in / 4, 1};+ std::vector<float> offsets(ov::shape_size(offset_shape)), scales(ov::shape_size(scale_shape));+ for (size_t i = 0; i < offsets.size(); ++i)+ offsets[i] = static_cast<float>(1 + (i + layer) % 5) / 8.0f;+ for (size_t i = 0; i < scales.size(); ++i)+ scales[i] = static_cast<float>(1 + (i + seed) % 7) / 32.0f;+ auto zero_point = ov::op::v0::Constant::create(ov::element::f32, offset_shape, offsets);+ auto shifted =+ std::make_shared<ov::op::v1::Subtract>(std::make_shared<ov::op::v0::Convert>(packed, ov::element::f32),+ zero_point);+ auto scaled = std::make_shared<ov::op::v1::Multiply>(+ shifted,+ ov::op::v0::Constant::create(ov::element::f32, scale_shape, scales));+ auto biased = std::make_shared<ov::op::v1::Add>(scaled, zero_point);+ return std::make_shared<ov::op::v1::Reshape>(+ biased,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {experts, out, in}),+ false);+ };+ auto tile = std::make_shared<ov::op::v0::Tile>(+ hidden_state,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {experts, size_t{1}}));+ auto expanded = std::make_shared<ov::op::v1::Reshape>(+ tile,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {experts, tokens, hidden}),+ false);+ auto gate = std::make_shared<ov::op::v0::MatMul>(expanded, weight(intermediate, hidden, 1), false, true);+ auto up = std::make_shared<ov::op::v0::MatMul>(expanded, weight(intermediate, hidden, 2), false, true);+ auto activated = std::make_shared<ov::op::v1::Multiply>(std::make_shared<ov::op::v4::Swish>(gate), up);+ auto down = std::make_shared<ov::op::v0::MatMul>(activated, weight(hidden, intermediate, 3), false, true);+ auto expert = std::make_shared<ov::op::v1::Reshape>(+ down,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {experts, tokens, hidden}),+ false);+ auto scatter = std::make_shared<ov::op::v12::ScatterElementsUpdate>(+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{tokens, experts}, {0.0f}),+ topk->output(1),+ scores,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {1}));+ auto transposed = std::make_shared<ov::op::v1::Transpose>(+ scatter,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {1, 0}));+ auto mixing = std::make_shared<ov::op::v1::Reshape>(+ transposed,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, {experts, tokens, size_t{1}}),+ false);+ outputs.push_back(+ std::make_shared<ov::op::v1::ReduceSum>(std::make_shared<ov::op::v1::Multiply>(expert, mixing),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}),+ false));+ }+ return std::make_shared<ov::Model>(outputs, ov::ParameterVector{x, router, scores}, "moe_dispatch_regression");+}++class MoEWeightChainDispatchTest : public SubgraphBehaviorInferTest, public ::testing::WithParamInterface<bool> {};++TEST_P(MoEWeightChainDispatchTest, MoESparseDispatchPreservesScoresUpstreamInputsAndCachedRequests) {+ for (const size_t tokens : {size_t{1}, size_t{7}}) {+ SCOPED_TRACE(tokens);+ auto model = build_moe_dispatch_test_model(tokens, GetParam());+ auto evaluation = std::make_shared<EvaluationLog>();+ auto plugin = std::make_shared<TestPlugin>();+ auto core = make_core(plugin, false, evaluation);+ plugin->set_core(core);+ ov::AnyMap props{{"NPUW_DEVICES", "CPU"},+ {"NPUW_FALLBACK_EXEC", "NO"},+ {"NPUW_FOLD", "YES"},+ {"NPUW_FUNCALL_FOR_ALL", "YES"},+ {"NPUW_UNFOLD_IREQS", "NO"},+ {"NPUW_ONLINE_PIPELINE", "REP"},+ {"NPUW_ONLINE_ISOLATE", "MOE"},+ {"NPUW_ONLINE_KEEP_BLOCKS_TAGGED", "expert"},+ {"NPUW_ONLINE_KEEP_BLOCK_SIZE", "4"},+ {"NPUW_F16IC", "NO"},+ {"NPUW_DQ", "NO"},+ {"NPUW_MOE_POOL_SIZE", "2"},+ {"NPUW_MOE_TOKEN_CHUNK_SIZE", "3"}};+ auto compiled = std::make_shared<ov::npuw::CompiledModel>(model->clone(), plugin, props);+ std::set<const ov::ICompiledModel*> expert_models;+ size_t expert_calls = 0;+ for (const auto& desc : compiled->m_compiled_submodels) {+ const auto real = desc.replaced_by ? &compiled->m_compiled_submodels.at(*desc.replaced_by) : &desc;+ if (const auto* state = ov::npuw::moe::get_compiled_experts(real->pipeline.context)) {+ ++expert_calls;+ EXPECT_EQ(state->num_active_experts, 2u);+ EXPECT_EQ(state->input_token_count, tokens);+ ASSERT_TRUE(state->_expert_input.original.has_value());+ const auto call_idx = static_cast<size_t>(&desc - compiled->m_compiled_submodels.data());+ EXPECT_TRUE(compiled->m_submodels_input_to_prev_output.count(+ {call_idx, state->_expert_input.original.value()}));+ for (const auto& [chunk, submodel] : state->_compiled_models)+ expert_models.insert(submodel._ptr.get());+ }+ }+ ASSERT_EQ(expert_calls, 2u) << "Must test the actual sparse executor, not a dense fallback";+ auto request = compiled->create_infer_request();+ evaluation->executions.clear(); // Exclude request-pool warmups.+ const auto history = [&]() {+ std::vector<const ov::ISyncInferRequest*> result;+ std::lock_guard<std::mutex> lock(evaluation->mutex);+ for (const auto* submodel : expert_models) {+ const auto& calls = evaluation->executions[submodel];+ result.insert(result.end(), calls.begin(), calls.end());+ }+ return result;+ };+ ov::TensorVector inputs;+ for (const auto& port : model->inputs())+ inputs.emplace_back(port.get_element_type(), port.get_shape());+ const auto check = [&]() {+ ov::TensorVector expected;+ for (const auto& port : model->outputs())+ expected.emplace_back(port.get_element_type(), port.get_shape());+ ASSERT_TRUE(model->evaluate(expected, inputs));+ for (size_t i = 0; i < inputs.size(); ++i)+ request->set_tensor(compiled->inputs()[i], ov::get_tensor_impl(inputs[i]));+ request->infer();+ EXPECT_EQ(evaluation->pending.load(), 0u);+ for (size_t i = 0; i < expected.size(); ++i) {+ const auto actual = request->get_tensor(compiled->outputs()[i]);+ ASSERT_EQ(actual->get_shape(), expected[i].get_shape());+ for (size_t element = 0; element < expected[i].get_size(); ++element)+ EXPECT_NEAR(actual->data<float>()[element], expected[i].data<float>()[element], 1e-5f);+ }+ };+ const std::vector<std::array<float, 2>> scores{{0.7f, 0.3f},+ {0.0f, 0.9f},+ {-0.4f, 0.8f},+ {0.0f, 0.0f},+ {0.6f, 0.0f},+ {0.7f, 0.3f},+ {0.0f, 0.9f},+ {1e-7f, -2e-8f}};+ for (size_t iteration = 0; iteration < scores.size(); ++iteration) {+ for (size_t i = 0; i < inputs[0].get_size(); ++i)+ inputs[0].data<float>()[i] = (static_cast<float>((i + iteration) % 9) - 4.0f) / 8.0f;+ std::fill_n(inputs[1].data<float>(), inputs[1].get_size(), -2.0f);+ for (size_t token = 0; token < tokens; ++token) {+ const size_t first = (iteration % 2 == 0 ? 0 : 1) + token;+ const size_t second = (iteration % 2 == 0 ? 1 : 3) + token;+ inputs[1].data<float>()[4 * token + first % 4] = 2.0f;+ inputs[1].data<float>()[4 * token + second % 4] = 1.0f;+ inputs[2].data<float>()[2 * token] = scores[iteration][0];+ inputs[2].data<float>()[2 * token + 1] = scores[iteration][1];+ }+ const auto before = history().size();+ check();+ if (scores[iteration][0] == 0.0f && scores[iteration][1] == 0.0f) {+ EXPECT_EQ(history().size(), before);+ for (const auto& port : compiled->outputs()) {+ const auto tensor = request->get_tensor(port);+ for (size_t i = 0; i < ov::shape_size(tensor->get_shape()); ++i)+ EXPECT_FLOAT_EQ(tensor->data<float>()[i], 0.0f);+ }+ } else if (tokens == 1) {+ EXPECT_EQ(history().size() - before, 2u); // One K-expert inference per layer.+ } else {+ EXPECT_GT(history().size(), before);+ }+ }+ if (tokens == 1) {+ const auto calls = history();+ ASSERT_EQ(calls.size(), 14u);+ // The first and third iterations select the same expert set with+ // different scores, separated by a different cached selection.+ EXPECT_EQ(calls[0], calls[4]);+ EXPECT_EQ(calls[1], calls[5]);+ EXPECT_NE(calls[0], calls[2]);+ } else {+ // Expert 0 starts before parse-ahead sees expert 1's invalid score.+ std::fill_n(inputs[1].data<float>(), inputs[1].get_size(), -2.0f);+ for (size_t token = 0; token < tokens; ++token) {+ inputs[1].data<float>()[4 * token] = 2.0f;+ inputs[1].data<float>()[4 * token + 1] = 1.0f;+ inputs[2].data<float>()[2 * token] = 0.7f;+ inputs[2].data<float>()[2 * token + 1] = std::numeric_limits<float>::quiet_NaN();+ }+ EXPECT_THROW(request->infer(), ov::Exception);+ EXPECT_EQ(evaluation->pending.load(), 0u) << "Exceptional prefill must drain outstanding chunks";+ for (size_t token = 0; token < tokens; ++token)+ inputs[2].data<float>()[2 * token + 1] = 0.3f;+ check(); // The same request remains usable after validation failure.+ }+ }+}++INSTANTIATE_TEST_SUITE_P(PlainAndOffsetWeights, MoEWeightChainDispatchTest, ::testing::Bool());+TEST_F(SubgraphBehaviorInferTest, SdpaBehaviorCanOverrideStaticLlmSubgraphExecution) {auto baseline_model = build_static_llm_model();ASSERT_GT(count_sdpa_nodes(baseline_model), 0u) << "The synthesized LLM model must contain SDPA nodes";@@ -425,7 +708,8 @@ TEST_F(SubgraphBehaviorInferTest, SdpaBehaviorCanOverrideStaticLlmSubgraphExecutauto behavior_model = build_static_llm_model();ASSERT_GT(count_sdpa_nodes(behavior_model), 0u);ov::npuw::v1::subgraphs::PatternRegistry behavior_registry;- auto behavior_compiled = std::make_shared<ov::npuw::CompiledModel>(behavior_model, plugin, base_props(), &behavior_registry);+ auto behavior_compiled =+ std::make_shared<ov::npuw::CompiledModel>(behavior_model, plugin, base_props(), &behavior_registry);bool attached_behavior = false;for (auto& desc : behavior_compiled->m_compiled_submodels) {if (!desc.compiled_model) {@@ -436,7 +720,8 @@ TEST_F(SubgraphBehaviorInferTest, SdpaBehaviorCanOverrideStaticLlmSubgraphExecutspec.registration.group = "test";spec.registration.name = "record-hit";spec.context.put<std::shared_ptr<BehaviorHits>>(hits);- spec.factory = [](const ov::npuw::v1::subgraphs::Context& ctx) -> ov::npuw::v1::subgraphs::ISubgraphBehavior::Ptr {+ spec.factory =+ [](const ov::npuw::v1::subgraphs::Context& ctx) -> ov::npuw::v1::subgraphs::ISubgraphBehavior::Ptr {const auto recorder = ctx.get<std::shared_ptr<BehaviorHits>>();return std::make_unique<ov::npuw::v1::subgraphs::DirectBehavior>([recorder](ov::npuw::v1::subgraphs::InferContext& infer_ctx) {@@ -470,7 +755,8 @@ TEST_F(SubgraphBehaviorInferTest, RuntimeBehaviorForcesJustInferRequestWhenUnfolauto behavior_model = build_static_llm_model();auto hits = std::make_shared<BehaviorHits>();ov::npuw::v1::subgraphs::PatternRegistry behavior_registry;- auto behavior_compiled = std::make_shared<ov::npuw::CompiledModel>(behavior_model, plugin, unfold_props(), &behavior_registry);+ auto behavior_compiled =+ std::make_shared<ov::npuw::CompiledModel>(behavior_model, plugin, unfold_props(), &behavior_registry);bool attached_behavior = false;for (auto& desc : behavior_compiled->m_compiled_submodels) {@@ -482,7 +768,8 @@ TEST_F(SubgraphBehaviorInferTest, RuntimeBehaviorForcesJustInferRequestWhenUnfolspec.registration.group = "test";spec.registration.name = "record-hit";spec.context.put<std::shared_ptr<BehaviorHits>>(hits);- spec.factory = [](const ov::npuw::v1::subgraphs::Context& ctx) -> ov::npuw::v1::subgraphs::ISubgraphBehavior::Ptr {+ spec.factory =+ [](const ov::npuw::v1::subgraphs::Context& ctx) -> ov::npuw::v1::subgraphs::ISubgraphBehavior::Ptr {const auto recorder = ctx.get<std::shared_ptr<BehaviorHits>>();return std::make_unique<ov::npuw::v1::subgraphs::DirectBehavior>([recorder](ov::npuw::v1::subgraphs::InferContext& infer_ctx) {@@ -541,8 +828,7 @@ TEST_F(SubgraphBehaviorInferTest, DynAttnBehaviorNotAttachedWithStaticAttentionMauto props = base_props();props["NPUW_ATTN"] = std::string("STATIC");auto compiled = std::make_shared<ov::npuw::CompiledModel>(model, plugin, props);- EXPECT_EQ(count_dyn_attn_behaviors(compiled), 0u)- << "DynAttnBehavior must NOT be attached when NPUW_ATTN=STATIC";+ EXPECT_EQ(count_dyn_attn_behaviors(compiled), 0u) << "DynAttnBehavior must NOT be attached when NPUW_ATTN=STATIC";}TEST_F(SubgraphBehaviorInferTest, DynAttnBehaviorNotAttachedWithoutAttnIsolation) {diff --git a/src/plugins/intel_npu/tests/unit/npuw/subgraph_pipeline.cpp b/src/plugins/intel_npu/tests/unit/npuw/subgraph_pipeline.cppindex 81617a2b4f7..ee2ff7f051f 100644--- a/src/plugins/intel_npu/tests/unit/npuw/subgraph_pipeline.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/subgraph_pipeline.cpp@@ -199,13 +199,24 @@ TEST(SubgraphPipelineBehaviorTest, MoERegistrationBuildsDeferredPartitionPipelinASSERT_TRUE(static_cast<bool>(function._pipeline.partition_stage));ASSERT_TRUE(static_cast<bool>(function._pipeline.compile_stage));EXPECT_EQ(function._pipeline.registration.group, ov::npuw::patterns::moe::GPTOSSExpert::group_name());- EXPECT_EQ(function._pipeline.registration.name, ov::npuw::patterns::moe::GPTOSSExpert::pattern_name());+ EXPECT_EQ(function._pipeline.registration.name, ov::npuw::patterns::moe::BatchedExpert::pattern_name());EXPECT_NE(std::find(function._pipeline.registration.patterns.begin(),function._pipeline.registration.patterns.end(),ov::npuw::patterns::moe::GPTOSSExpert::pattern_name()),function._pipeline.registration.patterns.end());}+TEST(SubgraphPipelineBehaviorTest, MissingExpertTopKMetadataDoesNotSilentlyRunDense) {+ ov::npuw::Function function;+ function.settag(ov::npuw::patterns::moe::BatchedExpert::isolation_tag());+ ov::npuw::v1::subgraphs::PatternRegistry registry;+ auto registrations = ov::npuw::moe::register_patterns(registry, 16u);+ registry.apply(function);++ ASSERT_TRUE(static_cast<bool>(function._pipeline.partition_stage));+ EXPECT_THROW(function._pipeline.partition_stage(function, function._pipeline.context), ov::Exception);+}+// Verify that attn::register_patterns() chains partition_stage and compile_stage on any// Function whose isolation tag matches SDPA::isolation_tag() ("attn").TEST(SubgraphPipelineBehaviorTest, AttnRegistrationSetsPartitionAndCompileStagesForAttnTaggedFunction) {