OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[NPUW][MoE Scaling]Support MoE expert layout variants (#36184)
intelgaoxiong3654766ffdd0
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cppindex 93f468466c7..f94629bc8c5 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp@@ -20,6 +20,7 @@#include "npuw_transformations/reshape_sliced_head_to_static.hpp"#include "npuw_transformations/reshape_to_static.hpp"#include "npuw_transformations/slice_out_embeds.hpp"+#include "npuw_transformations/split_kvcache_into_blocks.hpp"#include "openvino/op/convert.hpp"#include "openvino/op/greater.hpp"#include "openvino/op/ops.hpp"@@ -36,6 +37,7 @@#include "openvino/pass/validate.hpp"#include "openvino/runtime/iasync_infer_request.hpp"#include "openvino/runtime/properties.hpp"+#include "partitioning/patterns/fold_const.hpp"#include "partitioning/patterns/moe.hpp"#include "partitioning/patterns/pre_compute.hpp"#include "partitioning/patterns/sdpa.hpp"@@ -1079,13 +1081,22 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mconst auto generate_moe_hint = m_cfg.get<::intel_npu::NPUW_LLM_GENERATE_MOE_HINT>();apply_moe_config(generate_config, generate_moe_hint, "GENERATE");- // Apply model transformations only to GENERATE stage (PREFILL doesn't support DEVICE_ROUTED transformations)- if (generate_moe_hint == ::intel_npu::npuw::llm::MoEHint::DEVICE_ROUTED) {- LOG_INFO("Applying DEVICE_ROUTED MoE transformations to " << generate_model_variants.size() << " variants");+ // Fold shape-compute chains (ShapeOf→Gather→Concat etc.) in the prefill model before+ // online partitioning runs pattern matching (e.g. GPTOSSRouter). Must run after+ // ReshapeToStatic has made all shapes static so that ShapeOf bounds are resolvable.+ ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(prefill_model);+ if (generate_moe_hint == ::intel_npu::npuw::llm::MoEHint::HOST_ROUTED) {+ for (auto&& model_variant : generate_model_variants) {+ ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(model_variant);+ }+ } else if (generate_moe_hint == ::intel_npu::npuw::llm::MoEHint::DEVICE_ROUTED) {+ // Apply model transformations only to GENERATE stage (PREFILL doesn't support DEVICE_ROUTED+ // transformations)for (auto&& model_variant : generate_model_variants) {ov::npuw::ApplyMoEDeviceRoutedTransforms().run_on_model(model_variant);}- LOG_INFO("DEVICE_ROUTED MoE transformations completed");+ } else {+ OPENVINO_THROW("Unsupported MoE hint: " + std::to_string(static_cast<int>(generate_moe_hint)));}}diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_config.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_config.hppindex e40f30d2a6d..4173bbddc19 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_config.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_config.hpp@@ -36,9 +36,14 @@ struct MoEConfig {// Example: param[5] -> [param[10], param[11], param[12], param[13]] for K=4 expertsstd::map<size_t, std::vector<size_t>> param_mapping;- // Input parameter indices- std::optional<size_t> router_scores_idx; // Index of router scores input- std::optional<size_t> expert_input_param_idx; // Index of expert input (token embeddings)+ // Holds original-model index (for prologue matching / param_mapping lookup)+ // and compiled-model index (for direct port binding after transformation).+ struct ParamIndex {+ std::optional<size_t> original; // index in original model+ std::optional<size_t> compiled; // index in compiled/transformed model+ };+ ParamIndex router_scores; // router scores input parameter+ ParamIndex expert_input; // expert activation input parameter// Compiled models for different chunk sizes (for EXPERT_ITERATIVE mode)// Key: chunk_size (e.g., 256, 128, 64, 32, 16)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 8f0ad760bba..a81d38b3a07 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@@ -45,8 +45,10 @@ void MoEExecutor::prepare(size_t idx, size_t real_idx, size_t num_sublayers, sizm_config.input_token_count = moe_experts->input_token_count;m_config.expert_hidden_dim = moe_experts->expert_hidden_dim;m_config.param_mapping = moe_experts->_param_mapping;- m_config.router_scores_idx = moe_experts->_router_scores_idx;- m_config.expert_input_param_idx = moe_experts->_expert_input_param_idx;+ m_config.router_scores.original = moe_experts->_router_scores.original;+ m_config.router_scores.compiled = moe_experts->_router_scores.compiled;+ m_config.expert_input.original = moe_experts->_expert_input.original;+ m_config.expert_input.compiled = moe_experts->_expert_input.compiled;m_config.compiled_models = moe_experts->_compiled_models;// Validate configuration@@ -137,14 +139,14 @@ bool MoEExecutor::function_prologue_moe_input(size_t idx,// MoE expert layer: handle router scores and expert inputsif (const auto* moe = get_compiled_experts(desc.pipeline.context)) {// Router scores: store for later use in MoE inference- if (moe->_router_scores_idx.has_value() && param_idx == moe->_router_scores_idx.value()) {+ if (moe->_router_scores.original.has_value() && param_idx == moe->_router_scores.original.value()) {NPUW_ASSERT(idx < m_moe_io.size() && "MoEExecutor::prepare() must be called first");m_moe_io[idx].router_scores = i_tensor;return true; // Handled by MoE}// Expert inputs: store for later use (batch mode: cache binding, iterative mode: chunking)- if (moe->_expert_input_param_idx.has_value() && param_idx == moe->_expert_input_param_idx.value()) {+ if (moe->_expert_input.original.has_value() && param_idx == moe->_expert_input.original.value()) {NPUW_ASSERT(idx < m_moe_io.size() && "MoEExecutor::prepare() must be called first");m_moe_io[idx].expert_input = i_tensor;return true; // Handled by MoE@@ -298,8 +300,10 @@ void MoEExecutor::run_expert_batch(size_t idx, size_t real_idx, const std::vecto// Step 4: Bind input/output tensors to cached request (must bind every time as these tensors change)// 4.1: Bind expert input (token embeddings)- if (m_config.expert_input_param_idx.has_value()) {- const auto expert_input_idx = m_config.expert_input_param_idx.value();+ // Use the transformed parameter index to access the compiled model's port correctly.+ // (unroll_expert_dimension may shift the expert_input parameter index relative to the original model)+ if (m_config.expert_input.compiled.has_value()) {+ const auto expert_input_idx = m_config.expert_input.compiled.value();const auto& expert_input_port = desc.compiled_model->inputs()[expert_input_idx];auto expert_input_tensor = io.expert_input;if (!expert_input_tensor) {@@ -342,10 +346,10 @@ void MoEExecutor::run_expert_iterative(size_t idx, size_t real_idx, const std::vm_resources.expert_output_accumulator->get_byte_size());// Get tensor references (constant across all experts)- if (!m_config.router_scores_idx.has_value()) {+ if (!m_config.router_scores.compiled.has_value()) {OPENVINO_THROW("MoE: Router scores index not available");}- if (!m_config.expert_input_param_idx.has_value()) {+ if (!m_config.expert_input.compiled.has_value()) {OPENVINO_THROW("MoE: Expert input parameter index not available");}@@ -436,9 +440,10 @@ void MoEExecutor::run_expert_iterative(size_t idx, size_t real_idx, const std::v// Get input/output ports for selected infer requestauto selected_compiled_model = m_config.compiled_models.at(selected_chunk_size);- const auto& selected_router_iport = selected_compiled_model->inputs()[m_config.router_scores_idx.value()];+ const auto& selected_router_iport =+ selected_compiled_model->inputs()[m_config.router_scores.compiled.value()];const auto& selected_expert_input_iport =- selected_compiled_model->inputs()[m_config.expert_input_param_idx.value()];+ selected_compiled_model->inputs()[m_config.expert_input.compiled.value()];const auto& selected_oport = selected_compiled_model->outputs()[0];auto selected_router_dest = selected_infer_request->get_tensor(selected_router_iport);@@ -507,11 +512,11 @@ void MoEExecutor::set_router_scores(size_t idx,const auto& io = m_moe_io[idx];// Validate router scores index is provided- if (!m_config.router_scores_idx.has_value()) {+ if (!m_config.router_scores.original.has_value()) {OPENVINO_THROW("MoE: Router input parameter index not specified for expert model");}- const auto original_router_idx = m_config.router_scores_idx.value();+ const auto original_router_idx = m_config.router_scores.original.value();const auto& param_mapping = m_config.param_mapping;// Find unrolled router score parametersdiff --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 463bd377005..eb95e325f50 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@@ -65,6 +65,23 @@ ov::Tensor slice_expert_weight(const ov::Tensor& batched_weight, size_t expert_ireturn view_tensor;}+namespace {+// Returns the token-count dimension from a 4-D router output shape.+// Two layout variants exist depending on the opset version used during model export:+// Layout A: [num_experts, 1, token_num, 1] → returns shape[2]+// Layout B: [num_experts, token_num, 1, 1] → returns shape[1]+// ASSERTs if neither layout is recognised.+static size_t get_router_token_count(const ov::Shape& router_shape) {+ NPUW_ASSERT(router_shape.size() == 4);+ if (router_shape[1] == 1 && router_shape[3] == 1)+ return router_shape[2]; // Layout A+ if (router_shape[2] == 1 && router_shape[3] == 1)+ return router_shape[1]; // Layout B+ NPUW_ASSERT(false && "Unexpected router output shape - cannot determine token dimension!");+ return 0; // unreachable, suppress warning+}+} // namespace+std::vector<size_t> parse_selected_experts_from_router(const ov::SoPtr<ov::ITensor>& router_output,size_t num_experts,std::map<size_t, std::vector<size_t>>& token_to_experts,@@ -77,13 +94,12 @@ std::vector<size_t> parse_selected_experts_from_router(const ov::SoPtr<ov::ITenstoken_to_experts.clear();expert_to_tokens.clear();- // Expected router output shape: [num_experts, 1, token_num, 1]auto shape = router_output->get_shape();- if (shape.size() != 4 || shape[0] != num_experts || shape[1] != 1 || shape[3] != 1) {+ if (shape.size() != 4 || shape[0] != num_experts) {NPUW_ASSERT(false && "Unexpected router output shape!");}- size_t num_tokens = shape[2]; // token_num from shape+ size_t num_tokens = get_router_token_count(shape);// Parse which expert each token selects based on non-zero weightsauto parse_experts = [&](auto* data) {@@ -157,11 +173,12 @@ void gather_router_scores(const ov::SoPtr<ov::ITensor>& router_source,// Calculate expert offset in source tensorsize_t expert_offset;if (router_source_shape.size() == 4) {- expert_offset = expert_id * router_source_shape[2]; // [num_experts, 1, token_num, 1]+ expert_offset = expert_id * get_router_token_count(router_source_shape);} else if (router_source_shape.size() == 2) {expert_offset = expert_id * router_source_shape[1]; // [num_experts, token_num]} else {NPUW_ASSERT(false && "Unexpected router source shape");+ expert_offset = 0; // unreachable, suppress uninitialized warning}// Gather router scores for chunk tokensdiff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cppindex 4b1f140efe2..f3ec48e2bed 100644--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cpp@@ -60,10 +60,31 @@ void MoEResources::initialize_expert_iterative_mode(const size_t num_tokens = config.input_token_count;const size_t embed_dim = config.expert_hidden_dim;- ov::Shape buffer_shape = {active_experts, 1, num_tokens, embed_dim};+ // Derive accumulator shape from the expert model's output shape template.+ // Two layout variants exist depending on the opset version used during model export:+ // Layout A: [1, 1, chunk_size, embed_dim] → accumulator [active_experts, 1, num_tokens, embed_dim]+ // Layout B: [1, chunk_size, 1, embed_dim] → accumulator [active_experts, num_tokens, 1, embed_dim]+ //+ // We use the first chunk size's compiled model output shape as the template:+ // replace dim[0] with active_experts, replace any middle dim (1..n-2) equal to+ // chunk_size with num_tokens, and always preserve the last dim (embed_dim) unchanged.+ const size_t first_chunk_size = config.compiled_models.begin()->first;+ auto first_model = config.compiled_models.begin()->second;+ const auto output_shape = first_model->outputs()[0].get_shape();++ ov::Shape buffer_shape(output_shape.size());+ buffer_shape[0] = active_experts;+ for (size_t i = 1; i < output_shape.size() - 1; ++i) {+ if (output_shape[i] == first_chunk_size) {+ buffer_shape[i] = num_tokens;+ } else {+ buffer_shape[i] = output_shape[i]; // copy singleton (1) as-is+ }+ }+ buffer_shape.back() = output_shape.back(); // always preserve embed_dim (last dim)+ NPUW_ASSERT(buffer_shape.back() == embed_dim && "Accumulator last dim must equal expert_hidden_dim");// Infer element type from first compiled model output- auto first_model = config.compiled_models.begin()->second;auto output_element_type = first_model->outputs()[0].get_element_type();expert_output_accumulator = allocator(output_element_type, buffer_shape, device);diff --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 c494c7583c4..7d3adee3575 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@@ -52,6 +52,24 @@ static std::optional<size_t> extract_k_from_router(const std::shared_ptr<ov::Modreturn std::nullopt;}+// Scan the transformed model for a parameter bearing `tag` and return its new index.+// Falls back to `original_idx` when the tag is absent (e.g. router_scores is replaced+// by K closures in EXPERT_BATCH mode and its parameter no longer exists).+static std::optional<size_t> resolve_compiled_idx(const std::shared_ptr<ov::Model>& transformed_model,+ const char* tag,+ std::optional<size_t> original_idx) {+ const auto& params = transformed_model->get_parameters();+ for (size_t i = 0; i < params.size(); ++i) {+ if (params[i]->get_rt_info().count(tag) > 0) {+ LOG_INFO("Post-transform [" << tag << "] idx: " << i << " (original: " << original_idx.value_or(SIZE_MAX)+ << ")");+ return i;+ }+ }+ LOG_WARN("[" << tag << "] not found in transformed model; falling back to original index");+ return original_idx;+}+// Helper function to build parameter mapping from RTInfo metadatastatic std::map<size_t, std::vector<size_t>> build_parameter_mapping_from_rtinfo(const std::shared_ptr<ov::Model>& original_model,@@ -311,15 +329,19 @@ MoETransformConfig determine_transformation_params(const MoEStructureInfo& strucreturn config;}-// Helper: Update Reshape node's constant input at a specific dimension-// MoE Reshape patterns: 3D [num_experts, token_num, hidden_dim] or 4D [num_experts, 1, token_num, hidden_dim]-// - dimension_index can be:-// * 0: for num_experts (first dimension)-// * -2: for token_num (second-to-last dimension, works for both 3D and 4D)-static bool update_reshape_constant_dimension(const std::shared_ptr<ov::op::v1::Reshape>& reshape_node,- int dimension_index,- size_t old_value,- size_t new_value) {+// Helper: Update Reshape output-shape constant: replace old_value with new_value in+// dims [first_dim, last_dim_exclusive). Pass SIZE_MAX for last_dim_exclusive to stop+// before the last dimension (i.e. exclude hidden_dim at dim n-1).+//+// Typical MoE reshape layouts (3-D or 4-D):+// dim 0 : num_experts → call with first_dim=0, last_dim_exclusive=1+// dims 1 .. n-2 : seq_len / size-1 expansion → call with first_dim=1, last_dim_exclusive=SIZE_MAX+// dim n-1 (last) : hidden_dim (never touched; excluded when last_dim_exclusive==SIZE_MAX)+static bool update_reshape_dimensions(const std::shared_ptr<ov::op::v1::Reshape>& reshape_node,+ size_t old_value,+ size_t new_value,+ size_t first_dim = 0,+ size_t last_dim_exclusive = SIZE_MAX) {auto shape_input = reshape_node->input_value(1);auto shape_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(shape_input.get_node_shared_ptr());if (!shape_const) {@@ -328,34 +350,31 @@ static bool update_reshape_constant_dimension(const std::shared_ptr<ov::op::v1::auto shape_data = shape_const->cast_vector<int64_t>();- // MoE reshapes are either 3D or 4D+ // Only handle 3-D and 4-D MoE reshape patternsif (shape_data.size() < 3 || shape_data.size() > 4) {return false;}- // Convert negative index to positive (e.g., -2 means second-to-last)- size_t actual_index;- if (dimension_index < 0) {- actual_index = shape_data.size() + dimension_index;- } else {- actual_index = dimension_index;+ // Resolve SIZE_MAX sentinel: stop before the last dimension+ size_t end = (last_dim_exclusive == SIZE_MAX) ? shape_data.size() - 1 : last_dim_exclusive;+ end = std::min(end, shape_data.size());++ bool updated = false;+ for (size_t i = first_dim; i < end; ++i) {+ if (shape_data[i] == static_cast<int64_t>(old_value)) {+ LOG_DEBUG(" Updating Reshape '" << reshape_node->get_friendly_name() << "' shape[" << i << "] from "+ << old_value << " to " << new_value);+ shape_data[i] = static_cast<int64_t>(new_value);+ updated = true;+ }}- // Check if the dimension value matches and update it- if (actual_index < shape_data.size() && shape_data[actual_index] == static_cast<int64_t>(old_value)) {- LOG_DEBUG(" Updating Reshape '" << reshape_node->get_friendly_name() << "' shape[" << actual_index << "] from "- << old_value << " to " << new_value);-- shape_data[actual_index] = new_value;-+ if (updated) {auto new_shape_const =std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{shape_data.size()}, shape_data);reshape_node->input(1).replace_source_output(new_shape_const->output(0));-- return true;}-- return false;+ return updated;}// Helper: Check if parameter matches downstream pattern@@ -396,21 +415,31 @@ std::optional<MoEDownstream> detect_and_transform_moe_downstream(const std::sharLOG_DEBUG("Detecting MoE downstream pattern...");LOG_BLOCK();- // Pattern to match: Parameter -> Convert -> ReduceSum- // Looking for a parameter with shape [N, 1, H, W] where N is total_experts_num+ // Pattern to match: Parameter -> [Convert] -> ReduceSum+ // Looking for a parameter with shape [N, ..., W] where:+ // dim 0 = N (total experts, > 1)+ // dim n-1 = W (hidden_dim)+ // at least one of dims 1..n-2 equals 1 (singleton "batch" dimension)+ // Both [N, 1, H, W] (GPT-OSS) and [N, H, 1, W] (Qwen) are accepted.const auto& params = model->get_parameters();for (size_t param_idx = 0; param_idx < params.size(); ++param_idx) {const auto& param = params[param_idx];- // Validate shape: must be [N, 1, H, W] where N > 1+ // Validate shape: must be 4-D with dim 0 > 1auto param_shape = param->get_partial_shape();if (!param_shape.rank().is_static() || param_shape.rank().get_length() != 4) {continue;}auto shape = param_shape.to_shape();- if (shape[1] != 1 || shape[0] <= 1) {+ if (shape[0] <= 1) {+ continue;+ }++ // At least one of dims 1..2 must be 1 (singleton expansion dim)+ bool has_singleton_dim = (shape[1] == 1 || shape[2] == 1);+ if (!has_singleton_dim) {continue;}@@ -681,10 +710,9 @@ void MoEModelTransformer::fix_parameters_with_num_experts(const std::shared_ptr<continue;}- // For MoE Reshape patterns (3D or 4D), num_experts is always at dimension 0- // 3D: [num_experts, token_num, hidden_dim]- // 4D: [num_experts, 1, token_num, hidden_dim]- update_reshape_constant_dimension(reshape_node, 0, num_experts, num_target_experts);+ // For MoE Reshape patterns (3D or 4D), num_experts is always at dimension 0.+ // Scan only dim 0 (first_dim=0, last_dim_exclusive=1).+ update_reshape_dimensions(reshape_node, num_experts, num_target_experts, 0, 1);}}@@ -764,19 +792,17 @@ void MoEModelTransformer::fix_token_count_for_expert_iterative(}}- // Also fix Reshape nodes that contain original_token_count in their shape constants+ // Also fix Reshape nodes that contain original_token_count in their shape constants.+ // 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...");for (const auto& node : model->get_ordered_ops()) {auto reshape_node = std::dynamic_pointer_cast<ov::op::v1::Reshape>(node);if (!reshape_node) {continue;}-- // For MoE Reshape patterns (3D or 4D), token_num is always at second-to-last dimension- // 3D: [num_experts, token_num, hidden_dim] - token_num at index 1- // 4D: [num_experts, 1, token_num, hidden_dim] - token_num at index 2- // Use -2 to refer to second-to-last dimension in both cases- update_reshape_constant_dimension(reshape_node, -2, original_token_count, chunk_size);+ // Scan middle dims (1..n-2), skip dim 0 (num_experts) and last dim (hidden_dim).+ update_reshape_dimensions(reshape_node, original_token_count, chunk_size, 1);}// Trigger shape inference to propagate changes through the model@@ -926,6 +952,19 @@ std::optional<MoEExperts> MoEExperts::from(const std::shared_ptr<ov::Model>& mod}}+ // Tag activation parameters before transformation so we can re-locate them afterwards+ // (transformations may shift parameter indices).+ constexpr const char* expert_input_tag = "npuw_moe_expert_input";+ constexpr const char* router_scores_tag = "npuw_moe_router_scores";+ auto tag_param = [&](std::optional<size_t> idx, const char* tag) {+ if (idx.has_value()) {+ model->get_parameters()[idx.value()]->get_rt_info()[tag] = true;+ LOG_DEBUG("Tagged [" << tag << "] at original index " << idx.value());+ }+ };+ tag_param(structure_info->expert_input_param_idx, expert_input_tag);+ tag_param(structure_info->router_scores_idx, router_scores_tag);+// Step 4: Transform models for each chunk sizestd::map<size_t, std::shared_ptr<ov::Model>> transformed_models;for (auto chunk_size : chunk_sizes) {@@ -949,6 +988,16 @@ std::optional<MoEExperts> MoEExperts::from(const std::shared_ptr<ov::Model>& modreturn std::nullopt;}+ // Resolve compiled-model parameter indices via rt_info tags.+ // All chunk-size variants share the same parameter ordering, so the first model suffices.+ // router_scores may be absent in EXPERT_BATCH (unrolled into K closures); resolve_compiled_idx+ // falls back to the original index, which is harmless since run_expert_batch uses param_mapping.+ const auto& first_transformed_model = transformed_models.begin()->second;+ const auto expert_input_compiled_idx =+ resolve_compiled_idx(first_transformed_model, expert_input_tag, structure_info->expert_input_param_idx);+ const auto router_scores_compiled_idx =+ resolve_compiled_idx(first_transformed_model, router_scores_tag, structure_info->router_scores_idx);+// 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@@ -962,8 +1011,10 @@ std::optional<MoEExperts> MoEExperts::from(const std::shared_ptr<ov::Model>& modmoe_experts._chunk_token_count = structure_info->is_expert_batch_mode() ? 0 : iterative_chunk_size;moe_experts._num_active_experts = k_value; // Store actual K from routermoe_experts._transformed_models = std::move(transformed_models);- moe_experts._router_scores_idx = structure_info->router_scores_idx;- moe_experts._expert_input_param_idx = structure_info->expert_input_param_idx;+ moe_experts._router_scores.original = structure_info->router_scores_idx;+ moe_experts._router_scores.compiled = router_scores_compiled_idx;+ moe_experts._expert_input.original = structure_info->expert_input_param_idx;+ moe_experts._expert_input.compiled = expert_input_compiled_idx;moe_experts._param_mapping = std::move(param_mapping);if (!moe_experts.is_valid()) {@@ -998,8 +1049,10 @@ MoEExperts::MoEExperts(const function::MoEExperts& func_moe) {num_active_experts = func_moe._num_active_experts;input_token_count = func_moe._input_token_count;_models_to_compile = func_moe._transformed_models;- _router_scores_idx = func_moe._router_scores_idx;- _expert_input_param_idx = func_moe._expert_input_param_idx;+ _router_scores.original = func_moe._router_scores.original;+ _router_scores.compiled = func_moe._router_scores.compiled;+ _expert_input.original = func_moe._expert_input.original;+ _expert_input.compiled = func_moe._expert_input.compiled;_param_mapping = func_moe._param_mapping;LOG_DEBUG("Created compiled::MoEExperts:");@@ -1011,11 +1064,11 @@ MoEExperts::MoEExperts(const function::MoEExperts& func_moe) {for (const auto& entry : _models_to_compile) {LOG_DEBUG(" Chunk size: " << entry.first);}- if (_router_scores_idx.has_value()) {- LOG_DEBUG(" Router scores parameter index: " << _router_scores_idx.value());+ if (_router_scores.original.has_value()) {+ LOG_DEBUG(" Router scores parameter index: " << _router_scores.original.value());}- if (_expert_input_param_idx.has_value()) {- LOG_DEBUG(" Expert input parameter index: " << _expert_input_param_idx.value());+ if (_expert_input.original.has_value()) {+ LOG_DEBUG(" Expert input parameter index: " << _expert_input.original.value());}}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 ec754ce67fd..7cb4808bca9 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@@ -1,5 +1,6 @@// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0+//#pragma once@@ -25,6 +26,13 @@namespace ov {namespace npuw {+// Holds original-model index (for prologue matching / param_mapping lookup)+// and compiled-model index (for direct port binding after transformation).+struct ParamIndex {+ std::optional<size_t> original; // index in original model+ std::optional<size_t> compiled; // index in compiled/transformed model+};+namespace function {// Default chunk size variants for dynamic iterative mode chunking@@ -184,9 +192,9 @@ struct MoEExperts {// For EXPERT_BATCH: single model with chunk_size = 0 (no chunking, K active experts)std::map<size_t, std::shared_ptr<ov::Model>> _transformed_models;- // Parameter indices- std::optional<size_t> _router_scores_idx; // Parameter index for router scores- std::optional<size_t> _expert_input_param_idx; // Parameter index for expert's input (token embeddings)+ // Parameter indices (original = in original model, compiled = in compiled/transformed model)+ ParamIndex _router_scores; // router scores input parameter+ ParamIndex _expert_input; // expert activation input parameter// Parameter mapping: original_param_idx -> [unrolled_param_indices]// For EXPERT_ITERATIVE mode: no unrolling, so this will be empty or identity mapping@@ -197,7 +205,7 @@ struct MoEExperts {// Validation helpersbool is_valid() const {return _num_experts > 0 && _expert_hidden_dim > 0 && !_transformed_models.empty() &&- _router_scores_idx.has_value();+ _router_scores.original.has_value();}size_t num_experts() const {@@ -235,14 +243,6 @@ struct MoEExperts {return nullptr;}- std::optional<size_t> router_scores_idx() const {- return _router_scores_idx;- }-- std::optional<size_t> expert_input_param_idx() const {- return _expert_input_param_idx;- }-const std::map<size_t, std::vector<size_t>>& param_mapping() const {return _param_mapping;}@@ -277,10 +277,10 @@ struct MoEExperts {// Store models temporarily for compilation (chunk_size -> model)std::map<size_t, std::shared_ptr<ov::Model>> _models_to_compile;- // Router scores parameter index (from Multiply in output path)- std::optional<size_t> _router_scores_idx;- // Expert input parameter index (token embeddings)- std::optional<size_t> _expert_input_param_idx;+ // Router scores / expert input parameter indices+ // (.original = in original model; .compiled = in compiled/transformed model)+ ParamIndex _router_scores;+ ParamIndex _expert_input;// Parameter mapping: original_param_idx -> [unrolled_param_indices]// Same for all chunk sizes (unrolling only in EXPERT_BATCH mode)diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/fold_const.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/fold_const.cppnew file mode 100644index 00000000000..fa83cd137fd--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/fold_const.cpp@@ -0,0 +1,126 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "fold_const.hpp"++#include "openvino/core/graph_util.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/pass/pattern/op/label.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"++namespace opp = ov::pass::pattern;++namespace ov {+namespace npuw {+namespace patterns {+namespace util {++namespace {+// If every input to `node` is an ov::op::v0::Constant and every output shape+// is statically known, evaluate the node and return one folded Constant per+// output port. Returns true on success; `replacements` is populated.+bool fold_if_all_const(const std::shared_ptr<ov::Node>& node, ov::OutputVector& replacements) {+ ov::TensorVector inputs;+ inputs.reserve(node->get_input_size());+ for (size_t i = 0; i < node->get_input_size(); ++i) {+ auto c = ov::as_type_ptr<ov::op::v0::Constant>(node->get_input_node_shared_ptr(i));+ if (!c)+ return false;+ inputs.emplace_back(c->get_element_type(), c->get_shape(), const_cast<void*>(c->get_data_ptr()));+ }+ ov::TensorVector outputs;+ outputs.reserve(node->get_output_size());+ for (size_t i = 0; i < node->get_output_size(); ++i) {+ const auto& pshape = node->get_output_partial_shape(i);+ if (pshape.is_dynamic())+ return false;+ outputs.emplace_back(node->get_output_element_type(i), pshape.to_shape());+ }+ if (!node->evaluate(outputs, inputs))+ return false;+ replacements.reserve(outputs.size());+ for (size_t i = 0; i < outputs.size(); ++i) {+ auto new_c = std::make_shared<ov::op::v0::Constant>(outputs[i]);+ new_c->set_friendly_name("NPUW/Folded/" + node->get_friendly_name());+ replacements.push_back(new_c->output(0));+ }+ return true;+}+} // namespace++FoldShapeOf::FoldShapeOf() {+ auto shape_of = opp::wrap_type<ov::op::v3::ShapeOf>({opp::any_input()});++ register_matcher(std::make_shared<opp::Matcher>(shape_of, "FoldShapeOf"), [](opp::Matcher& m) {+ auto matched_out = m.get_match_root()->output(0);+ auto& tensor = matched_out.get_tensor();+ if (!tensor.has_and_set_bound())+ return false;+ auto new_c = std::make_shared<ov::op::v0::Constant>(tensor.get_upper_value());+ new_c->set_friendly_name("NPUW/Folded/" + m.get_match_root()->get_friendly_name());+ for (auto& input : matched_out.get_target_inputs()) {+ input.replace_source_output(new_c);+ }+ return false; // root itself not replaced, only consumers redirected+ });+}++FoldGatherOfConst::FoldGatherOfConst() {+ auto const_data = opp::wrap_type<ov::op::v0::Constant>();+ auto const_idx = opp::wrap_type<ov::op::v0::Constant>();+ auto const_axis = opp::wrap_type<ov::op::v0::Constant>();+ auto gather = opp::wrap_type<ov::op::v8::Gather>({const_data, const_idx, const_axis});++ register_matcher(std::make_shared<opp::Matcher>(gather, "FoldGatherOfConst"), [](opp::Matcher& m) {+ ov::OutputVector replacements;+ if (!fold_if_all_const(m.get_match_root(), replacements))+ return false;+ ov::replace_node(m.get_match_root(), replacements);+ return true;+ });+}++FoldUnsqueezeOfConst::FoldUnsqueezeOfConst() {+ auto const_data = opp::wrap_type<ov::op::v0::Constant>();+ auto const_axes = opp::wrap_type<ov::op::v0::Constant>();+ auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({const_data, const_axes});++ register_matcher(std::make_shared<opp::Matcher>(unsqueeze, "FoldUnsqueezeOfConst"), [](opp::Matcher& m) {+ ov::OutputVector replacements;+ if (!fold_if_all_const(m.get_match_root(), replacements))+ return false;+ ov::replace_node(m.get_match_root(), replacements);+ return true;+ });+}++FoldConcatOfConsts::FoldConcatOfConsts() {+ auto concat = opp::wrap_type<ov::op::v0::Concat>();++ register_matcher(std::make_shared<opp::Matcher>(concat, "FoldConcatOfConsts"), [](opp::Matcher& m) {+ ov::OutputVector replacements;+ if (!fold_if_all_const(m.get_match_root(), replacements))+ return false;+ ov::replace_node(m.get_match_root(), replacements);+ return true;+ });+}++bool FoldShapeComputeChain::run_on_model(const std::shared_ptr<ov::Model>& model) {+ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<FoldShapeOf>();+ rewr.add_matcher<FoldGatherOfConst>();+ rewr.add_matcher<FoldUnsqueezeOfConst>();+ rewr.add_matcher<FoldConcatOfConsts>();+ return rewr.run_on_model(model);+}++} // namespace util+} // namespace patterns+} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/fold_const.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/fold_const.hppnew file mode 100644index 00000000000..9bdf63c3c06--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/fold_const.hpp@@ -0,0 +1,68 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/pass/pass.hpp"++// Lightweight constant-folding passes for shape-compute chains that appear in+// extracted MoE expert subgraphs after RegularizeSDPA folds ShapeOf(param)+// into a Constant.+//+// Target chain (each step enables the next):+// ShapeOf(param) --[RegularizeSDPA/ShapeOfParameter]--> Const+// ShapeOf(any) --[FoldShapeOf]--> Const (bound-based, no input constraint)+// Gather(C,C,C) --[FoldGatherOfConst]--> Const+// Unsqueeze(C,C) --[FoldUnsqueezeOfConst]--> Const+// Concat(C...) --[FoldConcatOfConsts]--> Const++namespace ov {+namespace npuw {+namespace patterns {+namespace util {++// Fold ShapeOf(any) → Constant when the output tensor has a known upper bound.+// More general than RegularizeSDPA::ShapeOfParameter: no constraint on input type.+class FoldShapeOf : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::util::FoldShapeOf");+ FoldShapeOf();+};++// Fold Gather(Constant, Constant, Constant) → Constant.+class FoldGatherOfConst : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::util::FoldGatherOfConst");+ FoldGatherOfConst();+};++// Fold Unsqueeze(Constant, Constant) → Constant.+class FoldUnsqueezeOfConst : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::util::FoldUnsqueezeOfConst");+ FoldUnsqueezeOfConst();+};++// Fold Concat whose every input is a Constant → Constant.+// The pattern matches any Concat; the callback enforces the all-constant+// precondition so no variant for each arity is needed.+class FoldConcatOfConsts : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::util::FoldConcatOfConsts");+ FoldConcatOfConsts();+};++// Runs the full shape-compute-chain folding pipeline in a single pass:+// FoldShapeOf → FoldGatherOfConst → FoldUnsqueezeOfConst → FoldConcatOfConsts.+class FoldShapeComputeChain : public ov::pass::ModelPass {+public:+ OPENVINO_RTTI("npuw::patterns::util::FoldShapeComputeChain");+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;+};++} // namespace util+} // namespace patterns+} // namespace npuw+} // namespace ovdiff --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 32358073fd9..33488f09ced 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@@ -132,20 +132,47 @@ GPTOSSExpert::GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& snauto matched_reshape2 = node_to_output.at(reshape2).get_node_shared_ptr();auto matched_output_multiply = node_to_output.at(output_multiply).get_node_shared_ptr();- // Check if this is decoding stage by examining shape[rank-2]+ // Check if this is decoding stage by scanning the middle dimensions of+ // output_multiply for a non-1 token count. The shape is always rank-4+ // [num_experts, ..., hidden] with exactly one "token" dim and one singleton+ // among dims 1..rank-2.+ //+ // GPT-OSS: [N, token, 1, H] - prefill: token > 1; decoding: token = 1+ // Qwen: [N, 1, token, H] - same semantics, different layout+ //+ // Strategy: scan dims 1..rank-2 for the first non-1 value.+ // - Found non-1 value → that is the token count; if > 1 it's prefill.+ // - No non-1 found → all middle dims are 1 (decoding, token_count == 1).+ // Note: a token_count of exactly 1 always falls into the "not found" case+ // since both middle dims are 1, and the fallback correctly sets is_decoding.auto output_shape = matched_output_multiply->get_output_partial_shape(0);LOG_DEBUG("Expert Multiply output_shape: " << output_shape);bool is_decoding = false;- if (output_shape.rank().is_static() && output_shape.rank().get_length() >= 2) {- auto rank = output_shape.rank().get_length();- auto token_dim = output_shape[rank - 2];-- if (token_dim.is_static() && token_dim.get_length() == 1) {+ if (output_shape.rank().is_static()) {+ const auto rank = output_shape.rank().get_length();+ // Scan middle dims (skip dim 0 = num_experts, skip last = hidden_dim)+ bool found_token_dim = false;+ for (int64_t i = 1; i < rank - 1; ++i) {+ const auto& d = output_shape[i];+ if (!d.is_static()) {+ continue;+ }+ const auto val = d.get_length();+ if (val != 1) {+ // This is the token dimension and val > 1: prefill stage.+ // (val == 1 never reaches here; that case is handled by fallback.)+ is_decoding = false;+ LOG_DEBUG("GPT-OSS Expert pattern matched (Prefill stage): token_count=" << val);+ found_token_dim = true;+ break;+ }+ // val == 1: singleton layout dim, keep scanning+ }+ if (!found_token_dim) {+ // All middle dims are 1 (token_count == 1): decoding stage.is_decoding = true;LOG_DEBUG("GPT-OSS Expert pattern matched (Decoding stage): single token");- } else if (token_dim.is_static()) {- LOG_DEBUG("GPT-OSS Expert pattern matched (Prefill stage): token_count=" << token_dim.get_length());}}@@ -212,29 +239,39 @@ GPTOSSExpert::GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& sn}/*- GPT-OSS Router Pattern:+ GPT-OSS Router Pattern (constant-folded variant):- Matches MoE router layer (16 nodes: 9 pattern-matched + 7 manual retrieval)- Pattern: weights -> Multiply -> Convert -> MatMul -> Add -> TopK -> Softmax -> Slice- \-> Convert -> ShapeOf -/- Manual: Add -> ShapeOf -> Broadcast -> Scatter -> Transpose -> Reshape -> Unsqueeze+ All ShapeOf nodes in the router are constant-folded before this pattern runs.+ The resulting graph is:++ weights -> Multiply -> Convert -> MatMul -> Add -> TopK+ |\-> output(0) values -> Softmax -> Slice+ \-> output(1) indices -> Convert (indices)++ Slice -> ScatterElementsUpdate -> Transpose -> Reshape -> Unsqueeze+ Broadcast (zero base for Scatter, shape fed by folded Const)++ Pattern-matched (6): Multiply, Convert, MatMul, Add, TopK, Softmax, Slice+ Manually retrieved (4): topk_convert (indices Convert), Broadcast, Scatter,+ Transpose, Reshape, Unsqueeze*/GPTOSSRouter::GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag) {LOG_DEBUG("GPTOSSRouter pattern matcher registered with tag: " << isol_tag);- // Pattern-matched nodes (9 total)+ // Pattern-matched nodes (7): Multiply, Convert, MatMul, Add, TopK, Softmax, Slice+ // topk_convert (indices Convert) is retrieved manually - TopK has two outputs and+ // wrap_type always binds output(0), so output(1)->Convert cannot be expressed inline.auto weights_multiply = opp::wrap_type<ov::op::v1::Multiply>({opp::any_input(), opp::any_input()});auto weights_convert2 = opp::wrap_type<ov::op::v0::Convert>({weights_multiply});auto matmul = opp::wrap_type<ov::op::v0::MatMul>({opp::any_input(), weights_convert2});auto add = opp::wrap_type<ov::op::v1::Add>({matmul, opp::any_input()});auto topk = opp::wrap_type<ov::op::v11::TopK>({add, opp::any_input()});- auto softmax = opp::wrap_type<ov::op::v8::Softmax>({topk});- auto topk_convert = opp::wrap_type<ov::op::v0::Convert>({topk});- auto shapeof_topk = opp::wrap_type<ov::op::v3::ShapeOf>({topk_convert});+ auto softmax = opp::wrap_type<ov::op::v8::Softmax>({topk}); // connects to topk->output(0)- // Pattern root+ // Pattern root: Slice data input is Softmax output; all shape inputs are any_input()+ // because ShapeOf nodes are constant-folded before this pattern runs.auto slice = opp::wrap_type<ov::op::v8::Slice>(- {softmax, opp::any_input(), shapeof_topk, opp::any_input(), opp::any_input()});+ {softmax, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});auto node_to_gptr = snapshot->getNodeToGroupMap();@@ -264,10 +301,19 @@ GPTOSSRouter::GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& snauto matched_matmul = node_to_output.at(matmul).get_node_shared_ptr();auto matched_add = node_to_output.at(add).get_node_shared_ptr();auto matched_softmax = node_to_output.at(softmax).get_node_shared_ptr();- auto matched_topk_convert = node_to_output.at(topk_convert).get_node_shared_ptr();- auto matched_shapeof_topk = node_to_output.at(shapeof_topk).get_node_shared_ptr();auto matched_slice = node_to_output.at(slice).get_node_shared_ptr();+ // topk_convert: Convert on TopK indices output (output(1)). Not in the formal+ // pattern because TopK has two outputs and wrap_type always binds output(0).+ std::shared_ptr<ov::Node> matched_topk_convert = nullptr;+ for (auto& target : matched_topk->output(1).get_target_inputs()) {+ auto consumer = target.get_node()->shared_from_this();+ if (std::dynamic_pointer_cast<ov::op::v0::Convert>(consumer)) {+ matched_topk_convert = consumer;+ break;+ }+ }+// Manual retrieval (7 nodes): helper functionauto find_consumer_by_type =[](const std::shared_ptr<ov::Node>& node,@@ -300,19 +346,6 @@ GPTOSSRouter::GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& snreturn false;}- std::shared_ptr<ov::Node> matched_shapeof = nullptr;- for (size_t i = 0; i < matched_broadcast->inputs().size(); ++i) {- auto input_node = matched_broadcast->input_value(i).get_node_shared_ptr();- if (std::dynamic_pointer_cast<ov::op::v3::ShapeOf>(input_node)) {- matched_shapeof = input_node;- break;- }- }- if (!matched_shapeof) {- LOG_DEBUG("Router pattern: ShapeOf not found");- return false;- }-// Retrieve output chain (Transpose -> Reshape -> Unsqueeze)auto matched_transpose = find_consumer_by_type(matched_scatter, [](const std::shared_ptr<ov::Node>& n) {return std::dynamic_pointer_cast<ov::op::v1::Transpose>(n) != nullptr;@@ -352,9 +385,7 @@ GPTOSSRouter::GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& snisolate_if_exists(matched_topk);isolate_if_exists(matched_softmax);isolate_if_exists(matched_topk_convert);- isolate_if_exists(matched_shapeof_topk);isolate_if_exists(matched_slice);- isolate_if_exists(matched_shapeof);isolate_if_exists(matched_broadcast);isolate_if_exists(matched_scatter);isolate_if_exists(matched_transpose);diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.cppindex 895ae8b7a81..79be4dc96ed 100644--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp@@ -105,7 +105,8 @@ void ov::npuw::orc::serialize(Stream& stream, ov::npuw::compiled::HostFlashAttenvoid ov::npuw::orc::serialize(Stream& stream, ov::npuw::compiled::MoEExperts& var) {stream & var.num_experts & var.expert_hidden_dim & var.num_active_experts & var.input_token_count &- var._router_scores_idx & var._expert_input_param_idx & var._param_mapping;+ var._router_scores.original & var._router_scores.compiled & var._expert_input.original &+ var._expert_input.compiled & var._param_mapping;}void ov::npuw::orc::serialize(Stream& stream, ov::npuw::compiled::MoEDownstream& var) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hppindex ee78db033ff..d5072db6406 100644--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp@@ -44,7 +44,7 @@ const constexpr ov::npuw::s11n::IndicatorType NPUW_COMPILED_MODEL_INDICATOR =const constexpr ov::npuw::s11n::IndicatorType NPUW_LLM_COMPILED_MODEL_INDICATOR ={char{0x4c}, char{0x4c}, char{0x4d}, char{0x43}, char{0x4d}, char{0x4f}};-const constexpr char* NPUW_SERIALIZATION_VERSION = "0.24";+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.25";// Forward declarationnamespace intel_npu {diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex c25287dfde9..f0c1d728de1 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -78,6 +78,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/spatial.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/accuracy/comparator.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/fold_const.cpp# moe${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/fold_const_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/fold_const_test.cppnew file mode 100644index 00000000000..86938722299--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/fold_const_test.cpp@@ -0,0 +1,223 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "partitioning/patterns/fold_const.hpp"++#include <gtest/gtest.h>++#include "openvino/op/ops.hpp"++// Tests for ov::npuw::patterns::util::FoldShapeComputeChain.+//+// The graph built here mirrors Model0_prefill_01_REP00DE.xml – the simplified+// GPT-OSS MoE router subgraph after ReshapeToStatic has been applied. All+// tensor shapes are fully static (seq_len=1024, hidden=2880, experts=32, k=4).+//+// Two ShapeOf nodes are present in the pre-folded graph:+//+// ShapeOf_A : ShapeOf(Add[1024,32]) → Broadcast.shape (zeros-like template)+// ShapeOf_B : ShapeOf(Convert[1024,4]) → Slice.stop (scatter index bounds)+//+// Full edge topology (matches the XML edge list):+//+// Param[1024,2880] ──Convert──► MatMul ──► Add ──► TopK ──values──► Softmax ──► Slice ──► Scatter+// Const[32,2880]f32 ────────────────────────┘ │ ▲+// │ ShapeOf_B(Convert[1024,4]) │+// ├──► ShapeOf_A(Add[1024,32]) │+// │ └──► Broadcast(zeros) ──► Scatter │+// └──► TopK.indices ──► Convert ─────────── ┘+//+// FoldShapeComputeChain must replace both ShapeOf nodes with Constants.++namespace {++using namespace ov;++static std::shared_ptr<ov::Model> make_gptoss_router_model() {+ constexpr size_t seq_len = 1024;+ constexpr size_t hidden_dim = 2880;+ constexpr size_t num_experts = 32;+ constexpr int64_t k = 4;++ // ── Router input: [seq_len, hidden_dim] ──────────────────────────────────+ auto router_input = std::make_shared<op::v0::Parameter>(element::f32, Shape{seq_len, hidden_dim});+ router_input->set_friendly_name("router_input");++ // ── Weight: f32 Const [32, 2880] (mirrors the quantised-then-dequantised path) ──+ auto weight = op::v0::Constant::create(element::f32,+ Shape{num_experts, hidden_dim},+ std::vector<float>(num_experts * hidden_dim, 0.0f));+ weight->set_friendly_name("router/weight");++ // Convert input to f32 (matches Convert_f16ic_6 in XML)+ auto input_convert = std::make_shared<op::v0::Convert>(router_input, element::f32);+ input_convert->set_friendly_name("router/Convert_input");++ // MatMul: [1024,2880] × [32,2880]ᵀ → [1024,32]+ auto matmul = std::make_shared<op::v0::MatMul>(input_convert, weight, false, true);+ matmul->set_friendly_name("router/MatMul");++ // Add bias: [1,32] → broadcast gives [1024,32]+ auto bias = op::v0::Constant::create(element::f32, Shape{1, num_experts}, std::vector<float>(num_experts, 0.0f));+ bias->set_friendly_name("router/bias");+ auto add = std::make_shared<op::v1::Add>(matmul, bias);+ add->set_friendly_name("router/Add");++ // ── ShapeOf chain A: ShapeOf(Add[1024,32]) → Broadcast.shape ─────────────+ // Mirrors XML nodes 12 (ShapeOf) and 13 (Broadcast).+ // Creates the zeros-like template of shape [1024, 32].+ auto shape_of_a = std::make_shared<op::v3::ShapeOf>(add, element::i64);+ shape_of_a->set_friendly_name("router/zeros_like/ShapeOf");++ auto zeros_scalar = op::v0::Constant::create(element::f32, Shape{}, std::vector<float>{0.0f});+ zeros_scalar->set_friendly_name("router/zeros_like/scalar");++ // v3::Broadcast(scalar, target_shape) with NUMPY mode → zeros[1024,32]+ auto broadcast = std::make_shared<op::v3::Broadcast>(zeros_scalar, shape_of_a);+ broadcast->set_friendly_name("router/zeros_like/Broadcast");++ // ── TopK: top-k expert selection ─────────────────────────────────────────+ auto k_const = op::v0::Constant::create(element::i64, Shape{}, std::vector<int64_t>{k});+ k_const->set_friendly_name("router/k");+ auto topk = std::make_shared<op::v11::TopK>(add,+ k_const,+ /*axis=*/-1,+ op::v11::TopK::Mode::MAX,+ op::v11::TopK::SortType::NONE);+ topk->set_friendly_name("router/TopK");+ // topk->output(0) = values [1024,4]+ // topk->output(1) = indices [1024,4]++ auto softmax = std::make_shared<op::v8::Softmax>(topk->output(0), /*axis=*/-1);+ softmax->set_friendly_name("router/Softmax");++ // Convert TopK indices (mirrors XML node 16: Convert → i64)+ auto topk_idx_convert = std::make_shared<op::v0::Convert>(topk->output(1), element::i64);+ topk_idx_convert->set_friendly_name("router/scatter_/Convert");++ // ── ShapeOf chain B: ShapeOf(Convert[1024,4]) → Slice.stop ───────────────+ // Mirrors XML nodes 19 (ShapeOf) and 22 (Slice).+ auto shape_of_b = std::make_shared<op::v3::ShapeOf>(topk_idx_convert, element::i64);+ shape_of_b->set_friendly_name("router/scatter_/ShapeOf");++ // Slice the softmax values [0:1024, 0:4] – bounds are given by ShapeOf_B.+ // After folding, ShapeOf_B becomes Const([1024, 4]) and the slice is trivially static.+ auto slice_start = op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{0, 0});+ auto slice_step = op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{1, 1});+ auto slice_axes = op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{0, 1});+ // v8::Slice(data, start, stop, step, axes)+ auto slice = std::make_shared<op::v8::Slice>(softmax, slice_start, shape_of_b, slice_step, slice_axes);+ slice->set_friendly_name("router/scatter_/Slice");++ // ── ScatterElementsUpdate: scatter softmax scores back into [1024,32] ────+ // data=broadcast(zeros), indices=topk_idx_convert, updates=slice, axis=1+ auto scatter_axis = op::v0::Constant::create(element::i64, Shape{}, std::vector<int64_t>{1});+ scatter_axis->set_friendly_name("router/scatter_axis");+ auto scatter = std::make_shared<op::v12::ScatterElementsUpdate>(broadcast, topk_idx_convert, slice, scatter_axis);+ scatter->set_friendly_name("router/ScatterElementsUpdate");++ // ── Transpose [1024,32] → [32,1024] ──────────────────────────────────────+ auto transpose_order = op::v0::Constant::create(element::i32, Shape{2}, std::vector<int32_t>{1, 0});+ auto transpose = std::make_shared<op::v1::Transpose>(scatter, transpose_order);+ transpose->set_friendly_name("experts/Transpose");++ // ── Reshape [32,1024] → [32,1,1024] ──────────────────────────────────────+ auto reshape_shape = op::v0::Constant::create(+ element::i64,+ Shape{3},+ std::vector<int64_t>{static_cast<int64_t>(num_experts), 1LL, static_cast<int64_t>(seq_len)});+ auto reshape = std::make_shared<op::v1::Reshape>(transpose, reshape_shape, false);+ reshape->set_friendly_name("experts/Reshape");++ // ── Unsqueeze [32,1,1024] → [32,1,1024,1] ────────────────────────────────+ auto unsqueeze_axis = op::v0::Constant::create(element::i64, Shape{}, std::vector<int64_t>{3});+ auto unsqueeze = std::make_shared<op::v0::Unsqueeze>(reshape, unsqueeze_axis);+ unsqueeze->set_friendly_name("experts/Unsqueeze");++ auto result = std::make_shared<op::v0::Result>(unsqueeze);+ return std::make_shared<ov::Model>(ov::ResultVector{result},+ ov::ParameterVector{router_input},+ "gptoss_router_test");+}++// Count nodes of a specific op type in the model.+template <typename T>+static size_t count_ops_of_type(const std::shared_ptr<ov::Model>& model) {+ size_t count = 0;+ for (const auto& op : model->get_ordered_ops()) {+ if (ov::is_type<T>(op))+ ++count;+ }+ return count;+}++// ─────────────────────────────────────────────────────────────────────────────+// Test 1: The model has exactly 2 ShapeOf nodes before folding and 0 after.+// ─────────────────────────────────────────────────────────────────────────────+TEST(FoldConstTest, RouterShapeOfNodesRemovedAfterFolding) {+ auto model = make_gptoss_router_model();++ ASSERT_EQ(count_ops_of_type<op::v3::ShapeOf>(model), 2u)+ << "Precondition: ShapeOf_A (on Add) and ShapeOf_B (on TopK-indices-Convert)";++ ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(model);++ EXPECT_EQ(count_ops_of_type<op::v3::ShapeOf>(model), 0u)+ << "FoldShapeComputeChain must replace all ShapeOf nodes with Constants";+}++// ─────────────────────────────────────────────────────────────────────────────+// Test 2: After folding, the Broadcast shape input (was ShapeOf_A) is a+// Constant carrying value [1024, 32].+// ─────────────────────────────────────────────────────────────────────────────+TEST(FoldConstTest, RouterBroadcastShapeInputFoldedToConst) {+ auto model = make_gptoss_router_model();+ ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(model);++ bool found_broadcast = false;+ for (const auto& op : model->get_ordered_ops()) {+ if (!ov::is_type<op::v3::Broadcast>(op))+ continue;+ found_broadcast = true;+ // Input port 1 = target_shape (was ShapeOf_A → Const after folding).+ auto shape_input = op->input_value(1).get_node_shared_ptr();+ EXPECT_TRUE(ov::is_type<op::v0::Constant>(shape_input))+ << "Broadcast target-shape input must be a Constant after folding";+ auto c = ov::as_type_ptr<op::v0::Constant>(shape_input);+ ASSERT_NE(c, nullptr);+ auto vals = c->cast_vector<int64_t>();+ ASSERT_EQ(vals.size(), 2u);+ EXPECT_EQ(vals[0], 1024) << "dim[0] should equal seq_len=1024";+ EXPECT_EQ(vals[1], 32) << "dim[1] should equal num_experts=32";+ }+ EXPECT_TRUE(found_broadcast) << "Broadcast node not found in model";+}++// ─────────────────────────────────────────────────────────────────────────────+// Test 3: After folding, the Slice stop input (was ShapeOf_B) is a Constant+// carrying value [1024, 4].+// ─────────────────────────────────────────────────────────────────────────────+TEST(FoldConstTest, RouterSliceStopInputFoldedToConst) {+ auto model = make_gptoss_router_model();+ ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(model);++ bool found_slice = false;+ for (const auto& op : model->get_ordered_ops()) {+ if (!ov::is_type<op::v8::Slice>(op))+ continue;+ found_slice = true;+ // Input port 2 = stop (was ShapeOf_B → Const after folding).+ auto stop_input = op->input_value(2).get_node_shared_ptr();+ EXPECT_TRUE(ov::is_type<op::v0::Constant>(stop_input)) << "Slice stop input must be a Constant after folding";+ auto c = ov::as_type_ptr<op::v0::Constant>(stop_input);+ ASSERT_NE(c, nullptr);+ auto vals = c->cast_vector<int64_t>();+ ASSERT_EQ(vals.size(), 2u);+ EXPECT_EQ(vals[0], 1024) << "dim[0] should equal seq_len=1024";+ EXPECT_EQ(vals[1], 4) << "dim[1] should equal k=4";+ }+ EXPECT_TRUE(found_slice) << "Slice node not found in model";+}++} // namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp b/src/plugins/intel_npu/tests/unit/npuw/serialization.cppindex 22c8d374693..dce1fb74055 100644--- a/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp@@ -135,8 +135,10 @@ void expect_moe_experts_equal(const ov::npuw::compiled::MoEExperts& expected,EXPECT_EQ(expected.expert_hidden_dim, actual.expert_hidden_dim);EXPECT_EQ(expected.num_active_experts, actual.num_active_experts);EXPECT_EQ(expected.input_token_count, actual.input_token_count);- EXPECT_EQ(expected._router_scores_idx, actual._router_scores_idx);- EXPECT_EQ(expected._expert_input_param_idx, actual._expert_input_param_idx);+ EXPECT_EQ(expected._router_scores.original, actual._router_scores.original);+ EXPECT_EQ(expected._router_scores.compiled, actual._router_scores.compiled);+ EXPECT_EQ(expected._expert_input.original, actual._expert_input.original);+ EXPECT_EQ(expected._expert_input.compiled, actual._expert_input.compiled);EXPECT_EQ(expected._param_mapping, actual._param_mapping);}@@ -564,8 +566,10 @@ TEST(SerializationTest, OVTypes_MoEExperts) {var.expert_hidden_dim = 128;var.num_active_experts = 2;var.input_token_count = 64;- var._router_scores_idx = 5;- var._expert_input_param_idx = 3;+ var._router_scores.original = 5;+ var._router_scores.compiled = 7;+ var._expert_input.original = 3;+ var._expert_input.compiled = 2;var._param_mapping = {{0, {1, 2}}, {4, {6, 7, 8}}};ov::npuw::compiled::MoEExperts res;