Skip to content

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

NPUW: Transition MoE to the new subgraph handling (#35603)

Dmitry Matveev4dc0db6f92d8
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 9e5df682d7b..4c9130596b5 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
@@ -14,6 +14,7 @@
#include "intel_npu/utils/zero/zero_remote_tensor.hpp"
#include "intel_npu/utils/zero/zero_utils.hpp"
#include "logging.hpp"
+#include "moe/moe_subgraph.hpp"
#include "openvino/core/parallel.hpp"
#include "util.hpp"
@@ -326,7 +327,7 @@ void ov::npuw::IBaseInferRequest::unpack_closure(std::size_t idx, RqPtr request)
// 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()) {
+ if (ov::npuw::moe::has_compiled_experts(func_desc.pipeline)) {
return;
}
@@ -417,7 +418,7 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ
const auto& proto_comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];
- if (proto_comp_model_desc.moe_experts.has_value()) {
+ if (ov::npuw::moe::has_compiled_experts(proto_comp_model_desc.pipeline)) {
// Expert submodel does not have global parameters to bind
return;
}
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 15a478dc97d..bd6f2f12037 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
@@ -12,6 +12,7 @@
#include "intel_npu/npu_private_properties.hpp"
#include "just_sync_infer_request.hpp"
#include "logging.hpp"
+#include "moe/moe_subgraph.hpp"
#include "openvino/core/parallel.hpp"
#include "openvino/op/util/op_types.hpp"
#include "openvino/pass/constant_folding.hpp"
@@ -116,6 +117,7 @@ std::set<std::string> device_list_to_set(const std::string& device_list) {
namespace ov {
namespace npuw {
+
namespace {
ov::npuw::DeviceProperties get_properties_per_device(const std::shared_ptr<const ov::IPlugin>& plugin,
const std::string& device_priorities,
@@ -288,10 +290,20 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
// Store original constants' offset for serialization purposes
store_const_offsets(model);
+ std::optional<ov::npuw::v1::subgraphs::PatternRegistry> combined_subgraph_patterns;
+ std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> builtin_pattern_registrations;
+ combined_subgraph_patterns.emplace();
+ if (subgraph_patterns != nullptr) {
+ combined_subgraph_patterns->append_from(*subgraph_patterns);
+ }
+ builtin_pattern_registrations =
+ ov::npuw::moe::register_patterns(*combined_subgraph_patterns,
+ m_cfg.get<::intel_npu::NPUW_MOE_TOKEN_CHUNK_SIZE>());
+
ov::npuw::PartitioningContext ctx;
// Identify based on compiler version, user config and pattern
ctx.use_host_gather_quant = should_use_quantized_host_gather(model, npuw_props);
- ctx.subgraph_patterns = subgraph_patterns;
+ ctx.subgraph_patterns = &combined_subgraph_patterns.value();
ov::npuw::Partitioning partitioning;
m_profile["partitioning"].record([&]() {
@@ -471,24 +483,6 @@ 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_for_success)
- 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
@@ -541,8 +535,9 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& 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) {
+ if (const auto* moe_experts =
+ ov::npuw::moe::get_compiled_experts(m_compiled_submodels[real_id].pipeline.context)) {
+ for (const auto& [chunk_size, model] : moe_experts->_models_to_compile) {
fix_tensor_names(model);
}
}
@@ -810,74 +805,7 @@ void ov::npuw::CompiledModel::CompiledModelDesc::serialize(ov::npuw::s11n::Strea
}
}
- stream & moe_experts;
- if (moe_experts.has_value()) {
- size_t num_compiled_models = 0;
- if (stream.output()) {
- num_compiled_models = moe_experts.value()._compiled_models.size();
- }
- stream & num_compiled_models;
-
- if (stream.output()) {
- for (const auto& [chunk_size, compiled_model] : moe_experts.value()._compiled_models) {
- stream & chunk_size;
- bool has_model = compiled_model != nullptr;
- stream & has_model;
- if (has_model) {
- std::stringstream ss;
- compiled_model->export_model(ss);
- std::string model_str = ss.str();
- stream & model_str;
- }
- }
- } else {
- NPUW_ASSERT(submodel_ctx != nullptr);
- for (size_t i = 0; i < num_compiled_models; ++i) {
- size_t chunk_size = 0;
- stream & chunk_size;
- bool has_model = false;
- stream & has_model;
- if (has_model) {
- std::string model_str;
- stream & model_str;
- std::stringstream ss(model_str);
- moe_experts->_compiled_models[chunk_size] =
- submodel_ctx->plugin->get_core()->import_model(ss,
- submodel_ctx->device,
- submodel_ctx->import_config);
- LOG_DEBUG("Imported MoE compiled model for chunk_size=" << chunk_size);
- }
- }
- LOG_DEBUG("Deserialized " << moe_experts->_compiled_models.size() << " MoE expert models");
- }
- }
-
- stream & moe_experts_downstream;
- if (moe_experts_downstream.has_value()) {
- bool has_model = false;
- if (stream.output()) {
- has_model = moe_experts_downstream.value()._compiled_model != nullptr;
- }
- stream & has_model;
- if (has_model) {
- if (stream.output()) {
- std::stringstream ss;
- moe_experts_downstream.value()._compiled_model->export_model(ss);
- std::string model_str = ss.str();
- stream & model_str;
- } else {
- NPUW_ASSERT(submodel_ctx != nullptr);
- std::string model_str;
- stream & model_str;
- std::stringstream ss(model_str);
- moe_experts_downstream->_compiled_model =
- submodel_ctx->plugin->get_core()->import_model(ss,
- submodel_ctx->device,
- submodel_ctx->import_config);
- LOG_DEBUG("Imported MoE downstream compiled model");
- }
- }
- }
+ ov::npuw::moe::serialize_compiled_state(pipeline.context, stream, submodel_ctx);
stream & host_flash_attention;
if (host_flash_attention.has_value()) {
@@ -1834,36 +1762,13 @@ bool ov::npuw::CompiledModel::compile_for_success(std::size_t id, const std::vec
return main_cm;
};
- if (auto& moe_experts_opt = desc.moe_experts; moe_experts_opt.has_value()) {
- LOG_INFO("Compiling MoE expert models for Subgraph[" << id << "]...");
- LOG_BLOCK();
-
- auto& moe_experts = moe_experts_opt.value();
- LOG_INFO("Total MoE models to compile: " << moe_experts._models_to_compile.size());
-
- for (const auto& entry : moe_experts._models_to_compile) {
- LOG_INFO("Compiling MoE expert model for chunk_size=" << entry.first);
- moe_experts.set_compiled_model(
- entry.first,
- make_wrapped(entry.second, "/moe_chunk_" + std::to_string(entry.first), devices));
- LOG_INFO("Successfully compiled MoE expert model for chunk_size=" << entry.first);
- }
-
- const auto& compiled_models = moe_experts._compiled_models;
- OPENVINO_ASSERT(!compiled_models.empty(), "Expected at least one compiled MoE expert model");
- desc.compiled_model = compiled_models.begin()->second;
- LOG_INFO("MoE expert compilation complete for Subgraph[" << id << "]");
+ if (desc.pipeline.compile_executor) {
+ ov::npuw::v1::subgraphs::CompileContext compile_context{desc.model, desc.compiled_model, devices, make_wrapped};
+ desc.pipeline.compile_executor(compile_context);
} else {
desc.compiled_model = make_wrapped(desc.model, "", main_candidates);
}
- if (auto& moe_downstream_opt = desc.moe_experts_downstream; moe_downstream_opt.has_value()) {
- LOG_INFO("Wrapping compiled model into MoE downstream for Subgraph[" << id << "]...");
- OPENVINO_ASSERT(desc.compiled_model, "Expected compiled model before wrapping MoE downstream");
- moe_downstream_opt->set_compiled_model(std::move(desc.compiled_model));
- desc.compiled_model = moe_downstream_opt->_compiled_model;
- }
-
if (desc.pyramid_attention.has_value()) {
LOG_INFO("Compiling pyramid attention submodels for Subgraph[" << id << "]...");
LOG_BLOCK();
@@ -2006,9 +1911,9 @@ void ov::npuw::CompiledModel::dump_subgraph_model(std::size_t id,
const std::string dump_dir = m_cfg.get<::intel_npu::NPUW_DUMP_SUBS_DIR>();
// Dump MoE expert models if present
- if (m_compiled_submodels[id].moe_experts) {
+ if (const auto* moe_experts = ov::npuw::moe::get_compiled_experts(m_compiled_submodels[id].pipeline.context)) {
LOG_INFO("NOTE: Subgraph[" << id << "] has MoE experts mechanism.");
- const auto& moe_models = m_compiled_submodels[id].moe_experts.value()._models_to_compile;
+ const auto& moe_models = moe_experts->_models_to_compile;
if (moe_models.empty()) {
LOG_WARN("MoE experts models are empty (already compiled and cleared)");
@@ -2099,8 +2004,9 @@ void ov::npuw::CompiledModel::dump_subgraph_composition(const std::vector<ov::np
std::string base_name = format_subgraph_name(real_id, funcall);
subgraph_info.emplace_back(base_name, count);
- if (m_compiled_submodels[real_id].moe_experts) {
- const auto& moe_models = m_compiled_submodels[real_id].moe_experts.value()._models_to_compile;
+ if (const auto* moe_experts =
+ ov::npuw::moe::get_compiled_experts(m_compiled_submodels[real_id].pipeline.context)) {
+ const auto& moe_models = moe_experts->_models_to_compile;
if (!moe_models.empty()) {
for (const auto& [chunk_size, model] : moe_models) {
moe_subgraphs.push_back(base_name + "_moe_chunk_" + std::to_string(chunk_size) + ".xml");
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 7c9e9712eb7..e66c3c2d918 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
@@ -71,6 +71,10 @@ public:
// Forward declarations
class InferRequest;
+namespace v1::subgraphs {
+class Context;
+}
+
namespace moe {
class MoEExecutor;
}
@@ -229,8 +233,6 @@ 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;
ov::npuw::v1::subgraphs::CompiledPipeline pipeline;
// Infer requests for pyramid attention models (if pyramid_attention is present)
@@ -255,7 +257,7 @@ 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)
+ // Infer requests for MoE expert models with different chunk sizes (if MoE expert state is present)
// Map: chunk_size -> infer_request
std::map<size_t, ov::SoPtr<ov::IAsyncInferRequest>> moe_infer_requests;
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 a378ac4fa47..21ccf7ef489 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
@@ -14,6 +14,7 @@
#include "host_flash_attention.hpp"
#include "infer_request_utils.hpp" // to utilize copy_tensor_by_dim
#include "logging.hpp"
+#include "moe/moe_subgraph.hpp"
#include "openvino/core/except.hpp"
#include "openvino/core/parallel.hpp"
#include "openvino/runtime/iasync_infer_request.hpp"
@@ -342,7 +343,7 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
} // if(hfa)
// Initialize the MoE IO placeholders, if required
- if (proto_comp_model_desc.moe_experts) {
+ if (ov::npuw::moe::has_compiled_experts(proto_comp_model_desc.pipeline)) {
// 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");
@@ -526,17 +527,17 @@ void ov::npuw::JustInferRequest::initialize_subgraph_behaviors() {
if (!comp_model_desc.compiled_model && !comp_model_desc.replaced_by) {
continue;
}
- if (!comp_model_desc.pipeline.runtime_behavior.has_value()) {
+ const auto* spec = get_runtime_behavior_spec(idx);
+ if (spec == nullptr) {
continue;
}
- const auto& spec = comp_model_desc.pipeline.runtime_behavior.value();
- if (spec.factory) {
- m_subgraph_behaviors[idx] = spec.factory(spec.context);
+ if (spec->factory) {
+ m_subgraph_behaviors[idx] = spec->factory(spec->context);
}
if (m_subgraph_behaviors[idx]) {
continue;
}
- const auto* post_legacy_hook = spec.context.get_if<ov::npuw::v1::subgraphs::PostLegacyHook>();
+ const auto* post_legacy_hook = spec->context.get_if<ov::npuw::v1::subgraphs::PostLegacyHook>();
if (!post_legacy_hook) {
continue;
}
@@ -550,9 +551,38 @@ void ov::npuw::JustInferRequest::initialize_subgraph_behaviors() {
ov::npuw::v1::subgraphs::InferContext ov::npuw::JustInferRequest::make_behavior_context(std::size_t real_idx,
std::size_t idx) {
- return ov::npuw::v1::subgraphs::InferContext{*m_npuw_model, *this, idx, real_idx, [this, real_idx, idx]() {
- legacy_infer(real_idx, idx);
- }};
+ const bool is_function_call = m_npuw_model->m_compiled_submodels[idx].replaced_by.has_value();
+ return ov::npuw::v1::subgraphs::InferContext{
+ *m_npuw_model,
+ *this,
+ idx,
+ real_idx,
+ [this, real_idx, idx]() {
+ legacy_infer(real_idx, idx);
+ },
+ is_function_call ? std::function<void()>{[this, idx]() {
+ OPENVINO_ASSERT(m_moe_executor != nullptr, "Expected MoE executor for opaque MoE prologue");
+ function_prologue(idx);
+ }}
+ : std::function<void()>{},
+ [this, real_idx, idx]() {
+ OPENVINO_ASSERT(m_moe_executor != nullptr, "Expected MoE executor for opaque MoE run");
+ m_moe_executor->run(real_idx, idx);
+ }};
+}
+
+const ov::npuw::v1::subgraphs::RuntimeBehaviorSpec* ov::npuw::JustInferRequest::get_runtime_behavior_spec(
+ std::size_t idx) const {
+ if (idx >= m_npuw_model->m_compiled_submodels.size()) {
+ return nullptr;
+ }
+ const auto& desc = m_npuw_model->m_compiled_submodels[idx];
+ const auto behavior_idx = desc.replaced_by.value_or(idx);
+ const auto& behavior_desc = m_npuw_model->m_compiled_submodels[behavior_idx];
+ if (!behavior_desc.pipeline.runtime_behavior.has_value()) {
+ return nullptr;
+ }
+ return &behavior_desc.pipeline.runtime_behavior.value();
}
ov::npuw::v1::subgraphs::ISubgraphBehavior* ov::npuw::JustInferRequest::get_subgraph_behavior(std::size_t idx) const {
@@ -562,6 +592,11 @@ ov::npuw::v1::subgraphs::ISubgraphBehavior* ov::npuw::JustInferRequest::get_subg
return m_subgraph_behaviors[idx].get();
}
+bool ov::npuw::JustInferRequest::behavior_handles_function_prologue(std::size_t idx) const {
+ const auto* spec = get_runtime_behavior_spec(idx);
+ return spec != nullptr && spec->handles_function_prologue;
+}
+
void ov::npuw::JustInferRequest::set_tensor(const ov::Output<const ov::Node>& port,
const ov::SoPtr<ov::ITensor>& tensor) {
std::unique_lock lock(m_io_storages_mutex);
@@ -779,7 +814,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();
+ const bool is_moe = ov::npuw::moe::has_compiled_state(func_desc.pipeline);
// Generalized: check if input is neither param nor mask
auto is_non_param_mask = [](const auto& info, std::size_t in_idx) {
@@ -882,7 +917,7 @@ 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 (func_desc.moe_experts) {
+ if (ov::npuw::moe::has_compiled_experts(func_desc.pipeline)) {
// MoE case - delegate to executor for output binding
m_moe_executor->function_prologue_moe_output(idx, i, o_tensor);
} else if (is_hfa) {
@@ -1087,7 +1122,7 @@ void ov::npuw::JustInferRequest::initialize_moe_executor() {
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()) {
+ if (ov::npuw::moe::has_compiled_experts(real_desc.pipeline)) {
m_moe_executor->prepare(i, real_idx, m_num_submodels, pool_size);
}
}
@@ -1308,7 +1343,7 @@ void ov::npuw::JustInferRequest::run_subrequest_for_success(std::size_t idx) {
// the subrequest' outputs to global Results, if relevant.
bind_global_results(idx);
- if (comp_model_desc.replaced_by) {
+ if (comp_model_desc.replaced_by && !behavior_handles_function_prologue(idx)) {
function_prologue(idx);
}
if (behavior != nullptr) {
@@ -1338,7 +1373,8 @@ void ov::npuw::JustInferRequest::run_subrequest_for_success(std::size_t idx) {
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() && !comp_model_desc.moe_experts) {
+ if (!comp_model_desc.spatial && !comp_model_desc.host_flash_attention.has_value() &&
+ !ov::npuw::moe::has_compiled_experts(comp_model_desc.pipeline)) {
// 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()
@@ -1816,9 +1852,6 @@ void ov::npuw::JustInferRequest::legacy_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 b37548ff484..69d7d4ff984 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
@@ -123,7 +123,9 @@ protected:
void run_hfa_tiled_inference(std::size_t real_idx, std::size_t idx);
void legacy_infer(std::size_t real_idx, std::size_t idx);
ov::npuw::v1::subgraphs::InferContext make_behavior_context(std::size_t real_idx, std::size_t idx);
+ const ov::npuw::v1::subgraphs::RuntimeBehaviorSpec* get_runtime_behavior_spec(std::size_t idx) const;
ov::npuw::v1::subgraphs::ISubgraphBehavior* get_subgraph_behavior(std::size_t idx) const;
+ bool behavior_handles_function_prologue(std::size_t idx) const;
// HFA helper functions
static void hfa_extract_and_copy_tile(const ov::SoPtr<ov::ITensor>& source_tensor,
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
index cfc46862cbc..8f0ad760bba 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp
@@ -31,24 +31,23 @@ void MoEExecutor::prepare(size_t idx, size_t real_idx, size_t num_sublayers, siz
const auto& desc =
*static_cast<const ov::npuw::CompiledModel::CompiledModelDesc*>(m_accessor.get_submodel_desc(real_idx));
- if (!desc.moe_experts.has_value()) {
+ const auto* moe_experts = get_compiled_experts(desc.pipeline.context);
+ if (moe_experts == nullptr) {
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;
+ 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()) {
@@ -136,18 +135,16 @@ bool MoEExecutor::function_prologue_moe_input(size_t idx,
*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();
-
+ if (const auto* moe = get_compiled_experts(desc.pipeline.context)) {
// Router scores: store for later use in MoE inference
- if (moe._router_scores_idx.has_value() && param_idx == moe._router_scores_idx.value()) {
+ if (moe->_router_scores_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()) {
+ 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
@@ -159,12 +156,11 @@ bool MoEExecutor::function_prologue_moe_input(size_t idx,
}
// MoE downstream layer: bind expert output accumulator or other parameters
- if (desc.moe_experts_downstream) {
- const auto& moe_downstream = desc.moe_experts_downstream.value();
+ if (const auto* moe_downstream = get_compiled_downstream(desc.pipeline.context)) {
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) {
+ 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");
@@ -177,7 +173,7 @@ bool MoEExecutor::function_prologue_moe_input(size_t idx,
}
// 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");
+ NPUW_ASSERT(false && "MoE flag set but no compiled MoE state found");
return false;
}
@@ -580,8 +576,9 @@ void MoEExecutor::unpack_single_expert_closure(std::size_t idx, RqPtr request, s
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;
+ const auto* moe_experts = get_compiled_experts(func_desc.pipeline.context);
+ NPUW_ASSERT(moe_experts != nullptr);
+ const auto num_experts = moe_experts->num_experts;
auto& desc_closure = comp_model_desc.closure.get().closure;
@@ -675,11 +672,11 @@ void MoEExecutor::unpack_multiple_experts_closure(std::size_t idx,
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]
+ const auto* moe_experts = get_compiled_experts(func_desc.pipeline.context);
+ NPUW_ASSERT(moe_experts != nullptr);
+ 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();
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
index 4f690e29fa4..188cd281229 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.hpp
@@ -14,6 +14,7 @@
#include "../util.hpp" // For TensorPtr
#include "moe_config.hpp"
#include "moe_resources.hpp"
+#include "moe_subgraph.hpp"
#include "moe_types.hpp" // For MoEIO
#include "openvino/runtime/so_ptr.hpp"
@@ -27,12 +28,9 @@ class CompiledModel;
namespace ov {
namespace npuw {
-
-// Forward declare CompiledModelDesc to avoid circular dependency
-// Will be included in implementation file
namespace moe {
class MoEExecutor;
-}
+} // namespace moe
// Import TensorPtr from util namespace for use in this header
using ov::npuw::util::TensorPtr;
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.cpp
new file mode 100644
index 00000000000..0823e7836c6
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.cpp
@@ -0,0 +1,348 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "moe_subgraph.hpp"
+
+#include <sstream>
+
+#include "../logging.hpp"
+#include "../moe_transformations/moe_transformation.hpp"
+#include "../partitioning/partitioning.hpp"
+#include "../partitioning/patterns/moe.hpp"
+#include "../serialization.hpp"
+#include "openvino/core/except.hpp"
+
+namespace ov {
+namespace npuw {
+namespace moe {
+namespace {
+
+const char* behavior_name(const BehaviorRole role) {
+ switch (role) {
+ case BehaviorRole::EXPERTS:
+ return ov::npuw::patterns::moe::GPTOSSExpert::pattern_name();
+ case BehaviorRole::DOWNSTREAM:
+ return "MoEDownstream";
+ }
+ OPENVINO_THROW("Unsupported MoE behavior role");
+}
+
+ov::npuw::v1::subgraphs::RuntimeBehaviorFactory make_runtime_factory() {
+ return [](const ov::npuw::v1::subgraphs::Context& ctx) -> ov::npuw::v1::subgraphs::ISubgraphBehavior::Ptr {
+ class MoEBehavior final : public ov::npuw::v1::subgraphs::ISubgraphBehavior {
+ public:
+ explicit MoEBehavior(const BehaviorRole role) : m_role(role) {}
+
+ void prologue(ov::npuw::v1::subgraphs::InferContext& ctx) override {
+ if (ctx.opaque_prologue) {
+ ctx.opaque_prologue();
+ }
+ }
+
+ void run(ov::npuw::v1::subgraphs::InferContext& ctx) override {
+ if (m_role != BehaviorRole::EXPERTS) {
+ ctx.legacy_infer();
+ return;
+ }
+
+ OPENVINO_ASSERT(static_cast<bool>(ctx.opaque_run),
+ "Expected opaque run callback for MoE subgraph behavior");
+ ctx.opaque_run();
+ }
+
+ private:
+ BehaviorRole m_role = BehaviorRole::EXPERTS;
+ };
+
+ return std::make_unique<MoEBehavior>(ctx.get<BehaviorRole>());
+ };
+}
+
+void attach_runtime_behavior(ov::npuw::v1::subgraphs::CompiledPipeline& compiled_pipeline,
+ ov::npuw::v1::subgraphs::Context& compiled_context,
+ const BehaviorRole role,
+ const bool handles_function_prologue) {
+ compiled_context.put<BehaviorRole>(role);
+ compiled_pipeline.registration.group = ov::npuw::patterns::moe::GPTOSSExpert::group_name();
+ compiled_pipeline.registration.name = behavior_name(role);
+ ov::npuw::v1::subgraphs::RuntimeBehaviorSpec spec;
+ spec.registration = compiled_pipeline.registration;
+ spec.context = compiled_context;
+ spec.factory = make_runtime_factory();
+ spec.handles_function_prologue = handles_function_prologue;
+ compiled_pipeline.runtime_behavior = std::move(spec);
+}
+
+template <typename T>
+T* get_compiled_state(ov::npuw::v1::subgraphs::Context& context) {
+ auto* state = context.get_if<std::shared_ptr<T>>();
+ return state == nullptr ? nullptr : state->get();
+}
+
+template <typename T>
+const T* get_compiled_state(const ov::npuw::v1::subgraphs::Context& context) {
+ auto* state = context.get_if<std::shared_ptr<T>>();
+ return state == nullptr ? nullptr : state->get();
+}
+
+std::shared_ptr<ov::Model> find_router_model(ov::npuw::v1::subgraphs::Context& ctx) {
+ auto* callbacks = ctx.get_if<ov::npuw::v1::subgraphs::PartitioningCallbacks>();
+ if (callbacks == nullptr || !callbacks->find_tagged_model) {
+ return nullptr;
+ }
+ return callbacks->find_tagged_model(ov::npuw::patterns::moe::ROUTER_TAG);
+}
+
+void transform_experts(ov::npuw::Function& function,
+ ov::npuw::v1::subgraphs::Context& ctx,
+ const std::size_t moe_chunk_size) {
+ auto router_model = find_router_model(ctx);
+ if (!router_model) {
+ return;
+ }
+ auto experts = ov::npuw::function::MoEExperts::from(function._model, router_model, moe_chunk_size);
+ if (experts.has_value()) {
+ ctx.put<ov::npuw::function::MoEExperts>(std::move(experts.value()));
+ }
+}
+
+void compile_transformed_expert_models(const CompiledExpertsState& runtime_experts,
+ ov::npuw::v1::subgraphs::CompileContext& compile_ctx) {
+ OPENVINO_ASSERT(runtime_experts != nullptr, "Expected compiled MoE experts state");
+ LOG_INFO("Compiling MoE expert models...");
+ LOG_BLOCK();
+ for (const auto& entry : runtime_experts->_models_to_compile) {
+ runtime_experts->set_compiled_model(
+ entry.first,
+ compile_ctx.compile_model(entry.second, "/moe_chunk_" + std::to_string(entry.first), compile_ctx.devices));
+ }
+ const auto& compiled_models = runtime_experts->_compiled_models;
+ OPENVINO_ASSERT(!compiled_models.empty(), "Expected at least one compiled MoE expert model");
+ compile_ctx.compiled_model = compiled_models.begin()->second;
+}
+
+// Configure the generic compile stage to compile all expert variants produced by transform_experts().
+void configure_expert_compile(ov::npuw::v1::subgraphs::CompiledPipeline& compiled_pipeline,
+ ov::npuw::v1::subgraphs::Context& compiled_context) {
+ auto* experts = compiled_context.get_if<ov::npuw::function::MoEExperts>();
+ if (experts == nullptr) {
+ return;
+ }
+ auto compiled_experts = std::make_shared<ov::npuw::compiled::MoEExperts>(*experts);
+ const auto& models_to_compile = compiled_experts->_models_to_compile;
+ OPENVINO_ASSERT(!models_to_compile.empty(), "Fatal: MoEExperts has no models to compile!");
+ put_compiled_experts(compiled_context, compiled_experts);
+
+ attach_runtime_behavior(compiled_pipeline, compiled_context, BehaviorRole::EXPERTS, true);
+ compiled_pipeline.compile_executor = [compiled_experts](ov::npuw::v1::subgraphs::CompileContext& compile_ctx) {
+ compile_transformed_expert_models(compiled_experts, compile_ctx);
+ };
+}
+
+void transform_downstream(ov::npuw::Function& function, ov::npuw::v1::subgraphs::Context& ctx) {
+ auto router_model = find_router_model(ctx);
+ if (!router_model) {
+ return;
+ }
+ auto downstream = ov::npuw::function::create_moe_downstream(function._model, router_model);
+ if (downstream.has_value()) {
+ ctx.put<ov::npuw::function::MoEDownstream>(std::move(downstream.value()));
+ }
+}
+
+void compile_transformed_downstream_model(const ov::npuw::v1::subgraphs::CompileExecutor& previous_compile_executor,
+ const CompiledDownstreamState& runtime_downstream,
+ ov::npuw::v1::subgraphs::CompileContext& compile_ctx) {
+ OPENVINO_ASSERT(runtime_downstream != nullptr, "Expected compiled MoE downstream state");
+ compile_ctx.model = runtime_downstream->_model_to_compile;
+ if (previous_compile_executor) {
+ previous_compile_executor(compile_ctx);
+ } else {
+ compile_ctx.compiled_model = compile_ctx.compile_model(compile_ctx.model, "", compile_ctx.devices);
+ }
+ OPENVINO_ASSERT(compile_ctx.compiled_model, "Expected compiled model before wrapping MoE downstream");
+ runtime_downstream->set_compiled_model(std::move(compile_ctx.compiled_model));
+ compile_ctx.compiled_model = runtime_downstream->_compiled_model;
+}
+
+// Configure the generic compile stage to wrap the default compilation result into the transformed downstream model.
+void configure_downstream_compile(ov::npuw::v1::subgraphs::CompiledPipeline& compiled_pipeline,
+ ov::npuw::v1::subgraphs::Context& compiled_context) {
+ auto* downstream = compiled_context.get_if<ov::npuw::function::MoEDownstream>();
+ if (downstream == nullptr) {
+ return;
+ }
+ auto compiled_downstream = std::make_shared<ov::npuw::compiled::MoEDownstream>(*downstream);
+ put_compiled_downstream(compiled_context, compiled_downstream);
+
+ attach_runtime_behavior(compiled_pipeline, compiled_context, BehaviorRole::DOWNSTREAM, true);
+ const auto previous_compile_executor = compiled_pipeline.compile_executor;
+ compiled_pipeline.compile_executor = [previous_compile_executor,
+ compiled_downstream](ov::npuw::v1::subgraphs::CompileContext& compile_ctx) {
+ compile_transformed_downstream_model(previous_compile_executor, compiled_downstream, compile_ctx);
+ };
+}
+
+} // namespace
+
+void put_compiled_experts(v1::subgraphs::Context& context, CompiledExpertsState state) {
+ context.put<CompiledExpertsState>(std::move(state));
+}
+
+void put_compiled_downstream(v1::subgraphs::Context& context, CompiledDownstreamState state) {
+ context.put<CompiledDownstreamState>(std::move(state));
+}
+
+ov::npuw::compiled::MoEExperts* get_compiled_experts(v1::subgraphs::Context& context) {
+ return get_compiled_state<ov::npuw::compiled::MoEExperts>(context);
+}
+
+const ov::npuw::compiled::MoEExperts* get_compiled_experts(const v1::subgraphs::Context& context) {
+ return get_compiled_state<ov::npuw::compiled::MoEExperts>(context);
+}
+
+ov::npuw::compiled::MoEDownstream* get_compiled_downstream(v1::subgraphs::Context& context) {
+ return get_compiled_state<ov::npuw::compiled::MoEDownstream>(context);
+}
+
+const ov::npuw::compiled::MoEDownstream* get_compiled_downstream(const v1::subgraphs::Context& context) {
+ return get_compiled_state<ov::npuw::compiled::MoEDownstream>(context);
+}
+
+bool has_compiled_experts(const v1::subgraphs::CompiledPipeline& pipeline) {
+ return get_compiled_experts(pipeline.context) != nullptr;
+}
+
+bool has_compiled_downstream(const v1::subgraphs::CompiledPipeline& pipeline) {
+ return get_compiled_downstream(pipeline.context) != nullptr;
+}
+
+bool has_compiled_state(const v1::subgraphs::CompiledPipeline& pipeline) {
+ return has_compiled_experts(pipeline) || has_compiled_downstream(pipeline);
+}
+
+void serialize_compiled_state(v1::subgraphs::Context& context,
+ ov::npuw::s11n::Stream& stream,
+ const ov::npuw::s11n::SubmodelDeserializeCtx* submodel_ctx) {
+ std::optional<ov::npuw::compiled::MoEExperts> moe_experts;
+ if (const auto* experts = get_compiled_experts(context)) {
+ moe_experts = *experts;
+ }
+ stream & moe_experts;
+ if (!stream.output() && moe_experts.has_value()) {
+ put_compiled_experts(context, std::make_shared<ov::npuw::compiled::MoEExperts>(moe_experts.value()));
+ }
+ auto* mutable_moe_experts = get_compiled_experts(context);
+ if (mutable_moe_experts != nullptr) {
+ size_t num_compiled_models = 0;
+ if (stream.output()) {
+ num_compiled_models = mutable_moe_experts->_compiled_models.size();
+ }
+ stream & num_compiled_models;
+
+ if (stream.output()) {
+ for (const auto& [chunk_size, compiled_model] : mutable_moe_experts->_compiled_models) {
+ stream & chunk_size;
+ bool has_model = compiled_model != nullptr;
+ stream & has_model;
+ if (has_model) {
+ std::stringstream ss;
+ compiled_model->export_model(ss);
+ std::string model_str = ss.str();
+ stream & model_str;
+ }
+ }
+ } else {
+ NPUW_ASSERT(submodel_ctx != nullptr);
+ for (size_t i = 0; i < num_compiled_models; ++i) {
+ size_t chunk_size = 0;
+ stream & chunk_size;
+ bool has_model = false;
+ stream & has_model;
+ if (has_model) {
+ std::string model_str;
+ stream & model_str;
+ std::stringstream ss(model_str);
+ mutable_moe_experts->_compiled_models[chunk_size] =
+ submodel_ctx->plugin->get_core()->import_model(ss,
+ submodel_ctx->device,
+ submodel_ctx->import_config);
+ LOG_DEBUG("Imported MoE compiled model for chunk_size=" << chunk_size);
+ }
+ }
+ LOG_DEBUG("Deserialized " << mutable_moe_experts->_compiled_models.size() << " MoE expert models");
+ }
+ }
+
+ std::optional<ov::npuw::compiled::MoEDownstream> moe_downstream;
+ if (const auto* downstream = get_compiled_downstream(context)) {
+ moe_downstream = *downstream;
+ }
+ stream & moe_downstream;
+ if (!stream.output() && moe_downstream.has_value()) {
+ put_compiled_downstream(context, std::make_shared<ov::npuw::compiled::MoEDownstream>(moe_downstream.value()));
+ }
+ auto* mutable_moe_downstream = get_compiled_downstream(context);
+ if (mutable_moe_downstream != nullptr) {
+ bool has_model = false;
+ if (stream.output()) {
+ has_model = mutable_moe_downstream->_compiled_model != nullptr;
+ }
+ stream & has_model;
+ if (has_model) {
+ if (stream.output()) {
+ std::stringstream ss;
+ mutable_moe_downstream->_compiled_model->export_model(ss);
+ std::string model_str = ss.str();
+ stream & model_str;
+ } else {
+ NPUW_ASSERT(submodel_ctx != nullptr);
+ std::string model_str;
+ stream & model_str;
+ std::stringstream ss(model_str);
+ mutable_moe_downstream->_compiled_model =
+ submodel_ctx->plugin->get_core()->import_model(ss,
+ submodel_ctx->device,
+ submodel_ctx->import_config);
+ LOG_DEBUG("Imported MoE downstream compiled model");
+ }
+ }
+ }
+}
+
+std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> register_patterns(
+ ov::npuw::v1::subgraphs::PatternRegistry& registry,
+ const std::size_t moe_chunk_size) {
+ std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> registrations;
+ registrations.reserve(3);
+
+ registrations.emplace_back(registry.on<ov::npuw::patterns::moe::GPTOSSRouter>().scoped());
+
+ registrations.emplace_back(
+ registry.on<ov::npuw::patterns::moe::GPTOSSExpert>()
+ .at_partition([moe_chunk_size](ov::npuw::Function& function, ov::npuw::v1::subgraphs::Context& ctx) {
+ transform_experts(function, ctx, moe_chunk_size);
+ })
+ .at_compile([](ov::npuw::v1::subgraphs::CompiledPipeline& compiled_pipeline,
+ ov::npuw::v1::subgraphs::Context& compiled_context) {
+ configure_expert_compile(compiled_pipeline, compiled_context);
+ })
+ .scoped());
+
+ ov::npuw::v1::subgraphs::PatternRegistration downstream_registration;
+ downstream_registration.partition_stage = [](ov::npuw::Function& function, ov::npuw::v1::subgraphs::Context& ctx) {
+ transform_downstream(function, ctx);
+ };
+ downstream_registration.compile_stage = [](ov::npuw::v1::subgraphs::CompiledPipeline& compiled_pipeline,
+ ov::npuw::v1::subgraphs::Context& compiled_context) {
+ configure_downstream_compile(compiled_pipeline, compiled_context);
+ };
+ registrations.emplace_back(registry.add(std::move(downstream_registration)));
+
+ return registrations;
+}
+
+} // namespace moe
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.hpp
new file mode 100644
index 00000000000..6aceef1a3c3
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.hpp
@@ -0,0 +1,63 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <functional>
+#include <map>
+#include <memory>
+#include <vector>
+
+#include "../v1/subgraph_pipeline.hpp"
+
+namespace ov {
+class Model;
+namespace npuw {
+namespace function {
+struct MoEExperts;
+struct MoEDownstream;
+} // namespace function
+namespace compiled {
+struct MoEExperts;
+struct MoEDownstream;
+} // namespace compiled
+namespace s11n {
+class Stream;
+struct SubmodelDeserializeCtx;
+} // namespace s11n
+namespace moe {
+
+enum class BehaviorRole {
+ EXPERTS,
+ DOWNSTREAM,
+};
+
+using CompiledExpertsState = std::shared_ptr<ov::npuw::compiled::MoEExperts>;
+using CompiledDownstreamState = std::shared_ptr<ov::npuw::compiled::MoEDownstream>;
+
+void put_compiled_experts(v1::subgraphs::Context& context, CompiledExpertsState state);
+void put_compiled_downstream(v1::subgraphs::Context& context, CompiledDownstreamState state);
+
+ov::npuw::compiled::MoEExperts* get_compiled_experts(v1::subgraphs::Context& context);
+const ov::npuw::compiled::MoEExperts* get_compiled_experts(const v1::subgraphs::Context& context);
+
+ov::npuw::compiled::MoEDownstream* get_compiled_downstream(v1::subgraphs::Context& context);
+const ov::npuw::compiled::MoEDownstream* get_compiled_downstream(const v1::subgraphs::Context& context);
+
+bool has_compiled_experts(const v1::subgraphs::CompiledPipeline& pipeline);
+bool has_compiled_downstream(const v1::subgraphs::CompiledPipeline& pipeline);
+bool has_compiled_state(const v1::subgraphs::CompiledPipeline& pipeline);
+
+void serialize_compiled_state(v1::subgraphs::Context& context,
+ ov::npuw::s11n::Stream& stream,
+ const ov::npuw::s11n::SubmodelDeserializeCtx* submodel_ctx);
+
+std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> register_patterns(
+ ov::npuw::v1::subgraphs::PatternRegistry& registry,
+ std::size_t moe_chunk_size);
+
+} // namespace moe
+} // 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 ab58c5e7d72..4bd25174d2a 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
@@ -723,52 +723,58 @@ void Snapshot::earlyRegroup() {
break;
}
case PatternType::PATTERN: {
+ bool pattern_handled = false;
if (m_ctx.subgraph_patterns != nullptr) {
- handle_patterns =
- m_ctx.subgraph_patterns->register_matcher(rewr, shared_from_this(), isolate.pattern, isolate.tag) ||
- handle_patterns;
+ pattern_handled =
+ m_ctx.subgraph_patterns->register_matcher(rewr, shared_from_this(), isolate.pattern, isolate.tag);
+ handle_patterns = pattern_handled || handle_patterns;
}
+ if (!pattern_handled) {
+ // Keep the legacy built-in matcher list as a fallback so existing ISOLATE pattern names
+ // continue to work unchanged when they are not handled by the injected pattern registry.
#define HNDL(p) \
if (isolate.pattern == #p) { \
rewr.add_matcher<ov::npuw::patterns::compute::p>(shared_from_this(), isolate.tag); \
- handle_patterns = true; \
+ pattern_handled = true; \
}
#define HNDL_FAKE(p) \
if (isolate.pattern == #p) { \
rewr_fake.add_matcher<ov::npuw::patterns::compute::p>(shared_from_this(), isolate.tag); \
- handle_patterns = true; \
+ pattern_handled = true; \
}
#define HNDL_ATTN(p) \
if (isolate.pattern == #p) { \
rewr.add_matcher<ov::npuw::patterns::attn::p>(shared_from_this(), isolate.tag); \
- handle_patterns = true; \
+ pattern_handled = 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);
- HNDL(RMSNorm3);
- HNDL(RMSNorm4);
- HNDL(DQMatMulCWu4);
- HNDL(DQMatMulGQu4);
- HNDL(DQMatMulCWi4);
- HNDL(DQMatMulGQi4);
- HNDL(DQMatMulConv);
- HNDL(VocabMatMul);
- HNDL(VariadicSplit);
- HNDL_MOE(GPTOSSExpert);
- HNDL_MOE(GPTOSSRouter);
- HNDL_FAKE(FakeConvert);
- HNDL_FAKE(FakeQuantize);
- HNDL_ATTN(SDPA);
- HNDL_ATTN(SDPADecomposed);
+ pattern_handled = true; \
+ }
+ HNDL(RMSNorm);
+ HNDL(RMSNorm2);
+ HNDL(RMSNorm3);
+ HNDL(RMSNorm4);
+ HNDL(DQMatMulCWu4);
+ HNDL(DQMatMulGQu4);
+ HNDL(DQMatMulCWi4);
+ HNDL(DQMatMulGQi4);
+ 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
+ handle_patterns = pattern_handled || handle_patterns;
+ }
}
}
}
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 9dc34902125..7ec70b1336d 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp
@@ -37,7 +37,7 @@ inline bool operator==(const std::reference_wrapper<Subgraph>& lhs, const std::r
void ov::npuw::v1::subgraphs::PatternRegistry::apply(ov::npuw::Function& function) const {
for (const auto& registration : m_registrations) {
- if (function.gettag() != registration.tag) {
+ if (!registration.tag.empty() && function.gettag() != registration.tag) {
continue;
}
@@ -48,15 +48,24 @@ void ov::npuw::v1::subgraphs::PatternRegistry::apply(ov::npuw::Function& functio
if (func_pipeline.registration.name.empty()) {
func_pipeline.registration.name = registration.name;
}
- if (std::find(func_pipeline.registration.patterns.begin(),
+ if (!registration.pattern.empty() &&
+ std::find(func_pipeline.registration.patterns.begin(),
func_pipeline.registration.patterns.end(),
registration.pattern) == func_pipeline.registration.patterns.end()) {
func_pipeline.registration.patterns.push_back(registration.pattern);
}
- if (registration.partition_stage) {
- registration.partition_stage(function, func_pipeline.context);
- }
+ auto previous_partition_stage = func_pipeline.partition_stage;
+ func_pipeline.partition_stage = [previous_partition_stage, registration](
+ ov::npuw::Function& staged_function,
+ ov::npuw::v1::subgraphs::Context& ctx) {
+ if (previous_partition_stage) {
+ previous_partition_stage(staged_function, ctx);
+ }
+ if (registration.partition_stage) {
+ registration.partition_stage(staged_function, ctx);
+ }
+ };
auto previous_compile_stage = func_pipeline.compile_stage;
func_pipeline.compile_stage = [previous_compile_stage, registration](
@@ -81,7 +90,7 @@ void ov::npuw::v1::subgraphs::PatternRegistry::apply(ov::npuw::Function& functio
void ov::npuw::v1::subgraphs::PatternRegistry::apply(ov::npuw::Subgraph& subgraph) const {
for (const auto& registration : m_registrations) {
- if (subgraph.gettag() != registration.tag) {
+ if (!registration.tag.empty() && subgraph.gettag() != registration.tag) {
continue;
}
@@ -92,12 +101,25 @@ void ov::npuw::v1::subgraphs::PatternRegistry::apply(ov::npuw::Subgraph& subgrap
if (subgraph_pipeline.registration.name.empty()) {
subgraph_pipeline.registration.name = registration.name;
}
- if (std::find(subgraph_pipeline.registration.patterns.begin(),
+ if (!registration.pattern.empty() &&
+ std::find(subgraph_pipeline.registration.patterns.begin(),
subgraph_pipeline.registration.patterns.end(),
registration.pattern) == subgraph_pipeline.registration.patterns.end()) {
subgraph_pipeline.registration.patterns.push_back(registration.pattern);
}
+ auto previous_partition_stage = subgraph_pipeline.partition_stage;
+ subgraph_pipeline.partition_stage = [previous_partition_stage, registration](
+ ov::npuw::Function& staged_function,
+ ov::npuw::v1::subgraphs::Context& ctx) {
+ if (previous_partition_stage) {
+ previous_partition_stage(staged_function, ctx);
+ }
+ if (registration.partition_stage) {
+ registration.partition_stage(staged_function, ctx);
+ }
+ };
+
auto previous_compile_stage = subgraph_pipeline.compile_stage;
subgraph_pipeline.compile_stage = [previous_compile_stage, registration](
ov::npuw::v1::subgraphs::CompiledPipeline& compiled_pipeline,
@@ -119,6 +141,13 @@ void ov::npuw::v1::subgraphs::PatternRegistry::apply(ov::npuw::Subgraph& subgrap
}
}
+void ov::npuw::v1::subgraphs::PatternRegistry::append_from(const PatternRegistry& other) {
+ for (auto registration : other.m_registrations) {
+ registration.id = ++m_next_id;
+ m_registrations.push_back(std::move(registration));
+ }
+}
+
template <typename T2>
struct std::hash<std::pair<ov::npuw::Subgraph::Ref, T2>> {
std::size_t operator()(const std::pair<ov::npuw::Subgraph::Ref, T2>& p) const noexcept {
@@ -323,11 +352,6 @@ 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
@@ -426,12 +450,6 @@ public:
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);
@@ -2067,85 +2085,6 @@ 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;
@@ -2663,6 +2602,8 @@ ov::npuw::Partitioning ov::npuw::getPartitioning(const std::shared_ptr<ov::Model
LOG_BLOCK();
ov::npuw::Ensemble ens;
+ ov::npuw::Partitioning P;
+ ov::npuw::PartitioningContext effective_ctx = ctx;
// Try to load the partitioning plan...
// Ensure all nodes in the model have unique friendly names before online partitioning.
@@ -2695,7 +2636,7 @@ ov::npuw::Partitioning ov::npuw::getPartitioning(const std::shared_ptr<ov::Model
const std::string file_path = cfg.get<::intel_npu::NPUW_PLAN>();
if (file_path.empty()) {
LOG_INFO("No " << ::intel_npu::NPUW_PLAN().key() << " property is provided! Using online partitioning.");
- ens = ov::npuw::online::buildPartitioning(model, cfg);
+ ens = ov::npuw::online::buildPartitioning(model, cfg, effective_ctx.subgraph_patterns);
} else {
ens = load_groups(model, file_path);
}
@@ -2743,10 +2684,9 @@ ov::npuw::Partitioning ov::npuw::getPartitioning(const std::shared_ptr<ov::Model
} // for(ens.groups)
} // if(fcew.enabled)
- Partitioning P;
P.total_gflops = ens.gflops;
- Partitioner p(model, ens, P, cfg, ctx);
+ Partitioner p(model, ens, P, cfg, effective_ctx);
p.identifySubgraphs();
if (!ens.repeated.empty()) {
@@ -2778,19 +2718,33 @@ ov::npuw::Partitioning ov::npuw::getPartitioning(const std::shared_ptr<ov::Model
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
+ // Pass 2: run deferred partition-stage transformations after all functions are registered.
+ // Partitioning stays generic here: it only exposes shared lookup helpers through the
+ // pipeline context and then runs the registered callbacks.
for (auto&& func_group : all_functions) {
- LOG_INFO("FOLD Pass 2: MoE-specific transformations for " << func_group << "...");
+ LOG_INFO("FOLD Pass 2: Partition-stage pipeline for " << func_group << "...");
LOG_BLOCK();
- p.transformMoeExperts(func_group);
- p.transformMoeDownstream(func_group);
+ auto& function = P.functions.at(func_group);
+ if (function._pipeline.partition_stage) {
+ function._pipeline.context.put<ov::npuw::v1::subgraphs::PartitioningCallbacks>(
+ {[&P, &part_ctx = effective_ctx](const std::string& tag) -> std::shared_ptr<ov::Model> {
+ auto cached = part_ctx.tagged_models.find(tag);
+ if (cached != part_ctx.tagged_models.end()) {
+ return cached->second;
+ }
+ for (const auto& [name, candidate] : P.functions) {
+ if (candidate.gettag() == tag) {
+ part_ctx.tagged_models.emplace(tag, candidate._model);
+ return candidate._model;
+ }
+ }
+ return nullptr;
+ }});
+ function._pipeline.partition_stage(function, function._pipeline.context);
+ // The callback captures partitioning state by reference, so keep it scoped to this
+ // immediate partition-stage invocation and remove it before the context outlives us.
+ function._pipeline.context.erase<ov::npuw::v1::subgraphs::PartitioningCallbacks>();
+ }
}
} else if (cfg.get<::intel_npu::NPUW_CWAI>()) {
// Less brutal version - just transform repeated blocks
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 b37da683ef0..035c175612b 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp
@@ -6,6 +6,7 @@
#include <map>
#include <string>
+#include <unordered_map>
#include <variant>
#include <vector>
@@ -205,10 +206,7 @@ struct Partitioning {
struct PartitioningContext {
bool use_host_gather_quant = false;
const ov::npuw::v1::subgraphs::PatternRegistry* subgraph_patterns = nullptr;
-
- // 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;
+ mutable std::unordered_map<std::string, std::shared_ptr<ov::Model>> tagged_models;
};
Partitioning getPartitioning(const std::shared_ptr<ov::Model>& model,
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hpp
index 91d1bfb104c..df0a55881c5 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.hpp
@@ -29,12 +29,30 @@ constexpr const char* MLP_EXPERT_NAME = ".mlp.expert";
class GPTOSSExpert : public ov::pass::MatcherPass {
public:
OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::moe::GPTOSSExpert");
+ static constexpr const char* pattern_name() {
+ return "GPTOSSExpert";
+ }
+ static constexpr const char* isolation_tag() {
+ return EXPERT_TAG;
+ }
+ static constexpr const char* group_name() {
+ return "moe";
+ }
GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);
};
class GPTOSSRouter : public ov::pass::MatcherPass {
public:
OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::moe::GPTOSSRouter");
+ static constexpr const char* pattern_name() {
+ return "GPTOSSRouter";
+ }
+ static constexpr const char* isolation_tag() {
+ return ROUTER_TAG;
+ }
+ static constexpr const char* group_name() {
+ return "moe";
+ }
GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);
};
diff --git a/src/plugins/intel_npu/src/plugin/npuw/v1/subgraph_pipeline.hpp b/src/plugins/intel_npu/src/plugin/npuw/v1/subgraph_pipeline.hpp
index 9865e89ac29..5b23e612499 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/v1/subgraph_pipeline.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/v1/subgraph_pipeline.hpp
@@ -18,6 +18,12 @@
#include "openvino/core/except.hpp"
#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/runtime/so_ptr.hpp"
+
+namespace ov {
+class Model;
+class ICompiledModel;
+} // namespace ov
namespace ov::npuw {
class CompiledModel;
@@ -51,6 +57,11 @@ public:
return m_entries.find(std::type_index(typeid(T))) != m_entries.end();
}
+ template <typename T>
+ void erase() {
+ m_entries.erase(std::type_index(typeid(T)));
+ }
+
template <typename T>
T* get_if() {
auto it = m_entries.find(std::type_index(typeid(T)));
@@ -106,10 +117,24 @@ struct Registration {
struct CompiledPipeline;
struct InferContext;
+struct PartitioningCallbacks {
+ std::function<std::shared_ptr<ov::Model>(const std::string&)> find_tagged_model;
+};
+
+struct CompileContext {
+ std::shared_ptr<ov::Model>& model;
+ ov::SoPtr<ov::ICompiledModel>& compiled_model;
+ const std::vector<std::string>& devices;
+ std::function<ov::SoPtr<ov::ICompiledModel>(const std::shared_ptr<ov::Model>&,
+ const std::string&,
+ const std::vector<std::string>&)>
+ compile_model;
+};
struct FunctionPipeline {
Registration registration;
Context context;
+ std::function<void(ov::npuw::Function&, Context&)> partition_stage;
std::function<void(CompiledPipeline&, Context&)> compile_stage;
};
@@ -125,16 +150,19 @@ public:
};
using RuntimeBehaviorFactory = std::function<ISubgraphBehavior::Ptr(const Context&)>;
+using CompileExecutor = std::function<void(CompileContext&)>;
struct RuntimeBehaviorSpec {
Registration registration;
Context context;
RuntimeBehaviorFactory factory;
+ bool handles_function_prologue = false;
};
struct CompiledPipeline {
Registration registration;
Context context;
+ CompileExecutor compile_executor;
std::optional<RuntimeBehaviorSpec> runtime_behavior;
bool is_function_call = false;
std::optional<std::size_t> function_body_subgraph_idx;
@@ -146,6 +174,8 @@ struct InferContext {
std::size_t subgraph_idx = 0u;
std::size_t real_subgraph_idx = 0u;
std::function<void()> legacy_infer;
+ std::function<void()> opaque_prologue;
+ std::function<void()> opaque_run;
};
using PostLegacyHook = std::function<void(InferContext&)>;
@@ -303,6 +333,7 @@ public:
void apply(ov::npuw::Function& function) const;
void apply(ov::npuw::Subgraph& subgraph) const;
+ void append_from(const PatternRegistry& other);
private:
std::vector<PatternRegistration> m_registrations;
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index 99300764c5f..068a0304cf8 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -76,6 +76,7 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/accuracy/comparator.cpp
# moe
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe/moe_executor.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe/moe_resources.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.cpp
diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp
index b9a5b46ffb3..4183693c0a5 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp
@@ -32,6 +32,10 @@ protected:
return ov::test::npuw::build_llm_test_model();
}
+ std::shared_ptr<ov::Model> build_moe_llm_model() const {
+ return ov::test::npuw::build_moe_llm_test_model();
+ }
+
std::shared_ptr<ov::Model> build_whisper_decoder_model() const {
return ov::test::npuw::build_whisper_decoder_test_model();
}
@@ -426,6 +430,31 @@ TEST_F(LLMCompiledModelFactoryOptionsTest, HfaAttentionHintsEnableAttentionIsola
}
}
+TEST_F(LLMCompiledModelFactoryOptionsTest, MoeModelKeepsHostRoutedStageIntegration) {
+ RecordingFactory recorder;
+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;
+
+ ASSERT_NO_THROW(compiled = create_compiled_model(build_moe_llm_model(),
+ {{"NPUW_LLM_SHARED_HEAD", "NO"},
+ {"NPUW_LLM_PREFILL_MOE_HINT", "HOST_ROUTED"},
+ {"NPUW_LLM_GENERATE_MOE_HINT", "HOST_ROUTED"}},
+ recorder));
+ ASSERT_NE(compiled, nullptr);
+
+ const auto& prefill = require_call(recorder, "_prefill");
+ const auto& generate = require_call_containing(recorder, "_kv");
+
+ for (const auto* call : {&prefill, &generate}) {
+ expect_prop(call->props, "NPUW_ONLINE_PIPELINE", "REP");
+ expect_prop(call->props, "NPUW_ONLINE_ISOLATE", "MOE");
+ expect_prop(call->props, "NPUW_ONLINE_KEEP_BLOCK_SIZE", "4");
+ expect_prop(call->props, "NPUW_UNFOLD_IREQS", "NO");
+ }
+
+ EXPECT_EQ(recorder.count_suffix("_prefill"), 1u);
+ EXPECT_EQ(recorder.count_contains("_kv"), 1u);
+}
+
TEST_F(LLMCompiledModelFactoryOptionsTest, CacheRopeEnabledRoundsTripThroughCompiledModel) {
RecordingFactory recorder;
std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;
diff --git a/src/plugins/intel_npu/tests/unit/npuw/subgraph_pipeline.cpp b/src/plugins/intel_npu/tests/unit/npuw/subgraph_pipeline.cpp
index 9fea01d5952..b1fadd0dc3e 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/subgraph_pipeline.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/subgraph_pipeline.cpp
@@ -6,7 +6,9 @@
#include <string>
+#include "moe/moe_executor.hpp"
#include "partitioning/partitioning.hpp"
+#include "partitioning/patterns/moe.hpp"
#include "partitioning/patterns/sdpa.hpp"
#include "v1/subgraph_pipeline.hpp"
@@ -98,3 +100,22 @@ TEST(SubgraphPipelineBehaviorTest, RealPatternRegistrationBuildsRuntimeBehaviorF
auto behavior = compiled_pipeline.runtime_behavior->factory(compiled_pipeline.runtime_behavior->context);
EXPECT_NE(behavior, nullptr);
}
+
+TEST(SubgraphPipelineBehaviorTest, MoERegistrationBuildsDeferredPartitionPipelineForExpertFunction) {
+ ov::npuw::Function function;
+ function.settag(ov::npuw::patterns::moe::GPTOSSExpert::isolation_tag());
+
+ ov::npuw::v1::subgraphs::PatternRegistry registry;
+ auto registrations =
+ ov::npuw::moe::register_patterns(registry, 0u);
+ registry.apply(function);
+
+ ASSERT_TRUE(static_cast<bool>(function._pipeline.partition_stage));
+ ASSERT_TRUE(static_cast<bool>(function._pipeline.compile_stage));
+ EXPECT_EQ(function._pipeline.registration.group, ov::npuw::patterns::moe::GPTOSSExpert::group_name());
+ EXPECT_EQ(function._pipeline.registration.name, ov::npuw::patterns::moe::GPTOSSExpert::pattern_name());
+ EXPECT_NE(std::find(function._pipeline.registration.patterns.begin(),
+ function._pipeline.registration.patterns.end(),
+ ov::npuw::patterns::moe::GPTOSSExpert::pattern_name()),
+ function._pipeline.registration.patterns.end());
+}