Skip to content

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

[NPUW]Enable MoE (GPT-OSS-20B) on NPU - HOST_ROUTED. (#33372)

intelgaoxiong4eadb95f3cdc
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp
index 2f0940891d6..4d13b70724f 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp
@@ -118,6 +118,8 @@ DEFINE_OPT(NPUW_SPATIAL, bool, false, npuw::partitioning::spatial, RunTime);
DEFINE_OPT(NPUW_F16IC, bool, true, npuw::partitioning::f16_interconnect, RunTime);
DEFINE_OPT(NPUW_SPATIAL_NWAY, std::size_t, 128, npuw::partitioning::spatial_nway, RunTime);
DEFINE_OPT(NPUW_SPATIAL_DYN, bool, true, npuw::partitioning::spatial_dyn, RunTime);
+DEFINE_OPT(NPUW_MOE_TOKEN_CHUNK_SIZE, uint64_t, 0, npuw::partitioning::moe_token_chunk_size, RunTime);
+DEFINE_OPT(NPUW_MOE_POOL_SIZE, std::size_t, 8, npuw::partitioning::moe_pool_size, RunTime);
DEFINE_OPT(NPUW_ATTN, std::string, "STATIC", npuw::partitioning::attn, RunTime);
DEFINE_OPT(NPUW_ATTN_DYN, bool, true, npuw::partitioning::attn_dyn, RunTime);
DEFINE_OPT(NPUW_ATTN_NO_COPY, bool, false, npuw::partitioning::attn_no_copy, RunTime);
@@ -172,6 +174,7 @@ namespace llm {
enum class PrefillHint { DYNAMIC, STATIC };
enum class GenerateHint { FAST_COMPILE, BEST_PERF };
enum class AttentionHint { DYNAMIC, STATIC, PYRAMID, HFA };
+enum class MoEHint { DENSE, HOST_ROUTED, DEVICE_ROUTED };
} // namespace llm
} // namespace npuw
@@ -279,6 +282,62 @@ struct NPUW_LLM_PREFILL_ATTENTION_HINT final : ATTN_HINT_BASE {
}
};
+struct MOE_HINT_BASE : OptionBase<MOE_HINT_BASE, ::intel_npu::npuw::llm::MoEHint> {
+ static constexpr std::string_view getTypeName() {
+ return "::intel_npu::npuw::llm::MoEHint";
+ }
+
+ static ::intel_npu::npuw::llm::MoEHint defaultValue() {
+ return ::intel_npu::npuw::llm::MoEHint::HOST_ROUTED;
+ }
+
+ static ::intel_npu::npuw::llm::MoEHint parse(std::string_view val) {
+ if (val == "DENSE") {
+ return ::intel_npu::npuw::llm::MoEHint::DENSE;
+ } else if (val == "HOST_ROUTED") {
+ return ::intel_npu::npuw::llm::MoEHint::HOST_ROUTED;
+ } else if (val == "DEVICE_ROUTED") {
+ return ::intel_npu::npuw::llm::MoEHint::DEVICE_ROUTED;
+ }
+ OPENVINO_THROW("Unsupported MoE hint provided: ", val);
+ return {};
+ }
+
+ static std::string toString(const ::intel_npu::npuw::llm::MoEHint& val) {
+ switch (val) {
+ case ::intel_npu::npuw::llm::MoEHint::DENSE:
+ return "DENSE";
+ case ::intel_npu::npuw::llm::MoEHint::HOST_ROUTED:
+ return "HOST_ROUTED";
+ case ::intel_npu::npuw::llm::MoEHint::DEVICE_ROUTED:
+ return "DEVICE_ROUTED";
+ default:
+ OPENVINO_THROW("Can't convert provided MoE hint : ", int(val), " to string.");
+ }
+ return {};
+ }
+
+ static OptionMode mode() {
+ return OptionMode::RunTime;
+ }
+
+ static bool isPublic() {
+ return false;
+ }
+};
+
+struct NPUW_LLM_PREFILL_MOE_HINT final : MOE_HINT_BASE {
+ static std::string_view key() {
+ return ov::intel_npu::npuw::llm::prefill_moe_hint.name();
+ }
+};
+
+struct NPUW_LLM_GENERATE_MOE_HINT final : MOE_HINT_BASE {
+ static std::string_view key() {
+ return ov::intel_npu::npuw::llm::generate_moe_hint.name();
+ }
+};
+
struct NPUW_LLM_GENERATE_HINT final : OptionBase<NPUW_LLM_GENERATE_HINT, ::intel_npu::npuw::llm::GenerateHint> {
static std::string_view key() {
return ov::intel_npu::npuw::llm::generate_hint.name();
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp
index 8eebcd4281b..15affde95b6 100644
--- a/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp
+++ b/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp
@@ -248,6 +248,39 @@ static constexpr ov::Property<std::size_t> spatial_nway{"NPUW_SPATIAL_NWAY"};
*/
static constexpr ov::Property<bool> spatial_dyn{"NPUW_SPATIAL_DYN"};
+/**
+ * @brief
+ * Type: uint64_t.
+ * MoE expert model compilation strategy for prefill stage token chunking.
+ *
+ * When set to 0 (default): Compiles multiple expert models with different chunk sizes
+ * {16, 32, 64, 128, 256} for dynamic chunk selection at runtime. This provides optimal
+ * performance by selecting the best chunk size based on remaining tokens.
+ *
+ * When set to a specific value (e.g., 128, 256): Compiles only a single expert model
+ * with the specified fixed chunk size. This reduces compilation time and memory usage but
+ * may not be optimal for all token counts.
+ *
+ * The chunk size should be a power of two for best hardware utilization.
+ * Note: This only affects prefill stage (multi-token inference). Decoding stage (single token)
+ * always uses a dedicated model regardless of this setting.
+ *
+ * Default value: 0 (dynamic multi-model compilation).
+ */
+static constexpr ov::Property<uint64_t> moe_token_chunk_size{"NPUW_MOE_TOKEN_CHUNK_SIZE"};
+
+/**
+ * @brief Configure MoE request pool size per layer for caching expert configurations.
+ *
+ * Controls the number of pre-allocated inference requests per MoE layer to cache
+ * different expert combinations. Using LRU eviction when pool is full.
+ * Setting to 0 disables the MoE request cache entirely.
+ *
+ * Type: std::size_t.
+ * Default value: 8 (cache up to 8 expert configurations per layer).
+ */
+static constexpr ov::Property<std::size_t> moe_pool_size{"NPUW_MOE_POOL_SIZE"};
+
/**
* @brief
* Type: std::string.
@@ -433,6 +466,7 @@ static constexpr ov::Property<std::string> inputs_outputs{"NPUW_DUMP_IO"};
* Default value: false.
*/
static constexpr ov::Property<std::string> io_iters{"NPUW_DUMP_IO_ITERS"};
+
} // namespace dump
namespace llm {
@@ -511,6 +545,24 @@ static constexpr ov::Property<bool> optimize_v_tensors{"NPUW_LLM_OPTIMIZE_V_TENS
*/
static constexpr ov::Property<bool> cache_rope{"NPUW_LLM_CACHE_ROPE"};
+/**
+ * @brief
+ * Type: ::intel_npu::npuw::llm::MoEHint
+ * Specify MoE (Mixture of Experts) implementation strategy for prefill stage
+ * Possible values: DENSE, HOST_ROUTED, DEVICE_ROUTED
+ * Default value: HOST_ROUTED (recommended for prefill to avoid NPU-unfriendly operations)
+ */
+static constexpr ov::Property<std::string> prefill_moe_hint{"NPUW_LLM_PREFILL_MOE_HINT"};
+
+/**
+ * @brief
+ * Type: ::intel_npu::npuw::llm::MoEHint
+ * Specify MoE (Mixture of Experts) implementation strategy for generate/decoding stage
+ * Possible values: DENSE, HOST_ROUTED, DEVICE_ROUTED
+ * Default value: HOST_ROUTED (DEVICE_ROUTED recommended for better decoding performance)
+ */
+static constexpr ov::Property<std::string> generate_moe_hint{"NPUW_LLM_GENERATE_MOE_HINT"};
+
/**
* @brief
* Type: boolean
diff --git a/src/plugins/intel_npu/src/al/src/config/npuw.cpp b/src/plugins/intel_npu/src/al/src/config/npuw.cpp
index 09f03a73ca3..2bb4be950d1 100644
--- a/src/plugins/intel_npu/src/al/src/config/npuw.cpp
+++ b/src/plugins/intel_npu/src/al/src/config/npuw.cpp
@@ -33,6 +33,8 @@ void intel_npu::registerNPUWOptions(OptionsDesc& desc) {
desc.add<NPUW_SPATIAL>();
desc.add<NPUW_SPATIAL_NWAY>();
desc.add<NPUW_SPATIAL_DYN>();
+ desc.add<NPUW_MOE_TOKEN_CHUNK_SIZE>();
+ desc.add<NPUW_MOE_POOL_SIZE>();
desc.add<NPUW_ATTN>();
desc.add<NPUW_ATTN_DYN>();
desc.add<NPUW_ATTN_NO_COPY>();
@@ -69,6 +71,8 @@ void intel_npu::registerNPUWLLMOptions(OptionsDesc& desc) {
desc.add<NPUW_LLM_MAX_LORA_RANK>();
desc.add<NPUW_LLM_OPTIMIZE_V_TENSORS>();
desc.add<NPUW_LLM_CACHE_ROPE>();
+ desc.add<NPUW_LLM_PREFILL_MOE_HINT>();
+ desc.add<NPUW_LLM_GENERATE_MOE_HINT>();
desc.add<NPUW_LLM_GENERATE_PYRAMID>();
desc.add<NPUW_LLM_PREFILL_CHUNK_SIZE>();
desc.add<NPUW_LLM_ENABLE_PREFIX_CACHING>();
diff --git a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp
index d35fe0666f3..a5ba58a7554 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp
@@ -420,6 +420,12 @@ void ov::npuw::IBaseInferRequest::unpack_closure(std::size_t idx, RqPtr request)
const auto real_idx = comp_model_desc.replaced_by.value();
auto& func_desc = m_npuw_model->m_compiled_submodels[real_idx];
+ // Skip MoE expert submodels - MoE experts require special unpacking logic according to the
+ // expert selection, which is handled later in the inference flow.
+ if (func_desc.moe_experts.has_value()) {
+ return;
+ }
+
// Bind extra parameters from the function's closure
// First, do easy things & delay heavy stuff
std::vector<std::size_t> closure_unpack_required;
@@ -506,6 +512,12 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ
const auto& iodesc = m_subrequests_gio.at(idx);
const auto& proto_comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];
+
+ if (proto_comp_model_desc.moe_experts.has_value()) {
+ // Expert submodel does not have global parameters to bind
+ return;
+ }
+
const bool is_spatial = proto_comp_model_desc.spatial.has_value();
const bool is_attention = proto_comp_model_desc.attention.has_value();
const bool is_pyramid_attention = proto_comp_model_desc.pyramid_attention.has_value();
diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
index 0eb53d34e73..82d12fb32f6 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
@@ -403,6 +403,24 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
compiled::HostFlashAttention(fcn_template._host_flash_attention.value());
}
+ if (fcn_template._moe_experts) {
+ m_compiled_submodels[id].moe_experts = compiled::MoEExperts(fcn_template._moe_experts.value());
+
+ // Point model to first chunk size model (actual compilation handled by compile_moe_models)
+ const auto& models_to_compile = m_compiled_submodels[id].moe_experts.value()._models_to_compile;
+ NPUW_ASSERT(!models_to_compile.empty() && "Fatal: MoEExperts has no models to compile!");
+ m_compiled_submodels[id].model = models_to_compile.begin()->second;
+ }
+
+ if (fcn_template._moe_experts_downstream) {
+ m_compiled_submodels[id].moe_experts_downstream =
+ compiled::MoEDownstream(fcn_template._moe_experts_downstream.value());
+
+ // Set the model to compile from MoEDownstream
+ m_compiled_submodels[id].model =
+ m_compiled_submodels[id].moe_experts_downstream.value()._model_to_compile;
+ }
+
LOG_INFO("Subgraph[" << id << "] is a function body for " << subgraph._funcall);
} else {
// ...and refer to it in other calls
@@ -432,19 +450,28 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
// Do it just once if that's a function
if (real_id == id) {
auto fix_tensor_names = [&](const std::shared_ptr<ov::Model>& model) {
- remove_long_output_names(model);
- fill_empty_tensor_names(model);
+ if (model) {
+ remove_long_output_names(model);
+ fill_empty_tensor_names(model);
+ }
};
- fix_tensor_names(m_compiled_submodels[real_id].model);
+ // Fix tensor names for MoE expert models
+ if (const auto& moe_experts = m_compiled_submodels[real_id].moe_experts) {
+ for (const auto& [chunk_size, model] : moe_experts.value()._models_to_compile) {
+ fix_tensor_names(model);
+ }
+ }
- // Ensure all submodels (including pyramid attention) have consistent and valid tensor names
- // to avoid issues in downstream inference and model serialization.
+ // Fix tensor names for pyramid attention models
if (const auto& pyramid_attn = m_compiled_submodels[real_id].pyramid_attention) {
for (const auto& model : pyramid_attn.value()._models_to_compile) {
fix_tensor_names(model);
}
}
+
+ // Fix tensor names for main model (if not replaced by special models above)
+ fix_tensor_names(m_compiled_submodels[real_id].model);
}
dump_subgraph_model(id, subgraph._funcall, dump_sub_opt);
@@ -691,6 +718,40 @@ void ov::npuw::CompiledModel::CompiledModelDesc::serialize(std::ostream& stream,
}
}
+ // Serialize MoE experts
+ write(stream, moe_experts);
+ if (moe_experts.has_value()) {
+ const auto& moe = moe_experts.value();
+ size_t num_compiled_models = moe._compiled_models.size();
+ write(stream, num_compiled_models);
+
+ for (const auto& [chunk_size, compiled_model] : moe._compiled_models) {
+ write(stream, chunk_size);
+ if (compiled_model) {
+ write(stream, true);
+ std::stringstream ss;
+ compiled_model->export_model(ss);
+ write(stream, ss.str());
+ } else {
+ write(stream, false);
+ }
+ }
+ }
+
+ // Serialize MoE experts downstream
+ write(stream, moe_experts_downstream);
+ if (moe_experts_downstream.has_value()) {
+ const auto& moe_downstream = moe_experts_downstream.value();
+ if (moe_downstream._compiled_model) {
+ write(stream, true);
+ std::stringstream ss;
+ moe_downstream._compiled_model->export_model(ss);
+ write(stream, ss.str());
+ } else {
+ write(stream, false);
+ }
+ }
+
// Serialize host flash attention
write(stream, host_flash_attention);
if (host_flash_attention.has_value()) {
@@ -808,6 +869,48 @@ void ov::npuw::CompiledModel::CompiledModelDesc::deserialize(
}
}
+ // Deserialize MoE experts
+ read(stream, moe_experts);
+ if (moe_experts.has_value()) {
+ size_t num_compiled_models = 0;
+ read(stream, num_compiled_models);
+
+ for (size_t i = 0; i < num_compiled_models; ++i) {
+ size_t chunk_size = 0;
+ read(stream, chunk_size);
+
+ bool has_model = false;
+ read(stream, has_model);
+
+ if (has_model) {
+ std::string model_str;
+ read(stream, model_str);
+ std::stringstream ss(model_str);
+ auto compiled_model = submodel_ctx.plugin->get_core()->import_model(ss, submodel_ctx.device);
+ moe_experts->_compiled_models[chunk_size] = compiled_model;
+ LOG_DEBUG("Imported MoE compiled model for chunk_size=" << chunk_size);
+ }
+ }
+
+ LOG_DEBUG("Deserialized " << moe_experts->_compiled_models.size() << " MoE expert models");
+ }
+
+ // Deserialize MoE experts downstream
+ read(stream, moe_experts_downstream);
+ if (moe_experts_downstream.has_value()) {
+ bool has_model = false;
+ read(stream, has_model);
+
+ if (has_model) {
+ std::string model_str;
+ read(stream, model_str);
+ std::stringstream ss(model_str);
+ auto compiled_model = submodel_ctx.plugin->get_core()->import_model(ss, submodel_ctx.device);
+ moe_experts_downstream->_compiled_model = compiled_model;
+ LOG_DEBUG("Imported MoE downstream compiled model");
+ }
+ }
+
// Deserialize host flash attention
read(stream, host_flash_attention);
if (host_flash_attention.has_value()) {
@@ -1658,15 +1761,14 @@ bool ov::npuw::CompiledModel::compile_for_device(std::size_t id, const std::stri
}
try {
- // WARNING: These requests can be issues in parallel, so timer should be thread-safe
- m_profile["compile/" + device_to_try].record([&]() {
- m_compiled_submodels[id].compiled_model = compile_submodel(m_compiled_submodels[id].model, device_to_try);
- });
+ // WARNING: These requests can be issued in parallel, so timer should be thread-safe
- // Compile pyramid attention models if present
- compile_pyramid_attention_models(id, device_to_try);
+ // Compile main model (normal models only)
+ compile_main_model(id, device_to_try);
- // Compile host flash attention model if present
+ // Compile special model types
+ compile_moe_models(id, device_to_try);
+ compile_pyramid_attention_models(id, device_to_try);
compile_host_flash_attention_model(id, device_to_try);
} catch (const std::exception& ex) {
LOG_ERROR("Subgraph [" << id << "] Failed to compile: " << std::endl << ex.what());
@@ -1682,6 +1784,67 @@ bool ov::npuw::CompiledModel::compile_for_device(std::size_t id, const std::stri
return true;
}
+void ov::npuw::CompiledModel::compile_main_model(std::size_t id, const std::string& device) {
+ // Skip if this is a MoE model - handled separately
+ if (m_compiled_submodels[id].moe_experts.has_value() ||
+ m_compiled_submodels[id].moe_experts_downstream.has_value()) {
+ return;
+ }
+
+ // Normal compilation for standard models
+ m_profile["compile/" + device].record([&]() {
+ m_compiled_submodels[id].compiled_model = compile_submodel(m_compiled_submodels[id].model, device);
+ });
+}
+
+void ov::npuw::CompiledModel::compile_moe_models(std::size_t id, const std::string& device) {
+ // Check if we have MoE experts to compile
+ if (auto& moe_experts_opt = m_compiled_submodels[id].moe_experts; moe_experts_opt.has_value()) {
+ LOG_INFO("Compiling MoE expert models for different chunk sizes...");
+ LOG_BLOCK();
+
+ auto& moe_experts = moe_experts_opt.value();
+ const auto& models_to_compile = moe_experts._models_to_compile;
+
+ LOG_INFO("Total MoE models to compile: " << models_to_compile.size());
+
+ // Compile each chunk size model
+ for (const auto& entry : models_to_compile) {
+ LOG_INFO("Compiling MoE expert model for chunk_size=" << entry.first);
+
+ m_profile["compile/" + device + "/moe_chunk_" + std::to_string(entry.first)].record([&, entry]() {
+ auto compiled = compile_submodel(entry.second, device);
+ moe_experts.set_compiled_model(entry.first, std::move(compiled));
+ });
+
+ LOG_INFO("Successfully compiled MoE expert model for chunk_size=" << entry.first);
+ }
+
+ // Set compiled_model to first compiled model for backward compatibility
+ // Inference requests will be created from _compiled_models in MoEExperts
+ const auto& compiled_models = moe_experts._compiled_models;
+ if (!compiled_models.empty()) {
+ m_compiled_submodels[id].compiled_model = compiled_models.begin()->second;
+ }
+
+ LOG_INFO("MoE expert compilation complete for Subgraph[" << id << "]");
+ return;
+ }
+
+ // Check if we have MoE downstream to compile
+ if (auto& moe_downstream_opt = m_compiled_submodels[id].moe_experts_downstream; moe_downstream_opt.has_value()) {
+ LOG_INFO("Compiling MoE downstream model for Subgraph[" << id << "]...");
+
+ m_profile["compile/" + device].record([&]() {
+ auto compiled = compile_submodel(m_compiled_submodels[id].model, device);
+ m_compiled_submodels[id].compiled_model = compiled;
+ moe_downstream_opt->set_compiled_model(std::move(compiled));
+ });
+
+ LOG_INFO("MoE downstream compilation complete for Subgraph[" << id << "]");
+ }
+}
+
void ov::npuw::CompiledModel::compile_pyramid_attention_models(std::size_t id, const std::string& device) {
// Check if we have pyramid attention to compile
if (!m_compiled_submodels[id].pyramid_attention.has_value()) {
@@ -1856,7 +2019,35 @@ void ov::npuw::CompiledModel::dump_subgraph_model(std::size_t id,
if (real_id != id) {
LOG_INFO("NOTE: Dumping Subgraph[" << real_id << "]" << " as it is a function body for Subgraph[" << id << "]");
}
+
+ // Dump MoE expert models if present
+ if (m_compiled_submodels[id].moe_experts) {
+ LOG_INFO("NOTE: Subgraph[" << id << "] has MoE experts mechanism.");
+ const auto& moe_models = m_compiled_submodels[id].moe_experts.value()._models_to_compile;
+
+ if (moe_models.empty()) {
+ LOG_WARN("MoE experts models are empty (already compiled and cleared)");
+ } else {
+ for (const auto& entry : moe_models) {
+ size_t chunk_size = entry.first;
+ const auto& moe_model = entry.second;
+
+ std::string moe_model_dump_path = m_name + "_" + ov::npuw::util::fmt(id, m_compiled_submodels.size()) +
+ (funcall.empty() ? "" : "_" + funcall) + "_moe_chunk_" +
+ std::to_string(chunk_size) + ".xml";
+ ov::save_model(moe_model, moe_model_dump_path);
+ LOG_INFO("Wrote " << moe_model_dump_path);
+ }
+ }
+ return; // MoE experts don't have a single model to dump
+ }
+
const auto model_to_dump = m_compiled_submodels[real_id].model;
+ if (!model_to_dump) {
+ LOG_WARN("Model is null, cannot dump Subgraph[" << id << "]");
+ return;
+ }
+
std::string model_dump_path = m_name + "_" + ov::npuw::util::fmt(id, m_compiled_submodels.size()) +
(funcall.empty() ? "" : "_" + funcall) + ".xml";
ov::save_model(model_to_dump, model_dump_path);
diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
index e890d28975d..268b431c6b6 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
@@ -12,6 +12,7 @@
#include "host_flash_attention.hpp"
#include "intel_npu/config/config.hpp"
#include "intel_npu/config/npuw.hpp"
+#include "moe_transformations/moe_transformation.hpp"
#include "openvino/openvino.hpp"
#include "openvino/runtime/icompiled_model.hpp"
#include "openvino/runtime/shared_buffer.hpp"
@@ -38,7 +39,13 @@ public:
ICompiledModel(const std::shared_ptr<ov::Model>& model, const std::shared_ptr<const ov::IPlugin>& plugin);
};
+// Forward declarations
class InferRequest;
+
+namespace moe {
+class MoEExecutor;
+}
+
class CompiledModel : public ov::npuw::ICompiledModel {
using DevList = std::vector<std::string>;
using GetPropertiesMap =
@@ -75,11 +82,14 @@ private:
friend class FuncMemMgr;
friend class LLMCompiledModel;
friend class LLMInferRequest;
+ friend class moe::MoEExecutor;
bool compile_for_success(std::size_t id);
bool compile_for_device(std::size_t id, const std::string& device_to_try);
ov::SoPtr<ov::ICompiledModel> compile_submodel(const std::shared_ptr<ov::Model>& submodel,
const std::string& device);
+ void compile_main_model(std::size_t id, const std::string& device);
+ void compile_moe_models(std::size_t id, const std::string& device);
void compile_pyramid_attention_models(std::size_t id, const std::string& device);
void compile_host_flash_attention_model(std::size_t id, const std::string& device);
@@ -184,6 +194,8 @@ private:
std::optional<ov::npuw::compiled::Attention> attention;
std::optional<ov::npuw::compiled::PyramidAttention> pyramid_attention;
std::optional<ov::npuw::compiled::HostFlashAttention> host_flash_attention;
+ std::optional<ov::npuw::compiled::MoEExperts> moe_experts;
+ std::optional<ov::npuw::compiled::MoEDownstream> moe_experts_downstream;
// Infer requests for pyramid attention models (if pyramid_attention is present)
std::vector<ov::SoPtr<ov::IAsyncInferRequest>> pyramid_infer_requests;
@@ -207,6 +219,10 @@ private:
// pipelining is enabled)
std::vector<ov::SoPtr<ov::IAsyncInferRequest>> hfa_pipeline_requests;
+ // Infer requests for MoE expert models with different chunk sizes (if moe_experts is present)
+ // Map: chunk_size -> infer_request
+ std::map<size_t, ov::SoPtr<ov::IAsyncInferRequest>> moe_infer_requests;
+
// FIXME: This is a 1:1 copy of the ov::npuw::Subgraph structure
// w.r.t. function calls
std::size_t param_base = 0;
diff --git a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp
index fc38c548b43..b5bba87e612 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp
@@ -19,6 +19,40 @@
#include "pyramid_attention.hpp"
#include "weights_bank.hpp"
+// ====================================================================================================
+// ISubrequestAccessor Interface Implementation
+// ====================================================================================================
+
+ov::SoPtr<ov::IAsyncInferRequest> ov::npuw::JustInferRequest::get_subrequest(size_t idx) {
+ return m_subrequests[idx];
+}
+
+const void* ov::npuw::JustInferRequest::get_submodel_desc(size_t idx) {
+ return &m_npuw_model->m_compiled_submodels[idx];
+}
+
+ov::npuw::TensorPtr ov::npuw::JustInferRequest::allocate_mem(const ov::element::Type& type,
+ const ov::Shape& shape,
+ const std::string& device) {
+ return allocMem(type, shape, device);
+}
+
+bool ov::npuw::JustInferRequest::is_gather_closure(size_t idx, size_t cidx) {
+ return m_npuw_model->is_gather_closure(idx, cidx);
+}
+
+bool ov::npuw::JustInferRequest::unpack_required(size_t idx, size_t cidx) {
+ return m_npuw_model->unpack_required(idx, cidx);
+}
+
+bool ov::npuw::JustInferRequest::needs_copy_closure(size_t idx, size_t cidx) {
+ return IBaseInferRequest::needs_copy(idx, cidx);
+}
+
+// ====================================================================================================
+// Memory Access Simulation & Function Memory Management
+// ====================================================================================================
+
ov::npuw::MemAccessSim::MemAccessSim(const std::shared_ptr<ov::npuw::CompiledModel>& compiled_model) {
LOG_VERB("Running memory access simulation...");
LOG_BLOCK();
@@ -207,9 +241,11 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
bool has_dynamic = false;
bool has_pyramid = false;
bool has_hfa = false;
+ bool has_moe = false;
std::size_t dynamic_sub_idx = -1;
std::size_t pyramid_sub_idx = -1;
std::size_t hfa_sub_idx = -1;
+ std::size_t moe_real_idx = -1; // Track which real function has MoE
for (size_t i = 0; i < m_num_submodels; i++) {
LOG_INFO("Creating infer request for Subgraph[" << i << "]...");
LOG_BLOCK();
@@ -290,6 +326,16 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
m_hfa_io[i].outputs.resize(num_outputs);
} // if(hfa)
+ // Initialize the MoE IO placeholders, if required
+ if (proto_comp_model_desc.moe_experts) {
+ // Sanity check: ensure only one MoE function type exists
+ if (has_moe && moe_real_idx != real_idx) {
+ OPENVINO_THROW("Only single MoE type is permitted for model");
+ }
+ has_moe = true;
+ moe_real_idx = real_idx;
+ } // if(moe_experts)
+
for (size_t out_idx = 0; out_idx < num_outputs; out_idx++) {
const auto from = LinkFrom{i, out_idx};
m_funcall_result[from] = m_func_mem_mgr.get_tensor(from);
@@ -460,6 +506,11 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
}
LOG_VERB("Done");
}
+
+ // Initialize MoE executor if MoE was detected
+ if (has_moe) {
+ initialize_moe_executor();
+ }
}
void ov::npuw::JustInferRequest::set_tensor(const ov::Output<const ov::Node>& port,
@@ -679,6 +730,7 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {
const bool is_dynamic = func_desc.attention.has_value();
const bool is_pyramid = func_desc.pyramid_attention.has_value();
const bool is_hfa = func_desc.host_flash_attention.has_value();
+ const bool is_moe = func_desc.moe_experts.has_value() || func_desc.moe_experts_downstream.has_value();
// Generalized: check if input is neither param nor mask
auto is_non_param_mask = [](const auto& info, std::size_t in_idx) {
@@ -738,6 +790,11 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {
} else if (is_hfa) {
// Host Flash Attention case - defer, use dedicated HFA I/O structure
m_hfa_io[idx].inputs.at(i) = i_tensor;
+ } else if (is_moe) {
+ // MoE layer: delegate to executor for input binding
+ if (m_moe_executor->function_prologue_moe_input(idx, real_idx, i, i_tensor)) {
+ continue;
+ }
} else {
// Default case
m_subrequests[real_idx]->set_tensor(iport, i_tensor);
@@ -776,7 +833,10 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {
LOG_DEBUG("Binding result[" << i << "]...");
auto& oport = func_desc.compiled_model->outputs()[i];
auto o_tensor = m_funcall_result.at({idx, i});
- if (is_hfa) {
+ if (func_desc.moe_experts) {
+ // MoE case - delegate to executor for output binding
+ m_moe_executor->function_prologue_moe_output(idx, i, o_tensor);
+ } else if (is_hfa) {
// HFA case - defer, store in dedicated HFA I/O structure
m_hfa_io[idx].outputs.at(i) = o_tensor;
} else if (!is_spatial) {
@@ -983,6 +1043,10 @@ void ov::npuw::JustInferRequest::recreate_subrequests(std::size_t idx) {
if (proto_comp_model_desc.host_flash_attention) {
setup_hfa_infer_requests(real_idx, is_piped, /* is_recreate */ true, /* enable_hfa_optimizations */ true);
}
+ // Recreate MoE resources if this function has MoE
+ if (proto_comp_model_desc.moe_experts) {
+ recreate_moe_resources(idx, real_idx);
+ }
}
// After an infer request is recreated, the internal cross-request
@@ -994,6 +1058,47 @@ void ov::npuw::JustInferRequest::recreate_subrequests(std::size_t idx) {
m_subrequest_devices[idx] = *comp_model_desc.device_it;
}
+void ov::npuw::JustInferRequest::initialize_moe_executor() {
+ LOG_INFO("Creating MoE executor...");
+
+ // Create MoE executor with dependency injection
+ m_moe_executor = std::make_unique<ov::npuw::moe::MoEExecutor>(
+ *this, // ISubrequestAccessor
+ [this](const ov::element::Type& type, const ov::Shape& shape, const std::string& device) {
+ // Allocator callback
+ return allocMem(type, shape, device);
+ });
+
+ LOG_INFO("MoE executor created");
+
+ // Prepare MoE resources for each sublayer
+ size_t pool_size = m_npuw_model->m_cfg.get<::intel_npu::NPUW_MOE_POOL_SIZE>();
+ for (size_t i = 0; i < m_num_submodels; i++) {
+ auto& desc = m_npuw_model->m_compiled_submodels[i];
+
+ size_t real_idx = desc.replaced_by.value_or(i);
+ auto& real_desc = m_npuw_model->m_compiled_submodels[real_idx];
+
+ // Check if the real function body has MoE experts
+ if (real_desc.moe_experts.has_value()) {
+ m_moe_executor->prepare(i, real_idx, m_num_submodels, pool_size);
+ }
+ }
+
+ LOG_INFO("MoE executor initialized successfully");
+}
+
+void ov::npuw::JustInferRequest::recreate_moe_resources(std::size_t idx, std::size_t real_idx) {
+ LOG_INFO("Recreating MoE resources for submodel[" << idx << "] (real_idx=" << real_idx << ")...");
+ LOG_BLOCK();
+
+ // Re-prepare MoE resources for this specific submodel
+ size_t pool_size = m_npuw_model->m_cfg.get<::intel_npu::NPUW_MOE_POOL_SIZE>();
+ m_moe_executor->prepare(idx, real_idx, m_num_submodels, pool_size);
+
+ LOG_INFO("MoE resources recreated successfully");
+}
+
void ov::npuw::JustInferRequest::setup_pyramid_infer_requests(std::size_t real_idx, bool is_piped, bool is_recreate) {
auto& submodel_desc = m_npuw_model->m_compiled_submodels[real_idx];
if (!submodel_desc.pyramid_attention.has_value()) {
@@ -1308,7 +1413,7 @@ void ov::npuw::JustInferRequest::run_subrequest_for_success(std::size_t idx, boo
void ov::npuw::JustInferRequest::unsafe_during(std::size_t real_idx, std::size_t idx, const std::function<void()>& f) {
auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];
- if (!comp_model_desc.spatial && !comp_model_desc.host_flash_attention.has_value()) {
+ if (!comp_model_desc.spatial && !comp_model_desc.host_flash_attention.has_value() && !comp_model_desc.moe_experts) {
// Normal: trigger request asynchronously, run `f` in this context
// FIXME: dynamic could hit here too, but it has special logic
// around execution which makes it harder to run than a plain start_async()
@@ -1780,6 +1885,9 @@ void ov::npuw::JustInferRequest::unsafe_infer(std::size_t real_idx, std::size_t
unsafe_infer_spatial(real_idx, idx);
} else if (comp_model_desc.host_flash_attention) {
run_hfa_tiled_inference(real_idx, idx);
+ } else if (comp_model_desc.moe_experts.has_value()) {
+ // Use MoEExecutor
+ m_moe_executor->run(real_idx, idx);
} else {
r->infer(); // Run normally
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp
index a6eef756757..769114611f2 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp
@@ -12,6 +12,8 @@
#include "base_sync_infer_request.hpp"
#include "host_flash_attention.hpp"
+#include "moe/moe_executor.hpp"
+#include "moe/moe_infer_utils.hpp"
#include "openvino/runtime/iplugin.hpp"
#include "openvino/runtime/iremote_context.hpp"
#include "openvino/runtime/make_tensor.hpp"
@@ -67,10 +69,19 @@ private:
AllocFcn m_alloc;
};
-class JustInferRequest final : public IBaseInferRequest {
+class JustInferRequest final : public IBaseInferRequest, public ISubrequestAccessor {
public:
explicit JustInferRequest(const std::shared_ptr<ov::npuw::CompiledModel>& compiled_model);
+ ////////////////////////////////////
+ // Implement ISubrequestAccessor interface
+ ov::SoPtr<ov::IAsyncInferRequest> get_subrequest(size_t idx) override;
+ const void* get_submodel_desc(size_t idx) override;
+ TensorPtr allocate_mem(const ov::element::Type& type, const ov::Shape& shape, const std::string& device) override;
+ bool is_gather_closure(size_t idx, size_t cidx) override;
+ bool unpack_required(size_t idx, size_t cidx) override;
+ bool needs_copy_closure(size_t idx, size_t cidx) override;
+
protected:
////////////////////////////////////
// implement IBaseInferRequest
@@ -135,6 +146,12 @@ protected:
bool is_recreate,
bool enable_hfa_optimizations = true);
+ // Helper function to initialize/reinitialize MoE executor
+ void initialize_moe_executor();
+
+ // Helper function to recreate MoE resources after subrequest recreation
+ void recreate_moe_resources(std::size_t idx, std::size_t real_idx);
+
FuncMemMgr m_func_mem_mgr; // Owns memory
std::map<LinkFrom, TensorPtr> m_funcall_result; // Provides a convenient link
@@ -164,6 +181,9 @@ protected:
// HFA runtime context (holds cached masks, pre-allocated buffers, and state buffers)
std::optional<runtime::host_flash_attention::HFARuntimeContext> m_hfa_runtime_ctx;
+
+ // MoE executor (encapsulates MoE inference logic and profiling)
+ std::unique_ptr<ov::npuw::moe::MoEExecutor> m_moe_executor;
};
} // namespace npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
index 7acf4c6522c..6ced5a65bfb 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
@@ -25,6 +25,7 @@
#include "openvino/pass/validate.hpp"
#include "openvino/runtime/iasync_infer_request.hpp"
#include "openvino/runtime/properties.hpp"
+#include "partitioning/patterns/moe.hpp"
#include "partitioning/patterns/pre_compute.hpp"
#include "partitioning/patterns/sdpa.hpp"
#include "serialization.hpp"
@@ -1202,6 +1203,59 @@ std::map<std::string, std::string> any_copy(const ov::AnyMap& params) {
}
return result;
}
+
+// Detect if the model is a Mixture-of-Experts (MoE) architecture
+// by checking if any node name matches MoE patterns: layers.*.mlp.router or layers.*.mlp.experts
+bool is_moe_model(const std::shared_ptr<ov::Model>& model) {
+ for (const auto& op : model->get_ops()) {
+ const std::string& node_name = op->get_friendly_name();
+ // Check for MoE-specific patterns:
+ // - layers.*.mlp.router (router network for expert selection)
+ // - layers.*.mlp.experts (expert networks)
+ // Note: "expert" also matches "experts" (plural)
+ if (node_name.find(ov::npuw::patterns::moe::MLP_ROUTER_NAME) != std::string::npos ||
+ node_name.find(ov::npuw::patterns::moe::MLP_EXPERT_NAME) != std::string::npos) {
+ LOG_INFO("Detected MoE model: found node with MoE pattern - " << node_name);
+ return true;
+ }
+ }
+ LOG_DEBUG("Non-MoE model detected: no .mlp.router or .mlp.expert nodes found");
+ return false;
+}
+
+// Apply MoE-specific optimizations to stage configuration based on hint
+void apply_moe_optimizations(ov::AnyMap& stage_config,
+ ::intel_npu::npuw::llm::MoEHint moe_hint,
+ const std::string& stage_name) {
+ // MoE expert and router pattern isolation options
+ const ov::AnyMap expert_opts = {
+ {"NPUW_ONLINE_PIPELINE", "REP"},
+ {"NPUW_ONLINE_ISOLATE", "MOE"},
+ {"NPUW_ONLINE_KEEP_BLOCK_SIZE", "4"},
+ {"NPUW_UNFOLD_IREQS", "NO"},
+ };
+
+ if (moe_hint == ::intel_npu::npuw::llm::MoEHint::HOST_ROUTED) {
+ LOG_INFO("MoE architecture optimization for " << stage_name
+ << " stage: HOST_ROUTED (host-side expert routing)");
+ merge_config_with(stage_config, expert_opts);
+ } else if (moe_hint == ::intel_npu::npuw::llm::MoEHint::DEVICE_ROUTED) {
+ NPUW_ASSERT(false && "MoE DEVICE_ROUTED is not yet implemented! "
+ "DEVICE_ROUTED will use in-graph gather-based expert selection to avoid "
+ "graph splitting and reduce host-device communication overhead. "
+ "This feature is planned for future releases.");
+ } else if (moe_hint == ::intel_npu::npuw::llm::MoEHint::DENSE) {
+ LOG_INFO("MoE architecture optimization for " << stage_name << " stage: DENSE (all experts active)");
+ // DENSE mode requires CPU-only device due to extremely long NPU compilation time and high resource consumption
+ auto npuw_devices =
+ stage_config.count("NPUW_DEVICES") ? stage_config.at("NPUW_DEVICES").as<std::string>() : "NPU";
+ NPUW_ASSERT(npuw_devices == "CPU" &&
+ "MoE DENSE mode requires CPU-only device (NPUW_DEVICES must be 'CPU'). "
+ "DENSE activates all experts simultaneously, causing extremely long NPU compilation time. "
+ "Please set NPUW_DEVICES to 'CPU'.");
+ }
+}
+
} // namespace
void ov::npuw::LLMCompiledModel::convert_stateful_lora_to_stateless(std::shared_ptr<ov::Model>& model) {
@@ -1669,6 +1723,18 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
merge_config_with(generate_config, dyn_attn_opts);
}
+ // Auto-detect MoE model by scanning for router/expert nodes
+ const bool is_moe = is_moe_model(kvcache_model);
+ if (is_moe) {
+ // Apply MoE optimizations for prefill stage
+ const auto prefill_moe_hint = m_cfg.get<::intel_npu::NPUW_LLM_PREFILL_MOE_HINT>();
+ apply_moe_optimizations(prefill_config, prefill_moe_hint, "PREFILL");
+
+ // Apply MoE optimizations for generate stage
+ const auto generate_moe_hint = m_cfg.get<::intel_npu::NPUW_LLM_GENERATE_MOE_HINT>();
+ apply_moe_optimizations(generate_config, generate_moe_hint, "GENERATE");
+ }
+
// Note: with dynamic attention in EITHER STAGE, we have to
// explicitly disable the run-time fallback to so extra ov::Model
// references won't be held by the npuw::CompiledModel, resulting
@@ -2213,6 +2279,8 @@ void ov::npuw::LLMCompiledModel::implement_properties() {
BIND(npuw::llm::min_response_len, NPUW_LLM_MIN_RESPONSE_LEN, get),
BIND(npuw::llm::optimize_v_tensors, NPUW_LLM_OPTIMIZE_V_TENSORS, get),
BIND(npuw::llm::cache_rope, NPUW_LLM_CACHE_ROPE, get),
+ BIND(npuw::llm::prefill_moe_hint, NPUW_LLM_PREFILL_MOE_HINT, get),
+ BIND(npuw::llm::generate_moe_hint, NPUW_LLM_GENERATE_MOE_HINT, get),
BIND(npuw::llm::generate_pyramid, NPUW_LLM_GENERATE_PYRAMID, get),
BIND(npuw::llm::prefill_chunk_size, NPUW_LLM_PREFILL_CHUNK_SIZE, get),
BIND(npuw::llm::prefill_hint, NPUW_LLM_PREFILL_HINT, getString),
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.hpp
new file mode 100644
index 00000000000..e40f30d2a6d
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_config.hpp
@@ -0,0 +1,83 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <map>
+#include <optional>
+#include <vector>
+
+#include "moe_types.hpp"
+#include "openvino/runtime/icompiled_model.hpp"
+#include "openvino/runtime/so_ptr.hpp"
+
+namespace ov {
+namespace npuw {
+namespace moe {
+
+/**
+ * @brief MoE compilation-time configuration (read-only)
+ *
+ * Contains static configuration extracted from CompiledModel::MoEExperts.
+ * This structure is initialized once during prepare() and remains constant
+ * throughout the inference lifecycle.
+ */
+struct MoEConfig {
+ // Expert topology configuration
+ size_t num_experts = 0; // Total number of experts (e.g., 32)
+ size_t num_active_experts = 0; // Number of experts activated per token (e.g., 4)
+ size_t input_token_count = 0; // Number of input tokens
+ size_t expert_hidden_dim = 0; // Expert output embedding dimension
+
+ // Parameter mapping for unrolled models
+ // Maps original parameter index to unrolled parameter indices
+ // Example: param[5] -> [param[10], param[11], param[12], param[13]] for K=4 experts
+ std::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)
+
+ // Compiled models for different chunk sizes (for EXPERT_ITERATIVE mode)
+ // Key: chunk_size (e.g., 256, 128, 64, 32, 16)
+ // Value: Compiled model for that chunk size
+ std::map<size_t, ov::SoPtr<ov::ICompiledModel>> compiled_models;
+
+ /**
+ * @brief Get processing mode based on input token count
+ * @return EXPERT_BATCH for single token, EXPERT_ITERATIVE for multiple tokens
+ */
+ MoEProcessingMode get_processing_mode() const {
+ return determine_processing_mode(input_token_count);
+ }
+
+ /**
+ * @brief Check if using expert batch mode
+ * Single token processed with K experts in parallel
+ */
+ bool is_expert_batch_mode() const {
+ return get_processing_mode() == MoEProcessingMode::EXPERT_BATCH;
+ }
+
+ /**
+ * @brief Check if using expert iterative mode
+ * Multiple tokens processed by iterating through experts
+ */
+ bool is_expert_iterative_mode() const {
+ return get_processing_mode() == MoEProcessingMode::EXPERT_ITERATIVE;
+ }
+
+ /**
+ * @brief Validate configuration consistency
+ */
+ bool is_valid() const {
+ return num_experts > 0 && num_active_experts > 0 && num_active_experts <= num_experts &&
+ input_token_count > 0 && expert_hidden_dim > 0 && !compiled_models.empty();
+ }
+};
+
+} // namespace moe
+} // namespace npuw
+} // namespace ov
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.cpp
new file mode 100644
index 00000000000..bbc5b6e5713
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp
@@ -0,0 +1,799 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_executor.hpp"
+
+#include "../compiled_model.hpp" // For CompiledModel::CompiledModelDesc
+#include "../logging.hpp"
+#include "moe_infer_utils.hpp"
+#include "moe_types.hpp" // For MoEIO definition
+#include "openvino/core/except.hpp"
+#include "openvino/core/parallel.hpp" // For ov::parallel_for
+
+namespace ov {
+namespace npuw {
+namespace moe {
+
+MoEExecutor::MoEExecutor(ISubrequestAccessor& accessor, AllocatorFn allocator)
+ : m_accessor(accessor),
+ m_allocator(std::move(allocator)) {
+ // Profile will be initialized using profiling_enabled() in MoEProfile constructor
+ m_profile.emplace(); // MoEProfile constructor reads profiling_enabled()
+ LOG_DEBUG("MoEExecutor created");
+}
+
+void MoEExecutor::prepare(size_t idx, size_t real_idx, size_t num_sublayers, size_t pool_size) {
+ LOG_INFO("Preparing MoE resources for sublayer[" << idx << "] (real_idx=" << real_idx << ")...");
+ LOG_BLOCK();
+
+ // Get function body descriptor directly (no need to resolve, caller already did it)
+ const auto& desc =
+ *static_cast<const ov::npuw::CompiledModel::CompiledModelDesc*>(m_accessor.get_submodel_desc(real_idx));
+
+ if (!desc.moe_experts.has_value()) {
+ OPENVINO_THROW("MoEExecutor::prepare called on non-MoE submodel[real_idx=", real_idx, "]");
+ }
+
+ const auto& moe_experts = desc.moe_experts.value();
+
+ // Step 1: Initialize MoE config (only once, on first prepare call)
+ if (!m_config.is_valid()) {
+ LOG_DEBUG("Creating shared MoE config");
+
+ m_config.num_experts = moe_experts.num_experts;
+ m_config.num_active_experts = moe_experts.num_active_experts;
+ m_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.compiled_models = moe_experts._compiled_models;
+
+ // Validate configuration
+ if (!m_config.is_valid()) {
+ OPENVINO_THROW("Invalid MoE configuration");
+ }
+
+ LOG_DEBUG("MoE Config: num_experts=" << m_config.num_experts
+ << ", num_active_experts=" << m_config.num_active_experts
+ << ", input_token_count=" << m_config.input_token_count
+ << ", mode=" << get_mode_name(m_config.get_processing_mode()));
+
+ // Step 2: Initialize resources based on processing mode
+ LOG_DEBUG("Initializing MoE resources...");
+ if (m_config.is_expert_batch_mode()) {
+ m_resources.initialize_expert_batch_mode(m_config,
+ m_allocator,
+ get_device_name(idx, &desc),
+ num_sublayers,
+ pool_size);
+ } else {
+ m_resources.initialize_expert_iterative_mode(m_config, m_allocator, get_device_name(idx, &desc));
+ }
+ } else {
+ LOG_DEBUG("Reusing existing shared MoE config and resources");
+ }
+
+ // Step 3: Initialize request pool for this sublayer (expert batch mode only)
+ if (pool_size > 0 && m_config.is_expert_batch_mode()) {
+ std::vector<RqPtr> requests;
+ requests.resize(pool_size);
+
+ // Create first request separately (needed for tensor sharing)
+ try {
+ requests[0] = desc.compiled_model->create_infer_request();
+ requests[0]->infer(); // Warmup
+ LOG_DEBUG("Created and warmed up request[0]");
+ } catch (const std::exception& ex) {
+ LOG_ERROR("Failed to create MoE pool request[0] for sublayer[" << idx << "]: " << ex.what());
+ throw;
+ }
+
+ // Create remaining requests in parallel, sharing tensors from first request
+ ov::parallel_for(pool_size - 1, [&](size_t i) {
+ const size_t req_idx = i + 1;
+ try {
+ auto request = desc.compiled_model->create_infer_request();
+
+ // Share all input & output tensors from first request to save memory
+ const auto& inputs = desc.compiled_model->inputs();
+ for (size_t input_idx = 0; input_idx < inputs.size(); ++input_idx) {
+ request->set_tensor(inputs[input_idx], requests[0]->get_tensor(inputs[input_idx]));
+ }
+ const auto& outputs = desc.compiled_model->outputs();
+ for (size_t output_idx = 0; output_idx < outputs.size(); ++output_idx) {
+ request->set_tensor(outputs[output_idx], requests[0]->get_tensor(outputs[output_idx]));
+ }
+
+ request->infer(); // Warmup
+ requests[req_idx] = std::move(request);
+ } catch (const std::exception& ex) {
+ LOG_ERROR("Failed to create MoE pool request[" << req_idx << "] for sublayer[" << idx
+ << "]: " << ex.what());
+ throw;
+ }
+ });
+
+ // Initialize cache layer with pre-allocated requests
+ m_resources.request_cache->initialize_layer(idx, std::move(requests));
+ LOG_DEBUG("Request pool created with " << pool_size << " requests");
+ } else {
+ LOG_DEBUG("Request cache disabled (pool_size=" << pool_size << ", mode="
+ << get_mode_name(m_config.get_processing_mode()) << ")");
+ }
+
+ // Step 4: Initialize MoE I/O structure for this sublayer
+ if (m_moe_io.empty()) {
+ m_moe_io.resize(num_sublayers);
+ LOG_DEBUG("Pre-allocated MoE I/O storage for " << num_sublayers << " sublayers");
+ }
+ NPUW_ASSERT(idx < m_moe_io.size() && "Sublayer index out of range");
+
+ const auto num_outputs = desc.compiled_model->outputs().size();
+ m_moe_io[idx].outputs.resize(num_outputs);
+ LOG_DEBUG("Initialized MoE I/O with " << num_outputs << " outputs");
+
+ LOG_INFO("MoE preparation completed for sublayer[" << idx << "]");
+}
+
+bool MoEExecutor::function_prologue_moe_input(size_t idx,
+ size_t real_idx,
+ size_t param_idx,
+ const ov::SoPtr<ov::ITensor>& i_tensor) {
+ // Get descriptor
+ const auto& desc =
+ *static_cast<const ov::npuw::CompiledModel::CompiledModelDesc*>(m_accessor.get_submodel_desc(real_idx));
+
+ // MoE expert layer: handle router scores and expert inputs
+ if (desc.moe_experts) {
+ const auto& moe = desc.moe_experts.value();
+
+ // Router scores: store for later use in MoE inference
+ if (moe._router_scores_idx.has_value() && param_idx == moe._router_scores_idx.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()) {
+ 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
+ }
+
+ // For expert layer, all param_base parameters should be router_scores or expert_input
+ NPUW_ASSERT(false && "Unknown MoE expert parameter index");
+ return false; // Unreachable
+ }
+
+ // MoE downstream layer: bind expert output accumulator or other parameters
+ if (desc.moe_experts_downstream) {
+ const auto& moe_downstream = desc.moe_experts_downstream.value();
+ const auto& iport = desc.compiled_model->inputs()[param_idx];
+ auto real_request = m_accessor.get_subrequest(real_idx);
+
+ if (param_idx == moe_downstream.expert_output_param_idx) {
+ // Bind expert output accumulator
+ auto output_buffer = m_resources.expert_output_accumulator;
+ NPUW_ASSERT(output_buffer && "MoE output buffer not available");
+ real_request->set_tensor(iport, output_buffer);
+ } else {
+ // Other parameters use the input tensor directly
+ real_request->set_tensor(iport, i_tensor);
+ }
+ return true; // All downstream layer parameters handled by MoE
+ }
+
+ // Should not reach here if is_moe flag is set correctly
+ NPUW_ASSERT(false && "MoE flag set but no moe_experts/moe_experts_downstream found");
+ return false;
+}
+
+bool MoEExecutor::function_prologue_moe_output(size_t idx, size_t output_idx, const ov::SoPtr<ov::ITensor>& o_tensor) {
+ NPUW_ASSERT(idx < m_moe_io.size() && "MoEExecutor::prepare() must be called first");
+
+ // Store output tensor in MoE I/O structure
+ // For EXPERT_BATCH mode: deferred for cache lookup
+ // For EXPERT_ITERATIVE mode: relayouted from expert outputs, expert_output_accumulator will be used eventually
+ m_moe_io[idx].outputs.at(output_idx) = o_tensor;
+ return true; // Always handled by MoE for expert layers
+}
+
+void MoEExecutor::run(size_t real_idx, size_t idx) {
+ // Validate config is initialized
+ if (!m_config.is_valid()) {
+ OPENVINO_THROW("MoEExecutor::run() - Configuration not initialized");
+ }
+
+ LOG_DEBUG("\n========== MoE Expert Inference [Subgraph " << idx << "] ==========");
+
+ const auto num_experts = m_config.num_experts;
+ const auto num_active_experts = m_config.num_active_experts;
+ const auto input_token_count = m_config.input_token_count;
+ const auto processing_mode = m_config.get_processing_mode();
+
+ LOG_DEBUG("MoE Config: num_experts=" << num_experts << ", num_active_experts=" << num_active_experts
+ << ", input_token_count=" << input_token_count
+ << ", mode=" << get_mode_name(processing_mode));
+
+ // Get I/O for this sublayer
+ const auto& io = m_moe_io[idx];
+
+ if (!io.router_scores) {
+ OPENVINO_THROW("MoE: Router scores are required but not available");
+ }
+
+ // Parse router scores and populate routing maps
+ // Note: parse_selected_experts_from_router() clears the maps internally before populating
+ std::vector<size_t> selected_experts;
+ if (processing_mode == MoEProcessingMode::EXPERT_BATCH) {
+ m_profile->batch["Parse Router Output"].record([&]() {
+ selected_experts = ov::npuw::moe::parse_selected_experts_from_router(io.router_scores,
+ num_experts,
+ m_token_to_experts,
+ m_expert_to_tokens);
+ });
+ } else {
+ m_profile->iterative["Parse Router Output"].record([&]() {
+ selected_experts = ov::npuw::moe::parse_selected_experts_from_router(io.router_scores,
+ num_experts,
+ m_token_to_experts,
+ m_expert_to_tokens);
+ });
+ }
+
+ if (selected_experts.empty()) {
+ OPENVINO_THROW("MoE: No experts selected by router");
+ }
+
+ // Dispatch to appropriate inference function
+ if (processing_mode == MoEProcessingMode::EXPERT_BATCH) {
+ m_profile->batch["Total Expert Batch"].record([&]() {
+ run_expert_batch(idx, real_idx, selected_experts);
+ });
+ } else {
+ m_profile->iterative["Total Expert Iterative"].record([&]() {
+ run_expert_iterative(idx, real_idx, selected_experts);
+ });
+ }
+
+ LOG_DEBUG("========== MoE Expert Inference Completed ==========");
+}
+
+void MoEExecutor::run_expert_batch(size_t idx, size_t real_idx, const std::vector<size_t>& selected_experts) {
+ LOG_DEBUG("\n[EXPERT_BATCH] Processing single token with " << selected_experts.size() << " experts in parallel");
+
+ const auto num_active_experts = m_config.num_active_experts;
+ const auto& io = m_moe_io[idx];
+
+ // Validate expert count
+ if (selected_experts.size() != num_active_experts) {
+ OPENVINO_THROW("MoE Batch experts: number of selected experts does not match num_active_experts");
+ }
+
+ // Step 1: Try to find cached request (O(1) lookup) - if cache is enabled
+ // Note: Use idx because each function call has its own cache pool
+ RqPtr request{};
+ size_t pool_idx = 0;
+
+ const bool cache_enabled = (m_resources.request_cache != nullptr);
+
+ if (cache_enabled) {
+ request = m_resources.request_cache->find(idx, selected_experts);
+ }
+
+ if (!request) {
+ // Cache MISS or cache disabled: Get idle/LRU request or create new
+ if (cache_enabled) {
+ auto [idle_request, idx_in_pool] = m_resources.request_cache->get_idle_or_lru(idx);
+ request = idle_request;
+ pool_idx = idx_in_pool;
+ } else {
+ // Cache disabled - use the regular subrequest
+ request = m_accessor.get_subrequest(real_idx);
+ }
+
+ // Step 2: Configure expert weights
+ m_profile->batch["Unpack Closure"].record([&]() {
+ unpack_multiple_experts_closure(idx, request, selected_experts);
+ });
+
+ // Step 3: Register to cache for future hits (only if cache enabled)
+ if (cache_enabled) {
+ m_resources.request_cache->register_request(idx, pool_idx, selected_experts);
+ }
+ }
+
+ // Get compiled model descriptor
+ const auto& desc =
+ *static_cast<const ov::npuw::CompiledModel::CompiledModelDesc*>(m_accessor.get_submodel_desc(real_idx));
+
+ // 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();
+ const auto& expert_input_port = desc.compiled_model->inputs()[expert_input_idx];
+ auto expert_input_tensor = io.expert_input;
+ if (!expert_input_tensor) {
+ OPENVINO_THROW("MoE: Expert input tensor not available");
+ }
+ request->set_tensor(expert_input_port, expert_input_tensor);
+ }
+
+ // 4.2: Bind output tensor (from io, set in function_prologue)
+ const auto& output_port = desc.compiled_model->outputs()[0];
+ auto output_tensor = io.outputs.at(0);
+ if (!output_tensor) {
+ OPENVINO_THROW("MoE: Output tensor not available");
+ }
+ request->set_tensor(output_port, output_tensor);
+
+ // Step 5: Set unrolled router scores (always needed, even on cache hit)
+ m_profile->batch["Set Router Input"].record([&]() {
+ set_router_scores(idx, real_idx, selected_experts, request);
+ });
+
+ // Step 6: Execute inference once for all K experts in parallel
+ m_profile->batch["Expert Inference"].record([&]() {
+ request->infer();
+ });
+}
+
+void MoEExecutor::run_expert_iterative(size_t idx, size_t real_idx, const std::vector<size_t>& selected_experts) {
+ LOG_DEBUG("\n[EXPERT_ITERATIVE] Processing multiple tokens by iterating through experts");
+
+ const auto input_token_count = m_config.input_token_count;
+ const auto& io = m_moe_io[idx];
+
+ // Clear output buffer before accumulating expert outputs
+ if (!m_resources.expert_output_accumulator) {
+ OPENVINO_THROW("MoE: Expert output accumulator is null");
+ }
+ std::memset(m_resources.expert_output_accumulator->data(),
+ 0,
+ m_resources.expert_output_accumulator->get_byte_size());
+
+ // Get tensor references (constant across all experts)
+ if (!m_config.router_scores_idx.has_value()) {
+ OPENVINO_THROW("MoE: Router scores index not available");
+ }
+ if (!m_config.expert_input_param_idx.has_value()) {
+ OPENVINO_THROW("MoE: Expert input parameter index not available");
+ }
+
+ auto router_source = io.router_scores;
+ auto expert_input_source = io.expert_input;
+
+ // Calculate output embedding dimension from any compiled model (all have same output shape)
+ auto any_compiled_model = m_config.compiled_models.begin()->second;
+ auto output_shape = any_compiled_model->outputs()[0].get_shape();
+ size_t embed_dim = (output_shape.size() == 4) ? output_shape[3] : output_shape[1];
+
+ // Process each expert sequentially
+ for (size_t expert_id : selected_experts) {
+ LOG_DEBUG("\n Processing Expert[" << expert_id << "]...");
+
+ // Get tokens assigned to this expert
+ const auto& tokens_for_expert = m_expert_to_tokens.at(expert_id);
+ const size_t total_tokens = tokens_for_expert.size();
+
+ LOG_DEBUG(" Expert[" << expert_id << "] processing " << total_tokens << " tokens");
+
+ // Precompute expert slot for each token
+ // This eliminates map lookup + linear search in scatter_expert_outputs hot loop
+ std::vector<size_t> expert_slots_for_tokens(total_tokens);
+ for (size_t i = 0; i < total_tokens; ++i) {
+ size_t token_id = tokens_for_expert[i];
+ const auto& expert_ids = m_token_to_experts.at(token_id);
+ auto it = std::find(expert_ids.begin(), expert_ids.end(), expert_id);
+ if (it == expert_ids.end()) {
+ OPENVINO_THROW("MoE: Token should have this expert");
+ }
+ expert_slots_for_tokens[i] = std::distance(expert_ids.begin(), it);
+ }
+
+ // Process tokens in dynamic chunks based on available compiled models
+ // Priority: use largest possible chunk_size (256 > 128 > 64 > 32)
+ size_t processed_tokens = 0;
+ size_t last_chunk_size = 0; // Track last used chunk_size to detect changes
+ // Note: When switching to a new expert, last_chunk_size resets to 0,
+ // ensuring weights are unpacked for the first chunk of each expert
+ while (processed_tokens < total_tokens) {
+ size_t remaining_tokens = total_tokens - processed_tokens;
+
+ // Chunk selection strategy:
+ // - remaining_tokens <= smallest chunk → use smallest chunk
+ // - remaining_tokens >= largest chunk → use largest chunk
+ // - otherwise → use smallest chunk that is >= remaining_tokens
+ // Pre-sorted in descending order: [256, 128, 64, 32, 16]
+ if (m_resources.sorted_chunk_sizes.empty()) {
+ OPENVINO_THROW("MoE: Sorted chunk sizes cannot be empty");
+ }
+
+ size_t selected_chunk_size;
+ size_t smallest_chunk = m_resources.sorted_chunk_sizes.back();
+ size_t largest_chunk = m_resources.sorted_chunk_sizes.front();
+
+ if (remaining_tokens <= smallest_chunk) {
+ // Use smallest chunk
+ selected_chunk_size = smallest_chunk;
+ } else if (remaining_tokens >= largest_chunk) {
+ // Use largest chunk
+ selected_chunk_size = largest_chunk;
+ } else {
+ // Find smallest chunk >= remaining_tokens
+ // Since sorted descending, iterate from end to find first >= remaining_tokens
+ selected_chunk_size = smallest_chunk; // Default to smallest
+ for (auto it = m_resources.sorted_chunk_sizes.rbegin(); it != m_resources.sorted_chunk_sizes.rend();
+ ++it) {
+ if (*it >= remaining_tokens) {
+ selected_chunk_size = *it;
+ break;
+ }
+ }
+ }
+
+ // Actual tokens to process in this iteration
+ size_t current_chunk_size = std::min(selected_chunk_size, remaining_tokens);
+
+ LOG_DEBUG(" Processing tokens [" << processed_tokens << ", " << (processed_tokens + current_chunk_size)
+ << ") with chunk_size=" << selected_chunk_size);
+
+ // Get selected infer request from MoEResources
+ auto infer_request_it = m_resources.chunk_infer_requests.find(selected_chunk_size);
+ if (infer_request_it == m_resources.chunk_infer_requests.end()) {
+ OPENVINO_THROW("MoE: Infer request for chunk_size=", selected_chunk_size, " not found");
+ }
+ auto selected_infer_request = infer_request_it->second;
+
+ // Get input/output ports for selected infer request
+ auto 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_expert_input_iport =
+ selected_compiled_model->inputs()[m_config.expert_input_param_idx.value()];
+ const auto& selected_oport = selected_compiled_model->outputs()[0];
+
+ auto selected_router_dest = selected_infer_request->get_tensor(selected_router_iport);
+ auto selected_expert_input_dest = selected_infer_request->get_tensor(selected_expert_input_iport);
+ auto selected_expert_output = selected_infer_request->get_tensor(selected_oport);
+
+ // Step 1: Unpack expert weights when chunk_size changes (different infer request)
+ // This ensures each infer request has correct weights loaded
+ // Important: last_chunk_size is reset to 0 at the start of each expert loop,
+ // so the first chunk of a new expert will always trigger unpacking (0 != selected_chunk_size)
+ if (selected_chunk_size != last_chunk_size) {
+ m_profile->iterative["Unpack Closure"].record([&]() {
+ unpack_single_expert_closure(idx, selected_infer_request, expert_id);
+ });
+ last_chunk_size = selected_chunk_size;
+ }
+
+ // Step 2: Gather router scores for this chunk
+ m_profile->iterative["Gather Router Scores"].record([&]() {
+ ov::npuw::moe::gather_router_scores(router_source,
+ selected_router_dest,
+ expert_id,
+ tokens_for_expert,
+ processed_tokens,
+ current_chunk_size);
+ });
+
+ // Step 3: Gather expert inputs for this chunk
+ m_profile->iterative["Gather Expert Input"].record([&]() {
+ ov::npuw::moe::gather_expert_inputs(expert_input_source,
+ selected_expert_input_dest,
+ tokens_for_expert,
+ processed_tokens,
+ current_chunk_size);
+ });
+
+ // Step 4: Execute expert inference
+ m_profile->iterative["Expert Inference"].record([&]() {
+ selected_infer_request->infer();
+ });
+
+ // Step 5: Scatter expert outputs back to global buffer
+ m_profile->iterative["Scatter Output"].record([&]() {
+ ov::npuw::moe::scatter_expert_outputs(selected_expert_output,
+ m_resources.expert_output_accumulator,
+ tokens_for_expert,
+ processed_tokens,
+ current_chunk_size,
+ embed_dim,
+ input_token_count,
+ expert_slots_for_tokens);
+ });
+
+ // Move to next chunk
+ processed_tokens += current_chunk_size;
+ }
+ LOG_DEBUG(" Expert[" << expert_id << "] completed");
+ }
+}
+
+void MoEExecutor::set_router_scores(size_t idx,
+ size_t real_idx,
+ const std::vector<size_t>& selected_experts,
+ RqPtr& request) {
+ const auto num_active_experts = m_config.num_active_experts;
+ const auto& io = m_moe_io[idx];
+
+ // Validate router scores index is provided
+ if (!m_config.router_scores_idx.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& param_mapping = m_config.param_mapping;
+
+ // Find unrolled router score parameters
+ auto mapping_it = param_mapping.find(original_router_idx);
+ if (mapping_it == param_mapping.end()) {
+ LOG_WARN("Router parameter index " << original_router_idx << " not found in param_mapping");
+ OPENVINO_THROW("MoE: Router parameter not in mapping - unexpected for expert batch mode");
+ }
+
+ const auto& unrolled_router_indices = mapping_it->second;
+ LOG_DEBUG(" Setting " << unrolled_router_indices.size() << " router score parameters");
+
+ // Validate unrolled parameter count
+ if (unrolled_router_indices.size() != num_active_experts) {
+ LOG_ERROR("Router parameter count mismatch: expected " << num_active_experts << ", got "
+ << unrolled_router_indices.size());
+ OPENVINO_THROW("MoE: Router parameter unroll count mismatch");
+ }
+
+ // Get router scores source tensor and element type
+ auto router_scores_source = io.router_scores;
+ auto elem_type = router_scores_source->get_element_type();
+
+ // Get compiled model from config
+ const auto& desc =
+ *static_cast<const ov::npuw::CompiledModel::CompiledModelDesc*>(m_accessor.get_submodel_desc(real_idx));
+
+ // Set each unrolled router score parameter
+ for (size_t k = 0; k < num_active_experts; ++k) {
+ size_t expert_id = selected_experts[k];
+ size_t unrolled_param_idx = unrolled_router_indices[k];
+
+ const auto& router_iport = desc.compiled_model->inputs()[unrolled_param_idx];
+ auto router_tensor = request->get_tensor(router_iport);
+
+ // Copy router score from source[expert_id] to dest[0]
+ if (elem_type == ov::element::f16) {
+ auto* src = router_scores_source->data<ov::float16>();
+ auto* dst = router_tensor->data<ov::float16>();
+ dst[0] = src[expert_id];
+ } else if (elem_type == ov::element::f32) {
+ auto* src = router_scores_source->data<float>();
+ auto* dst = router_tensor->data<float>();
+ dst[0] = src[expert_id];
+ } else {
+ OPENVINO_THROW("Unsupported router scores element type: ", elem_type);
+ }
+ }
+}
+
+std::string MoEExecutor::get_device_name(size_t idx, const void* compiled_model_desc_ptr) const {
+ const auto& desc = compiled_model_desc_ptr
+ ? *static_cast<const CompiledModel::CompiledModelDesc*>(compiled_model_desc_ptr)
+ : *static_cast<const CompiledModel::CompiledModelDesc*>(m_accessor.get_submodel_desc(idx));
+ return *desc.device_it;
+}
+
+void MoEExecutor::unpack_single_expert_closure(std::size_t idx, RqPtr request, size_t expert_id) {
+ // Get model descriptors
+ const auto& comp_model_desc =
+ *static_cast<const CompiledModel::CompiledModelDesc*>(m_accessor.get_submodel_desc(idx));
+ NPUW_ASSERT(comp_model_desc.replaced_by);
+
+ const auto real_idx = comp_model_desc.replaced_by.value();
+ const auto& func_desc =
+ *static_cast<const CompiledModel::CompiledModelDesc*>(m_accessor.get_submodel_desc(real_idx));
+
+ NPUW_ASSERT(func_desc.moe_experts.has_value());
+ const auto num_experts = func_desc.moe_experts->num_experts;
+
+ auto& desc_closure = comp_model_desc.closure.get().closure;
+
+ for (std::size_t cidx = 0u; cidx < desc_closure.size(); cidx++) {
+ auto& closure = desc_closure[cidx];
+ const auto closure_param_id = comp_model_desc.param_base + cidx;
+
+ // Skip gather closures
+ if (m_accessor.is_gather_closure(idx, cidx)) {
+ continue;
+ }
+
+ auto& 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;
+
+ if (needs_slicing) {
+ // Slice expert weight using view (no copy) - returns ov::Tensor object
+ auto sliced_weight_tensor = ov::npuw::moe::slice_expert_weight(closure, expert_id, num_experts);
+
+ // Get impl pointer for use in unpacking/setting
+ auto sliced_weight = ov::get_tensor_impl(sliced_weight_tensor);
+
+ // Handle unpacking if needed
+ if (m_accessor.unpack_required(idx, cidx)) {
+ auto clparam = request->get_tensor(iport);
+
+ if (!comp_model_desc.scales.empty() && comp_model_desc.scales[cidx] && comp_model_desc.zerops[cidx]) {
+ ov::npuw::util::unpack(sliced_weight,
+ ov::get_tensor_impl(comp_model_desc.zerops[cidx]),
+ ov::get_tensor_impl(comp_model_desc.scales[cidx]),
+ clparam);
+ } else if (!comp_model_desc.scales.empty() && comp_model_desc.scales[cidx]) {
+ ov::npuw::util::unpack(sliced_weight, ov::get_tensor_impl(comp_model_desc.scales[cidx]), clparam);
+ } else {
+ ov::npuw::util::unpack(sliced_weight, clparam);
+ }
+ } else {
+ // Direct set (no unpacking needed)
+ // When cache is enabled: Use direct set_tensor to avoid polluting shared input tensors
+ // When cache is disabled: Use set_tensor_optimized for better performance (copies small tensors)
+ if (m_resources.request_cache) {
+ request->set_tensor(iport, sliced_weight);
+ } else {
+ ov::npuw::moe::set_tensor_optimized(request, iport, sliced_weight);
+ }
+ }
+ } else {
+ // This closure parameter doesn't need slicing, use original logic
+ if (m_accessor.needs_copy_closure(idx, cidx)) {
+ auto clparam = request->get_tensor(iport);
+ ov::get_tensor_impl(closure)->copy_to(clparam._ptr);
+ } else {
+ request->set_tensor(iport, ov::get_tensor_impl(closure));
+ }
+ }
+ }
+}
+
+void MoEExecutor::unpack_multiple_experts_closure(std::size_t idx,
+ RqPtr request,
+ const std::vector<size_t>& expert_ids) {
+ /**
+ * MoE Batch Expert Closure Unpacking for Expert Batch Mode
+ *
+ * Purpose: Process K active experts simultaneously (batch mode, 1 token)
+ *
+ * Input:
+ * - Batched closure parameters: shape [num_experts, ...] (original model)
+ * - expert_ids: K selected expert IDs [e0, e1, e2, e3]
+ *
+ * Output:
+ * - Unrolled model parameters populated with sliced expert weights
+ * - Each parameter receives data for one specific expert
+ *
+ * Flow:
+ * 1. Iterate over original closure parameters
+ * 2. For each closure parameter, process its K unrolled variants
+ * 3. Slice expert weight from batched tensor
+ * 4. Unpack (if dtype mismatch) or direct set (if dtype match)
+ */
+
+ // ========== Step 1: Get model descriptors and validate MoE structure ==========
+ const auto& comp_model_desc =
+ *static_cast<const CompiledModel::CompiledModelDesc*>(m_accessor.get_submodel_desc(idx));
+ NPUW_ASSERT(comp_model_desc.replaced_by);
+
+ const auto real_idx = comp_model_desc.replaced_by.value();
+ const auto& func_desc =
+ *static_cast<const CompiledModel::CompiledModelDesc*>(m_accessor.get_submodel_desc(real_idx));
+
+ NPUW_ASSERT(func_desc.moe_experts.has_value());
+ const auto& moe_experts = func_desc.moe_experts.value();
+ const auto num_experts = moe_experts.num_experts; // Total experts in model (e.g., 32)
+ const size_t K = expert_ids.size(); // Active experts (e.g., 4)
+ const auto& param_mapping = moe_experts._param_mapping; // original_idx -> [unrolled_indices]
+
+ auto& desc_closure = comp_model_desc.closure.get().closure;
+ const auto& compiled_inputs = func_desc.compiled_model->inputs();
+
+ // ========== Step 2: Process each original closure parameter ==========
+ // Iterate over closure parameters, then process their K unrolled variants
+ for (std::size_t closure_idx = 0; closure_idx < desc_closure.size(); ++closure_idx) {
+ // Skip gather closures (dummy tensors, not real weights)
+ if (m_accessor.is_gather_closure(idx, closure_idx)) {
+ continue;
+ }
+
+ // Calculate original parameter index in the model
+ const size_t original_param_idx = comp_model_desc.param_base + closure_idx;
+
+ // 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()) {
+ continue; // Not unrolled
+ }
+
+ const auto& unrolled_indices = mapping_it->second;
+ NPUW_ASSERT(unrolled_indices.size() == K);
+
+ auto& batched_closure = desc_closure[closure_idx];
+ const auto& closure_shape = batched_closure.get_shape();
+
+ // Verify this is a batched parameter [num_experts, ...]
+ const bool is_batched = !closure_shape.empty() && closure_shape[0] == num_experts;
+ if (!is_batched) {
+ // Shared parameter path - all K unrolled parameters share same weight
+ const bool do_copy = m_accessor.needs_copy_closure(idx, closure_idx);
+ auto batched_impl = ov::get_tensor_impl(batched_closure);
+
+ for (size_t position = 0; position < K; ++position) {
+ const auto& iport = compiled_inputs[unrolled_indices[position]];
+ if (do_copy) {
+ batched_impl->copy_to(request->get_tensor(iport)._ptr);
+ } else {
+ request->set_tensor(iport, batched_impl);
+ }
+ }
+ continue;
+ }
+
+ // ========== Step 3: Process batched parameters (K experts) ==========
+
+ // Pre-determine unpack configuration (same for all K experts)
+ const auto batched_elem_type = batched_closure.get_element_type();
+ const auto target_elem_type = request->get_tensor(compiled_inputs[unrolled_indices[0]])->get_element_type();
+ const bool needs_unpack = (batched_elem_type != target_elem_type);
+
+ ov::SoPtr<ov::ITensor> scales_impl, zerops_impl;
+ if (needs_unpack) {
+ if (!comp_model_desc.scales.empty() && comp_model_desc.scales[closure_idx]) {
+ scales_impl = ov::get_tensor_impl(comp_model_desc.scales[closure_idx]);
+ }
+ if (!comp_model_desc.zerops.empty() && comp_model_desc.zerops[closure_idx]) {
+ zerops_impl = ov::get_tensor_impl(comp_model_desc.zerops[closure_idx]);
+ }
+ }
+
+ // Process K experts
+ for (size_t position = 0; position < K; ++position) {
+ const size_t expert_id = expert_ids[position];
+ const auto& iport = compiled_inputs[unrolled_indices[position]];
+
+ // Slice expert weight (zero-copy view)
+ ov::Tensor sliced_expert = ov::npuw::moe::slice_expert_weight(batched_closure, expert_id, num_experts);
+
+ if (needs_unpack) {
+ // Unpack path (dtype mismatch)
+ auto sliced_impl = ov::get_tensor_impl(sliced_expert);
+ auto clparam = request->get_tensor(iport);
+
+ if (scales_impl && zerops_impl) {
+ ov::npuw::util::unpack(sliced_impl, zerops_impl, scales_impl, clparam);
+ } else if (scales_impl) {
+ ov::npuw::util::unpack(sliced_impl, scales_impl, clparam);
+ } else if (zerops_impl) {
+ ov::npuw::util::unpack(sliced_impl, zerops_impl, clparam);
+ } else {
+ ov::npuw::util::unpack(sliced_impl, clparam);
+ }
+ } else {
+ auto sliced_impl = ov::get_tensor_impl(sliced_expert);
+ // Direct set (no unpacking needed)
+ // When cache is enabled: Use direct set_tensor to avoid polluting shared input tensors
+ // When cache is disabled: Use set_tensor_optimized for better performance (copies small tensors)
+ if (m_resources.request_cache) {
+ request->set_tensor(iport, sliced_impl);
+ } else {
+ ov::npuw::moe::set_tensor_optimized(request, iport, sliced_impl);
+ }
+ }
+ } // for each expert
+ } // for each closure parameter
+
+ LOG_DEBUG("Done unpacking MoE batch expert closure");
+}
+
+} // namespace moe
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hpp
new file mode 100644
index 00000000000..47d4ce6f3a6
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hpp
@@ -0,0 +1,309 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <functional>
+#include <map>
+#include <memory>
+#include <string>
+#include <vector>
+
+#include "../util.hpp" // For TensorPtr
+#include "moe_config.hpp"
+#include "moe_resources.hpp"
+#include "moe_types.hpp" // For MoEIO
+#include "openvino/runtime/so_ptr.hpp"
+
+// Forward declarations
+namespace ov {
+class ITensor;
+namespace npuw {
+class CompiledModel;
+} // namespace npuw
+} // namespace ov
+
+namespace ov {
+namespace npuw {
+
+// Forward declare CompiledModelDesc to avoid circular dependency
+// Will be included in implementation file
+namespace moe {
+class MoEExecutor;
+}
+
+// Import TensorPtr from util namespace for use in this header
+using ov::npuw::util::TensorPtr;
+
+/**
+ * @brief Accessor interface for MoEExecutor to access JustInferRequest internals
+ *
+ * This interface decouples MoEExecutor from JustInferRequest implementation details,
+ * following the Dependency Inversion Principle. JustInferRequest implements this
+ * interface to provide controlled access to its internal resources.
+ */
+class ISubrequestAccessor {
+public:
+ virtual ~ISubrequestAccessor() = default;
+
+ /**
+ * @brief Get subrequest by index
+ * @param idx Submodel index
+ * @return Infer request pointer
+ */
+ virtual ov::SoPtr<ov::IAsyncInferRequest> get_subrequest(size_t idx) = 0;
+
+ /**
+ * @brief Get compiled submodel descriptor
+ * @param idx Submodel index
+ * @return Reference to CompiledModelDesc
+ */
+ virtual const void* get_submodel_desc(size_t idx) = 0; // Returns CompiledModelDesc*
+
+ /**
+ * @brief Allocate memory tensor
+ * @param type Element type
+ * @param shape Tensor shape
+ * @param device Target device
+ * @return Allocated tensor pointer
+ */
+ virtual TensorPtr allocate_mem(const ov::element::Type& type,
+ const ov::Shape& shape,
+ const std::string& device) = 0;
+
+ /**
+ * @brief Check if closure parameter is a gather closure (should be skipped)
+ * @param idx Submodel index
+ * @param cidx Closure parameter index
+ * @return True if it's a gather closure
+ */
+ virtual bool is_gather_closure(size_t idx, size_t cidx) = 0;
+
+ /**
+ * @brief Check if unpacking is required for closure parameter
+ * @param idx Submodel index
+ * @param cidx Closure parameter index
+ * @return True if unpacking is required
+ */
+ virtual bool unpack_required(size_t idx, size_t cidx) = 0;
+
+ /**
+ * @brief Check if tensor copy is needed for closure parameter
+ * @param idx Submodel index
+ * @param cidx Closure parameter index
+ * @return True if copy is needed
+ */
+ virtual bool needs_copy_closure(size_t idx, size_t cidx) = 0;
+};
+
+namespace moe {
+
+/**
+ * @brief MoE execution engine
+ *
+ * Encapsulates all MoE-specific inference logic, isolated from JustInferRequest.
+ * Manages expert routing, weight unpacking, caching, and execution for both
+ * decoding (single token) and prefill (multiple tokens) modes.
+ *
+ * Design principles:
+ * - Composition over inheritance: Used as a component in JustInferRequest
+ * - Dependency injection: Accesses host request via ISubrequestAccessor
+ * - Single responsibility: Only handles MoE inference logic
+ */
+class MoEExecutor {
+public:
+ using RqPtr = ov::SoPtr<ov::IAsyncInferRequest>;
+ using AllocatorFn = std::function<TensorPtr(const ov::element::Type&, const ov::Shape&, const std::string&)>;
+
+ /**
+ * @brief Constructor
+ *
+ * @param accessor Interface to access JustInferRequest internals
+ * @param allocator Memory allocation function
+ */
+ MoEExecutor(ISubrequestAccessor& accessor, AllocatorFn allocator);
+
+ /**
+ * @brief Prepare MoE resources for a sublayer
+ *
+ * Must be called once for each sublayer (including function calls) before first run.
+ * Initializes:
+ * - Config: Once on first call (singleton, shared by all sublayers)
+ * - Shared resources: Once on first call (sorted_chunk_sizes, expert_output_accumulator)
+ * - Request cache: Created on first call (manages all sublayers)
+ *
+ * @param idx Sublayer index (used for cache layer indexing, may be function call)
+ * @param real_idx Real function body index (for accessing config descriptor)
+ * @param num_sublayers Total number of sublayers (for cache creation on first call)
+ * @param pool_size Request cache pool size (0 = disabled)
+ */
+ void prepare(size_t idx, size_t real_idx, size_t num_sublayers, size_t pool_size);
+
+ /**
+ * @brief Execute MoE inference
+ *
+ * Main entry point called from JustInferRequest::unsafe_infer().
+ * Handles router parsing, expert selection, and dispatches to
+ * appropriate execution mode (batch vs iterative).
+ *
+ * @param real_idx Submodel index (after replaced_by resolution)
+ * @param idx Function call index
+ */
+ void run(size_t real_idx, size_t idx);
+
+ /**
+ * @brief Handle MoE input parameter binding in function_prologue
+ *
+ * Called for each input parameter in function_prologue loop.
+ * Handles router_scores, expert_input, and downstream layer inputs.
+ *
+ * @param idx Function call index
+ * @param real_idx Real function body index
+ * @param param_idx Input parameter index
+ * @param i_tensor Input tensor
+ * @return true if this parameter was handled by MoE (skip default binding)
+ */
+ bool function_prologue_moe_input(size_t idx,
+ size_t real_idx,
+ size_t param_idx,
+ const ov::SoPtr<ov::ITensor>& i_tensor);
+
+ /**
+ * @brief Handle MoE output binding in function_prologue
+ *
+ * Called for each output in function_prologue loop.
+ * Stores output tensor in MoE I/O structure for later use.
+ *
+ * @param idx Function call index
+ * @param output_idx Output index
+ * @param o_tensor Output tensor
+ * @return true if this output was handled by MoE (skip default binding)
+ */
+ bool function_prologue_moe_output(size_t idx, size_t output_idx, const ov::SoPtr<ov::ITensor>& o_tensor);
+
+ /**
+ * @brief Get MoE performance profile statistics
+ *
+ * @return Optional reference to MoE profile (nullopt if profiling disabled)
+ */
+ const std::optional<MoEProfile>& get_profile() const {
+ return m_profile;
+ }
+
+private:
+ // === Dependency injection ===
+ ISubrequestAccessor& m_accessor; // Access to JustInferRequest internals
+ AllocatorFn m_allocator; // Memory allocation function
+
+ // === Profiling ===
+ std::optional<MoEProfile>
+ m_profile; // Performance statistics (always collects, reports based on profiling_enabled())
+
+ // === Weight unpacking methods ===
+ /**
+ * @brief Unpack single expert's closure (expert-specific weights)
+ * @param idx Function call index
+ * @param request Target infer request
+ * @param expert_id Expert ID to unpack
+ */
+ void unpack_single_expert_closure(size_t idx, RqPtr request, size_t expert_id);
+
+ /**
+ * @brief Unpack multiple experts' closure (batch expert mode)
+ * @param idx Function call index
+ * @param request Target infer request
+ * @param expert_ids Expert IDs to unpack
+ */
+ void unpack_multiple_experts_closure(size_t idx, RqPtr request, const std::vector<size_t>& expert_ids);
+
+ // === State management ===
+ // MoE configuration (single instance, shared by all sublayers)
+ // Sanity check in JustInferRequest ensures only one MoE type exists
+ MoEConfig m_config;
+
+ // Shared resources for all sublayers
+ // - request_caches: per-sublayer (map inside MoEResources, indexed by idx)
+ // - sorted_chunk_sizes: shared (single instance)
+ // - expert_output_accumulator: shared (single instance)
+ MoEResources m_resources; // Single instance, shared by all sublayers
+
+ // Routing maps (reused across inferences to avoid repeated allocation)
+ std::map<size_t, std::vector<size_t>> m_token_to_experts;
+ std::map<size_t, std::vector<size_t>> m_expert_to_tokens;
+
+ // MoE I/O storage (per-sublayer)
+ std::vector<MoEIO> m_moe_io;
+
+ // === Execution modes ===
+
+ /**
+ * @brief Execute expert batch mode inference
+ *
+ * Processing mode: Single token processed with K experts in parallel
+ * Uses cached infer requests for specific expert combinations.
+ *
+ * @param idx Function call index
+ * @param real_idx Submodel index
+ * @param selected_experts List of selected expert IDs
+ */
+ void run_expert_batch(size_t idx, size_t real_idx, const std::vector<size_t>& selected_experts);
+
+ /**
+ * @brief Execute expert iterative mode inference
+ *
+ * Processing mode: Iterate through experts, each processes multiple tokens
+ * Uses dynamic chunk sizing and accumulates outputs.
+ *
+ * @param idx Function call index
+ * @param real_idx Submodel index
+ * @param selected_experts List of selected expert IDs
+ */
+ void run_expert_iterative(size_t idx, size_t real_idx, const std::vector<size_t>& selected_experts);
+
+ /**
+ * @brief Execute batch experts inference (deprecated)
+ * @deprecated Use run_expert_batch() instead
+ */
+ [[deprecated("Use run_expert_batch() instead")]]
+ void run_batch_experts(size_t idx, size_t real_idx, const std::vector<size_t>& selected_experts) {
+ run_expert_batch(idx, real_idx, selected_experts);
+ }
+
+ /**
+ * @brief Execute iterative experts inference (deprecated)
+ * @deprecated Use run_expert_iterative() instead
+ */
+ [[deprecated("Use run_expert_iterative() instead")]]
+ void run_iterative_experts(size_t idx, size_t real_idx, const std::vector<size_t>& selected_experts) {
+ run_expert_iterative(idx, real_idx, selected_experts);
+ }
+
+ // === Helper functions ===
+
+ /**
+ * @brief Set unrolled router scores for expert batch mode
+ *
+ * Maps router scores from [num_experts] to K unrolled parameters.
+ *
+ * @param idx Function call index
+ * @param real_idx Submodel index
+ * @param selected_experts List of selected expert IDs
+ * @param request Target infer request
+ */
+ void set_router_scores(size_t idx, size_t real_idx, const std::vector<size_t>& selected_experts, RqPtr& request);
+
+ /**
+ * @brief Get device name for a submodel
+ *
+ * @param idx Submodel/function call index
+ * @param compiled_model_desc Optional compiled model descriptor (used during prepare)
+ * @return Device name string
+ */
+ std::string get_device_name(size_t idx, const void* compiled_model_desc = nullptr) const;
+};
+
+} // namespace moe
+} // namespace npuw
+} // namespace ov
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.cpp
new file mode 100644
index 00000000000..463bd377005
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp
@@ -0,0 +1,422 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_infer_utils.hpp"
+
+#include <iomanip>
+#include <iostream>
+
+#include "../logging.hpp"
+#include "../util.hpp"
+#include "openvino/core/except.hpp"
+#include "openvino/runtime/make_tensor.hpp"
+
+namespace ov {
+namespace npuw {
+namespace moe {
+
+// MoEProfile constructor - uses existing profiling infrastructure
+MoEProfile::MoEProfile() {
+ iterative.area = "MoE Expert Iterative"; // EXPERT_ITERATIVE mode profiling
+ batch.area = "MoE Expert Batch"; // EXPERT_BATCH mode profiling
+ iterative.report_on_die = ov::npuw::profiling_enabled();
+ batch.report_on_die = ov::npuw::profiling_enabled();
+}
+
+ov::Tensor slice_expert_weight(const ov::Tensor& batched_weight, size_t expert_id, size_t num_experts) {
+ // Slice weight tensor from batched (num_experts, ...) to single expert (1, ...)
+ auto shape = batched_weight.get_shape();
+ if (shape.empty() || shape[0] != num_experts) {
+ NPUW_ASSERT(false && "Expected batched weight with first dimension equal to num_experts");
+ }
+
+ // Calculate new shape: replace first dimension with 1
+ ov::Shape view_shape = shape;
+ view_shape[0] = 1;
+
+ // Check if element type is sub-byte (4-bit types)
+ // For sub-byte types, we can't use strides, but we can create a zero-copy view
+ // by wrapping the data pointer at the correct byte offset
+ auto elem_type = batched_weight.get_element_type();
+ if (elem_type == ov::element::nf4 || elem_type == ov::element::u4 || elem_type == ov::element::i4) {
+ // Calculate byte-level offset for this expert
+ size_t total_byte_size = batched_weight.get_byte_size();
+ size_t expert_byte_size = total_byte_size / num_experts;
+
+ // Get pointer to this expert's data
+ const uint8_t* base_ptr = static_cast<const uint8_t*>(batched_weight.data());
+ void* expert_ptr = const_cast<uint8_t*>(base_ptr + expert_id * expert_byte_size);
+
+ // Create zero-copy tensor wrapping the expert's data slice
+ ov::Tensor expert_tensor(elem_type, view_shape, expert_ptr);
+
+ LOG_DEBUG("Sliced expert " << expert_id << " weight (4-bit, zero-copy): " << shape << " -> " << view_shape);
+ return expert_tensor;
+ }
+
+ // For >= 8-bit types, use util::view to create zero-copy strided view
+ auto view_impl = ov::npuw::util::view(ov::get_tensor_impl(batched_weight), 0, expert_id, 1);
+ ov::Tensor view_tensor = ov::make_tensor(view_impl);
+
+ LOG_DEBUG("Sliced expert " << expert_id << " weight using util::view: " << shape << " -> "
+ << view_tensor.get_shape());
+
+ return view_tensor;
+}
+
+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,
+ std::map<size_t, std::vector<size_t>>& expert_to_tokens) {
+ if (!router_output) {
+ NPUW_ASSERT(false && "Router output tensor is null");
+ }
+
+ // Clear input maps
+ token_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) {
+ NPUW_ASSERT(false && "Unexpected router output shape!");
+ }
+
+ size_t num_tokens = shape[2]; // token_num from shape
+
+ // Parse which expert each token selects based on non-zero weights
+ auto parse_experts = [&](auto* data) {
+ // For each token, find which experts have non-zero weights
+ for (size_t token_id = 0; token_id < num_tokens; ++token_id) {
+ for (size_t expert_id = 0; expert_id < num_experts; ++expert_id) {
+ // Index calculation for shape [num_experts, 1, token_num, 1]
+ // data[expert_id, 0, token_id, 0]
+ size_t idx = expert_id * num_tokens + token_id;
+
+ float value = std::abs(static_cast<float>(data[idx]));
+ if (value > 1e-6f) {
+ // This token selected this expert
+ token_to_experts[token_id].push_back(expert_id);
+ expert_to_tokens[expert_id].push_back(token_id);
+ }
+ }
+ }
+ };
+
+ auto elem_type = router_output->get_element_type();
+ if (elem_type == ov::element::f32) {
+ parse_experts(router_output->data<float>());
+ } else if (elem_type == ov::element::f16) {
+ parse_experts(router_output->data<ov::float16>());
+ } else {
+ NPUW_ASSERT(false && "Unsupported element type in router output tensor");
+ }
+
+ // Convert expert_to_tokens keys to vector
+ std::vector<size_t> selected_experts;
+ selected_experts.reserve(expert_to_tokens.size());
+ for (const auto& [expert_id, tokens] : expert_to_tokens) {
+ selected_experts.push_back(expert_id);
+ }
+
+ return selected_experts;
+}
+
+void set_tensor_optimized(ov::SoPtr<ov::IAsyncInferRequest> request,
+ const ov::Output<const ov::Node>& iport,
+ const ov::SoPtr<ov::ITensor>& tensor_impl) {
+ // Optimization: For small tensors, use copy instead of set_tensor to avoid overhead
+ // Threshold: 11520 bytes (~11.25KB, typically 5760 f16 elements or 2880 f32 elements)
+ // Empirically verified to have performance benefit for small tensors
+ // Typical shapes: 1x2880x1 (f16: 5760 bytes), 1x5760x1 (f16: 11520 bytes)
+ constexpr size_t SMALL_TENSOR_THRESHOLD_BYTES = 11520;
+
+ size_t tensor_bytes = tensor_impl->get_byte_size();
+
+ if (tensor_bytes <= SMALL_TENSOR_THRESHOLD_BYTES) {
+ // Small tensor: direct copy to avoid set_tensor overhead (~0.65ms per call)
+ // Copy is faster for small tensors due to avoiding NPU plugin overhead
+ auto clparam = request->get_tensor(iport);
+ tensor_impl->copy_to(clparam._ptr);
+ LOG_DEBUG("Using copy for small tensor (" << tensor_bytes << " bytes)");
+ } else {
+ // Large tensor: use set_tensor (zero-copy)
+ request->set_tensor(iport, tensor_impl);
+ }
+}
+
+void gather_router_scores(const ov::SoPtr<ov::ITensor>& router_source,
+ const ov::SoPtr<ov::ITensor>& router_dest,
+ size_t expert_id,
+ const std::vector<size_t>& token_ids,
+ size_t chunk_start,
+ size_t chunk_size) {
+ auto router_source_shape = router_source->get_shape();
+
+ // Calculate expert offset in source tensor
+ size_t expert_offset;
+ if (router_source_shape.size() == 4) {
+ expert_offset = expert_id * router_source_shape[2]; // [num_experts, 1, token_num, 1]
+ } 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");
+ }
+
+ // Gather router scores for chunk tokens
+ if (router_source->get_element_type() == ov::element::f16) {
+ const auto* src_base = router_source->data<ov::float16>() + expert_offset;
+ auto* dst_base = router_dest->data<ov::float16>();
+ for (size_t i = 0; i < chunk_size; ++i) {
+ dst_base[i] = src_base[token_ids[chunk_start + i]];
+ }
+ } else if (router_source->get_element_type() == ov::element::f32) {
+ const auto* src_base = router_source->data<float>() + expert_offset;
+ auto* dst_base = router_dest->data<float>();
+ for (size_t i = 0; i < chunk_size; ++i) {
+ dst_base[i] = src_base[token_ids[chunk_start + i]];
+ }
+ } else {
+ NPUW_ASSERT(false && "Unsupported router element type for gathering");
+ }
+}
+
+void gather_expert_inputs(const ov::SoPtr<ov::ITensor>& input_source,
+ const ov::SoPtr<ov::ITensor>& input_dest,
+ const std::vector<size_t>& token_ids,
+ size_t chunk_start,
+ size_t chunk_size) {
+ auto input_shape = input_source->get_shape();
+
+ // Determine dimensions
+ size_t hidden_dim;
+ size_t token_stride;
+ if (input_shape.size() == 2) {
+ hidden_dim = input_shape[1];
+ token_stride = hidden_dim;
+ } else if (input_shape.size() == 4) {
+ hidden_dim = input_shape[3];
+ token_stride = hidden_dim;
+ } else {
+ NPUW_ASSERT(false && "Unexpected expert input tensor shape");
+ }
+
+ // Gather input embeddings for chunk tokens
+ if (input_source->get_element_type() == ov::element::f16) {
+ const auto* src_base = input_source->data<ov::float16>();
+ auto* dst_base = input_dest->data<ov::float16>();
+ for (size_t i = 0; i < chunk_size; ++i) {
+ size_t token_id = token_ids[chunk_start + i];
+ const auto* src_token = src_base + token_id * token_stride;
+ auto* dst_token = dst_base + i * hidden_dim;
+ std::memcpy(dst_token, src_token, hidden_dim * sizeof(ov::float16));
+ }
+ } else if (input_source->get_element_type() == ov::element::f32) {
+ const auto* src_base = input_source->data<float>();
+ auto* dst_base = input_dest->data<float>();
+ for (size_t i = 0; i < chunk_size; ++i) {
+ size_t token_id = token_ids[chunk_start + i];
+ const auto* src_token = src_base + token_id * token_stride;
+ auto* dst_token = dst_base + i * hidden_dim;
+ std::memcpy(dst_token, src_token, hidden_dim * sizeof(float));
+ }
+ } else {
+ NPUW_ASSERT(false && "Unsupported expert input element type for gathering");
+ }
+}
+
+void scatter_expert_outputs(const ov::SoPtr<ov::ITensor>& expert_output,
+ const ov::SoPtr<ov::ITensor>& global_output_buffer,
+ const std::vector<size_t>& token_ids,
+ size_t chunk_start,
+ size_t chunk_size,
+ size_t embed_dim,
+ size_t input_token_count,
+ const std::vector<size_t>& expert_slots_for_tokens) {
+ auto elem_type = global_output_buffer->get_element_type();
+
+ for (size_t i = 0; i < chunk_size; ++i) {
+ size_t original_token_id = token_ids[chunk_start + i];
+ size_t expert_slot = expert_slots_for_tokens[chunk_start + i];
+
+ // Calculate offsets
+ size_t src_offset = i * embed_dim;
+ size_t dst_offset = expert_slot * input_token_count * embed_dim + original_token_id * embed_dim;
+
+ // Scatter output to global buffer
+ if (elem_type == ov::element::f32) {
+ const float* src = expert_output->data<float>() + src_offset;
+ float* dst = global_output_buffer->data<float>() + dst_offset;
+ std::memcpy(dst, src, embed_dim * sizeof(float));
+ } else if (elem_type == ov::element::f16) {
+ const ov::float16* src = expert_output->data<ov::float16>() + src_offset;
+ ov::float16* dst = global_output_buffer->data<ov::float16>() + dst_offset;
+ std::memcpy(dst, src, embed_dim * sizeof(ov::float16));
+ } else {
+ OPENVINO_THROW("MoE: Unsupported element type for chunk output relayout: ", elem_type);
+ }
+ }
+}
+
+// ====================================================================================================
+// MoE Request Cache Implementation
+// ====================================================================================================
+
+RequestCache::RequestCache(size_t num_layers, size_t pool_size_per_layer) : m_pool_size_per_layer(pool_size_per_layer) {
+ m_pool.resize(num_layers);
+ m_cache_lookup.resize(num_layers);
+ m_free_list.resize(num_layers);
+ m_lru_index.resize(num_layers);
+
+ m_report_on_die = ov::npuw::profiling_enabled();
+}
+
+RequestCache::~RequestCache() {
+ print_statistics();
+}
+
+void RequestCache::initialize_layer(size_t sublayer_idx, std::vector<RqPtr>&& requests) {
+ NPUW_ASSERT(requests.size() == m_pool_size_per_layer && "Request count must match pool size");
+ NPUW_ASSERT(sublayer_idx < m_pool.size() && "Invalid sublayer index");
+
+ auto& pool = m_pool[sublayer_idx];
+ auto& free_list = m_free_list[sublayer_idx];
+
+ pool.reserve(m_pool_size_per_layer);
+ free_list.reserve(m_pool_size_per_layer);
+
+ for (size_t i = 0; i < m_pool_size_per_layer; ++i) {
+ PoolEntry entry;
+ entry.request = std::move(requests[i]);
+ entry.is_configured = false;
+ entry.last_use_iter = 0;
+ pool.push_back(std::move(entry));
+ free_list.push_back(i); // All entries start as free
+ }
+
+ LOG_DEBUG("MoE Cache: Initialized layer " << sublayer_idx << " with " << m_pool_size_per_layer << " pool entries");
+}
+
+RequestCache::RqPtr RequestCache::find(size_t sublayer_idx, const std::vector<size_t>& expert_ids) {
+ NPUW_ASSERT(sublayer_idx < m_cache_lookup.size() && "Invalid sublayer index");
+
+ m_total_queries++;
+
+ auto& lookup = m_cache_lookup[sublayer_idx];
+ std::string cache_key = make_cache_key(expert_ids);
+
+ auto it = lookup.find(cache_key);
+ if (it != lookup.end()) {
+ // Cache HIT
+ m_cache_hits++;
+ size_t pool_idx = it->second;
+ auto& pool = m_pool[sublayer_idx];
+ auto& entry = pool[pool_idx];
+
+ LOG_VERB("MoE Cache HIT for sublayer[" << sublayer_idx << "] experts: " << cache_key);
+
+ // Update LRU timestamp using m_total_queries (monotonically increasing)
+ auto& lru_index = m_lru_index[sublayer_idx];
+ lru_index.erase({entry.last_use_iter, pool_idx});
+ entry.last_use_iter = m_total_queries;
+ lru_index.insert({entry.last_use_iter, pool_idx});
+
+ return entry.request;
+ }
+
+ // Cache MISS
+ LOG_VERB("MoE Cache MISS for sublayer[" << sublayer_idx << "] experts: " << cache_key);
+ return {};
+}
+
+std::pair<RequestCache::RqPtr, size_t> RequestCache::get_idle_or_lru(size_t sublayer_idx) {
+ NPUW_ASSERT(sublayer_idx < m_pool.size() && "Invalid sublayer index");
+
+ auto& pool = m_pool[sublayer_idx];
+ auto& free_list = m_free_list[sublayer_idx];
+ auto& lru_index = m_lru_index[sublayer_idx];
+ auto& lookup = m_cache_lookup[sublayer_idx];
+
+ // Priority 1: Use free (unconfigured) request if available
+ if (!free_list.empty()) {
+ size_t pool_idx = free_list.back();
+ free_list.pop_back();
+ LOG_VERB("MoE Cache: Allocated free pool entry " << pool_idx << " for sublayer " << sublayer_idx);
+ return {pool[pool_idx].request, pool_idx};
+ }
+
+ // Priority 2: Evict LRU entry
+ NPUW_ASSERT(!lru_index.empty() && "LRU index should not be empty when free list is empty");
+
+ auto lru_it = lru_index.begin(); // Oldest entry (smallest timestamp)
+ size_t pool_idx = lru_it->second;
+ auto& entry = pool[pool_idx];
+
+ // Remove old cache entry
+ std::string old_key = make_cache_key(entry.expert_ids);
+ lookup.erase(old_key);
+ lru_index.erase(lru_it);
+
+ // Mark as unconfigured (will be reconfigured by caller)
+ entry.is_configured = false;
+ entry.expert_ids.clear();
+
+ LOG_VERB("MoE Cache: Evicted LRU pool entry " << pool_idx << " (old key: " << old_key << ")");
+ return {entry.request, pool_idx};
+}
+
+void RequestCache::register_request(size_t sublayer_idx, size_t pool_idx, const std::vector<size_t>& expert_ids) {
+ NPUW_ASSERT(sublayer_idx < m_pool.size() && "Invalid sublayer index");
+ NPUW_ASSERT(pool_idx < m_pool[sublayer_idx].size() && "Invalid pool index");
+
+ auto& pool = m_pool[sublayer_idx];
+ auto& lookup = m_cache_lookup[sublayer_idx];
+ auto& lru_index = m_lru_index[sublayer_idx];
+
+ auto& entry = pool[pool_idx];
+
+ // Update entry state
+ entry.expert_ids = expert_ids;
+ entry.is_configured = true;
+ // last_use_iter will be set by next find() call
+
+ // Register in cache lookup
+ std::string cache_key = make_cache_key(expert_ids);
+ lookup[cache_key] = pool_idx;
+
+ // Add to LRU index (with timestamp 0, will be updated on first use)
+ lru_index.insert({entry.last_use_iter, pool_idx});
+
+ LOG_VERB("MoE Cache: Registered pool entry " << pool_idx << " with key: " << cache_key);
+}
+
+std::pair<uint64_t, uint64_t> RequestCache::get_statistics() const {
+ return {m_total_queries, m_cache_hits};
+}
+
+void RequestCache::print_statistics() const {
+ if (m_total_queries > 0 && m_report_on_die) {
+ double hit_rate = static_cast<double>(m_cache_hits) / m_total_queries * 100.0;
+ std::cout << "[MoE Cache Statistics]" << std::endl;
+ std::cout << " Total Queries: " << m_total_queries << std::endl;
+ std::cout << " Cache Hits: " << m_cache_hits << std::endl;
+ std::cout << " Cache Misses: " << (m_total_queries - m_cache_hits) << std::endl;
+ std::cout << " Hit Rate: " << std::fixed << std::setprecision(2) << hit_rate << "%" << std::endl;
+ }
+}
+
+std::string RequestCache::make_cache_key(const std::vector<size_t>& expert_ids) const {
+ std::string key;
+ key.reserve(expert_ids.size() * 4);
+ for (size_t i = 0; i < expert_ids.size(); ++i) {
+ if (i > 0)
+ key += ",";
+ key += std::to_string(expert_ids[i]);
+ }
+ return key;
+}
+
+} // namespace moe
+} // namespace npuw
+} // namespace ov
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.hpp
new file mode 100644
index 00000000000..f78c0cab8a7
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.hpp
@@ -0,0 +1,252 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <map>
+#include <vector>
+
+#include "../perf.hpp"
+#include "openvino/runtime/iasync_infer_request.hpp"
+#include "openvino/runtime/so_ptr.hpp"
+#include "openvino/runtime/tensor.hpp"
+
+namespace ov {
+namespace npuw {
+namespace moe {
+
+/**
+ * @brief MoE performance profiling structure.
+ *
+ * Tracks performance metrics for MoE operations in different processing modes.
+ * Uses ov::npuw::perf::Profile framework for automatic metric collection and reporting.
+ */
+struct MoEProfile {
+ ov::npuw::perf::Profile<ov::npuw::perf::metric<ov::npuw::perf::MSec>> iterative; // EXPERT_ITERATIVE mode
+ ov::npuw::perf::Profile<ov::npuw::perf::metric<ov::npuw::perf::MSec>> batch; // EXPERT_BATCH mode
+
+ MoEProfile();
+};
+
+/**
+ * @brief Slice a single expert's weight from batched weight tensor.
+ *
+ * Creates a zero-copy view of expert weight from batched tensor with shape [num_experts, ...].
+ * Handles both sub-byte (4-bit) and regular (>=8-bit) element types.
+ *
+ * @param batched_weight Source tensor with shape [num_experts, ...]
+ * @param expert_id ID of the expert to slice (0 to num_experts-1)
+ * @param num_experts Total number of experts in the batch
+ * @return ov::Tensor Zero-copy view with shape [1, ...] for the selected expert
+ */
+ov::Tensor slice_expert_weight(const ov::Tensor& batched_weight, size_t expert_id, size_t num_experts);
+
+/**
+ * @brief Parse selected experts from router output tensor.
+ *
+ * Analyzes router output to determine which experts are selected by each token.
+ * Router output has shape [num_experts, 1, token_num, 1] with non-zero weights
+ * indicating expert selection.
+ *
+ * @param router_output Router output tensor with expert selection weights
+ * @param num_experts Total number of experts
+ * @param token_to_experts[out] Map from token_id to list of selected expert_ids
+ * @param expert_to_tokens[out] Map from expert_id to list of tokens that selected it
+ * @return Vector of selected expert IDs (sorted)
+ */
+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,
+ std::map<size_t, std::vector<size_t>>& expert_to_tokens);
+
+/**
+ * @brief Optimized tensor setter for small/large tensors.
+ *
+ * Uses copy for small tensors (<= 11520 bytes) to avoid set_tensor overhead.
+ * Uses set_tensor for large tensors (zero-copy).
+ *
+ * @param request Inference request
+ * @param iport Input port to set tensor for
+ * @param tensor_impl Tensor to set or copy
+ */
+void set_tensor_optimized(ov::SoPtr<ov::IAsyncInferRequest> request,
+ const ov::Output<const ov::Node>& iport,
+ const ov::SoPtr<ov::ITensor>& tensor_impl);
+
+/**
+ * @brief Gather router scores for selected tokens from router output.
+ *
+ * Extracts router scores for a specific expert and token range from batched router output.
+ * Supports both 4D [num_experts, 1, token_num, 1] and 2D [num_experts, token_num] shapes.
+ *
+ * @param router_source Source router tensor with all expert scores
+ * @param router_dest Destination tensor to write gathered scores
+ * @param expert_id ID of the expert to gather scores for
+ * @param token_ids List of token IDs to process
+ * @param chunk_start Starting index in token_ids list
+ * @param chunk_size Number of tokens to process
+ */
+void gather_router_scores(const ov::SoPtr<ov::ITensor>& router_source,
+ const ov::SoPtr<ov::ITensor>& router_dest,
+ size_t expert_id,
+ const std::vector<size_t>& token_ids,
+ size_t chunk_start,
+ size_t chunk_size);
+
+/**
+ * @brief Gather expert input embeddings for selected tokens.
+ *
+ * Extracts input embeddings for a range of tokens from the source tensor.
+ * Supports both 2D [num_tokens, hidden_dim] and 4D [1, 1, num_tokens, hidden_dim] shapes.
+ *
+ * @param input_source Source tensor with all token embeddings
+ * @param input_dest Destination tensor to write gathered embeddings
+ * @param token_ids List of token IDs to process
+ * @param chunk_start Starting index in token_ids list
+ * @param chunk_size Number of tokens to process
+ */
+void gather_expert_inputs(const ov::SoPtr<ov::ITensor>& input_source,
+ const ov::SoPtr<ov::ITensor>& input_dest,
+ const std::vector<size_t>& token_ids,
+ size_t chunk_start,
+ size_t chunk_size);
+
+/**
+ * @brief Scatter expert outputs back to global output buffer.
+ *
+ * Writes expert output for processed tokens to the correct positions in the global
+ * output buffer based on expert slot assignments.
+ *
+ * @param expert_output Expert's output tensor for current chunk
+ * @param global_output_buffer Global output buffer [K, 1, num_tokens, embed_dim]
+ * @param token_ids List of token IDs that were processed
+ * @param chunk_start Starting index in token_ids list
+ * @param chunk_size Number of tokens processed
+ * @param embed_dim Embedding dimension size
+ * @param input_token_count Total number of input tokens
+ * @param expert_slots_for_tokens Precomputed expert slot for each token in token_ids (same size as token_ids)
+ */
+void scatter_expert_outputs(const ov::SoPtr<ov::ITensor>& expert_output,
+ const ov::SoPtr<ov::ITensor>& global_output_buffer,
+ const std::vector<size_t>& token_ids,
+ size_t chunk_start,
+ size_t chunk_size,
+ size_t embed_dim,
+ size_t input_token_count,
+ const std::vector<size_t>& expert_slots_for_tokens);
+
+/**
+ * @brief MoE Request Cache - LRU cache for expert inference requests.
+ *
+ * Manages a fixed-size pool of pre-configured inference requests per MoE sublayer.
+ * Caches requests by expert combination to avoid redundant weight configuration.
+ * Uses LRU eviction when pool is full.
+ */
+class RequestCache {
+public:
+ using RqPtr = ov::SoPtr<ov::IAsyncInferRequest>;
+
+ /**
+ * @brief Construct a new Request Cache.
+ *
+ * @param num_layers Total number of sublayers (indexed 0 to num_layers-1)
+ * @param pool_size_per_layer Number of cached requests per MoE layer
+ */
+ RequestCache(size_t num_layers, size_t pool_size_per_layer);
+
+ /**
+ * @brief Destructor - prints cache statistics on destruction.
+ */
+ ~RequestCache();
+
+ /**
+ * @brief Find cached request for expert combination.
+ *
+ * @param sublayer_idx Sublayer index
+ * @param expert_ids Expert IDs (order preserved, not sorted)
+ * @return RqPtr Cached request if found, nullptr on cache miss
+ */
+ RqPtr find(size_t sublayer_idx, const std::vector<size_t>& expert_ids);
+
+ /**
+ * @brief Get idle or least-recently-used request from pool.
+ *
+ * Returns an unconfigured request from free list (if available),
+ * or evicts the LRU entry and returns it for reconfiguration.
+ *
+ * @param sublayer_idx Sublayer index
+ * @return std::pair<RqPtr, size_t> {request, pool_index}
+ */
+ std::pair<RqPtr, size_t> get_idle_or_lru(size_t sublayer_idx);
+
+ /**
+ * @brief Register configured request to cache.
+ *
+ * Associates the given pool entry with the expert combination.
+ * Removes entry from free list and adds to LRU index.
+ *
+ * @param sublayer_idx Sublayer index
+ * @param pool_idx Index in the pool
+ * @param expert_ids Expert IDs this request is configured for
+ */
+ void register_request(size_t sublayer_idx, size_t pool_idx, const std::vector<size_t>& expert_ids);
+
+ /**
+ * @brief Initialize request pool for a specific MoE sublayer.
+ *
+ * Pre-allocates inference requests for the given sublayer.
+ * Must be called before using find/get_idle_or_lru for this sublayer.
+ *
+ * @param sublayer_idx Sublayer index
+ * @param requests Pre-allocated inference requests for this layer
+ */
+ void initialize_layer(size_t sublayer_idx, std::vector<RqPtr>&& requests);
+
+ /**
+ * @brief Get cache hit rate statistics.
+ *
+ * @return std::pair<uint64_t, uint64_t> {total_queries, cache_hits}
+ */
+ std::pair<uint64_t, uint64_t> get_statistics() const;
+
+ /**
+ * @brief Print cache statistics to log.
+ */
+ void print_statistics() const;
+
+private:
+ struct PoolEntry {
+ RqPtr request; // Inference request
+ std::vector<size_t> expert_ids; // Expert IDs currently configured
+ uint64_t last_use_iter; // LRU timestamp
+ bool is_configured; // Whether request has valid configuration
+ };
+
+ size_t m_pool_size_per_layer;
+
+ // Pool storage: indexed by sublayer_idx
+ std::vector<std::vector<PoolEntry>> m_pool;
+
+ // Fast lookup: sublayer_idx -> (expert_ids_key -> pool_idx)
+ std::vector<std::unordered_map<std::string, size_t>> m_cache_lookup;
+
+ // Free list: sublayer_idx -> list of unconfigured pool indices
+ std::vector<std::vector<size_t>> m_free_list;
+
+ // LRU index: sublayer_idx -> sorted set of (last_use_iter, pool_idx)
+ std::vector<std::set<std::pair<uint64_t, size_t>>> m_lru_index;
+
+ // Statistics
+ bool m_report_on_die = false;
+
+ mutable uint64_t m_total_queries = 0;
+ mutable uint64_t m_cache_hits = 0;
+
+ // Helper: Convert expert_ids to cache key string
+ std::string make_cache_key(const std::vector<size_t>& expert_ids) const;
+};
+
+} // namespace moe
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cpp
new file mode 100644
index 00000000000..780e0082bee
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cpp
@@ -0,0 +1,125 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_resources.hpp"
+
+#include <algorithm>
+
+#include "../logging.hpp"
+#include "openvino/core/except.hpp"
+
+namespace ov {
+namespace npuw {
+namespace moe {
+
+void MoEResources::initialize_expert_iterative_mode(
+ const MoEConfig& config,
+ std::function<TensorPtr(const ov::element::Type&, const ov::Shape&, const std::string&)> allocator,
+ const std::string& device) {
+ LOG_DEBUG("Initializing MoE resources for EXPERT_ITERATIVE mode...");
+ LOG_BLOCK();
+
+ if (config.input_token_count <= 1) {
+ OPENVINO_THROW("initialize_expert_iterative_mode called with input_token_count=",
+ config.input_token_count,
+ ", expected > 1. Use initialize_expert_batch_mode instead.");
+ }
+
+ // Step 1: Create chunk infer requests and collect chunk sizes
+ LOG_DEBUG("Creating chunk infer requests for expert iterative mode...");
+ sorted_chunk_sizes.clear();
+ chunk_infer_requests.clear();
+ sorted_chunk_sizes.reserve(config.compiled_models.size());
+
+ for (const auto& entry : config.compiled_models) {
+ const size_t chunk_size = entry.first;
+ const auto& compiled_model = entry.second;
+
+ if (!compiled_model) {
+ LOG_WARN("Compiled model for chunk_size=" << chunk_size << " is null, skipping...");
+ continue;
+ }
+
+ try {
+ auto infer_request = compiled_model->create_infer_request();
+ chunk_infer_requests[chunk_size] = std::move(infer_request);
+ sorted_chunk_sizes.push_back(chunk_size);
+ LOG_DEBUG(" Created chunk infer request for chunk_size=" << chunk_size);
+ } catch (const std::exception& ex) {
+ OPENVINO_THROW("MoE chunk infer request creation failed for chunk_size=", chunk_size, ": ", ex.what());
+ }
+ }
+
+ // Step 2: Sort chunk sizes in descending order for greedy selection
+ std::sort(sorted_chunk_sizes.begin(), sorted_chunk_sizes.end(), std::greater<size_t>());
+ LOG_DEBUG("Created " << chunk_infer_requests.size() << " chunk infer requests with sorted sizes");
+
+ // Step 3: Allocate output accumulator buffer
+ const size_t active_experts = config.num_active_experts;
+ 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};
+
+ // 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);
+
+ LOG_DEBUG("Allocated iterative mode output buffer: shape=" << buffer_shape << ", type=" << output_element_type
+ << ", device=" << device);
+
+ LOG_DEBUG("Expert iterative mode initialization completed");
+}
+
+void MoEResources::initialize_expert_batch_mode(
+ const MoEConfig& config,
+ std::function<TensorPtr(const ov::element::Type&, const ov::Shape&, const std::string&)> allocator,
+ const std::string& device,
+ size_t num_sublayers,
+ size_t pool_size) {
+ LOG_DEBUG("Initializing MoE resources for EXPERT_BATCH mode...");
+ LOG_BLOCK();
+
+ if (config.input_token_count != 1) {
+ OPENVINO_THROW("initialize_expert_batch_mode called with input_token_count=",
+ config.input_token_count,
+ ", expected = 1. Use initialize_expert_iterative_mode instead.");
+ }
+
+ // Expert batch mode resources:
+ // - No chunk_infer_requests (uses batch-unrolled model via cache/subrequest)
+ // - No expert_output_accumulator (expert outputs go directly to downstream via normal tensor connections)
+ // - Request cache (optional, if pool_size > 0)
+
+ if (pool_size > 0) {
+ // Create the RequestCache once for all sublayers
+ if (!request_cache) {
+ LOG_DEBUG("Creating RequestCache for " << num_sublayers << " sublayers with pool_size=" << pool_size);
+ request_cache = std::make_unique<ov::npuw::moe::RequestCache>(num_sublayers, pool_size);
+ LOG_DEBUG("RequestCache created successfully");
+ }
+ // Note: Actual request pool creation (initialize_layer) is done by caller
+ // after creating the inference requests for each sublayer
+ } else {
+ LOG_DEBUG("Request cache disabled (pool_size=0)");
+ }
+
+ LOG_DEBUG("Expert batch mode initialization completed");
+}
+
+void MoEResources::reset_cache() {
+ LOG_DEBUG("Resetting request cache...");
+ request_cache.reset();
+
+ // Keep sorted_chunk_sizes (static data)
+ // Keep expert_output_accumulator (reusable allocation)
+
+ LOG_DEBUG("Request cache reset completed");
+}
+
+} // namespace moe
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.hpp
new file mode 100644
index 00000000000..47cd91e1348
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.hpp
@@ -0,0 +1,145 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <memory>
+#include <vector>
+
+#include "../util.hpp" // For TensorPtr
+#include "moe_config.hpp"
+#include "moe_infer_utils.hpp" // For RequestCache
+
+namespace ov {
+namespace npuw {
+namespace moe {
+
+// Import TensorPtr from parent namespace
+using ov::npuw::util::TensorPtr;
+
+/**
+ * @brief MoE runtime resources for reusable allocations across inferences
+ *
+ * Resources are mode-specific:
+ * - EXPERT_ITERATIVE mode (input_token_count > 1): Uses chunk_infer_requests + expert_output_accumulator
+ * - EXPERT_BATCH mode (input_token_count = 1): Uses request_cache only
+ *
+ * Each JustInferRequest has independent MoEResources.
+ * Resources are initialized once and reused across multiple inference calls.
+ */
+struct MoEResources {
+ // ============================================================================
+ // EXPERT_BATCH MODE ONLY (nullptr/empty in EXPERT_ITERATIVE mode)
+ // ============================================================================
+
+ // Request cache for expert combination caching (batch mode optimization)
+ // Created only when pool_size > 0 and mode is EXPERT_BATCH
+ std::unique_ptr<ov::npuw::moe::RequestCache> request_cache;
+
+ // ============================================================================
+ // EXPERT_ITERATIVE MODE ONLY (nullptr/empty in EXPERT_BATCH mode)
+ // ============================================================================
+
+ // Pre-sorted chunk sizes in descending order for greedy selection
+ // Example: [256, 128, 64, 32, 16]
+ // Used to select optimal chunk size for token batches
+ std::vector<size_t> sorted_chunk_sizes;
+
+ // Infer requests for different chunk sizes
+ // Map: chunk_size -> infer_request
+ // Reused across experts by unpacking different weights
+ std::map<size_t, ov::SoPtr<ov::IAsyncInferRequest>> chunk_infer_requests;
+
+ // Output accumulation buffer
+ // Shape: [num_active_experts, 1, input_token_count, expert_hidden_dim]
+ // Accumulates expert outputs before final reduction
+ TensorPtr expert_output_accumulator;
+
+ /**
+ * @brief Initialize resources for expert iterative mode
+ *
+ * Mode: Iterate through experts, each processes multiple tokens in chunks
+ * Use cases: Prompt processing, speculative decoding
+ *
+ * Initializes:
+ * - sorted_chunk_sizes: extracted from config.compiled_models
+ * - chunk_infer_requests: created for each chunk size model
+ * - expert_output_accumulator: allocated with given shape and device
+ *
+ * @param config MoE configuration (must have input_token_count > 1)
+ * @param allocator Memory allocation function
+ * @param device Target device for buffer allocation
+ */
+ void initialize_expert_iterative_mode(
+ const MoEConfig& config,
+ std::function<TensorPtr(const ov::element::Type&, const ov::Shape&, const std::string&)> allocator,
+ const std::string& device);
+
+ /**
+ * @brief Initialize resources for expert batch mode
+ *
+ * Mode: Process K experts in parallel for single token
+ * Use cases: Token generation in autoregressive mode
+ *
+ * Creates request cache if pool_size > 0. Request cache enables expert
+ * combination caching for improved batch mode performance.
+ *
+ * @param config MoE configuration (must have input_token_count = 1)
+ * @param allocator Memory allocation function
+ * @param device Target device for buffer allocation
+ * @param num_sublayers Total number of sublayers (for cache structure)
+ * @param pool_size Request cache pool size (0 = cache disabled)
+ */
+ void initialize_expert_batch_mode(
+ const MoEConfig& config,
+ std::function<TensorPtr(const ov::element::Type&, const ov::Shape&, const std::string&)> allocator,
+ const std::string& device,
+ size_t num_sublayers,
+ size_t pool_size);
+
+ /**
+ * @brief Initialize resources for multi-token inference (deprecated)
+ * @deprecated Use initialize_expert_iterative_mode() instead
+ */
+ [[deprecated("Use initialize_expert_iterative_mode() instead")]]
+ void initialize_for_prefill(
+ const MoEConfig& config,
+ std::function<TensorPtr(const ov::element::Type&, const ov::Shape&, const std::string&)> allocator,
+ const std::string& device) {
+ initialize_expert_iterative_mode(config, allocator, device);
+ }
+
+ /**
+ * @brief Initialize resources for single-token inference (deprecated)
+ * @deprecated Use initialize_expert_batch_mode() instead
+ */
+ [[deprecated("Use initialize_expert_batch_mode() instead")]]
+ void initialize_for_decoding(
+ const MoEConfig& config,
+ std::function<TensorPtr(const ov::element::Type&, const ov::Shape&, const std::string&)> allocator,
+ const std::string& device,
+ size_t num_sublayers,
+ size_t pool_size) {
+ initialize_expert_batch_mode(config, allocator, device, num_sublayers, pool_size);
+ }
+
+ /**
+ * @brief Reset request cache (for recreation after failure)
+ *
+ * Clears the entire request cache. All sublayers will need re-initialization.
+ */
+ void reset_cache();
+
+ /**
+ * @brief Check if resources are initialized
+ */
+ bool is_initialized() const {
+ return expert_output_accumulator != nullptr;
+ }
+};
+
+} // namespace moe
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_types.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_types.hpp
new file mode 100644
index 00000000000..ad194a29d5e
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_types.hpp
@@ -0,0 +1,99 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <vector>
+
+#include "openvino/runtime/itensor.hpp"
+#include "openvino/runtime/so_ptr.hpp"
+
+namespace ov {
+namespace npuw {
+
+namespace moe {
+
+/**
+ * @brief MoE inference processing mode
+ *
+ * Determines how experts are processed based on token count and expert activation pattern.
+ *
+ * The mode is determined by input token count:
+ * - input_token_count == 1 → EXPERT_BATCH (single token, K experts in parallel)
+ * - input_token_count > 1 → EXPERT_ITERATIVE (multiple tokens, iterate through experts)
+ */
+enum class MoEProcessingMode {
+ /**
+ * @brief Expert iterative mode
+ *
+ * Characteristics:
+ * - Expert dimension: Iterative (process one expert at a time)
+ * - Token dimension: Batch/Chunked (each expert processes N tokens in chunks)
+ * - Pattern: for each expert { process N tokens in chunks }
+ *
+ * Use cases:
+ * - Traditional prompt processing (multiple tokens from user input)
+ * - Speculative decoding (processing multiple candidate tokens)
+ * - Any scenario with multiple tokens requiring expert processing
+ */
+ EXPERT_ITERATIVE,
+
+ /**
+ * @brief Expert batch mode
+ *
+ * Characteristics:
+ * - Expert dimension: Batch (process K experts simultaneously in parallel)
+ * - Token dimension: Single (1 token per iteration)
+ * - Pattern: process K experts in parallel for 1 token
+ *
+ * Use cases:
+ * - Traditional token generation (token-by-token generation in autoregressive mode)
+ * - Single-token inference scenarios
+ */
+ EXPERT_BATCH
+};
+
+/**
+ * @brief Determine processing mode based on token count
+ *
+ * @param input_token_count Number of input tokens
+ * @return EXPERT_BATCH for single token, EXPERT_ITERATIVE for multiple tokens
+ */
+inline MoEProcessingMode determine_processing_mode(size_t input_token_count) {
+ return (input_token_count == 1) ? MoEProcessingMode::EXPERT_BATCH : MoEProcessingMode::EXPERT_ITERATIVE;
+}
+
+/**
+ * @brief Get human-readable mode name for logging
+ *
+ * @param mode Processing mode
+ * @return String representation of the mode
+ */
+inline const char* get_mode_name(MoEProcessingMode mode) {
+ switch (mode) {
+ case MoEProcessingMode::EXPERT_ITERATIVE:
+ return "EXPERT_ITERATIVE";
+ case MoEProcessingMode::EXPERT_BATCH:
+ return "EXPERT_BATCH";
+ default:
+ return "UNKNOWN";
+ }
+}
+
+} // namespace moe
+
+/**
+ * @brief MoE I/O tensors structure
+ *
+ * Contains input and output tensors for MoE expert inference.
+ * Shared between IBaseInferRequest and MoEExecutor.
+ */
+struct MoEIO {
+ std::vector<ov::SoPtr<ov::ITensor>> outputs; // # of elements - # of subgraph outputs
+ ov::SoPtr<ov::ITensor> router_scores; // Expert model input: router output for expert selection
+ ov::SoPtr<ov::ITensor> expert_input; // Expert model input: token embeddings
+};
+
+} // namespace npuw
+} // namespace ov
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.cpp
new file mode 100644
index 00000000000..2eb6932183a
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.cpp
@@ -0,0 +1,1038 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#include "moe_transformation.hpp"
+
+#include "moe_unroll_patterns.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/ops.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/result.hpp"
+#include "openvino/op/topk.hpp"
+#include "openvino/openvino.hpp"
+#include "openvino/pass/manager.hpp"
+#include "openvino/pass/validate.hpp"
+#include "openvino/runtime/icompiled_model.hpp"
+#include "openvino/runtime/isync_infer_request.hpp"
+#include "openvino/runtime/tensor.hpp"
+
+namespace ov {
+namespace npuw {
+namespace function {
+
+// Helper function to extract K value from TopK node in router model
+static std::optional<size_t> extract_k_from_router(const std::shared_ptr<ov::Model>& router_model) {
+ if (!router_model) {
+ LOG_ERROR("Router model is null, cannot extract K from TopK");
+ return std::nullopt;
+ }
+
+ LOG_DEBUG("Searching for TopK node in router model: " << router_model->get_friendly_name());
+
+ for (const auto& node : router_model->get_ordered_ops()) {
+ if (auto topk = std::dynamic_pointer_cast<ov::op::v11::TopK>(node)) {
+ LOG_DEBUG("Found TopK node: " << topk->get_friendly_name());
+
+ // K is the second input to TopK
+ auto k_input = topk->input_value(1);
+ if (auto k_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(k_input.get_node_shared_ptr())) {
+ auto k_data = k_const->cast_vector<int64_t>();
+ if (!k_data.empty()) {
+ size_t k_value = static_cast<size_t>(k_data[0]);
+ LOG_INFO("Extracted K=" << k_value << " from TopK node in router model");
+ return k_value;
+ }
+ }
+ }
+ }
+
+ LOG_DEBUG("TopK node not found in router model");
+ return std::nullopt;
+}
+
+// Helper function to build parameter mapping from RTInfo metadata
+static std::map<size_t, std::vector<size_t>> build_parameter_mapping_from_rtinfo(
+ const std::shared_ptr<ov::Model>& original_model,
+ const std::shared_ptr<ov::Model>& transformed_model) {
+ std::map<size_t, std::vector<size_t>> param_mapping;
+ LOG_DEBUG("Building parameter mapping from RTInfo...");
+
+ // Get original model parameters for index lookup
+ const auto& original_params = original_model->get_parameters();
+ const auto& transformed_params = transformed_model->get_parameters();
+
+ // Walk through transformed model parameters and extract RTInfo
+ for (size_t new_param_idx = 0; new_param_idx < transformed_params.size(); ++new_param_idx) {
+ const auto& param = transformed_params[new_param_idx];
+ const auto& rt_info = param->get_rt_info();
+
+ // Check if this parameter has MoE RTInfo metadata
+ if (rt_info.count("moe_original_param") > 0 && rt_info.count("moe_expert_index") > 0) {
+ std::string original_param_name = rt_info.at("moe_original_param").as<std::string>();
+ int64_t expert_idx = rt_info.at("moe_expert_index").as<int64_t>();
+
+ // Find the original parameter index by name
+ size_t original_param_idx = 0;
+ bool found = false;
+ for (size_t i = 0; i < original_params.size(); ++i) {
+ if (original_params[i]->get_friendly_name() == original_param_name) {
+ original_param_idx = i;
+ found = true;
+ break;
+ }
+ }
+
+ if (found) {
+ // Add to mapping: original_idx -> [unrolled_indices]
+ param_mapping[original_param_idx].push_back(new_param_idx);
+
+ LOG_DEBUG(" Mapped: original param[" << original_param_idx << "] '" << original_param_name
+ << "' -> transformed param[" << new_param_idx << "] (expert "
+ << expert_idx << ")");
+ } else {
+ LOG_WARN(" Could not find original parameter '" << original_param_name << "' in original model");
+ }
+ }
+ }
+
+ 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");
+ }
+
+ return param_mapping;
+}
+
+// Helper: Trace back from a node to find the source Parameter
+static std::optional<size_t> trace_to_parameter(const std::shared_ptr<ov::Node>& start_node,
+ const std::shared_ptr<ov::Model>& model) {
+ std::shared_ptr<ov::Node> current_node = start_node;
+
+ while (current_node) {
+ if (auto param = std::dynamic_pointer_cast<ov::op::v0::Parameter>(current_node)) {
+ // Found parameter, get its index
+ const auto& params = model->get_parameters();
+ for (size_t idx = 0; idx < params.size(); ++idx) {
+ if (params[idx]->get_friendly_name() == param->get_friendly_name()) {
+ return idx;
+ }
+ }
+ return std::nullopt;
+ }
+
+ // Only skip Convert and Reshape nodes when tracing back
+ if (current_node->get_input_size() == 1) {
+ if (std::dynamic_pointer_cast<ov::op::v0::Convert>(current_node) ||
+ std::dynamic_pointer_cast<ov::op::v1::Reshape>(current_node)) {
+ current_node = current_node->input_value(0).get_node_shared_ptr();
+ continue;
+ }
+ }
+
+ // Cannot trace further through this node
+ break;
+ }
+
+ return std::nullopt;
+}
+
+// Helper: Find Tile node and extract expert configuration
+static bool find_tile_and_extract_config(const std::shared_ptr<ov::Model>& model, MoEStructureInfo& info) {
+ for (const auto& node : model->get_ordered_ops()) {
+ auto tile = std::dynamic_pointer_cast<ov::op::v0::Tile>(node);
+ if (!tile)
+ continue;
+
+ auto repeats_input = tile->input_value(1);
+ auto repeats_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(repeats_input.get_node_shared_ptr());
+ if (!repeats_const)
+ continue;
+
+ auto repeats_data = repeats_const->cast_vector<int64_t>();
+ if (repeats_data.empty() || repeats_data[0] <= 1)
+ continue;
+
+ // Found valid Tile node
+ info.num_experts = static_cast<size_t>(repeats_data[0]);
+ info.expert_input_tile_node = tile;
+
+ // Validate and extract shape information
+ auto tile_output_shape = tile->output(0).get_shape();
+ if (tile_output_shape.empty() || tile_output_shape[0] % info.num_experts != 0) {
+ LOG_WARN("Invalid Tile output shape");
+ return false;
+ }
+
+ info.input_token_count = tile->input_value(0).get_shape()[0];
+ info.expert_hidden_dim = tile->input_value(0).get_shape()[1];
+
+ LOG_DEBUG("Found Tile: num_experts=" << info.num_experts << ", expert_hidden_dim=" << info.expert_hidden_dim
+ << ", input_token_count=" << info.input_token_count);
+
+ // Find the parameter index for Tile's input
+ auto tile_input_node = tile->input_value(0).get_node_shared_ptr();
+ info.expert_input_param_idx = trace_to_parameter(tile_input_node, model);
+
+ if (info.expert_input_param_idx.has_value()) {
+ LOG_DEBUG(" Found expert input parameter at index " << info.expert_input_param_idx.value());
+ }
+
+ return true;
+ }
+
+ LOG_WARN("Could not find valid Tile operation");
+ return false;
+}
+
+// Helper: Find router scores parameter from output path
+// Output path: Result <- [Convert] <- [ReduceSum] <- Multiply <- router_param
+static bool find_router_scores_from_output(const std::shared_ptr<ov::Model>& model, MoEStructureInfo& info) {
+ LOG_DEBUG("Detecting router scores parameter from output path...");
+
+ for (const auto& result_node : model->get_results()) {
+ auto current = result_node->input_value(0).get_node_shared_ptr();
+
+ // Skip Convert node if present
+ if (auto convert_node = std::dynamic_pointer_cast<ov::op::v0::Convert>(current)) {
+ LOG_DEBUG(" Skipping Convert node before Result");
+ current = convert_node->input_value(0).get_node_shared_ptr();
+ }
+
+ // Skip ReduceSum node if present
+ if (auto reduce_sum_node = std::dynamic_pointer_cast<ov::op::v1::ReduceSum>(current)) {
+ LOG_DEBUG(" Skipping ReduceSum node before Result");
+ current = reduce_sum_node->input_value(0).get_node_shared_ptr();
+ }
+
+ // Check for Multiply node
+ auto multiply_node = std::dynamic_pointer_cast<ov::op::v1::Multiply>(current);
+ if (!multiply_node)
+ continue;
+
+ LOG_DEBUG(" Found Multiply node before Result");
+ info.router_scores_multiply_node = multiply_node;
+
+ // Multiply has two inputs, one is expert output (from Reshape), other is router scores
+ for (size_t i = 0; i < 2; ++i) {
+ auto multiply_input = multiply_node->input_value(i).get_node_shared_ptr();
+
+ // Skip the Reshape input (expert output)
+ if (std::dynamic_pointer_cast<ov::op::v1::Reshape>(multiply_input)) {
+ continue;
+ }
+
+ // Trace back to find Parameter (router scores)
+ info.router_scores_idx = trace_to_parameter(multiply_input, model);
+
+ if (info.router_scores_idx.has_value()) {
+ LOG_DEBUG(" Found router scores parameter at index " << info.router_scores_idx.value());
+ return true;
+ }
+ }
+ }
+
+ LOG_WARN("Could not find router scores Multiply node in output path");
+ return false;
+}
+
+// Analyze MoE model structure - comprehensive single-pass analysis
+std::optional<MoEStructureInfo> analyze_moe_structure(const std::shared_ptr<ov::Model>& model) {
+ LOG_DEBUG("Analyzing MoE model structure...");
+ LOG_BLOCK();
+
+ MoEStructureInfo info;
+
+ // Step 1: Find Tile operation and extract expert configuration
+ if (!find_tile_and_extract_config(model, info)) {
+ return std::nullopt;
+ }
+
+ // Step 2: Detect router_scores parameter from output path
+ if (!find_router_scores_from_output(model, info)) {
+ return std::nullopt;
+ }
+
+ // 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)
+ if (info.input_token_count == 1) {
+ info.processing_mode = moe::MoEProcessingMode::EXPERT_BATCH;
+ LOG_DEBUG("Inferred EXPERT_BATCH mode (input_token_count=1)");
+ } else if (info.input_token_count > 1) {
+ info.processing_mode = moe::MoEProcessingMode::EXPERT_ITERATIVE;
+ LOG_DEBUG("Inferred EXPERT_ITERATIVE mode (input_token_count=" << info.input_token_count << ")");
+ }
+
+ LOG_INFO("MoE structure analysis completed:");
+ LOG_INFO(" - Num experts: " << info.num_experts);
+ LOG_INFO(" - Expert hidden dim: " << info.expert_hidden_dim);
+ LOG_INFO(" - Input token count: " << info.input_token_count);
+ LOG_INFO(" - Mode: " << (info.is_expert_batch_mode() ? "EXPERT_BATCH" : "EXPERT_ITERATIVE"));
+ if (info.expert_input_param_idx.has_value()) {
+ LOG_INFO(" - Expert input param idx: " << info.expert_input_param_idx.value());
+ }
+ if (info.router_scores_idx.has_value()) {
+ LOG_INFO(" - Router scores param idx: " << info.router_scores_idx.value());
+ }
+
+ return info;
+}
+
+// Determine transformation parameters based on structure analysis and router K
+MoETransformConfig determine_transformation_params(const MoEStructureInfo& structure_info,
+ size_t k_from_router,
+ size_t iterative_chunk_size) {
+ LOG_DEBUG("Determining transformation parameters...");
+ LOG_BLOCK();
+
+ MoETransformConfig config;
+
+ if (structure_info.is_expert_batch_mode()) {
+ // EXPERT_BATCH mode: transform to K active experts for parallel processing
+ config.num_target_experts = k_from_router;
+ config.chunk_size = 0; // Not used in batch mode
+
+ LOG_INFO("Transformation config for EXPERT_BATCH mode:");
+ LOG_INFO(" - Mode: BATCH_K_EXPERTS");
+ LOG_INFO(" - Target experts: " << config.num_target_experts);
+ } else {
+ // EXPERT_ITERATIVE mode: transform to 1 expert for iterative processing
+ config.num_target_experts = 1;
+ config.chunk_size = iterative_chunk_size;
+
+ LOG_INFO("Transformation config for EXPERT_ITERATIVE mode:");
+ LOG_INFO(" - Mode: SINGLE_EXPERT_ITERATIVE");
+ LOG_INFO(" - Target experts: 1");
+ LOG_INFO(" - Chunk size: " << config.chunk_size);
+ }
+
+ return 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) {
+ 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) {
+ return false;
+ }
+
+ auto shape_data = shape_const->cast_vector<int64_t>();
+
+ // MoE reshapes are either 3D or 4D
+ if (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;
+ }
+
+ // 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;
+
+ 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;
+}
+
+// Helper: Check if parameter matches downstream pattern
+// Pattern: Parameter -> [Convert] -> ReduceSum (Convert is optional)
+static bool check_downstream_pattern(const std::shared_ptr<ov::op::v0::Parameter>& param) {
+ // Parameter should have exactly one user
+ auto param_users = param->output(0).get_target_inputs();
+ if (param_users.size() != 1) {
+ return false;
+ }
+
+ auto first_consumer = param_users.begin()->get_node()->shared_from_this();
+
+ // Check if first consumer is ReduceSum (no Convert)
+ if (auto reduce_sum = std::dynamic_pointer_cast<ov::op::v1::ReduceSum>(first_consumer)) {
+ return true;
+ }
+
+ // Check if first consumer is Convert
+ auto convert_node = std::dynamic_pointer_cast<ov::op::v0::Convert>(first_consumer);
+ if (!convert_node) {
+ return false;
+ }
+
+ // Convert should have exactly one user (ReduceSum node)
+ auto convert_users = convert_node->output(0).get_target_inputs();
+ if (convert_users.size() != 1) {
+ return false;
+ }
+
+ auto reduce_sum =
+ std::dynamic_pointer_cast<ov::op::v1::ReduceSum>(convert_users.begin()->get_node()->shared_from_this());
+ return reduce_sum != nullptr;
+}
+
+std::optional<MoEDownstream> detect_and_transform_moe_downstream(const std::shared_ptr<ov::Model>& model,
+ size_t active_experts_num) {
+ LOG_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
+ 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
+ auto 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) {
+ continue;
+ }
+
+ // Check pattern: Parameter -> Convert -> ReduceSum
+ if (!check_downstream_pattern(param)) {
+ continue;
+ }
+
+ LOG_DEBUG(" Found downstream pattern for Parameter: " << param->get_friendly_name());
+ LOG_DEBUG(" Pattern matched: Parameter -> Convert -> ReduceSum");
+
+ size_t total_experts_num = shape[0];
+
+ // Validate configuration
+ if (active_experts_num > total_experts_num) {
+ LOG_WARN("Active experts (" << active_experts_num << ") > total experts (" << total_experts_num
+ << "), skipping this parameter");
+ continue;
+ }
+
+ // Clone and modify the model
+ auto modified_model = model->clone();
+ auto& cloned_params = modified_model->get_parameters();
+ auto& target_param = cloned_params[param_idx];
+
+ auto new_shape = shape;
+ new_shape[0] = active_experts_num;
+
+ LOG_DEBUG(" Modifying parameter shape from " << shape << " to " << new_shape);
+ LOG_DEBUG(" Parameter name: " << target_param->get_friendly_name());
+
+ target_param->set_partial_shape(ov::PartialShape(new_shape));
+ target_param->validate_and_infer_types();
+ modified_model->validate_nodes_and_infer_types();
+
+ LOG_INFO("Successfully detected and transformed MoE downstream pattern");
+ LOG_INFO(" Expert output parameter: " << param->get_friendly_name());
+ LOG_INFO(" Expert output parameter index: " << param_idx);
+
+ // Build and return result
+ MoEDownstream result;
+ result.total_experts_num = total_experts_num;
+ result.active_experts_num = active_experts_num;
+ result.expert_output_param_idx = param_idx;
+ result.modified_model = modified_model;
+
+ return result;
+ }
+
+ LOG_DEBUG("MoE downstream pattern not found");
+ return std::nullopt;
+}
+
+std::optional<MoEDownstream> create_moe_downstream(const std::shared_ptr<ov::Model>& model,
+ const std::shared_ptr<ov::Model>& router_model) {
+ LOG_DEBUG("Creating MoEDownstream from model: " << model->get_friendly_name());
+ LOG_BLOCK();
+
+ // Extract K from router model (required)
+ if (!router_model) {
+ LOG_ERROR("Router model is required to extract K from TopK node");
+ return std::nullopt;
+ }
+
+ auto k_from_router = extract_k_from_router(router_model);
+ if (!k_from_router.has_value()) {
+ LOG_ERROR("Failed to extract K from router model for downstream");
+ return std::nullopt;
+ }
+
+ size_t active_experts_num = k_from_router.value();
+ LOG_INFO("Extracted K=" << active_experts_num << " from router model for downstream");
+
+ auto downstream_info = detect_and_transform_moe_downstream(model, active_experts_num);
+ if (downstream_info && downstream_info->is_valid()) {
+ LOG_INFO("Successfully created MoEDownstream:");
+ LOG_INFO(" - Total experts: " << downstream_info->total_experts_num);
+ LOG_INFO(" - Active experts: " << downstream_info->active_experts_num);
+ LOG_INFO(" - Expert output parameter index: " << downstream_info->expert_output_param_idx);
+ LOG_INFO(" - Modified model: " << downstream_info->modified_model->get_friendly_name());
+
+ return downstream_info;
+ }
+
+ LOG_WARN("Failed to create MoEDownstream - downstream pattern not found");
+ return std::nullopt;
+}
+
+// ============================================================================
+// MoEModelTransformer Implementation
+// ============================================================================
+
+std::optional<MoEModelTransformer::KeyNodes> MoEModelTransformer::find_key_nodes_in_cloned_model(
+ const std::shared_ptr<ov::Model>& model) const {
+ KeyNodes nodes;
+ const std::string tile_name = m_structure_info.expert_input_tile_node->get_friendly_name();
+ const std::string multiply_name = m_structure_info.router_scores_multiply_node->get_friendly_name();
+
+ for (const auto& node : model->get_ordered_ops()) {
+ if (auto tile = std::dynamic_pointer_cast<ov::op::v0::Tile>(node)) {
+ if (tile->get_friendly_name() == tile_name) {
+ nodes.tile_node = tile;
+ LOG_DEBUG("Found Tile node in cloned model: " << tile_name);
+ }
+ }
+
+ if (auto multiply = std::dynamic_pointer_cast<ov::op::v1::Multiply>(node)) {
+ if (multiply->get_friendly_name() == multiply_name) {
+ nodes.multiply_node = multiply;
+ LOG_DEBUG("Found Multiply node in cloned model: " << multiply_name);
+ }
+ }
+
+ if (nodes.tile_node && nodes.multiply_node) {
+ break; // Found all required nodes
+ }
+ }
+
+ if (!nodes.tile_node || !nodes.multiply_node) {
+ LOG_ERROR("Could not find required nodes in cloned model - Tile: " << tile_name
+ << ", Multiply: " << multiply_name);
+ return std::nullopt;
+ }
+
+ return nodes;
+}
+
+std::pair<std::shared_ptr<ov::Node>, ov::Output<ov::Node>> MoEModelTransformer::find_matmul_and_predecessor(
+ ov::Output<ov::Node>& tile_output) const {
+ for (const auto& target_input : tile_output.get_target_inputs()) {
+ auto consumer = target_input.get_node()->shared_from_this();
+
+ if (auto reshape_op = std::dynamic_pointer_cast<ov::op::v1::Reshape>(consumer)) {
+ LOG_DEBUG("Found Reshape after Tile: " << reshape_op->get_friendly_name());
+ for (const auto& reshape_target : reshape_op->output(0).get_target_inputs()) {
+ if (auto mm =
+ std::dynamic_pointer_cast<ov::op::v0::MatMul>(reshape_target.get_node()->shared_from_this())) {
+ LOG_DEBUG("Found MatMul after Reshape: " << mm->get_friendly_name());
+ return {mm, reshape_op->output(0)};
+ }
+ }
+ } else if (auto mm = std::dynamic_pointer_cast<ov::op::v0::MatMul>(consumer)) {
+ LOG_DEBUG("Found MatMul directly after Tile: " << mm->get_friendly_name());
+ return {mm, tile_output};
+ }
+ }
+ return {nullptr, ov::Output<ov::Node>()};
+}
+
+void MoEModelTransformer::replace_tile_with_new_tile(const ov::Output<ov::Node>& tile_input,
+ ov::Output<ov::Node>& node_before_matmul,
+ const std::string& friendly_name,
+ size_t num_target_experts) const {
+ auto matmul_input_shape = node_before_matmul.get_shape();
+ ov::Shape target_expert_shape = matmul_input_shape;
+ target_expert_shape[0] = num_target_experts;
+
+ LOG_DEBUG("Original MatMul input shape: " << matmul_input_shape);
+ LOG_DEBUG("Target expert shape (" << num_target_experts << " experts): " << target_expert_shape);
+
+ std::shared_ptr<ov::Node> new_node;
+
+ if (num_target_experts == 1) {
+ // For single expert (iterative mode), use Reshape since no repetition needed
+ auto target_shape_const = std::make_shared<ov::op::v0::Constant>(ov::element::i64,
+ ov::Shape{target_expert_shape.size()},
+ target_expert_shape);
+ new_node = std::make_shared<ov::op::v1::Reshape>(tile_input, target_shape_const, false);
+ new_node->set_friendly_name(friendly_name + "_transformed_single_expert");
+ LOG_DEBUG("Using Reshape for single expert");
+ } else {
+ // For multiple active experts (batch mode), use Tile to replicate data, then Reshape to expand dims
+ std::vector<int64_t> repeats_data(tile_input.get_shape().size(), 1);
+ repeats_data[0] = num_target_experts; // Repeat along first dimension
+
+ auto repeats_const =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{repeats_data.size()}, repeats_data);
+ auto tile_node = std::make_shared<ov::op::v0::Tile>(tile_input, repeats_const);
+ tile_node->set_friendly_name(friendly_name + "_transformed_tile_" + std::to_string(num_target_experts));
+ LOG_DEBUG("Using Tile with repeats=" << num_target_experts << " for multiple active experts");
+
+ // After Tile: [4, 2880] -> need Reshape to [4, token_num, 2880]
+ // target_expert_shape already has the correct 3D shape
+ auto reshape_shape_const = std::make_shared<ov::op::v0::Constant>(ov::element::i64,
+ ov::Shape{target_expert_shape.size()},
+ target_expert_shape);
+ new_node = std::make_shared<ov::op::v1::Reshape>(tile_node, reshape_shape_const, false);
+ new_node->set_friendly_name(friendly_name + "_transformed_" + std::to_string(num_target_experts) +
+ "_experts_reshape");
+ LOG_DEBUG("Added Reshape after Tile to expand to 3D shape: " << target_expert_shape);
+ }
+
+ node_before_matmul.replace(new_node->output(0));
+}
+
+void MoEModelTransformer::ensure_tensor_names(const std::shared_ptr<ov::Model>& model) const {
+ LOG_DEBUG("Ensuring all tensors have names...");
+ size_t in_tensor_idx = 0;
+ for (auto& input : model->inputs()) {
+ if (input.get_tensor().get_names().empty()) {
+ std::string name = "moe_in_tensor_" + std::to_string(in_tensor_idx);
+ input.get_tensor().set_names({name});
+ LOG_DEBUG(" Added input tensor name: " << name);
+ }
+ in_tensor_idx++;
+ }
+
+ size_t out_tensor_idx = 0;
+ for (auto& output : model->outputs()) {
+ if (output.get_tensor().get_names().empty()) {
+ std::string name = "moe_out_tensor_" + std::to_string(out_tensor_idx);
+ output.get_tensor().set_names({name});
+ LOG_DEBUG(" Added output tensor name: " << name);
+ }
+ out_tensor_idx++;
+ }
+}
+
+void MoEModelTransformer::fix_parameters_with_num_experts(const std::shared_ptr<ov::Model>& model,
+ size_t num_experts,
+ size_t num_target_experts) const {
+ LOG_DEBUG("Fixing Parameter nodes with num_experts in shape to " << num_target_experts << " experts...");
+
+ const auto& all_params = model->get_parameters();
+ for (size_t param_idx = 0; param_idx < all_params.size(); ++param_idx) {
+ const auto& param = all_params[param_idx];
+
+ // Skip the tile input parameter - it does not contain expert dimension
+ if (m_structure_info.expert_input_param_idx.has_value() &&
+ param_idx == m_structure_info.expert_input_param_idx.value()) {
+ LOG_DEBUG(" Skipping tile input parameter at index " << param_idx << ": " << param->get_friendly_name());
+ continue;
+ }
+
+ auto param_shape = param->get_partial_shape();
+ if (param_shape.rank().is_static() && param_shape.rank().get_length() > 0) {
+ auto shape = param_shape.to_shape();
+ 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;
+ }
+ }
+
+ if (needs_fix) {
+ LOG_DEBUG(" Found Parameter '" << param->get_friendly_name() << "' with shape[" << fix_dim
+ << "]=" << num_experts);
+
+ shape[fix_dim] = num_target_experts;
+
+ // Directly set the new shape on the parameter
+ param->set_partial_shape(ov::PartialShape(shape));
+ param->validate_and_infer_types();
+ LOG_DEBUG(" Successfully updated parameter shape to " << num_target_experts);
+ }
+ }
+ }
+
+ // Also fix Reshape nodes that contain num_experts in their shape constants
+ 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) {
+ 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);
+ }
+}
+
+void MoEModelTransformer::fix_token_count_for_expert_iterative(
+ const std::shared_ptr<ov::Model>& model,
+ size_t num_target_experts,
+ 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) {
+ return; // Only apply to EXPERT_ITERATIVE mode (single expert)
+ }
+
+ LOG_DEBUG("Fixing token count from " << m_structure_info.input_token_count << " to " << chunk_size
+ << " for EXPERT_ITERATIVE mode...");
+
+ if (!expert_input_tile_op) {
+ LOG_WARN("Tile node not available for token count fixing");
+ return;
+ }
+
+ // Trace back from Tile input to find Parameters
+ 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));
+ }
+
+ // Fix Parameter shapes
+ size_t original_token_count = m_structure_info.input_token_count;
+ for (const auto& param : params_to_fix) {
+ auto param_shape = param->get_partial_shape();
+ 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;
+ }
+ }
+
+ param->set_partial_shape(ov::PartialShape(shape));
+ param->validate_and_infer_types();
+ }
+ }
+
+ // Also fix Reshape nodes that contain original_token_count in their shape constants
+ 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);
+ }
+
+ // Trigger shape inference to propagate changes through the model
+ LOG_DEBUG("Triggering shape inference after token count changes...");
+ model->validate_nodes_and_infer_types();
+}
+
+// Unroll MoE expert model on expert dimension using GraphRewrite patterns
+std::shared_ptr<ov::Model> MoEModelTransformer::unroll_expert_dimension(const std::shared_ptr<ov::Model>& model,
+ size_t num_experts,
+ bool full_optimization) const {
+ if (num_experts <= 1) {
+ LOG_DEBUG("No unrolling needed for single expert");
+ return model;
+ }
+
+ LOG_INFO("Unrolling expert dimension for " << num_experts << " experts using GraphRewrite");
+ LOG_INFO("Optimization mode: " << (full_optimization ? "Full (weights + activations)" : "WeightsOnly"));
+ LOG_BLOCK();
+
+ try {
+ auto unrolled_model = model->clone();
+
+ ov::pass::Manager manager;
+ if (full_optimization) {
+ manager.register_pass<ov::npuw::pass::MoEExpertUnrolling>(unrolled_model);
+ } else {
+ manager.register_pass<ov::npuw::pass::MoEExpertUnrollingWeightsOnly>(unrolled_model);
+ }
+ manager.run_passes(unrolled_model);
+
+ unrolled_model->validate_nodes_and_infer_types();
+ LOG_INFO("Successfully unrolled and validated model for " << num_experts << " experts");
+
+ return unrolled_model;
+ } catch (const std::exception& e) {
+ LOG_ERROR("Failed to unroll expert dimension: " << e.what());
+ return nullptr;
+ }
+}
+
+// Transform MoE model based on configuration
+std::shared_ptr<ov::Model> MoEModelTransformer::apply_expert_transformation(
+ const std::shared_ptr<ov::Model>& original_model,
+ const MoETransformConfig& config) const {
+ LOG_DEBUG("Transforming MoE model to " << config.num_target_experts << " expert(s), mode: "
+ << (config.is_expert_iterative() ? "EXPERT_ITERATIVE" : "EXPERT_BATCH")
+ << ", chunk_size: " << config.chunk_size);
+ LOG_BLOCK();
+
+ auto model = original_model->clone();
+ const auto num_experts = m_structure_info.num_experts;
+ const auto num_target_experts = config.num_target_experts;
+ const auto chunk_size = config.chunk_size;
+
+ // Find key nodes in the cloned model
+ auto key_nodes = find_key_nodes_in_cloned_model(model);
+ if (!key_nodes) {
+ return nullptr;
+ }
+ auto expert_input_tile_op = key_nodes->tile_node;
+ auto router_scores_multiply_op = key_nodes->multiply_node;
+
+ // Main transformation flow
+ auto tile_input = expert_input_tile_op->input_value(0);
+ auto tile_output = expert_input_tile_op->output(0);
+
+ auto [matmul_node, node_before_matmul] = find_matmul_and_predecessor(tile_output);
+ if (!matmul_node) {
+ LOG_ERROR("Could not find MatMul operation after Tile");
+ return nullptr;
+ }
+
+ // Apply transformations in sequence
+ fix_token_count_for_expert_iterative(model,
+ num_target_experts,
+ chunk_size,
+ expert_input_tile_op,
+ router_scores_multiply_op);
+ replace_tile_with_new_tile(tile_input,
+ node_before_matmul,
+ expert_input_tile_op->get_friendly_name(),
+ num_target_experts);
+ fix_parameters_with_num_experts(model, num_experts, num_target_experts);
+ ensure_tensor_names(model);
+
+ model->validate_nodes_and_infer_types();
+ LOG_DEBUG("Successfully transformed to " << num_target_experts << " expert(s) model");
+
+ if (num_target_experts > 1) {
+ model = unroll_expert_dimension(model, num_target_experts);
+ }
+
+ return model;
+}
+
+std::optional<MoEExperts> MoEExperts::from(const std::shared_ptr<ov::Model>& model,
+ const std::shared_ptr<ov::Model>& router_model,
+ size_t iterative_chunk_size) {
+ LOG_DEBUG("Creating MoEExperts from model: " << model->get_friendly_name());
+ LOG_BLOCK();
+
+ // Step 1: Extract K from router model
+ if (!router_model) {
+ LOG_ERROR("Router model is required to extract K from TopK node");
+ return std::nullopt;
+ }
+
+ auto k_from_router = extract_k_from_router(router_model);
+ if (!k_from_router.has_value()) {
+ LOG_ERROR("Failed to extract K from router model");
+ return std::nullopt;
+ }
+
+ size_t k_value = k_from_router.value();
+ LOG_INFO("Extracted K=" << k_value << " from router model");
+
+ // Step 2: Analyze model structure
+ auto structure_info = analyze_moe_structure(model);
+ if (!structure_info || !structure_info->is_valid()) {
+ LOG_WARN("Model structure analysis failed for MoE expert pattern");
+ return std::nullopt;
+ }
+
+ // Step 3: Determine chunk sizes based on processing mode and configuration
+ std::vector<size_t> chunk_sizes;
+ if (structure_info->is_expert_batch_mode()) {
+ // EXPERT_BATCH mode: single model with K active experts, no chunking
+ chunk_sizes = {0};
+ LOG_INFO("EXPERT_BATCH mode: Creating single model for K=" << k_value << " active experts");
+ } else {
+ if (iterative_chunk_size == 0) {
+ chunk_sizes.assign(DEFAULT_ITERATIVE_CHUNKING_VARIANTS.begin(), DEFAULT_ITERATIVE_CHUNKING_VARIANTS.end());
+ LOG_INFO("EXPERT_ITERATIVE mode: Creating multiple models for dynamic chunking");
+ } else {
+ chunk_sizes = {iterative_chunk_size};
+ LOG_INFO("EXPERT_ITERATIVE mode: Creating single model with chunk_size=" << iterative_chunk_size);
+ }
+ }
+
+ // Step 4: Transform models for each chunk size
+ std::map<size_t, std::shared_ptr<ov::Model>> transformed_models;
+ for (auto chunk_size : chunk_sizes) {
+ auto config = determine_transformation_params(*structure_info, k_value, chunk_size);
+
+ MoEModelTransformer transformer(*structure_info);
+ auto transformed_model = transformer.apply_expert_transformation(model, config);
+ if (!transformed_model) {
+ LOG_WARN("Failed to transform model with chunk_size=" << chunk_size);
+ continue;
+ }
+
+ // Store the transformed model
+ transformed_models[chunk_size] = transformed_model;
+
+ LOG_INFO("Successfully transformed model for chunk_size=" << chunk_size);
+ }
+
+ if (transformed_models.empty()) {
+ LOG_ERROR("Failed to transform any models");
+ return std::nullopt;
+ }
+
+ // 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);
+
+ // Step 6: Populate and validate MoEExperts structure
+ MoEExperts moe_experts;
+ moe_experts._num_experts = structure_info->num_experts;
+ moe_experts._expert_hidden_dim = structure_info->expert_hidden_dim;
+ moe_experts._input_token_count = structure_info->input_token_count;
+ moe_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 router
+ moe_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._param_mapping = std::move(param_mapping);
+
+ if (!moe_experts.is_valid()) {
+ LOG_ERROR("Created MoEExperts structure is invalid");
+ return std::nullopt;
+ }
+
+ LOG_INFO("Successfully created MoEExperts:");
+ LOG_INFO(" - Total number of experts: " << moe_experts._num_experts);
+ LOG_INFO(" - Num active experts: " << moe_experts._num_active_experts);
+ LOG_INFO(" - Expert hidden dim: " << moe_experts._expert_hidden_dim);
+ LOG_INFO(" - Number of transformed models: " << moe_experts._transformed_models.size());
+ if (structure_info->is_expert_batch_mode()) {
+ LOG_INFO(" - EXPERT_BATCH model (no chunking)");
+ } else {
+ LOG_INFO(" - EXPERT_ITERATIVE models with chunk sizes:");
+ for (const auto& entry : moe_experts._transformed_models) {
+ LOG_INFO(" * chunk_size=" << entry.first);
+ }
+ }
+
+ return moe_experts;
+}
+
+} // namespace function
+
+namespace compiled {
+
+MoEExperts::MoEExperts(const function::MoEExperts& func_moe) {
+ num_experts = func_moe._num_experts;
+ expert_hidden_dim = func_moe._expert_hidden_dim;
+ 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;
+ _param_mapping = func_moe._param_mapping;
+
+ LOG_DEBUG("Created compiled::MoEExperts:");
+ LOG_DEBUG(" Mode: " << (func_moe.is_expert_iterative() ? "EXPERT_ITERATIVE" : "EXPERT_BATCH"));
+ LOG_DEBUG(" Total experts: " << num_experts);
+ LOG_DEBUG(" Active experts: " << num_active_experts);
+ LOG_DEBUG(" Input token count: " << input_token_count);
+ LOG_DEBUG(" Number of models to compile: " << _models_to_compile.size());
+ 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 (_expert_input_param_idx.has_value()) {
+ LOG_DEBUG(" Expert input parameter index: " << _expert_input_param_idx.value());
+ }
+}
+
+void MoEExperts::set_compiled_model(size_t chunk_size, ov::SoPtr<ov::ICompiledModel>&& compiled_model) {
+ _compiled_models[chunk_size] = std::move(compiled_model);
+ _models_to_compile.erase(chunk_size); // Free memory after compilation
+
+ LOG_DEBUG("Set compiled model for MoE experts, chunk_size=" << chunk_size);
+}
+
+MoEDownstream::MoEDownstream(const function::MoEDownstream& func_downstream) {
+ total_experts_num = func_downstream.total_experts_num;
+ active_experts_num = func_downstream.active_experts_num;
+ expert_output_param_idx = func_downstream.expert_output_param_idx;
+ _model_to_compile = func_downstream.modified_model;
+
+ LOG_DEBUG("Created compiled::MoEDownstream with " << total_experts_num << " total experts and "
+ << active_experts_num << " active experts");
+}
+
+void MoEDownstream::set_compiled_model(ov::SoPtr<ov::ICompiledModel>&& compiled_model) {
+ _compiled_model = std::move(compiled_model);
+ _model_to_compile.reset(); // Free memory after compilation
+
+ LOG_DEBUG("Set compiled model for MoE downstream");
+}
+
+} // namespace compiled
+} // namespace npuw
+} // namespace ov
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.hpp
new file mode 100644
index 00000000000..ec754ce67fd
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.hpp
@@ -0,0 +1,351 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#pragma once
+
+#include <map>
+#include <optional>
+#include <vector>
+
+#include "../logging.hpp"
+#include "../moe/moe_types.hpp" // For MoEProcessingMode
+#include "openvino/core/model.hpp"
+#include "openvino/core/node.hpp"
+#include "openvino/core/partial_shape.hpp"
+#include "openvino/core/shape.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/op/multiply.hpp"
+#include "openvino/op/tile.hpp"
+#include "openvino/openvino.hpp"
+#include "openvino/runtime/icompiled_model.hpp"
+#include "openvino/runtime/isync_infer_request.hpp"
+#include "openvino/runtime/so_ptr.hpp"
+#include "openvino/runtime/tensor.hpp"
+
+namespace ov {
+namespace npuw {
+
+namespace function {
+
+// Default chunk size variants for dynamic iterative mode chunking
+constexpr std::array<size_t, 5> DEFAULT_ITERATIVE_CHUNKING_VARIANTS = {16, 32, 64, 128, 256};
+
+// Complete structure analysis result (immutable after analysis)
+struct MoEStructureInfo {
+ // Expert configuration
+ size_t num_experts = 0; // Total number of experts in the model
+ size_t expert_hidden_dim = 0; // Hidden dimension of single expert
+ size_t input_token_count = 0; // Number of input tokens
+
+ // Key nodes in the graph
+ std::shared_ptr<ov::op::v0::Tile> expert_input_tile_node = nullptr; // Tile node for replicating expert inputs
+ std::shared_ptr<ov::op::v1::Multiply> router_scores_multiply_node =
+ nullptr; // Multiply node in output path (expert_output * router_scores)
+
+ // 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)
+
+ // Processing mode (inferred from input_token_count)
+ moe::MoEProcessingMode processing_mode = moe::MoEProcessingMode::EXPERT_ITERATIVE;
+
+ // Helper: Check if using expert batch mode
+ bool is_expert_batch_mode() const {
+ return processing_mode == moe::MoEProcessingMode::EXPERT_BATCH;
+ }
+
+ // Helper: Check if using expert iterative mode
+ bool is_expert_iterative_mode() const {
+ return processing_mode == moe::MoEProcessingMode::EXPERT_ITERATIVE;
+ }
+
+ bool is_valid() const {
+ return num_experts > 0 && expert_hidden_dim > 0 && expert_input_tile_node != nullptr &&
+ router_scores_multiply_node != nullptr && expert_input_param_idx.has_value() &&
+ router_scores_idx.has_value();
+ }
+};
+
+// Transformation configuration (clear decision parameters)
+struct MoETransformConfig {
+ size_t num_target_experts; // Number of experts in transformed model (1 for EXPERT_ITERATIVE, K for EXPERT_BATCH)
+ size_t chunk_size; // Token chunk size for EXPERT_ITERATIVE (0 for EXPERT_BATCH)
+
+ // Helper: Check if this is expert iterative mode (single expert)
+ bool is_expert_iterative() const {
+ return num_target_experts == 1;
+ }
+
+ // Helper: Check if this is expert batch mode (K experts)
+ bool is_expert_batch() const {
+ return num_target_experts > 1;
+ }
+};
+
+// Structure to hold MoE downstream processing information (ReduceSum + QKV + attention postproc + downstream layers)
+struct MoEDownstream {
+ size_t total_experts_num = 0; // Total number of experts
+ size_t active_experts_num = 0; // Number of active experts (K in top-K)
+ size_t expert_output_param_idx = 0; // Index of the parameter that receives expert outputs
+ std::shared_ptr<ov::Model> modified_model = nullptr; // Model with modified input shape
+
+ bool is_valid() const {
+ return total_experts_num > 0 && active_experts_num > 0 && active_experts_num <= total_experts_num &&
+ modified_model != nullptr;
+ }
+};
+
+// Analyze MoE model structure and detect all necessary information
+// This function is pure analysis - no modification to input model
+std::optional<MoEStructureInfo> analyze_moe_structure(const std::shared_ptr<ov::Model>& model);
+
+// Determine transformation parameters based on structure info and K from router
+MoETransformConfig determine_transformation_params(const MoEStructureInfo& structure_info,
+ size_t k_from_router,
+ size_t iterative_chunk_size);
+
+// MoE Model Transformer - encapsulates all transformation logic for MoE expert models
+// This class provides a clean interface for transforming MoE models with different expert configurations
+class MoEModelTransformer {
+public:
+ // Constructor takes the structure info which remains constant during transformations
+ explicit MoEModelTransformer(const MoEStructureInfo& structure_info) : m_structure_info(structure_info) {}
+
+ // Apply expert transformation to the model based on configuration
+ // Returns transformed model with adjusted expert count and token dimensions
+ std::shared_ptr<ov::Model> apply_expert_transformation(const std::shared_ptr<ov::Model>& original_model,
+ const MoETransformConfig& config) const;
+
+private:
+ // Helper methods for specific transformation steps
+
+ // Find Tile and Multiply nodes in cloned model by matching friendly names
+ struct KeyNodes {
+ std::shared_ptr<ov::op::v0::Tile> tile_node;
+ std::shared_ptr<ov::op::v1::Multiply> multiply_node;
+ };
+ std::optional<KeyNodes> find_key_nodes_in_cloned_model(const std::shared_ptr<ov::Model>& model) const;
+
+ std::pair<std::shared_ptr<ov::Node>, ov::Output<ov::Node>> find_matmul_and_predecessor(
+ ov::Output<ov::Node>& tile_output) const;
+
+ void replace_tile_with_new_tile(const ov::Output<ov::Node>& tile_input,
+ ov::Output<ov::Node>& node_before_matmul,
+ const std::string& friendly_name,
+ size_t num_target_experts) const;
+
+ void fix_output_reshapes(const std::shared_ptr<ov::Model>& model,
+ size_t num_experts,
+ size_t num_target_experts) const;
+
+ void ensure_tensor_names(const std::shared_ptr<ov::Model>& model) const;
+
+ void fix_parameters_with_num_experts(const std::shared_ptr<ov::Model>& model,
+ size_t num_experts,
+ size_t num_target_experts) const;
+
+ void fix_token_count_for_expert_iterative(
+ const std::shared_ptr<ov::Model>& model,
+ size_t num_target_experts,
+ 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;
+
+ // Unroll the MoE expert model on the expert dimension using GraphRewrite patterns
+ // This creates separate computation branches for each expert
+ // @param full_optimization If true, uses MoEExpertUnrolling (all optimizations)
+ // If false (default), uses MoEExpertUnrollingWeightsOnly
+ std::shared_ptr<ov::Model> unroll_expert_dimension(const std::shared_ptr<ov::Model>& model,
+ size_t num_experts,
+ bool full_optimization = false) const;
+
+ const MoEStructureInfo& m_structure_info;
+};
+
+// Helper function to detect and transform MoE downstream pattern
+// Looks for: Parameter -> Convert -> ReduceSum pattern
+// If found, modifies input shape from [total_experts, 1, H, W] to [active_experts, 1, H, W]
+std::optional<MoEDownstream> detect_and_transform_moe_downstream(const std::shared_ptr<ov::Model>& model,
+ size_t active_experts_num);
+
+// Structure to hold MoE expert information at partition-time
+struct MoEExperts {
+ // Basic information about the expert model
+ size_t _num_experts = 0; // Total number of experts in the model
+ size_t _expert_hidden_dim = 0; // Hidden dimension for a single expert
+ size_t _input_token_count = 0; // Number of input tokens (original total token count)
+ size_t _chunk_token_count = 0; // Chunk size for iterative mode (0 for batch mode)
+
+ // Transformation mode and target expert count
+ size_t _num_active_experts = 1; // Number of active experts (1 for EXPERT_ITERATIVE, K for EXPERT_BATCH)
+
+ // Transformed expert models for different chunk sizes (chunk_size -> model)
+ // For EXPERT_ITERATIVE: multiple models with different chunk sizes {32, 64, 128, 256, 512}
+ // 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 mapping: original_param_idx -> [unrolled_param_indices]
+ // For EXPERT_ITERATIVE mode: no unrolling, so this will be empty or identity mapping
+ // For EXPERT_BATCH mode: maps original params to K unrolled params
+ // Same for all chunk sizes since unrolling only happens in batch mode
+ std::map<size_t, std::vector<size_t>> _param_mapping;
+
+ // Validation helpers
+ bool is_valid() const {
+ return _num_experts > 0 && _expert_hidden_dim > 0 && !_transformed_models.empty() &&
+ _router_scores_idx.has_value();
+ }
+
+ size_t num_experts() const {
+ return _num_experts;
+ }
+
+ size_t expert_hidden_dim() const {
+ return _expert_hidden_dim;
+ }
+
+ size_t num_active_experts() const {
+ return _num_active_experts;
+ }
+
+ // Helper: Check if this is expert iterative mode
+ bool is_expert_iterative() const {
+ return _num_active_experts == 1;
+ }
+
+ // Helper: Check if this is expert batch mode
+ bool is_expert_batch() const {
+ return _num_active_experts > 1;
+ }
+
+ const std::map<size_t, std::shared_ptr<ov::Model>>& transformed_models() const {
+ return _transformed_models;
+ }
+
+ // Get transformed model for a specific chunk size
+ std::shared_ptr<ov::Model> get_model_for_chunk_size(size_t chunk_size) const {
+ auto it = _transformed_models.find(chunk_size);
+ if (it != _transformed_models.end()) {
+ return it->second;
+ }
+ 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;
+ }
+
+ // Factory method to create MoEExperts from a model (for expert pattern only)
+ // router_model: Router model to extract actual K from TopK node (required)
+ // iterative_chunk_size: Token chunk size for iterative mode processing (default: 128)
+ static std::optional<MoEExperts> from(const std::shared_ptr<ov::Model>& model,
+ const std::shared_ptr<ov::Model>& router_model,
+ size_t iterative_chunk_size);
+};
+
+// Factory method to create MoEDownstream from a model (for downstream pattern)
+// router_model: Router model to extract actual K from TopK node (required)
+std::optional<MoEDownstream> create_moe_downstream(const std::shared_ptr<ov::Model>& model,
+ const std::shared_ptr<ov::Model>& router_model);
+
+} // namespace function
+
+namespace compiled {
+
+// Compile-time MoE expert information
+struct MoEExperts {
+ size_t num_experts = 0;
+ size_t expert_hidden_dim = 0;
+ size_t num_active_experts = 1; // Number of active experts (1 for EXPERT_ITERATIVE, K for EXPERT_BATCH)
+ size_t input_token_count = 0; // Number of input tokens (original total token count)
+
+ // Compiled expert models for different chunk sizes (chunk_size -> compiled_model)
+ std::map<size_t, ov::SoPtr<ov::ICompiledModel>> _compiled_models;
+
+ // 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;
+
+ // Parameter mapping: original_param_idx -> [unrolled_param_indices]
+ // Same for all chunk sizes (unrolling only in EXPERT_BATCH mode)
+ std::map<size_t, std::vector<size_t>> _param_mapping;
+
+ MoEExperts() = default;
+
+ // Constructor that extracts metadata and stores model for compilation
+ explicit MoEExperts(const function::MoEExperts& func_moe);
+
+ // Set compiled model for a specific chunk size after compilation completes
+ void set_compiled_model(size_t chunk_size, ov::SoPtr<ov::ICompiledModel>&& compiled_model);
+
+ // Get compiled model for a specific chunk size
+ ov::SoPtr<ov::ICompiledModel> get_compiled_model(size_t chunk_size) const {
+ auto it = _compiled_models.find(chunk_size);
+ if (it != _compiled_models.end()) {
+ return it->second;
+ }
+ return {};
+ }
+
+ // Validation
+ bool is_valid() const {
+ return num_experts > 0 && expert_hidden_dim > 0 && !_compiled_models.empty();
+ }
+};
+
+// Compiled MoE Downstream structure
+struct MoEDownstream {
+ size_t total_experts_num = 0;
+ size_t active_experts_num = 0;
+ size_t expert_output_param_idx = 0; // Index of the parameter that receives expert outputs
+
+ // Compiled modified downstream model
+ ov::SoPtr<ov::ICompiledModel> _compiled_model;
+
+ // Store model temporarily for compilation
+ std::shared_ptr<ov::Model> _model_to_compile;
+
+ MoEDownstream() = default;
+
+ // Constructor that extracts metadata and stores model for compilation
+ explicit MoEDownstream(const function::MoEDownstream& func_downstream);
+
+ // Set compiled model after compilation completes
+ void set_compiled_model(ov::SoPtr<ov::ICompiledModel>&& compiled_model);
+
+ // Validation
+ bool is_valid() const {
+ return total_experts_num > 0 && active_experts_num > 0 && active_experts_num <= total_experts_num &&
+ _compiled_model != nullptr;
+ }
+};
+
+} // namespace compiled
+
+namespace runtime {
+namespace moe_experts {
+
+// TODO: Implement runtime dispatcher for MoE experts
+// This will execute individual experts during inference
+
+} // namespace moe_experts
+} // namespace runtime
+
+} // namespace npuw
+} // namespace ov
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.cpp
new file mode 100644
index 00000000000..d7b08d63b48
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.cpp
@@ -0,0 +1,1114 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_unroll_patterns.hpp"
+
+#include <cstddef>
+#include <memory>
+#include <vector>
+
+#include "../logging.hpp"
+#include "openvino/core/node_vector.hpp"
+#include "openvino/core/rt_info.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/swish.hpp"
+#include "openvino/opsets/opset1.hpp"
+#include "openvino/pass/pattern/matcher.hpp"
+#include "openvino/pass/pattern/op/label.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+
+#define MATCHER_SCOPE(region) const std::string matcher_name = std::string(typeid(*this).name()) + "_" + #region
+
+namespace ov {
+namespace npuw {
+namespace pass {
+
+namespace {
+
+// =============================================================================
+// Common Helper Functions
+// =============================================================================
+
+/**
+ * @brief Skip Convert node if present and return the underlying input
+ */
+inline ov::Output<ov::Node> skip_convert(ov::Output<ov::Node> out) {
+ if (auto conv = std::dynamic_pointer_cast<ov::opset1::Convert>(out.get_node_shared_ptr())) {
+ return conv->input_value(0);
+ }
+ 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
+ */
+inline std::shared_ptr<ov::op::v0::Parameter> get_param_node(ov::Output<ov::Node> out) {
+ auto skipped = skip_convert(out);
+ return 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;
+};
+
+/**
+ * @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);
+ }
+
+ // 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);
+ }
+ return new_multiply->output(0);
+}
+
+/**
+ * @brief Helper to prepare input branches based on detected pattern
+ */
+inline ov::OutputVector prepare_input_branches(ov::Output<ov::Node> matmul_input0,
+ size_t num_branches,
+ const std::string& matmul_name) {
+ ov::OutputVector branches;
+
+ // Pattern 1: Check for Reshape → Tile → Convert (batched pattern)
+ if (auto reshape_node = std::dynamic_pointer_cast<ov::opset1::Reshape>(matmul_input0.get_node_shared_ptr())) {
+ auto tile_node =
+ std::dynamic_pointer_cast<ov::opset1::Tile>(reshape_node->input_value(0).get_node_shared_ptr());
+ if (tile_node) {
+ auto convert_input =
+ std::dynamic_pointer_cast<ov::opset1::Convert>(tile_node->input_value(0).get_node_shared_ptr());
+ if (convert_input) {
+ LOG_INFO(" Detected Pattern 1: Batched (Reshape→Tile→Convert)");
+
+ // Create shared Convert and Reshape for all branches
+ auto input_param_source = convert_input->input_value(0);
+ auto shared_convert =
+ std::make_shared<ov::opset1::Convert>(input_param_source, convert_input->get_destination_type());
+ shared_convert->set_friendly_name(convert_input->get_friendly_name() + "/shared");
+
+ // Modify reshape shape: change first dim from num_experts to 1
+ auto orig_reshape_const =
+ std::dynamic_pointer_cast<ov::opset1::Constant>(reshape_node->input_value(1).get_node_shared_ptr());
+ auto orig_shape_vec = orig_reshape_const->cast_vector<int64_t>();
+ std::vector<int64_t> new_shape_vec = orig_shape_vec;
+ new_shape_vec[0] = 1;
+
+ auto new_reshape_const = std::make_shared<ov::opset1::Constant>(ov::element::i64,
+ ov::Shape{new_shape_vec.size()},
+ new_shape_vec);
+ auto shared_reshape =
+ std::make_shared<ov::opset1::Reshape>(shared_convert->output(0), new_reshape_const, false);
+ shared_reshape->set_friendly_name(reshape_node->get_friendly_name() + "/shared");
+
+ // All branches use the same shared reshape
+ for (size_t i = 0; i < num_branches; ++i) {
+ branches.push_back(shared_reshape->output(0));
+ }
+ return branches;
+ }
+ }
+ }
+
+ // Pattern 2: Check for Concat
+ if (auto concat = std::dynamic_pointer_cast<ov::opset1::Concat>(matmul_input0.get_node_shared_ptr())) {
+ LOG_INFO(" Detected Pattern 2: Concat with " << concat->get_input_size() << " branches");
+ return concat->input_values();
+ }
+
+ // Pattern 3: Sliceable input - create Slice operations
+ LOG_INFO(" Detected Pattern 3: Sliceable input, creating " << num_branches << " Slice operations");
+
+ auto input0_shape = matmul_input0.get_partial_shape();
+ if (!input0_shape.rank().is_static()) {
+ LOG_ERROR(" Input0 shape rank is not static for slicing");
+ return branches;
+ }
+
+ for (size_t i = 0; i < num_branches; ++i) {
+ std::vector<int64_t> start_vec = {static_cast<int64_t>(i)};
+ std::vector<int64_t> stop_vec = {static_cast<int64_t>(i + 1)};
+ std::vector<int64_t> step_vec = {1};
+ std::vector<int64_t> axes_vec = {0};
+
+ auto start_const = std::make_shared<ov::opset1::Constant>(ov::element::i64, ov::Shape{1}, start_vec);
+ auto stop_const = std::make_shared<ov::opset1::Constant>(ov::element::i64, ov::Shape{1}, stop_vec);
+ auto step_const = std::make_shared<ov::opset1::Constant>(ov::element::i64, ov::Shape{1}, step_vec);
+ auto axes_const = std::make_shared<ov::opset1::Constant>(ov::element::i64, ov::Shape{1}, axes_vec);
+
+ auto slice_op =
+ std::make_shared<ov::op::v8::Slice>(matmul_input0, start_const, stop_const, step_const, axes_const);
+ slice_op->set_friendly_name(matmul_name + "/slice_input0_expert_" + std::to_string(i));
+ branches.push_back(slice_op->output(0));
+ }
+
+ return branches;
+}
+
+} // anonymous namespace
+
+// =============================================================================
+// UnrollMoEMatMul
+// =============================================================================
+// Unified pass for unrolling MoE expert MatMul patterns
+// Automatically detects and handles three input patterns:
+// 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)
+//
+// Transforms to N expert branches with individual parameters and Concat output
+
+UnrollMoEMatMul::UnrollMoEMatMul(std::shared_ptr<ov::Model> model) : model_(model) {
+ MATCHER_SCOPE(UnrollMoEMatMul);
+
+ auto matmul_pattern = ov::pass::pattern::wrap_type<ov::opset1::MatMul>();
+
+ auto callback = [this](ov::pass::pattern::Matcher& m) {
+ auto matmul = std::dynamic_pointer_cast<ov::opset1::MatMul>(m.get_match_root());
+ if (!matmul)
+ return false;
+
+ LOG_INFO("UnrollMoEMatMul: Checking MatMul " << matmul->get_friendly_name());
+
+ auto matmul_input0 = matmul->input_value(0);
+ auto 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");
+ 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");
+ 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)");
+
+ // ========== Step 2: Prepare input0 branches (pattern-specific) ==========
+ auto input0_branches = prepare_input_branches(matmul_input0, num_experts, matmul->get_friendly_name());
+
+ if (input0_branches.empty()) {
+ LOG_ERROR(" Failed to prepare input branches");
+ return false;
+ }
+
+ if (input0_branches.size() != num_experts) {
+ LOG_DEBUG(" Input branches count " << input0_branches.size() << " != num_experts " << num_experts
+ << ", skipping");
+ return 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);
+
+ ov::NodeVector expert_outputs;
+ ov::ParameterVector new_params;
+
+ // ========== 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 × weights
+ auto new_matmul = std::make_shared<ov::opset1::MatMul>(input0_branch,
+ weights_for_matmul,
+ matmul->get_transpose_a(),
+ matmul->get_transpose_b());
+ new_matmul->set_friendly_name(matmul->get_friendly_name() + "/expert_" + std::to_string(expert_idx));
+
+ expert_outputs.push_back(new_matmul);
+ }
+
+ // ========== Step 5: Concat and replace ==========
+ auto output_concat = std::make_shared<ov::opset1::Concat>(expert_outputs, 0);
+ output_concat->set_friendly_name(matmul->get_friendly_name() + "/concat");
+
+ // Register new parameters with model
+ model_->add_parameters(new_params);
+
+ // Replace original MatMul
+ ov::copy_runtime_info(matmul, output_concat);
+ ov::replace_node(matmul, output_concat);
+
+ LOG_INFO(" Successfully created " << num_experts << " expert branches with " << new_params.size()
+ << " new parameters");
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(matmul_pattern, matcher_name);
+ register_matcher(m, callback);
+}
+
+// =============================================================================
+// PushElementwiseBeforeConcat
+// =============================================================================
+// Transforms: Parameter[N,...] + Concat([a,b,c]) => Concat([a+param[0], b+param[1], c+param[2]])
+// Supports Add and Multiply operations
+// Optimization: Distributes elementwise operations into concat branches to enable further optimizations
+
+PushElementwiseBeforeConcat::PushElementwiseBeforeConcat(std::shared_ptr<ov::Model> model) : model_(model) {
+ MATCHER_SCOPE(PushElementwiseBeforeConcat);
+
+ auto concat_pattern = ov::pass::pattern::wrap_type<ov::opset1::Concat>();
+ auto elementwise_pattern = ov::pass::pattern::wrap_type<ov::opset1::Add, ov::opset1::Multiply>(
+ {concat_pattern, ov::pass::pattern::any_input()});
+
+ auto callback = [this, concat_pattern](ov::pass::pattern::Matcher& m) {
+ auto& pm = m.get_pattern_value_map();
+ auto elementwise_node = m.get_match_root();
+ auto concat = std::dynamic_pointer_cast<ov::opset1::Concat>(pm.at(concat_pattern).get_node_shared_ptr());
+
+ if (!elementwise_node || !concat)
+ return false;
+
+ // Check if it's Add or Multiply
+ auto add_op = std::dynamic_pointer_cast<ov::opset1::Add>(elementwise_node);
+ auto multiply_op = std::dynamic_pointer_cast<ov::opset1::Multiply>(elementwise_node);
+
+ if (!add_op && !multiply_op)
+ return false;
+
+ // Find which input is concat and which is the parameter
+ ov::Output<ov::Node> other_input;
+ if (elementwise_node->input_value(0).get_node_shared_ptr() == concat) {
+ other_input = elementwise_node->input_value(1);
+ } else if (elementwise_node->input_value(1).get_node_shared_ptr() == concat) {
+ other_input = elementwise_node->input_value(0);
+ } else {
+ return false;
+ }
+
+ // Check if other_input comes from a Parameter (possibly through Convert)
+ auto other_node = other_input.get_node_shared_ptr();
+ std::shared_ptr<ov::op::v0::Parameter> param_node;
+ std::shared_ptr<ov::opset1::Convert> convert_node;
+
+ if (auto param = std::dynamic_pointer_cast<ov::op::v0::Parameter>(other_node)) {
+ param_node = param;
+ } else if (auto conv = std::dynamic_pointer_cast<ov::opset1::Convert>(other_node)) {
+ convert_node = conv;
+ param_node = std::dynamic_pointer_cast<ov::op::v0::Parameter>(conv->input_value(0).get_node_shared_ptr());
+ }
+
+ if (!param_node) {
+ LOG_DEBUG(" Other input is not a Parameter, skipping");
+ return false;
+ }
+
+ // Check parameter shape: should be [N, ...] where N = concat input count
+ auto param_shape = param_node->get_partial_shape();
+ if (!param_shape.rank().is_static() || !param_shape[0].is_static()) {
+ return false;
+ }
+
+ size_t num_branches = concat->get_input_size();
+ if (param_shape[0].get_length() != static_cast<int64_t>(num_branches)) {
+ return false;
+ }
+
+ std::string op_type = add_op ? "Add" : "Multiply";
+ LOG_INFO("PushElementwiseBeforeConcat: Pushing " << op_type << " with Parameter before Concat");
+ LOG_INFO(" Parameter shape: " << param_shape << ", num branches: " << num_branches);
+
+ // Create new per-branch parameters
+ auto orig_shape = param_shape.to_shape();
+ ov::Shape new_param_shape = orig_shape;
+ new_param_shape[0] = 1; // Change first dimension from N to 1
+
+ auto concat_inputs = concat->input_values();
+ ov::NodeVector new_add_ops;
+ ov::ParameterVector new_params;
+
+ for (size_t i = 0; i < num_branches; ++i) {
+ // Create new parameter for this branch
+ auto new_param = std::make_shared<ov::op::v0::Parameter>(param_node->get_element_type(),
+ ov::PartialShape(new_param_shape));
+ new_param->set_friendly_name(param_node->get_friendly_name() + "/branch_" + std::to_string(i));
+ // Add RTInfo for parameter mapping
+ new_param->get_rt_info()["moe_original_param"] = param_node->get_friendly_name();
+ new_param->get_rt_info()["moe_expert_index"] = static_cast<int64_t>(i);
+ new_params.push_back(new_param);
+
+ // Apply Convert if original had one
+ ov::Output<ov::Node> param_for_add;
+ if (convert_node) {
+ auto new_convert =
+ std::make_shared<ov::opset1::Convert>(new_param, convert_node->get_destination_type());
+ new_convert->set_friendly_name(convert_node->get_friendly_name() + "/branch_" + std::to_string(i));
+ param_for_add = new_convert->output(0);
+ } else {
+ param_for_add = new_param->output(0);
+ }
+
+ // Create Add or Multiply: concat_input[i] op param[i]
+ std::shared_ptr<ov::Node> new_elementwise;
+ if (add_op) {
+ new_elementwise = std::make_shared<ov::opset1::Add>(concat_inputs[i], param_for_add);
+ } else {
+ new_elementwise = std::make_shared<ov::opset1::Multiply>(concat_inputs[i], param_for_add);
+ }
+ new_elementwise->set_friendly_name(elementwise_node->get_friendly_name() + "/branch_" + std::to_string(i));
+ new_add_ops.push_back(new_elementwise);
+ }
+
+ auto new_concat = std::make_shared<ov::opset1::Concat>(new_add_ops, concat->get_axis());
+ new_concat->set_friendly_name(concat->get_friendly_name() + "/after_" + op_type);
+
+ // Register new parameters with model
+ model_->add_parameters(new_params);
+
+ ov::NodeVector from_nodes = {elementwise_node, concat};
+ ov::copy_runtime_info(from_nodes, new_concat);
+ ov::replace_node(elementwise_node, new_concat);
+
+ LOG_INFO(" Pushed " << op_type << " into " << num_branches << " branches with new parameters");
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(elementwise_pattern, matcher_name);
+ register_matcher(m, callback);
+}
+
+// =============================================================================
+// PushSliceBeforeConcat
+// =============================================================================
+// Transforms: Concat([a,b,c], axis=0) → Slice(axis=k) => Concat([Slice(a,axis=k), Slice(b,axis=k), Slice(c,axis=k)])
+// Safety constraint: Only safe when slice axis != concat axis
+// Rationale: Slicing on concat axis would produce incorrect results after transformation
+
+PushSliceBeforeConcat::PushSliceBeforeConcat() {
+ MATCHER_SCOPE(PushSliceBeforeConcat);
+
+ auto concat_pattern = ov::pass::pattern::wrap_type<ov::opset1::Concat>();
+ auto slice_pattern = ov::pass::pattern::wrap_type<ov::op::v8::Slice>({concat_pattern,
+ ov::pass::pattern::any_input(),
+ ov::pass::pattern::any_input(),
+ ov::pass::pattern::any_input(),
+ ov::pass::pattern::any_input()});
+
+ auto callback = [concat_pattern](ov::pass::pattern::Matcher& m) {
+ auto& pm = m.get_pattern_value_map();
+ auto slice = std::dynamic_pointer_cast<ov::op::v8::Slice>(m.get_match_root());
+ auto concat = std::dynamic_pointer_cast<ov::opset1::Concat>(pm.at(concat_pattern).get_node_shared_ptr());
+
+ if (!slice || !concat)
+ return false;
+
+ // Get slice parameters: start, stop, step, axes
+ auto start_const = std::dynamic_pointer_cast<ov::opset1::Constant>(slice->input_value(1).get_node_shared_ptr());
+ auto stop_const = std::dynamic_pointer_cast<ov::opset1::Constant>(slice->input_value(2).get_node_shared_ptr());
+ auto step_const = std::dynamic_pointer_cast<ov::opset1::Constant>(slice->input_value(3).get_node_shared_ptr());
+ auto axes_const = std::dynamic_pointer_cast<ov::opset1::Constant>(slice->input_value(4).get_node_shared_ptr());
+
+ if (!start_const || !stop_const || !step_const || !axes_const) {
+ LOG_DEBUG(" Slice parameters are not constants, skipping");
+ return false;
+ }
+
+ auto axes_data = axes_const->cast_vector<int64_t>();
+ if (axes_data.empty())
+ return false;
+
+ int64_t concat_axis = concat->get_axis();
+
+ // Check if any slice axis matches concat axis
+ for (auto axis : axes_data) {
+ if (axis == concat_axis) {
+ LOG_DEBUG(" Slice axis matches Concat axis, not safe to push, skipping");
+ return false;
+ }
+ }
+
+ LOG_INFO("PushSliceBeforeConcat: Pushing Slice before Concat");
+ LOG_INFO(" Concat axis: " << concat_axis << ", Slice axes: " << axes_data[0]);
+
+ auto concat_inputs = concat->input_values();
+ ov::NodeVector new_sliced_outputs;
+
+ for (size_t i = 0; i < concat_inputs.size(); ++i) {
+ auto new_slice = std::make_shared<ov::op::v8::Slice>(concat_inputs[i],
+ slice->input_value(1), // start
+ slice->input_value(2), // stop
+ slice->input_value(3), // step
+ slice->input_value(4)); // axes
+ new_slice->set_friendly_name(slice->get_friendly_name() + "/branch_" + std::to_string(i));
+ new_sliced_outputs.push_back(new_slice);
+ }
+
+ auto new_concat = std::make_shared<ov::opset1::Concat>(new_sliced_outputs, concat->get_axis());
+ new_concat->set_friendly_name(concat->get_friendly_name() + "/after_Slice");
+
+ ov::NodeVector from_nodes = {slice, concat};
+ ov::copy_runtime_info(from_nodes, new_concat);
+ ov::replace_node(slice, new_concat);
+
+ LOG_INFO(" Pushed Slice into " << concat_inputs.size() << " branches");
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(slice_pattern, matcher_name);
+ register_matcher(m, callback);
+}
+
+// =============================================================================
+// PushClampBeforeConcat
+// =============================================================================
+// Transforms: Concat([a,b,c]) → Clamp => Concat([Clamp(a), Clamp(b), Clamp(c)])
+
+PushClampBeforeConcat::PushClampBeforeConcat() {
+ MATCHER_SCOPE(PushClampBeforeConcat);
+
+ auto concat_pattern = ov::pass::pattern::wrap_type<ov::opset1::Concat>();
+ auto clamp_pattern = ov::pass::pattern::wrap_type<ov::opset1::Clamp>({concat_pattern});
+
+ auto callback = [concat_pattern](ov::pass::pattern::Matcher& m) {
+ auto& pm = m.get_pattern_value_map();
+ auto clamp = std::dynamic_pointer_cast<ov::opset1::Clamp>(m.get_match_root());
+ auto concat = std::dynamic_pointer_cast<ov::opset1::Concat>(pm.at(concat_pattern).get_node_shared_ptr());
+
+ if (!clamp || !concat)
+ return false;
+
+ LOG_INFO("PushClampBeforeConcat: Pushing Clamp before Concat");
+ LOG_INFO(" Clamp min: " << clamp->get_min() << ", max: " << clamp->get_max());
+
+ auto concat_inputs = concat->input_values();
+ ov::NodeVector new_clamped_outputs;
+
+ for (size_t i = 0; i < concat_inputs.size(); ++i) {
+ auto new_clamp = std::make_shared<ov::opset1::Clamp>(concat_inputs[i], clamp->get_min(), clamp->get_max());
+ new_clamp->set_friendly_name(clamp->get_friendly_name() + "/branch_" + std::to_string(i));
+ new_clamped_outputs.push_back(new_clamp);
+ }
+
+ auto new_concat = std::make_shared<ov::opset1::Concat>(new_clamped_outputs, concat->get_axis());
+ new_concat->set_friendly_name(concat->get_friendly_name() + "/after_Clamp");
+
+ ov::NodeVector from_nodes = {clamp, concat};
+ ov::copy_runtime_info(from_nodes, new_concat);
+ ov::replace_node(clamp, new_concat);
+
+ LOG_INFO(" Pushed Clamp into " << concat_inputs.size() << " branches");
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(clamp_pattern, matcher_name);
+ register_matcher(m, callback);
+}
+
+// =============================================================================
+// PushScalarElementwiseBeforeConcat
+// =============================================================================
+// Transforms: Concat([a,b,c]) → Add/Minimum/Swish(scalar) => Concat([Op(a,scalar), Op(b,scalar), Op(c,scalar)])
+// Constraint: scalar input must have exactly 1 element (shape like [1,1,1])
+// Optimization: Broadcasting scalar operation can be distributed into branches
+
+PushScalarElementwiseBeforeConcat::PushScalarElementwiseBeforeConcat() {
+ MATCHER_SCOPE(PushScalarElementwiseBeforeConcat);
+
+ auto concat_pattern = ov::pass::pattern::wrap_type<ov::opset1::Concat>();
+ auto elementwise_pattern = ov::pass::pattern::wrap_type<ov::opset1::Add, ov::opset1::Minimum, ov::op::v4::Swish>(
+ {concat_pattern, ov::pass::pattern::any_input()});
+
+ auto callback = [concat_pattern](ov::pass::pattern::Matcher& m) {
+ auto& pm = m.get_pattern_value_map();
+ auto elementwise = m.get_match_root();
+ auto concat = std::dynamic_pointer_cast<ov::opset1::Concat>(pm.at(concat_pattern).get_node_shared_ptr());
+
+ if (!elementwise || !concat)
+ return false;
+
+ // Find which input is concat and which is the scalar
+ ov::Output<ov::Node> scalar_input;
+ size_t concat_input_idx = 0;
+
+ if (elementwise->input_value(0).get_node_shared_ptr() == concat) {
+ scalar_input = elementwise->input_value(1);
+ concat_input_idx = 0;
+ } else if (elementwise->input_value(1).get_node_shared_ptr() == concat) {
+ scalar_input = elementwise->input_value(0);
+ concat_input_idx = 1;
+ } else {
+ return false;
+ }
+
+ // Check if scalar_input has shape like 1x1x1 (single element)
+ auto scalar_shape = scalar_input.get_partial_shape();
+ if (!scalar_shape.rank().is_static()) {
+ return false;
+ }
+
+ size_t total_elements = 1;
+ for (int64_t i = 0; i < scalar_shape.rank().get_length(); ++i) {
+ if (!scalar_shape[i].is_static()) {
+ return false;
+ }
+ total_elements *= scalar_shape[i].get_length();
+ }
+
+ if (total_elements != 1) {
+ LOG_DEBUG(" Scalar input has " << total_elements << " elements, not a scalar, skipping");
+ return false;
+ }
+
+ std::string op_type = elementwise->get_type_name();
+ LOG_INFO("PushScalarElementwiseBeforeConcat: Pushing " << op_type << " with scalar before Concat");
+ LOG_INFO(" Scalar shape: " << scalar_shape);
+
+ auto concat_inputs = concat->input_values();
+ ov::NodeVector new_elementwise_outputs;
+
+ for (size_t i = 0; i < concat_inputs.size(); ++i) {
+ std::shared_ptr<ov::Node> new_elementwise;
+
+ if (auto add_op = std::dynamic_pointer_cast<ov::opset1::Add>(elementwise)) {
+ if (concat_input_idx == 0) {
+ new_elementwise = std::make_shared<ov::opset1::Add>(concat_inputs[i], scalar_input);
+ } else {
+ new_elementwise = std::make_shared<ov::opset1::Add>(scalar_input, concat_inputs[i]);
+ }
+ } else if (auto min_op = std::dynamic_pointer_cast<ov::opset1::Minimum>(elementwise)) {
+ if (concat_input_idx == 0) {
+ new_elementwise = std::make_shared<ov::opset1::Minimum>(concat_inputs[i], scalar_input);
+ } else {
+ new_elementwise = std::make_shared<ov::opset1::Minimum>(scalar_input, concat_inputs[i]);
+ }
+ } else if (auto swish_op = std::dynamic_pointer_cast<ov::op::v4::Swish>(elementwise)) {
+ // Swish has input order: data, beta (scalar)
+ if (concat_input_idx == 0) {
+ new_elementwise = std::make_shared<ov::op::v4::Swish>(concat_inputs[i], scalar_input);
+ } else {
+ new_elementwise = std::make_shared<ov::op::v4::Swish>(scalar_input, concat_inputs[i]);
+ }
+ } else {
+ return false;
+ }
+
+ new_elementwise->set_friendly_name(elementwise->get_friendly_name() + "/branch_" + std::to_string(i));
+ new_elementwise_outputs.push_back(new_elementwise);
+ }
+
+ auto new_concat = std::make_shared<ov::opset1::Concat>(new_elementwise_outputs, concat->get_axis());
+ new_concat->set_friendly_name(concat->get_friendly_name() + "/after_" + op_type);
+
+ ov::NodeVector from_nodes = {elementwise, concat};
+ ov::copy_runtime_info(from_nodes, new_concat);
+ ov::replace_node(elementwise, new_concat);
+
+ LOG_INFO(" Pushed " << op_type << " into " << concat_inputs.size() << " branches");
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(elementwise_pattern, matcher_name);
+ register_matcher(m, callback);
+}
+
+// =============================================================================
+// PushMultiplyBeforeConcat
+// =============================================================================
+// Transforms: Concat([a,b,c]) * Concat([d,e,f]) => Concat([a*d, b*e, c*f])
+// Requirements: Both Concat operations must have:
+// 1. Same concatenation axis
+// 2. Same number of inputs
+// 3. Pairwise compatible input shapes
+// Optimization: Fuses two concat operations by distributing Multiply element-wise
+
+PushMultiplyBeforeConcat::PushMultiplyBeforeConcat() {
+ MATCHER_SCOPE(PushMultiplyBeforeConcat);
+
+ auto concat1_pattern = ov::pass::pattern::wrap_type<ov::opset1::Concat>();
+ auto concat2_pattern = ov::pass::pattern::wrap_type<ov::opset1::Concat>();
+ auto multiply_pattern = ov::pass::pattern::wrap_type<ov::opset1::Multiply>({concat1_pattern, concat2_pattern});
+
+ auto callback = [concat1_pattern, concat2_pattern](ov::pass::pattern::Matcher& m) {
+ auto& pm = m.get_pattern_value_map();
+ auto multiply = std::dynamic_pointer_cast<ov::opset1::Multiply>(m.get_match_root());
+ auto concat1 = std::dynamic_pointer_cast<ov::opset1::Concat>(pm.at(concat1_pattern).get_node_shared_ptr());
+ auto concat2 = std::dynamic_pointer_cast<ov::opset1::Concat>(pm.at(concat2_pattern).get_node_shared_ptr());
+
+ if (!multiply || !concat1 || !concat2)
+ return false;
+
+ // Check if both Concat have the same axis
+ if (concat1->get_axis() != concat2->get_axis()) {
+ LOG_DEBUG(" Concat axes differ, skipping");
+ return false;
+ }
+
+ auto concat1_inputs = concat1->input_values();
+ auto concat2_inputs = concat2->input_values();
+
+ // Check if both Concat have the same number of inputs
+ if (concat1_inputs.size() != concat2_inputs.size()) {
+ LOG_DEBUG(" Concat input counts differ, skipping");
+ return false;
+ }
+
+ // Check if all corresponding inputs have matching shapes
+ bool shapes_match = true;
+ for (size_t i = 0; i < concat1_inputs.size(); ++i) {
+ auto shape1 = concat1_inputs[i].get_partial_shape();
+ auto shape2 = concat2_inputs[i].get_partial_shape();
+
+ if (!shape1.compatible(shape2)) {
+ shapes_match = false;
+ break;
+ }
+ }
+
+ if (!shapes_match) {
+ LOG_DEBUG(" Concat input shapes are not compatible, skipping");
+ return false;
+ }
+
+ LOG_INFO("PushMultiplyBeforeConcat: Pushing Multiply before Concat with matching input shapes");
+ LOG_INFO(" Moving Multiply before Concat with " << concat1_inputs.size() << " branches");
+
+ ov::NodeVector new_multiply_outputs;
+
+ for (size_t i = 0; i < concat1_inputs.size(); ++i) {
+ auto new_multiply = std::make_shared<ov::opset1::Multiply>(concat1_inputs[i], concat2_inputs[i]);
+ new_multiply->set_friendly_name(multiply->get_friendly_name() + "/branch_" + std::to_string(i));
+ new_multiply_outputs.push_back(new_multiply);
+ }
+
+ auto new_concat = std::make_shared<ov::opset1::Concat>(new_multiply_outputs, concat1->get_axis());
+ new_concat->set_friendly_name(concat1->get_friendly_name() + "/after_Multiply");
+
+ ov::NodeVector from_nodes = {multiply, concat1, concat2};
+ ov::copy_runtime_info(from_nodes, new_concat);
+ ov::replace_node(multiply, new_concat);
+
+ LOG_INFO(" Created " << concat1_inputs.size() << " Multiply operations before single Concat");
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(multiply_pattern, matcher_name);
+ register_matcher(m, callback);
+}
+
+// =============================================================================
+// PushReshapeBeforeConcat
+// =============================================================================
+// Transforms: Concat([a,b,c,d], axis=0) → Reshape => Concat([Reshape(a), Reshape(b), Reshape(c), Reshape(d)])
+// Example: Concat(4x1x2880) → Reshape(4x1x1x2880) becomes Concat([1x1x2880→1x1x1x2880, ...])
+//
+// Safety constraints:
+// 1. Concat axis must be 0 (highest dimension)
+// 2. Reshape must preserve dimension 0 (e.g., [N,...] → [N,...,extra])
+// Rationale: Ensures reshape can be safely distributed to each branch
+
+PushReshapeBeforeConcat::PushReshapeBeforeConcat() {
+ MATCHER_SCOPE(PushReshapeBeforeConcat);
+
+ auto concat_pattern = ov::pass::pattern::wrap_type<ov::opset1::Concat>();
+ auto reshape_pattern =
+ ov::pass::pattern::wrap_type<ov::opset1::Reshape>({concat_pattern, ov::pass::pattern::any_input()});
+
+ auto callback = [concat_pattern](ov::pass::pattern::Matcher& m) {
+ auto& pm = m.get_pattern_value_map();
+ auto reshape = std::dynamic_pointer_cast<ov::opset1::Reshape>(m.get_match_root());
+ auto concat = std::dynamic_pointer_cast<ov::opset1::Concat>(pm.at(concat_pattern).get_node_shared_ptr());
+
+ if (!reshape || !concat)
+ return false;
+
+ // Get reshape target shape
+ auto reshape_pattern_const =
+ std::dynamic_pointer_cast<ov::opset1::Constant>(reshape->input_value(1).get_node_shared_ptr());
+
+ if (!reshape_pattern_const) {
+ LOG_DEBUG(" Reshape pattern is not a Constant, skipping");
+ return false;
+ }
+
+ auto concat_output_shape = concat->get_output_partial_shape(0);
+ auto reshape_output_shape = reshape->get_output_partial_shape(0);
+
+ if (!concat_output_shape.rank().is_static() || !reshape_output_shape.rank().is_static()) {
+ LOG_DEBUG(" Shapes are not static, skipping");
+ return false;
+ }
+
+ int64_t concat_axis = concat->get_axis();
+
+ // Strict check: concat axis must be 0 (highest dimension)
+ if (concat_axis != 0) {
+ LOG_DEBUG(" Concat axis is not 0, skipping");
+ return false;
+ }
+
+ auto concat_inputs = concat->input_values();
+ size_t num_branches = concat_inputs.size();
+
+ // Check that reshape output shape[0] == concat output shape[0]
+ if (!concat_output_shape[0].is_static() || !reshape_output_shape[0].is_static()) {
+ LOG_DEBUG(" First dimension is not static, skipping");
+ return false;
+ }
+
+ int64_t concat_dim0 = concat_output_shape[0].get_length();
+ int64_t reshape_dim0 = reshape_output_shape[0].get_length();
+
+ if (concat_dim0 != reshape_dim0) {
+ LOG_DEBUG(" Concat shape[0]=" << concat_dim0 << " != Reshape shape[0]=" << reshape_dim0 << ", skipping");
+ return false;
+ }
+
+ LOG_INFO("PushReshapeBeforeConcat: Pushing Reshape before Concat");
+ LOG_INFO(" Concat shape: " << concat_output_shape << " → Reshape shape: " << reshape_output_shape);
+ LOG_INFO(" Concat axis: " << concat_axis << ", num branches: " << num_branches);
+
+ // Calculate per-branch reshape target shape
+ // Concat output: [N, ...], Reshape output: [N, ..., extra_dims]
+ // Branch input: [1, ...], Branch reshape: [1, ..., extra_dims]
+ auto reshape_shape_vec = reshape_pattern_const->cast_vector<int64_t>();
+ std::vector<int64_t> branch_reshape_shape = reshape_shape_vec;
+
+ // Set first dimension to 1 (per branch)
+ branch_reshape_shape[0] = 1;
+
+ ov::NodeVector new_reshaped_outputs;
+
+ for (size_t i = 0; i < num_branches; ++i) {
+ auto new_reshape_shape_const =
+ std::make_shared<ov::opset1::Constant>(ov::element::i64,
+ ov::Shape{branch_reshape_shape.size()},
+ branch_reshape_shape);
+
+ auto new_reshape = std::make_shared<ov::opset1::Reshape>(concat_inputs[i],
+ new_reshape_shape_const,
+ reshape->get_special_zero());
+ new_reshape->set_friendly_name(reshape->get_friendly_name() + "/branch_" + std::to_string(i));
+ new_reshaped_outputs.push_back(new_reshape);
+ }
+
+ // New concat also on axis 0 (highest dimension)
+ auto new_concat = std::make_shared<ov::opset1::Concat>(new_reshaped_outputs, 0);
+ new_concat->set_friendly_name(concat->get_friendly_name() + "/after_Reshape");
+
+ ov::NodeVector from_nodes = {reshape, concat};
+ ov::copy_runtime_info(from_nodes, new_concat);
+ ov::replace_node(reshape, new_concat);
+
+ LOG_INFO(" Pushed Reshape into " << num_branches << " branches");
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(reshape_pattern, matcher_name);
+ register_matcher(m, callback);
+}
+
+// =============================================================================
+// FuseConcatReduceSum
+// =============================================================================
+// Transforms: Concat([a,b,c], axis=0) → ReduceSum(axis=0) => a + b + c
+// Optimizes sum reduction over concatenation axis by converting to cascaded Add
+// Handles both keep_dims=true and keep_dims=false cases
+
+FuseConcatReduceSum::FuseConcatReduceSum() {
+ MATCHER_SCOPE(FuseConcatReduceSum);
+
+ auto concat_pattern = ov::pass::pattern::wrap_type<ov::opset1::Concat>();
+ auto reduce_sum_pattern =
+ ov::pass::pattern::wrap_type<ov::opset1::ReduceSum>({concat_pattern, ov::pass::pattern::any_input()});
+
+ auto callback = [concat_pattern](ov::pass::pattern::Matcher& m) {
+ auto& pm = m.get_pattern_value_map();
+ auto reduce_sum = std::dynamic_pointer_cast<ov::opset1::ReduceSum>(m.get_match_root());
+ auto concat = std::dynamic_pointer_cast<ov::opset1::Concat>(pm.at(concat_pattern).get_node_shared_ptr());
+
+ if (!reduce_sum || !concat)
+ return false;
+
+ // Validate: reduction axes must be constant
+ auto reduce_axes_const =
+ std::dynamic_pointer_cast<ov::opset1::Constant>(reduce_sum->input_value(1).get_node_shared_ptr());
+ if (!reduce_axes_const)
+ return false;
+
+ // Validate: only single axis reduction matching concat axis is safe to optimize
+ // If axes differ, the transformation would produce incorrect results
+ auto reduce_axes = reduce_axes_const->cast_vector<int64_t>();
+ if (reduce_axes.size() != 1 || reduce_axes[0] != concat->get_axis()) {
+ return false;
+ }
+
+ // Check keep_dims attribute to determine output shape handling
+ // keep_dims=false: ReduceSum([N,H], axis=0) → [H] (removes axis)
+ // keep_dims=true: ReduceSum([N,H], axis=0) → [1,H] (keeps axis with size 1)
+ bool keep_dims = reduce_sum->get_keep_dims();
+
+ LOG_INFO("FuseConcatReduceSum: Fusing Concat+ReduceSum to cascaded Add");
+ LOG_INFO(" keep_dims: " << keep_dims);
+
+ auto inputs = concat->input_values();
+ if (inputs.size() < 2)
+ return false;
+
+ // Prepare inputs based on keep_dims to match output shape
+ // Example: Concat([a,b,c], axis=0) → ReduceSum(axis=0)
+ // If keep_dims=false: need Squeeze([1,H])→[H] for each input, then a+b+c → [H]
+ // If keep_dims=true: directly add [1,H] inputs, then a+b+c → [1,H]
+ ov::OutputVector prepared_inputs;
+ if (!keep_dims) {
+ // ReduceSum removes the reduction axis, so Squeeze concat inputs to match
+ auto squeeze_axes = std::make_shared<ov::opset1::Constant>(ov::element::i64,
+ ov::Shape{1},
+ std::vector<int64_t>{concat->get_axis()});
+ for (size_t i = 0; i < inputs.size(); ++i) {
+ auto squeeze = std::make_shared<ov::opset1::Squeeze>(inputs[i], squeeze_axes);
+ squeeze->set_friendly_name(reduce_sum->get_friendly_name() + "/squeeze_" + std::to_string(i));
+ prepared_inputs.push_back(squeeze->output(0));
+ }
+ } else {
+ // keep_dims=true: ReduceSum preserves the axis dimension, Add directly
+ for (size_t i = 0; i < inputs.size(); ++i) {
+ prepared_inputs.push_back(inputs[i]);
+ }
+ }
+
+ // Create cascaded Add operations
+ ov::Output<ov::Node> accumulated = prepared_inputs[0];
+ for (size_t i = 1; i < prepared_inputs.size(); ++i) {
+ auto add_node = std::make_shared<ov::opset1::Add>(accumulated, prepared_inputs[i]);
+ add_node->set_friendly_name(reduce_sum->get_friendly_name() + "/add_" + std::to_string(i));
+ accumulated = add_node->output(0);
+ }
+
+ ov::NodeVector from_nodes = {reduce_sum, concat};
+ ov::copy_runtime_info(from_nodes, accumulated.get_node_shared_ptr());
+ ov::replace_node(reduce_sum, accumulated.get_node_shared_ptr());
+
+ LOG_INFO(" Created " << (inputs.size() - 1) << " Add operations");
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(reduce_sum_pattern, matcher_name);
+ register_matcher(m, callback);
+}
+
+// =============================================================================
+// RemoveUnusedParameters: Clean up parameters that have no consumers
+// =============================================================================
+
+RemoveUnusedParameters::RemoveUnusedParameters(std::shared_ptr<ov::Model> model) : model_(model) {
+ MATCHER_SCOPE(RemoveUnusedParameters);
+
+ // Match any Result node to trigger cleanup after all other patterns
+ auto result_pattern = ov::pass::pattern::wrap_type<ov::op::v0::Result>();
+
+ auto callback = [this](ov::pass::pattern::Matcher& m) {
+ LOG_INFO("RemoveUnusedParameters: Scanning for unused parameters");
+
+ auto params = model_->get_parameters();
+ ov::ParameterVector unused_params;
+
+ for (const auto& param : params) {
+ bool has_consumers = false;
+
+ // Check if parameter output has any target inputs
+ for (const auto& output : param->outputs()) {
+ if (!output.get_target_inputs().empty()) {
+ has_consumers = true;
+ break;
+ }
+ }
+
+ if (!has_consumers) {
+ unused_params.push_back(param);
+ LOG_INFO(" Found unused parameter: " << param->get_friendly_name());
+ }
+ }
+
+ if (!unused_params.empty()) {
+ LOG_INFO(" Removing " << unused_params.size() << " unused parameters");
+ for (const auto& param : unused_params) {
+ model_->remove_parameter(param);
+ }
+ return true; // Model was modified
+ } else {
+ LOG_INFO(" No unused parameters found");
+ return false; // Model was not modified
+ }
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(result_pattern, matcher_name);
+ register_matcher(m, callback);
+}
+
+} // namespace pass
+} // namespace npuw
+} // namespace ov
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.hpp
new file mode 100644
index 00000000000..787fbc4edfb
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.hpp
@@ -0,0 +1,290 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+/**
+ * @file moe_unroll_patterns.hpp
+ * @brief Graph transformation patterns for Mixture of Experts (MoE) model optimization
+ *
+ * This file contains a collection of transformation patterns designed to optimize
+ * MoE model graphs for execution on Intel NPU. The patterns focus on:
+ * - Unrolling batched expert computations into parallel branches
+ * - Distributing operations before concatenation for better parallelism
+ * - Fusing operation sequences to reduce computational overhead
+ *
+ * Usage: Apply MoEExpertUnrolling pass to the model with specified number of experts
+ */
+
+#pragma once
+
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/pass/manager.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+
+namespace ov {
+namespace npuw {
+namespace pass {
+
+// =============================================================================
+// UnrollMoEMatMul: Unified MoE MatMul unrolling for all input patterns
+// =============================================================================
+/**
+ * @brief Unrolls MoE expert MatMul operations into separate expert branches
+ *
+ * Automatically detects and handles three input patterns:
+ * Pattern 1 (Batched): input_param → convert → tile → reshape ─┐
+ * scale + weights → multiply ─────────────┤ MatMul
+ * Pattern 2 (Concat): Concat([a,b,c,d]) ──────────────────────┐
+ * scale + weights → multiply ─────────────┤ MatMul
+ * Pattern 3 (Sliceable): AnyInput[N,...] ───────────────────────┐ (auto-sliced)
+ * scale + weights → multiply ─────────────┤ MatMul
+ *
+ * Number of experts is automatically detected from scale/weights parameter shapes.
+ * Transforms to: N expert branches with individual parameters, concatenated output
+ *
+ * @param model Model to register new parameters with
+ */
+
+class UnrollMoEMatMul : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::pass::UnrollMoEMatMul");
+ explicit UnrollMoEMatMul(std::shared_ptr<ov::Model> model);
+
+private:
+ std::shared_ptr<ov::Model> model_;
+};
+
+// =============================================================================
+// PushElementwiseBeforeConcat: Push elementwise operations before Concat
+// =============================================================================
+/**
+ * @brief Distributes elementwise operations (Add/Multiply) before Concat
+ *
+ * Transforms: Param[N,...] + Concat([a,b,c]) → Concat([a+Param[0], b+Param[1], c+Param[2]])
+ * Benefits: Enables per-branch optimization and reduces parameter size
+ *
+ * @param model Model to register split parameters with
+ */
+
+class PushElementwiseBeforeConcat : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::pass::PushElementwiseBeforeConcat");
+ explicit PushElementwiseBeforeConcat(std::shared_ptr<ov::Model> model);
+
+private:
+ std::shared_ptr<ov::Model> model_;
+};
+
+// =============================================================================
+// PushSliceBeforeConcat: Push Slice before Concat
+// =============================================================================
+/**
+ * @brief Distributes Slice operations before Concat when safe
+ *
+ * Safety: Only applies when slice axis != concat axis
+ * Transforms: Concat([a,b,c], axis=0) → Slice(axis=k) → Concat([Slice(a), Slice(b), Slice(c)])
+ */
+
+class PushSliceBeforeConcat : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::pass::PushSliceBeforeConcat");
+ PushSliceBeforeConcat();
+};
+
+// =============================================================================
+// PushClampBeforeConcat: Push Clamp before Concat
+// =============================================================================
+/**
+ * @brief Distributes Clamp operations before Concat
+ *
+ * Transforms: Concat([a,b,c]) → Clamp(min,max) → Concat([Clamp(a), Clamp(b), Clamp(c)])
+ * Always safe: Clamp operates element-wise independently
+ */
+
+class PushClampBeforeConcat : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::pass::PushClampBeforeConcat");
+ PushClampBeforeConcat();
+};
+
+// =============================================================================
+// PushScalarElementwiseBeforeConcat: Push scalar elementwise operations before Concat
+// =============================================================================
+/**
+ * @brief Distributes scalar operations (Add/Minimum/Swish) before Concat
+ *
+ * Constraint: Scalar input must have exactly 1 element
+ * Transforms: Concat([a,b,c]) → Op(scalar) → Concat([Op(a,scalar), Op(b,scalar), Op(c,scalar)])
+ */
+
+class PushScalarElementwiseBeforeConcat : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::pass::PushScalarElementwiseBeforeConcat");
+ PushScalarElementwiseBeforeConcat();
+};
+
+// =============================================================================
+// PushMultiplyBeforeConcat: Push Multiply before Concat
+// =============================================================================
+/**
+ * @brief Fuses two Concat operations with element-wise Multiply
+ *
+ * Requirements: Same axis, same branch count, compatible shapes
+ * Transforms: Concat([a,b,c]) * Concat([d,e,f]) → Concat([a*d, b*e, c*f])
+ */
+
+class PushMultiplyBeforeConcat : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::pass::PushMultiplyBeforeConcat");
+ PushMultiplyBeforeConcat();
+};
+
+// =============================================================================
+// FuseConcatReduceSum: Fuse Concat + ReduceSum
+// =============================================================================
+/**
+ * @brief Converts Concat followed by ReduceSum to cascaded Add operations
+ *
+ * Requirements: ReduceSum axis must match Concat axis
+ * Handles both keep_dims=true and keep_dims=false
+ * Transforms: Concat([a,b,c], axis=0) → ReduceSum(axis=0) → a + b + c
+ */
+
+class FuseConcatReduceSum : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::pass::FuseConcatReduceSum");
+ FuseConcatReduceSum();
+};
+
+// =============================================================================
+// PushReshapeBeforeConcat: Push Reshape before Concat
+// =============================================================================
+/**
+ * @brief Distributes Reshape operations before Concat on axis 0
+ *
+ * Safety: Concat axis must be 0 and Reshape must preserve first dimension
+ * Example: Concat([a,b,c,d], axis=0) → Reshape → Concat([Reshape(a), Reshape(b), ...])
+ */
+
+class PushReshapeBeforeConcat : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::pass::PushReshapeBeforeConcat");
+ PushReshapeBeforeConcat();
+};
+
+// =============================================================================
+// RemoveUnusedParameters: Clean up unused parameters after unrolling
+// =============================================================================
+/**
+ * @brief Removes parameters that have no consumers after MoE unrolling
+ *
+ * After unrolling batched parameters into per-expert parameters,
+ * the original batched parameters may become unused. This pass removes them.
+ *
+ * @param model Model to clean up
+ */
+
+class RemoveUnusedParameters : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::pass::RemoveUnusedParameters");
+ explicit RemoveUnusedParameters(std::shared_ptr<ov::Model> model);
+
+private:
+ std::shared_ptr<ov::Model> model_;
+};
+
+// =============================================================================
+// Main transformation: Combine all MoE unrolling patterns
+// =============================================================================
+/**
+ * @brief Full MoE expert unrolling with comprehensive optimizations
+ *
+ * Applies all available unrolling and optimization patterns including both
+ * weight-related and activation-related transformations:
+ *
+ * Weight-related patterns:
+ * - UnrollMoEMatMul: Unified MatMul unrolling for all input patterns
+ * - PushElementwiseBeforeConcat: Distribute Add/Multiply operations
+ * - PushMultiplyBeforeConcat: Fuse two Concat with Multiply
+ * - PushReshapeBeforeConcat: Distribute Reshape on axis 0
+ * - FuseConcatReduceSum: Convert Concat+ReduceSum to Add chain
+ *
+ * Activation-related patterns:
+ * - PushSliceBeforeConcat: Distribute Slice when safe
+ * - PushClampBeforeConcat: Distribute Clamp operations
+ * - PushScalarElementwiseBeforeConcat: Distribute scalar operations
+ *
+ * Usage:
+ * @code
+ * auto model = std::make_shared<ov::Model>(...);
+ * ov::pass::Manager manager;
+ * manager.register_pass<ov::npuw::pass::MoEExpertUnrolling>(model);
+ * manager.run_passes(model);
+ * @endcode
+ *
+ * @param model Model instance for parameter registration
+ */
+
+class MoEExpertUnrolling : public ov::pass::GraphRewrite {
+public:
+ OPENVINO_GRAPH_REWRITE_RTTI("npuw::pass::MoEExpertUnrolling");
+
+ explicit MoEExpertUnrolling(std::shared_ptr<ov::Model> model) {
+ // Weight-related unrolling patterns
+ add_matcher<UnrollMoEMatMul>(model);
+ add_matcher<PushElementwiseBeforeConcat>(model);
+ add_matcher<PushMultiplyBeforeConcat>();
+ add_matcher<PushReshapeBeforeConcat>();
+ add_matcher<FuseConcatReduceSum>();
+
+ // Activation-related optimization patterns
+ add_matcher<PushSliceBeforeConcat>();
+ add_matcher<PushClampBeforeConcat>();
+ add_matcher<PushScalarElementwiseBeforeConcat>();
+
+ // Cleanup
+ add_matcher<RemoveUnusedParameters>(model);
+ }
+};
+
+/**
+ * @brief Weight-focused MoE expert unrolling for parameter optimization
+ *
+ * Applies only weight-related unrolling patterns, focusing on splitting
+ * batched parameters and weight operations into per-expert branches.
+ * This variant excludes activation-related optimizations (Slice, Clamp, etc.)
+ * to minimize graph modifications while still achieving parameter unrolling.
+ *
+ * Included patterns:
+ * - UnrollMoEMatMul: Unified MatMul unrolling for all input patterns
+ * - PushElementwiseBeforeConcat: Distribute Add/Multiply with parameters
+ * - PushMultiplyBeforeConcat: Fuse two Concat with Multiply
+ * - PushReshapeBeforeConcat: Distribute Reshape on axis 0
+ * - FuseConcatReduceSum: Convert Concat+ReduceSum to Add chain
+ *
+ * Use cases:
+ * - When only parameter splitting is needed
+ * - When activation graph should remain unchanged
+ * - For more conservative optimization strategy
+ *
+ * @param model Model instance for parameter registration
+ */
+
+class MoEExpertUnrollingWeightsOnly : public ov::pass::GraphRewrite {
+public:
+ OPENVINO_GRAPH_REWRITE_RTTI("npuw::pass::MoEExpertUnrollingWeightsOnly");
+
+ explicit MoEExpertUnrollingWeightsOnly(std::shared_ptr<ov::Model> model) {
+ // Only weight-related patterns - no activation optimizations
+ add_matcher<UnrollMoEMatMul>(model);
+ add_matcher<PushElementwiseBeforeConcat>(model);
+ add_matcher<PushMultiplyBeforeConcat>();
+ add_matcher<PushReshapeBeforeConcat>();
+ add_matcher<FuseConcatReduceSum>();
+ add_matcher<RemoveUnusedParameters>(model);
+ }
+};
+
+} // namespace pass
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp
index 1846de287dd..13786781bec 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
@@ -8,6 +8,7 @@
#include "../../util.hpp"
#include "../patterns/avoid.hpp"
#include "../patterns/compute.hpp"
+#include "../patterns/moe.hpp"
#include "../patterns/sdpa.hpp"
#include "group.hpp"
#include "openvino/op/util/op_types.hpp"
@@ -642,6 +643,11 @@ void Snapshot::earlyRegroup() {
if (isolate.pattern == #p) { \
rewr.add_matcher<ov::npuw::patterns::attn::p>(shared_from_this(), isolate.tag); \
handle_patterns = true; \
+ }
+#define HNDL_MOE(p) \
+ if (isolate.pattern == #p) { \
+ rewr.add_matcher<ov::npuw::patterns::moe::p>(shared_from_this(), isolate.tag); \
+ handle_patterns = true; \
}
HNDL(RMSNorm);
HNDL(RMSNorm2);
@@ -654,10 +660,13 @@ void Snapshot::earlyRegroup() {
HNDL(DQMatMulConv);
HNDL(VocabMatMul);
HNDL(VariadicSplit);
+ HNDL_MOE(GPTOSSExpert);
+ HNDL_MOE(GPTOSSRouter);
HNDL_FAKE(FakeConvert);
HNDL_FAKE(FakeQuantize);
HNDL_ATTN(SDPA);
HNDL_ATTN(SDPADecomposed);
+#undef HNDL_MOE
#undef HNDL_ATTN
#undef HNDL_FAKE
#undef HNDL
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.cpp
index a61fc34e72d..30fb9c1ef1f 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.cpp
@@ -169,32 +169,41 @@ std::vector<ov::npuw::online::Isolate> ov::npuw::online::util::getIsolates(const
}
std::vector<Isolate> isolates;
- std::string s = isolates_unparsed;
- auto preset_iter = ov::npuw::online::util::ISOL_PRESETS.find(s);
- if (preset_iter != ov::npuw::online::util::ISOL_PRESETS.end()) {
- s = preset_iter->second;
- }
+ // Lambda to split comma-separated string into tokens
+ auto splitByComma = [](const std::string& s) {
+ std::vector<std::string> tokens;
+ size_t pos = 0;
+ size_t start = 0;
- size_t pos = 0;
- size_t start = 0;
- std::string token;
+ while ((pos = s.find(',', start)) != std::string::npos) {
+ tokens.push_back(s.substr(start, pos - start));
+ start = pos + 1;
+ }
+ tokens.push_back(s.substr(start, s.size() - start)); // Handle tail
+
+ return tokens;
+ };
+
+ // Split input and expand presets
+ std::vector<std::string> expanded_tokens;
+ for (const auto& token : splitByComma(isolates_unparsed)) {
+ auto preset_iter = ov::npuw::online::util::ISOL_PRESETS.find(token);
+ if (preset_iter != ov::npuw::online::util::ISOL_PRESETS.end()) {
+ // Expand preset into individual tokens
+ auto preset_tokens = splitByComma(preset_iter->second);
+ expanded_tokens.insert(expanded_tokens.end(), preset_tokens.begin(), preset_tokens.end());
+ } else {
+ expanded_tokens.push_back(token);
+ }
+ }
- while ((pos = s.find(',', start)) != std::string::npos) {
- token = s.substr(start, pos - start);
+ // Parse the expanded tokens
+ for (const auto& token : expanded_tokens) {
auto isolate_opt = util::parseIsolate(token);
- // Check that parsing was a success
if (isolate_opt) {
isolates.push_back(*isolate_opt);
}
- start = pos + 1;
- }
-
- // Parse the tail
- auto isolate_opt = util::parseIsolate(s.substr(start, s.size() - start));
- // Check that parsing was a success
- if (isolate_opt) {
- isolates.push_back(*isolate_opt);
}
if (!isolates.empty()) {
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp
index 5f15a1bb3e6..abd5800ec1f 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
@@ -96,7 +96,8 @@ static const std::map<std::string, std::string> ISOL_PRESETS = {{"COMPUTE",
"P:RMSNorm3/compute,P:RMSNorm4/compute,"
"P:VariadicSplit/compute"},
{"FAKE", "P:FakeConvert/fake,P:FakeQuantize/fake"},
- {"ATTN", "P:SDPA/attn,P:SDPADecomposed/attn"}};
+ {"ATTN", "P:SDPA/attn,P:SDPADecomposed/attn"},
+ {"MOE", "P:GPTOSSExpert/expert,P:GPTOSSRouter/router"}};
} // namespace util
} // namespace online
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp
index 29d4c3adf5a..3af791d2d46 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp
@@ -21,6 +21,7 @@
#include "openvino/util/common_util.hpp"
#include "openvino/util/xml_parse_utils.hpp"
#include "patterns/dcoff.hpp"
+#include "patterns/moe.hpp"
#include "patterns/opt.hpp"
#include "traits.hpp"
@@ -238,6 +239,11 @@ private:
using Match = std::function<bool(const std::shared_ptr<ov::Node>& node)>;
void propagate(const std::string& func_name, const Match& test, ov::npuw::RepeatedBlock::MatchedBank& bank);
+ // Helper method to find and cache router model for MoE transformations
+ // Returns cached router model if available, otherwise searches P.functions
+ // for a function tagged as "router" and caches it for future use
+ std::shared_ptr<ov::Model> getRouterModel();
+
void createFunction(FunctionPipeline& func_ggg);
// NB(dm): This method should get a better place, it is here only because
@@ -335,6 +341,13 @@ public:
void matchRepeatedSubgraphs(const std::string& func_name);
void spatial(const std::string& func_name);
void attention(const std::string& func_name);
+
+ // MoE-specific transformations (require router model availability)
+ // transformMoeExperts: Transform expert functions (tag="expert") to optimized MoE expert models
+ // transformMoeDownstream: Transform downstream processing (pattern-based detection)
+ void transformMoeExperts(const std::string& func_name);
+ void transformMoeDownstream(const std::string& func_name);
+
void optimize(const std::string& func_name);
void decompressionCutOff(const std::string& func_name);
@@ -1391,6 +1404,7 @@ void Partitioner::saveRepeatedConstants(const std::string& func_name) {
HANDLE_CASE(f8e4m3, uint8_t);
HANDLE_CASE(f16, uint16_t);
HANDLE_CASE(f32, float);
+ HANDLE_CASE(u8, uint8_t);
#undef HANDLE_CASE
default:
OPENVINO_THROW("Unable to handle type ", node_a->output(0));
@@ -1942,6 +1956,85 @@ void Partitioner::attention(const std::string& func_name) {
}
}
+std::shared_ptr<ov::Model> Partitioner::getRouterModel() {
+ // Find and cache router model in context if not already cached
+ if (part_ctx.router_model != nullptr) {
+ return part_ctx.router_model;
+ }
+
+ for (const auto& [name, func] : P.functions) {
+ LOG_DEBUG("Checking function " << name << " with tag " << func.gettag());
+ if (func.gettag() != ov::npuw::patterns::moe::ROUTER_TAG) {
+ continue;
+ }
+
+ part_ctx.router_model = func._model;
+ LOG_INFO("Found router model: " << name);
+ break;
+ }
+
+ return part_ctx.router_model;
+}
+
+void Partitioner::transformMoeExperts(const std::string& func_name) {
+ ov::npuw::Function& f = P.functions.at(func_name);
+
+ // Only process functions tagged as "expert"
+ if (f.gettag() != ov::npuw::patterns::moe::EXPERT_TAG) {
+ return;
+ }
+
+ // Retrieve router model (required for extracting K from TopK node)
+ auto router_model = getRouterModel();
+ if (!router_model) {
+ LOG_WARN("Router model not available yet, skipping MoE expert transformation for " << func_name);
+ return;
+ }
+
+ LOG_DEBUG("Transforming " << func_name << " into MoE expert block in model " << model->get_friendly_name()
+ << "...");
+ LOG_BLOCK();
+
+ // Determine compilation strategy from configuration:
+ // - moe_chunk_size = 0 (default): Compile multiple models for various chunk sizes
+ // {16, 32, 64, 128, 256} to enable dynamic chunk selection at runtime
+ // - moe_chunk_size > 0: Compile a single model with the specified fixed chunk size
+ const auto moe_chunk_size = cfg.get<::intel_npu::NPUW_MOE_TOKEN_CHUNK_SIZE>();
+
+ // Create MoEExperts using factory method:
+ // - Analyzes expert model structure
+ // - Extracts K (number of active experts) from router model's TopK node
+ // - Generates optimized expert models for prefill and/or decoding stages
+ f._moe_experts = ov::npuw::function::MoEExperts::from(f._model, router_model, moe_chunk_size);
+}
+
+void Partitioner::transformMoeDownstream(const std::string& func_name) {
+ ov::npuw::Function& f = P.functions.at(func_name);
+
+ // Retrieve router model (required for extracting active expert count)
+ auto router_model = getRouterModel();
+ if (!router_model) {
+ LOG_WARN("Router model not available, skipping MoE downstream transformation for " << func_name);
+ return;
+ }
+
+ LOG_DEBUG("Attempting MoE downstream transformation for " << func_name << "...");
+ LOG_BLOCK();
+
+ // Detect and transform MoE downstream processing pattern:
+ // Expected pattern: Parameter[total_experts, 1, H, W] -> Convert -> ReduceSum
+ //
+ // Transformation:
+ // - Identifies parameters with expert dimension (first dimension = total_experts)
+ // - Reshapes from [total_experts, ...] to [active_experts, ...]
+ // - active_experts (K) is extracted from router model's TopK node
+ //
+ // Note: No tag-based filtering - pattern matching determines applicability
+ // This allows downstream processing to be detected in any function that follows
+ // the structural pattern, regardless of how it was originally tagged
+ f._moe_experts_downstream = ov::npuw::function::create_moe_downstream(f._model, router_model);
+}
+
void Partitioner::optimize(const std::string& func_name) {
using namespace ov::npuw::weights;
@@ -2522,8 +2615,13 @@ ov::npuw::Partitioning ov::npuw::getPartitioning(const std::shared_ptr<ov::Model
if (cfg.get<::intel_npu::NPUW_FOLD>()) {
// Do full-featured folding
auto all_functions = p.initFunctionPipeline(Partitioner::FunctionPipelineType::FOLD);
+
+ // Pass 1: Register all functions and apply general transformations
+ // - matchRepeatedSubgraphs() populates P.functions with all function definitions
+ // - Other transformations (spatial, attention, optimize, etc.) can be applied
+ // independently without cross-function dependencies
for (auto&& func_group : all_functions) {
- LOG_INFO("FOLD: Process function " << func_group << "...");
+ LOG_INFO("FOLD Pass 1: Register and transform function " << func_group << "...");
LOG_BLOCK();
p.propagateSlices(func_group);
p.propagateConverts(func_group);
@@ -2535,12 +2633,27 @@ ov::npuw::Partitioning ov::npuw::getPartitioning(const std::shared_ptr<ov::Model
p.saveTailDictConstants(func_group);
p.matchParameters(func_group);
p.matchResults(func_group);
- p.matchRepeatedSubgraphs(func_group);
+ p.matchRepeatedSubgraphs(func_group); // This populates P.functions
p.spatial(func_group);
p.attention(func_group);
p.optimize(func_group);
p.decompressionCutOff(func_group);
}
+
+ // Pass 2: MoE-specific transformations (requires all functions registered)
+ //
+ // Why separate pass?
+ // - transformMoeExperts() and transformMoeDownstream() require the "router" function
+ // - Router function must be found in P.functions (populated in Pass 1)
+ // - Processing order in Pass 1 is not guaranteed (router may come after experts)
+ // - Therefore, MoE transformations run in Pass 2 after all function registration
+ // completes, ensuring router model is always available when needed
+ for (auto&& func_group : all_functions) {
+ LOG_INFO("FOLD Pass 2: MoE-specific transformations for " << func_group << "...");
+ LOG_BLOCK();
+ p.transformMoeExperts(func_group);
+ p.transformMoeDownstream(func_group);
+ }
} else if (cfg.get<::intel_npu::NPUW_CWAI>()) {
// Less brutal version - just transform repeated blocks
// into the closure forms, but don't do folding.
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp
index 9c0a8ed6d1c..c8dff61741a 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp
@@ -12,6 +12,7 @@
#include "../attention.hpp"
#include "../host_flash_attention.hpp"
#include "../lazy_tensor.hpp"
+#include "../moe_transformations/moe_transformation.hpp"
#include "../pyramid_attention.hpp"
#include "../spatial.hpp"
#include "intel_npu/config/config.hpp"
@@ -103,6 +104,9 @@ struct Function {
std::optional<ov::npuw::function::PyramidAttention> _pyramid_attention;
// Host Flash Attention
std::optional<ov::npuw::function::HostFlashAttention> _host_flash_attention;
+ // MoE expert information - single expert model
+ std::optional<ov::npuw::function::MoEExperts> _moe_experts;
+ std::optional<ov::npuw::function::MoEDownstream> _moe_experts_downstream;
// FIXME: They should exclude each other (introduce a hierarchy, finally?)
// FIXME: shouldn't be here. Needed to not unpack some lazy closures in DCOFF
std::set<std::size_t> _idx_lazy_unpack;
@@ -189,6 +193,10 @@ struct Partitioning {
struct PartitioningContext {
bool use_host_gather_quant = false;
+
+ // Router model for MoE (shared during partitioning process)
+ // Will be populated during first pass and used in second pass
+ mutable std::shared_ptr<ov::Model> router_model;
};
Partitioning getPartitioning(const std::shared_ptr<ov::Model>& model,
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.cpp
new file mode 100644
index 00000000000..4ace2fd0eb3
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.cpp
@@ -0,0 +1,349 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe.hpp"
+
+#include "../../logging.hpp"
+#include "openvino/op/ops.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "openvino/util/common_util.hpp"
+
+namespace ov {
+namespace npuw {
+namespace patterns {
+namespace moe {
+
+namespace opp = ov::pass::pattern;
+
+/*
+ GPT-OSS Expert Pattern:
+
+ Input:
+ Tile -> Reshape1
+
+ First MatMul (gate + up projections):
+ Reshape1 -> MatMul1 (with weights Convert1) -> Add1
+
+ Dual branches from Add1:
+
+ Gate branch (left):
+ Add1 -> Slice2 -> Clamp -> Add2 (with Convert constant) ──┐
+ │
+ Activation branch (right): │
+ Add1 -> Slice1 -> Minimum (with Convert constant) │
+ -> Swish (with const input) ────────────────┤
+ │
+ Merge branches: │
+ Add2 + Swish -> Multiply1 <───────────────────────────────┘
+
+ Second MatMul (down projection):
+ Multiply1 -> MatMul2 (with weights Convert2) -> Add3
+
+ Output (stage-dependent):
+ Prefill stage: Add3 -> Reshape2 -> Multiply (output here)
+ ReduceSum will be performed in downstream subgraph
+
+ Decoding stage: Add3 -> Reshape2 -> Multiply -> ReduceSum (output here)
+ ReduceSum is included in expert subgraph
+
+ Isolation strategy:
+ - Prefill (token_count > 1): Isolate up to Multiply, ReduceSum stays in downstream
+ - Decoding (token_count == 1): Isolate including ReduceSum, self-contained expert subgraph
+*/
+GPTOSSExpert::GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag) {
+ LOG_DEBUG("GPTOSSExpert pattern matcher registered with tag: " << isol_tag);
+
+ // Input preparation
+ auto tile = opp::wrap_type<ov::op::v0::Tile>({opp::any_input(), opp::any_input()});
+ auto reshape1 = opp::wrap_type<ov::op::v1::Reshape>({tile, opp::any_input()});
+
+ // First MatMul (gate + up projections) - weights path: Multiply -> Convert -> MatMul
+ auto weights_multiply1 = opp::wrap_type<ov::op::v1::Multiply>({opp::any_input(), opp::any_input()});
+ auto weights_convert1 = opp::wrap_type<ov::op::v0::Convert>({weights_multiply1});
+ auto matmul1 = opp::wrap_type<ov::op::v0::MatMul>({reshape1, weights_convert1});
+ auto add1 = opp::wrap_type<ov::op::v1::Add>({matmul1, opp::any_input()});
+
+ // Activation branch: Slice -> Minimum -> Swish
+ auto slice = opp::wrap_type<ov::op::v8::Slice>(
+ {add1, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});
+ auto minimum = opp::wrap_type<ov::op::v1::Minimum>({slice, opp::any_input()});
+ auto swish = opp::wrap_type<ov::op::v4::Swish>({minimum, opp::any_input()});
+
+ // Gate branch: Slice -> Clamp -> Add2
+ auto other_slice = opp::wrap_type<ov::op::v8::Slice>(
+ {add1, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});
+ auto clamp = opp::wrap_type<ov::op::v0::Clamp>({other_slice});
+ auto add2 = opp::wrap_type<ov::op::v1::Add>({clamp, opp::any_input()});
+
+ // Merge branches
+ auto multiply1 = opp::wrap_type<ov::op::v1::Multiply>({add2, swish});
+
+ // Second MatMul (down projection) - weights path: Multiply -> Convert -> MatMul
+ auto weights_multiply2 = opp::wrap_type<ov::op::v1::Multiply>({opp::any_input(), opp::any_input()});
+ auto weights_convert2 = opp::wrap_type<ov::op::v0::Convert>({weights_multiply2});
+ auto matmul2 = opp::wrap_type<ov::op::v0::MatMul>({multiply1, weights_convert2});
+ auto add3 = opp::wrap_type<ov::op::v1::Add>({matmul2, opp::any_input()});
+
+ // Output reshape - Multiply
+ auto reshape2 = opp::wrap_type<ov::op::v1::Reshape>({add3, opp::any_input()});
+ auto output_multiply = opp::wrap_type<ov::op::v1::Multiply>({reshape2, opp::any_input()});
+
+ auto node_to_gptr = snapshot->getNodeToGroupMap();
+
+ auto callback = [=](ov::pass::pattern::Matcher& m) {
+ auto& node_to_output = m.get_pattern_value_map();
+
+ auto matched_tile = node_to_output.at(tile).get_node_shared_ptr();
+ auto matched_reshape1 = node_to_output.at(reshape1).get_node_shared_ptr();
+ auto matched_weights_multiply1 = node_to_output.at(weights_multiply1).get_node_shared_ptr();
+ auto matched_weights_convert1 = node_to_output.at(weights_convert1).get_node_shared_ptr();
+ auto matched_matmul1 = node_to_output.at(matmul1).get_node_shared_ptr();
+ auto matched_add1 = node_to_output.at(add1).get_node_shared_ptr();
+ auto matched_slice = node_to_output.at(slice).get_node_shared_ptr();
+ auto matched_minimum = node_to_output.at(minimum).get_node_shared_ptr();
+ auto matched_swish = node_to_output.at(swish).get_node_shared_ptr();
+ auto matched_other_slice = node_to_output.at(other_slice).get_node_shared_ptr();
+ auto matched_clamp = node_to_output.at(clamp).get_node_shared_ptr();
+ auto matched_add2 = node_to_output.at(add2).get_node_shared_ptr();
+ auto matched_multiply1 = node_to_output.at(multiply1).get_node_shared_ptr();
+ auto matched_weights_multiply2 = node_to_output.at(weights_multiply2).get_node_shared_ptr();
+ auto matched_weights_convert2 = node_to_output.at(weights_convert2).get_node_shared_ptr();
+ auto matched_matmul2 = node_to_output.at(matmul2).get_node_shared_ptr();
+ auto matched_add3 = node_to_output.at(add3).get_node_shared_ptr();
+ auto matched_reshape2 = node_to_output.at(reshape2).get_node_shared_ptr();
+ auto matched_output_multiply = node_to_output.at(output_multiply).get_node_shared_ptr();
+
+ // Check if this is decoding stage by examining shape[rank-2]
+ 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) {
+ 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());
+ }
+ }
+
+ // Isolate all common expert nodes
+ node_to_gptr->at(matched_tile)->isolate(isol_tag);
+ node_to_gptr->at(matched_reshape1)->isolate(isol_tag);
+ node_to_gptr->at(matched_weights_multiply1)->isolate(isol_tag);
+ node_to_gptr->at(matched_weights_convert1)->isolate(isol_tag);
+ node_to_gptr->at(matched_matmul1)->isolate(isol_tag);
+ node_to_gptr->at(matched_add1)->isolate(isol_tag);
+ node_to_gptr->at(matched_slice)->isolate(isol_tag);
+ node_to_gptr->at(matched_minimum)->isolate(isol_tag);
+ node_to_gptr->at(matched_swish)->isolate(isol_tag);
+ node_to_gptr->at(matched_other_slice)->isolate(isol_tag);
+ node_to_gptr->at(matched_clamp)->isolate(isol_tag);
+ node_to_gptr->at(matched_add2)->isolate(isol_tag);
+ node_to_gptr->at(matched_multiply1)->isolate(isol_tag);
+ node_to_gptr->at(matched_weights_multiply2)->isolate(isol_tag);
+ node_to_gptr->at(matched_weights_convert2)->isolate(isol_tag);
+ node_to_gptr->at(matched_matmul2)->isolate(isol_tag);
+ node_to_gptr->at(matched_add3)->isolate(isol_tag);
+ node_to_gptr->at(matched_reshape2)->isolate(isol_tag);
+ node_to_gptr->at(matched_output_multiply)->isolate(isol_tag);
+
+ // If decoding stage, find and isolate ReduceSum after Multiply
+ if (is_decoding) {
+ LOG_DEBUG("Decoding stage detected, searching for ReduceSum to isolate...");
+ std::shared_ptr<ov::Node> matched_reduce_sum = nullptr;
+
+ for (auto& output : matched_output_multiply->outputs()) {
+ for (auto& input : output.get_target_inputs()) {
+ auto consumer = input.get_node()->shared_from_this();
+ if (auto reduce_sum = std::dynamic_pointer_cast<ov::op::v1::ReduceSum>(consumer)) {
+ matched_reduce_sum = reduce_sum;
+ LOG_DEBUG(" Found ReduceSum after Multiply, isolating for decoding stage");
+ break;
+ }
+ }
+ if (matched_reduce_sum)
+ break;
+ }
+
+ if (matched_reduce_sum && node_to_gptr->count(matched_reduce_sum)) {
+ node_to_gptr->at(matched_reduce_sum)->isolate(isol_tag);
+ LOG_DEBUG(" ReduceSum successfully isolated");
+ } else if (matched_reduce_sum) {
+ LOG_WARN(" ReduceSum found but not in node_to_gptr map");
+ } else {
+ LOG_WARN(" No ReduceSum found after Multiply (unexpected for decoding stage)");
+ }
+ }
+
+ return false;
+ };
+
+ register_matcher(std::make_shared<opp::Matcher>(output_multiply, "TagGPTOSSExpert"), std::move(callback));
+}
+
+/*
+ GPT-OSS Router Pattern:
+
+ 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
+*/
+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)
+ 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});
+
+ // Pattern root
+ auto slice = opp::wrap_type<ov::op::v8::Slice>(
+ {softmax, opp::any_input(), shapeof_topk, opp::any_input(), opp::any_input()});
+
+ auto node_to_gptr = snapshot->getNodeToGroupMap();
+
+ auto callback = [=](ov::pass::pattern::Matcher& m) {
+ auto& node_to_output = m.get_pattern_value_map();
+
+ // Validate TopK mode (MAX) and Router keywords
+ auto matched_topk = node_to_output.at(topk).get_node_shared_ptr();
+ auto topk_node = std::dynamic_pointer_cast<ov::op::v11::TopK>(matched_topk);
+ if (!topk_node || topk_node->get_mode() != ov::op::v11::TopK::Mode::MAX) {
+ return false;
+ }
+
+ std::string topk_name = matched_topk->get_friendly_name();
+ // Check if node name contains MoE router/expert patterns
+ bool is_router = (topk_name.find(MLP_ROUTER_NAME) != std::string::npos ||
+ topk_name.find(MLP_EXPERT_NAME) != std::string::npos);
+ if (!is_router) {
+ return false;
+ }
+
+ LOG_DEBUG("GPT-OSS Router pattern matched: " << topk_name);
+
+ // Get pattern-matched nodes
+ auto matched_weights_multiply = node_to_output.at(weights_multiply).get_node_shared_ptr();
+ auto matched_weights_convert2 = node_to_output.at(weights_convert2).get_node_shared_ptr();
+ auto matched_matmul = node_to_output.at(matmul).get_node_shared_ptr();
+ auto matched_add = node_to_output.at(add).get_node_shared_ptr();
+ auto matched_softmax = node_to_output.at(softmax).get_node_shared_ptr();
+ 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();
+
+ // Manual retrieval (7 nodes): helper function
+ auto find_consumer_by_type =
+ [](const std::shared_ptr<ov::Node>& node,
+ const std::function<bool(const std::shared_ptr<ov::Node>&)>& pred) -> std::shared_ptr<ov::Node> {
+ for (auto& output : node->outputs()) {
+ for (auto& input : output.get_target_inputs()) {
+ auto consumer = input.get_node()->shared_from_this();
+ if (pred(consumer)) {
+ return consumer;
+ }
+ }
+ }
+ return nullptr;
+ };
+
+ auto matched_scatter = find_consumer_by_type(matched_slice, [](const std::shared_ptr<ov::Node>& n) {
+ return std::dynamic_pointer_cast<ov::op::v3::ScatterElementsUpdate>(n) ||
+ std::dynamic_pointer_cast<ov::op::v12::ScatterElementsUpdate>(n);
+ });
+ if (!matched_scatter) {
+ LOG_DEBUG("Router pattern: ScatterElementsUpdate not found");
+ return false;
+ }
+
+ // Retrieve Broadcast and ShapeOf
+ auto broadcast_node = matched_scatter->input_value(0).get_node_shared_ptr();
+ auto matched_broadcast = std::dynamic_pointer_cast<ov::op::v3::Broadcast>(broadcast_node);
+ if (!matched_broadcast) {
+ LOG_DEBUG("Router pattern: Broadcast not found");
+ return 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;
+ });
+ if (!matched_transpose) {
+ LOG_DEBUG("Router pattern: Transpose not found");
+ return false;
+ }
+
+ auto matched_reshape = find_consumer_by_type(matched_transpose, [](const std::shared_ptr<ov::Node>& n) {
+ return std::dynamic_pointer_cast<ov::op::v1::Reshape>(n) != nullptr;
+ });
+ if (!matched_reshape) {
+ LOG_DEBUG("Router pattern: Reshape not found");
+ return false;
+ }
+
+ auto matched_unsqueeze = find_consumer_by_type(matched_reshape, [](const std::shared_ptr<ov::Node>& n) {
+ return std::dynamic_pointer_cast<ov::op::v0::Unsqueeze>(n) != nullptr;
+ });
+ if (!matched_unsqueeze) {
+ LOG_DEBUG("Router pattern: Unsqueeze not found");
+ return false;
+ }
+
+ // Isolate all 16 nodes
+ auto isolate_if_exists = [&](const std::shared_ptr<ov::Node>& node) {
+ if (node && node_to_gptr->count(node)) {
+ node_to_gptr->at(node)->isolate(isol_tag);
+ }
+ };
+
+ isolate_if_exists(matched_weights_multiply);
+ isolate_if_exists(matched_weights_convert2);
+ isolate_if_exists(matched_matmul);
+ isolate_if_exists(matched_add);
+ isolate_if_exists(matched_topk);
+ isolate_if_exists(matched_softmax);
+ isolate_if_exists(matched_topk_convert);
+ isolate_if_exists(matched_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);
+ isolate_if_exists(matched_reshape);
+ isolate_if_exists(matched_unsqueeze);
+
+ LOG_DEBUG("Router pattern isolated");
+ return false;
+ };
+
+ register_matcher(std::make_shared<opp::Matcher>(slice, "TagGPTOSSRouter"), std::move(callback));
+}
+
+} // namespace moe
+} // namespace patterns
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hpp
new file mode 100644
index 00000000000..91d1bfb104c
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hpp
@@ -0,0 +1,44 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <string>
+
+#include "../online/group.hpp" // online::Group
+#include "../online/snapshot.hpp" // online::Snapshot
+#include "openvino/openvino.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+
+namespace ov {
+namespace npuw {
+
+namespace patterns {
+namespace moe {
+
+// MoE pattern matching keywords
+constexpr const char* ROUTER_TAG = "router";
+constexpr const char* EXPERT_TAG = "expert";
+
+// MoE layer name patterns for model detection
+constexpr const char* MLP_ROUTER_NAME = ".mlp.router";
+constexpr const char* MLP_EXPERT_NAME = ".mlp.expert";
+
+class GPTOSSExpert : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::moe::GPTOSSExpert");
+ GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);
+};
+
+class GPTOSSRouter : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::moe::GPTOSSRouter");
+ GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);
+};
+
+} // namespace moe
+} // namespace patterns
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
index c3073e7eb9b..0e90cbfb2a4 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
@@ -10,6 +10,7 @@
#include "intel_npu/config/npuw.hpp"
#include "lazy_tensor.hpp"
#include "logging.hpp"
+#include "moe_transformations/moe_transformation.hpp"
#include "openvino/core/rt_info/weightless_caching_attributes.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/util/op_types.hpp"
@@ -167,6 +168,46 @@ void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::HostF
// They are handled separately in CompiledModelDesc::serialize()
}
+void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::MoEExperts& var) {
+ using ov::npuw::s11n::write;
+
+ // Serialize basic MoE metadata
+ write(stream, var.num_experts);
+ write(stream, var.expert_hidden_dim);
+ write(stream, var.num_active_experts);
+ write(stream, var.input_token_count);
+
+ // Serialize router scores index
+ write(stream, var._router_scores_idx.has_value());
+ if (var._router_scores_idx.has_value()) {
+ write(stream, var._router_scores_idx.value());
+ }
+
+ // Serialize expert input parameter index
+ write(stream, var._expert_input_param_idx.has_value());
+ if (var._expert_input_param_idx.has_value()) {
+ write(stream, var._expert_input_param_idx.value());
+ }
+
+ // Serialize parameter mapping
+ write(stream, var._param_mapping);
+
+ // Note: _compiled_models and _models_to_compile are not serialized here
+ // They are handled separately in CompiledModelDesc::serialize()
+}
+
+void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::MoEDownstream& var) {
+ using ov::npuw::s11n::write;
+
+ // Serialize MoE downstream metadata
+ write(stream, var.total_experts_num);
+ write(stream, var.active_experts_num);
+ write(stream, var.expert_output_param_idx);
+
+ // Note: _compiled_model and _model_to_compile are not serialized here
+ // They are handled separately in CompiledModelDesc::serialize()
+}
+
void ov::npuw::s11n::write(std::ostream& stream, const ov::Tensor& var) {
using ov::npuw::s11n::write;
@@ -352,6 +393,52 @@ void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::HostFlashAtt
// They are handled separately in CompiledModelDesc::deserialize()
}
+void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::MoEExperts& var) {
+ using ov::npuw::s11n::read;
+
+ // Deserialize basic MoE metadata
+ read(stream, var.num_experts);
+ read(stream, var.expert_hidden_dim);
+ read(stream, var.num_active_experts);
+ read(stream, var.input_token_count);
+
+ // Deserialize router scores index
+ bool has_router_scores_idx = false;
+ read(stream, has_router_scores_idx);
+ if (has_router_scores_idx) {
+ size_t value = 0;
+ read(stream, value);
+ var._router_scores_idx = value;
+ }
+
+ // Deserialize expert input parameter index
+ bool has_expert_input_param_idx = false;
+ read(stream, has_expert_input_param_idx);
+ if (has_expert_input_param_idx) {
+ size_t value = 0;
+ read(stream, value);
+ var._expert_input_param_idx = value;
+ }
+
+ // Deserialize parameter mapping
+ read(stream, var._param_mapping);
+
+ // Note: _compiled_models and _models_to_compile are not deserialized here
+ // They are handled separately in CompiledModelDesc::deserialize()
+}
+
+void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::MoEDownstream& var) {
+ using ov::npuw::s11n::read;
+
+ // Deserialize MoE downstream metadata
+ read(stream, var.total_experts_num);
+ read(stream, var.active_experts_num);
+ read(stream, var.expert_output_param_idx);
+
+ // Note: _compiled_model and _model_to_compile are not deserialized here
+ // They are handled separately in CompiledModelDesc::deserialize()
+}
+
void ov::npuw::s11n::read(std::istream& stream, ov::Tensor& var) {
bool is_initialized = false;
read(stream, is_initialized);
diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
index 28fcea5b34f..d9151298f6e 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
@@ -36,7 +36,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.18";
+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.19";
// Forward declaration
namespace intel_npu {
@@ -82,6 +82,8 @@ struct Spatial;
struct Attention;
struct PyramidAttention;
struct HostFlashAttention;
+struct MoEExperts;
+struct MoEDownstream;
} // namespace compiled
namespace weights {
class LazyTensor;
@@ -180,6 +182,8 @@ void write(std::ostream& stream, const ov::npuw::compiled::Spatial& var);
void write(std::ostream& stream, const ov::npuw::compiled::Attention& var);
void write(std::ostream& stream, const ov::npuw::compiled::PyramidAttention& var);
void write(std::ostream& stream, const ov::npuw::compiled::HostFlashAttention& var);
+void write(std::ostream& stream, const ov::npuw::compiled::MoEExperts& var);
+void write(std::ostream& stream, const ov::npuw::compiled::MoEDownstream& var);
void write(std::ostream& stream, const ov::Tensor& var);
void write(std::ostream& stream, const ::intel_npu::Config& var);
void write(std::ostream& stream, const ov::Output<const ov::Node>& var);
@@ -198,6 +202,8 @@ void read(std::istream& stream, ov::npuw::compiled::Spatial& var);
void read(std::istream& stream, ov::npuw::compiled::Attention& var);
void read(std::istream& stream, ov::npuw::compiled::PyramidAttention& var);
void read(std::istream& stream, ov::npuw::compiled::HostFlashAttention& var);
+void read(std::istream& stream, ov::npuw::compiled::MoEExperts& var);
+void read(std::istream& stream, ov::npuw::compiled::MoEDownstream& var);
void read(std::istream& stream, ov::Tensor& var);
void read(std::istream& stream, ::intel_npu::Config& var);
void read(std::istream& stream, std::shared_ptr<ov::op::v0::Parameter>& var);
diff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
index a22d1ce6c9f..1a54655dfba 100644
--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
@@ -388,6 +388,8 @@ void Plugin::init_options() {
REGISTER_OPTION(NPUW_LLM_MIN_RESPONSE_LEN);
REGISTER_OPTION(NPUW_LLM_OPTIMIZE_V_TENSORS);
REGISTER_OPTION(NPUW_LLM_CACHE_ROPE);
+ REGISTER_OPTION(NPUW_LLM_PREFILL_MOE_HINT);
+ REGISTER_OPTION(NPUW_LLM_GENERATE_MOE_HINT);
REGISTER_OPTION(NPUW_LLM_GENERATE_PYRAMID);
REGISTER_OPTION(NPUW_LLM_PREFILL_CHUNK_SIZE);
REGISTER_OPTION(NPUW_LLM_SHARED_HEAD);
diff --git a/src/plugins/intel_npu/src/plugin/src/properties.cpp b/src/plugins/intel_npu/src/plugin/src/properties.cpp
index 89da3db7b37..25f65bd1cd0 100644
--- a/src/plugins/intel_npu/src/plugin/src/properties.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/properties.cpp
@@ -467,6 +467,8 @@ void Properties::registerPluginProperties() {
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::min_response_len, NPUW_LLM_MIN_RESPONSE_LEN);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::optimize_v_tensors, NPUW_LLM_OPTIMIZE_V_TENSORS);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::cache_rope, NPUW_LLM_CACHE_ROPE);
+ TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::prefill_moe_hint, NPUW_LLM_PREFILL_MOE_HINT);
+ TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::generate_moe_hint, NPUW_LLM_GENERATE_MOE_HINT);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::generate_pyramid, NPUW_LLM_GENERATE_PYRAMID);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::prefill_chunk_size, NPUW_LLM_PREFILL_CHUNK_SIZE);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::shared_lm_head, NPUW_LLM_SHARED_HEAD);
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index 3f33d655379..67d204adca0 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -43,6 +43,8 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/attention.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.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_unroll_patterns.cpp
LINK_LIBRARIES
${MANDATORY_UNIT_TESTS_LIBS}
LABELS
diff --git a/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cpp
new file mode 100644
index 00000000000..1321f5809cd
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cpp
@@ -0,0 +1,261 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_transformations/moe_transformation.hpp"
+
+#include <gtest/gtest.h>
+
+#include <common_test_utils/test_common.hpp>
+
+#include "openvino/op/ops.hpp"
+#include "openvino/pass/serialize.hpp"
+
+/*
+ * Test suite for MoE Expert Transformation
+ *
+ * Testing Strategy:
+ * - ExpertBatchMode: Tests transformation for batch mode (N=8 total experts, K=4 active, token=1)
+ * - ExpertIterativeMode: Tests transformation for iterative mode (N=8 total experts, K=1 active, token=16, chunk=8)
+ */
+
+// Uncomment to save debug XML files during test execution
+// #define SAVE_TEST_MODELS
+
+namespace {
+
+using namespace ov;
+using namespace ov::npuw::function;
+
+// ============================================================================
+// Test Utilities
+// ============================================================================
+
+class MoETransformationTest : public ::testing::Test {
+protected:
+ void SetUp() override {
+ // Common setup for all tests
+ }
+
+ void TearDown() override {
+ // Common cleanup
+ }
+
+ // Helper: Save model to XML for debugging
+ void save_model(const std::shared_ptr<Model>& model, const std::string& prefix) {
+#ifdef SAVE_TEST_MODELS
+ std::string xml_path = prefix + ".xml";
+ std::string bin_path = prefix + ".bin";
+ ov::pass::Serialize serialize_pass(xml_path, bin_path);
+ serialize_pass.run_on_model(const_cast<std::shared_ptr<Model>&>(model));
+#endif
+ }
+};
+
+// ============================================================================
+// Synthetic Test Graph Builders
+// ============================================================================
+
+// Create MoE graph with complete structure required by apply_expert_transformation
+// Pattern: Parameter -> Tile -> Reshape -> MatMul -> Add -> Reshape -> Multiply -> Result
+std::shared_ptr<Model> create_transformable_moe_graph(size_t num_experts,
+ size_t hidden_dim = 2880,
+ size_t token_count = 1) {
+ ov::ParameterVector params;
+
+ // 1. Expert input: [token_count, hidden_dim]
+ auto expert_input = std::make_shared<op::v0::Parameter>(element::f32, Shape{token_count, hidden_dim});
+ expert_input->set_friendly_name("expert_input");
+ params.push_back(expert_input);
+
+ // 2. Tile to replicate for experts: [token_count, hidden_dim] -> [num_experts*token_count, hidden_dim]
+ auto repeats =
+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{static_cast<int64_t>(num_experts), 1});
+ auto tile = std::make_shared<op::v0::Tile>(expert_input, repeats);
+ tile->set_friendly_name("expert_tile");
+
+ // 3. Reshape to 3D: [num_experts, token_count, hidden_dim]
+ auto reshape_shape = op::v0::Constant::create(element::i64,
+ Shape{3},
+ std::vector<int64_t>{static_cast<int64_t>(num_experts),
+ static_cast<int64_t>(token_count),
+ static_cast<int64_t>(hidden_dim)});
+ auto reshape_in = std::make_shared<op::v1::Reshape>(tile, reshape_shape, false);
+ reshape_in->set_friendly_name("expert_reshape_in");
+
+ // 4. Expert weights with quantization pattern (NF4 -> FP16 -> Multiply with scale -> FP32)
+ // Weight parameter: [num_experts, hidden_dim*2, hidden_dim] (NF4)
+ auto weights_nf4 =
+ std::make_shared<op::v0::Parameter>(element::nf4, Shape{num_experts, hidden_dim * 2, hidden_dim});
+ weights_nf4->set_friendly_name("expert_weights_nf4");
+ params.push_back(weights_nf4);
+
+ // Convert NF4 to FP16
+ auto weights_fp16 = std::make_shared<op::v0::Convert>(weights_nf4, element::f16);
+ weights_fp16->set_friendly_name("expert_weights_convert_fp16");
+
+ // Scale parameter: [num_experts, hidden_dim*2, 1] (FP16)
+ auto weights_scale = std::make_shared<op::v0::Parameter>(element::f16, Shape{num_experts, hidden_dim * 2, 1});
+ weights_scale->set_friendly_name("expert_weights_scale");
+ params.push_back(weights_scale);
+
+ // Multiply with scale (dequantization)
+ auto weights_scaled = std::make_shared<op::v1::Multiply>(weights_fp16, weights_scale);
+ weights_scaled->set_friendly_name("expert_weights_scaled");
+
+ // Convert FP16 to FP32 for MatMul
+ auto weights_fp32 = std::make_shared<op::v0::Convert>(weights_scaled, element::f32);
+ weights_fp32->set_friendly_name("expert_weights_convert_fp32");
+
+ // 5. MatMul
+ auto matmul = std::make_shared<op::v0::MatMul>(reshape_in, weights_fp32, false, true); // transpose_b=true
+ matmul->set_friendly_name("expert_matmul");
+
+ // 6. Biases: [num_experts, 1, hidden_dim*2]
+ auto biases = std::make_shared<op::v0::Parameter>(element::f32, Shape{num_experts, 1, hidden_dim * 2});
+ biases->set_friendly_name("expert_biases");
+ params.push_back(biases);
+
+ // 7. Add bias
+ auto add = std::make_shared<op::v1::Add>(matmul, biases);
+ add->set_friendly_name("expert_add");
+
+ // 8. Reshape output: [num_experts, token_count, hidden_dim*2]
+ auto reshape_out_shape = op::v0::Constant::create(element::i64,
+ Shape{3},
+ std::vector<int64_t>{static_cast<int64_t>(num_experts),
+ static_cast<int64_t>(token_count),
+ static_cast<int64_t>(hidden_dim * 2)});
+ auto reshape_out = std::make_shared<op::v1::Reshape>(add, reshape_out_shape, false);
+ reshape_out->set_friendly_name("expert_reshape_out");
+
+ // 9. Router scores: [num_experts, token_count, 1]
+ auto router_scores = std::make_shared<op::v0::Parameter>(element::f32, Shape{num_experts, token_count, 1});
+ router_scores->set_friendly_name("router_scores");
+ params.push_back(router_scores);
+
+ // 10. Multiply with router scores (REQUIRED by apply_expert_transformation)
+ auto multiply = std::make_shared<op::v1::Multiply>(reshape_out, router_scores);
+ multiply->set_friendly_name("router_multiply");
+
+ // 11. Result
+ auto result = std::make_shared<op::v0::Result>(multiply);
+ result->set_friendly_name("output");
+
+ auto model = std::make_shared<Model>(ResultVector{result}, params);
+ model->set_friendly_name("moe_" + std::to_string(num_experts) + "_experts");
+
+ return model;
+}
+
+// ============================================================================
+// Unit Tests - MoE Expert Transformation
+// ============================================================================
+
+// Test expert batch mode: N total experts, K active experts (K < N), token_count = 1
+TEST_F(MoETransformationTest, ExpertBatchMode) {
+ constexpr size_t num_total_experts = 8;
+ constexpr size_t num_active_experts = 4;
+ constexpr size_t hidden_dim = 2880;
+ constexpr size_t token_count = 1; // EXPERT_BATCH: single token
+
+ auto model = create_transformable_moe_graph(num_total_experts, hidden_dim, token_count);
+ save_model(model, "moe_expert_batch_before");
+
+ auto structure_info = analyze_moe_structure(model);
+ ASSERT_TRUE(structure_info.has_value()) << "Failed to analyze MoE structure";
+ EXPECT_EQ(structure_info->num_experts, num_total_experts);
+ EXPECT_EQ(structure_info->input_token_count, token_count);
+ EXPECT_TRUE(structure_info->is_expert_batch_mode());
+
+ // Transform to K active experts for batch mode
+ MoETransformConfig config;
+ config.num_target_experts = num_active_experts;
+ config.chunk_size = 0;
+
+ MoEModelTransformer transformer(*structure_info);
+ auto transformed = transformer.apply_expert_transformation(model, config);
+
+ ASSERT_NE(transformed, nullptr) << "Expert batch mode transformation failed";
+ EXPECT_NO_THROW(transformed->validate_nodes_and_infer_types());
+
+ save_model(transformed, "moe_expert_batch_after");
+
+ // Expert batch mode with K>1: expect unrolling, more nodes created
+ EXPECT_GT(transformed->get_ordered_ops().size(), model->get_ordered_ops().size())
+ << "Expected node count increase after unrolling " << num_active_experts << " experts";
+
+ // After unrolling, parameters are duplicated for each active expert
+ EXPECT_GT(transformed->get_parameters().size(), model->get_parameters().size())
+ << "Expected parameter count increase after unrolling";
+
+ // Result count should remain the same
+ EXPECT_EQ(transformed->get_results().size(), model->get_results().size());
+
+ // Verify output shape: [num_active_experts, token_count, hidden_dim*2]
+ // After batch mode transformation, expert dimension should be num_active_experts and token dimension should be 1
+ auto result = transformed->get_results()[0];
+ auto output_shape = result->get_input_partial_shape(0);
+ ASSERT_TRUE(output_shape.is_static()) << "Output shape should be static";
+
+ auto shape = output_shape.to_shape();
+ EXPECT_EQ(shape.size(), 3) << "Output should be 3D tensor";
+ EXPECT_EQ(shape[0], num_active_experts)
+ << "Expert dimension should be " << num_active_experts << " after batch mode transformation";
+ EXPECT_EQ(shape[1], token_count) << "Token dimension should be 1 for batch mode";
+ EXPECT_EQ(shape[2], hidden_dim * 2) << "Hidden dimension should remain unchanged";
+}
+
+// Test expert iterative mode: N total experts, 1 active expert, token_count > 1
+TEST_F(MoETransformationTest, ExpertIterativeMode) {
+ constexpr size_t num_total_experts = 8;
+ constexpr size_t num_active_experts = 1;
+ constexpr size_t hidden_dim = 2880;
+ constexpr size_t token_count = 16; // EXPERT_ITERATIVE: multiple tokens
+ constexpr size_t chunk_size = 8;
+
+ auto model = create_transformable_moe_graph(num_total_experts, hidden_dim, token_count);
+ save_model(model, "moe_expert_iterative_before");
+
+ auto structure_info = analyze_moe_structure(model);
+ ASSERT_TRUE(structure_info.has_value()) << "Failed to analyze MoE structure";
+ EXPECT_EQ(structure_info->num_experts, num_total_experts);
+ EXPECT_EQ(structure_info->input_token_count, token_count);
+ EXPECT_FALSE(structure_info->is_expert_batch_mode());
+
+ // Transform to single expert with chunking for iterative mode
+ MoETransformConfig config;
+ config.num_target_experts = num_active_experts;
+ config.chunk_size = chunk_size;
+
+ MoEModelTransformer transformer(*structure_info);
+ auto transformed = transformer.apply_expert_transformation(model, config);
+
+ ASSERT_NE(transformed, nullptr) << "Expert iterative mode transformation failed";
+ EXPECT_NO_THROW(transformed->validate_nodes_and_infer_types());
+
+ save_model(transformed, "moe_expert_iterative_after");
+
+ // Iterative mode with single expert: no unrolling happens (num_target_experts=1)
+ // Tile is replaced with Reshape, token count is adjusted to chunk size
+ // Parameters count preserved (no unrolling for single expert)
+ EXPECT_EQ(transformed->get_parameters().size(), model->get_parameters().size())
+ << "Expected parameter count to stay the same (no unrolling for single expert)";
+
+ // Result count should remain the same
+ EXPECT_EQ(transformed->get_results().size(), model->get_results().size());
+
+ // Verify output shape: [num_target_experts, chunk_size, hidden_dim*2]
+ // After iterative mode transformation, expert dimension should be 1 and token dimension should be chunk_size
+ auto result = transformed->get_results()[0];
+ auto output_shape = result->get_input_partial_shape(0);
+ ASSERT_TRUE(output_shape.is_static()) << "Output shape should be static";
+
+ auto shape = output_shape.to_shape();
+ EXPECT_EQ(shape.size(), 3) << "Output should be 3D tensor";
+ EXPECT_EQ(shape[0], num_active_experts) << "Expert dimension should be 1 after iterative mode transformation";
+ EXPECT_EQ(shape[1], chunk_size) << "Token dimension should be chunk_size after iterative mode transformation";
+ EXPECT_EQ(shape[2], hidden_dim * 2) << "Hidden dimension should remain unchanged";
+}
+
+} // namespace