Skip to content

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

[NPUW][MoE]Remove Router isolation and propagate K via rt_info. (#36427)

intelgaoxiongb90dd6e8403d
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
index 4b80df840c7..373bf8d5900 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_subgraph.cpp
@@ -90,22 +90,27 @@ const T* get_compiled_state(const ov::npuw::v1::subgraphs::Context& context) {
return state == nullptr ? nullptr : state->get();
}
-std::shared_ptr<ov::Model> find_router_model(ov::npuw::v1::subgraphs::Context& ctx) {
+static std::optional<size_t> find_moe_k_value(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;
+ if (callbacks == nullptr || !callbacks->find_node_with_rt_info) {
+ return std::nullopt;
}
- return callbacks->find_tagged_model(ov::npuw::patterns::moe::ROUTER_TAG);
+ auto node = callbacks->find_node_with_rt_info(ov::npuw::patterns::moe::RT_INFO_MOE_K);
+ if (!node) {
+ return std::nullopt;
+ }
+ return node->get_rt_info().at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>();
}
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) {
+ auto k_value = find_moe_k_value(ctx);
+ if (!k_value.has_value()) {
+ LOG_WARN("MoE K value not found in context; skipping expert transformation");
return;
}
- auto experts = ov::npuw::function::MoEExperts::from(function._model, router_model, moe_chunk_size);
+ auto experts = ov::npuw::function::MoEExperts::from(function._model, k_value.value(), moe_chunk_size);
if (experts.has_value()) {
ctx.put<ov::npuw::function::MoEExperts>(std::move(experts.value()));
}
@@ -153,11 +158,12 @@ void configure_expert_compile(ov::npuw::v1::subgraphs::CompiledPipeline& compile
}
void transform_downstream(ov::npuw::Function& function, ov::npuw::v1::subgraphs::Context& ctx) {
- auto router_model = find_router_model(ctx);
- if (!router_model) {
+ auto k_value = find_moe_k_value(ctx);
+ if (!k_value.has_value()) {
+ LOG_WARN("MoE K value not found in context; skipping downstream transformation");
return;
}
- auto downstream = ov::npuw::function::create_moe_downstream(function._model, router_model);
+ auto downstream = ov::npuw::function::create_moe_downstream(function._model, k_value.value());
if (downstream.has_value()) {
ctx.put<ov::npuw::function::MoEDownstream>(std::move(downstream.value()));
}
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
index 7d3adee3575..d6102c19da4 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.cpp
@@ -22,36 +22,6 @@ 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;
-}
-
// Scan the transformed model for a parameter bearing `tag` and return its new index.
// Falls back to `original_idx` when the tag is absent (e.g. router_scores is replaced
// by K closures in EXPERT_BATCH mode and its parameter no longer exists).
@@ -493,25 +463,11 @@ std::optional<MoEDownstream> detect_and_transform_moe_downstream(const std::shar
return std::nullopt;
}
-std::optional<MoEDownstream> create_moe_downstream(const std::shared_ptr<ov::Model>& model,
- const std::shared_ptr<ov::Model>& router_model) {
+std::optional<MoEDownstream> create_moe_downstream(const std::shared_ptr<ov::Model>& model, size_t active_experts_num) {
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");
+ LOG_INFO("Using K=" << active_experts_num << " active experts for downstream");
auto downstream_info = detect_and_transform_moe_downstream(model, active_experts_num);
if (downstream_info && downstream_info->is_valid()) {
@@ -909,25 +865,12 @@ std::shared_ptr<ov::Model> MoEModelTransformer::apply_expert_transformation(
}
std::optional<MoEExperts> MoEExperts::from(const std::shared_ptr<ov::Model>& model,
- const std::shared_ptr<ov::Model>& router_model,
+ size_t k_value,
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");
+ LOG_INFO("Using K=" << k_value << " active experts");
// Step 2: Analyze model structure
auto structure_info = analyze_moe_structure(model);
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
index 7cb4808bca9..9920b4783de 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_transformation.hpp
@@ -247,18 +247,17 @@ struct MoEExperts {
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)
+ // Factory method to create MoEExperts from a model (for expert pattern only).
+ // k_value: number of active experts (K from TopK in the Router, extracted during pattern matching).
// 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 k_value,
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);
+// Factory method to create MoEDownstream from a model (for downstream pattern).
+// k_value: number of active experts (K from TopK in the Router, extracted during pattern matching).
+std::optional<MoEDownstream> create_moe_downstream(const std::shared_ptr<ov::Model>& model, size_t k_value);
} // namespace function
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 a21abb07dd2..6457727cc15 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp
@@ -22,7 +22,6 @@
#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"
@@ -2740,25 +2739,46 @@ ov::npuw::Partitioning ov::npuw::getPartitioning(const std::shared_ptr<ov::Model
// 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.
+ std::unordered_map<std::string, std::shared_ptr<ov::Node>> rt_info_node_cache;
for (auto&& func_group : all_functions) {
LOG_INFO("FOLD Pass 2: Partition-stage pipeline for " << func_group << "...");
LOG_BLOCK();
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;
+ auto find_tagged_model =
+ [&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;
}
- for (const auto& [name, candidate] : P.functions) {
- if (candidate.gettag() == tag) {
- part_ctx.tagged_models.emplace(tag, candidate._model);
- return candidate._model;
+ }
+ return nullptr;
+ };
+
+ auto find_node_with_rt_info =
+ [&P, &cache = rt_info_node_cache](const std::string& key) -> std::shared_ptr<ov::Node> {
+ auto cached = cache.find(key);
+ if (cached != cache.end()) {
+ return cached->second;
+ }
+ for (const auto& [name, func] : P.functions) {
+ for (const auto& node : func._model->get_ordered_ops()) {
+ if (node->get_rt_info().count(key) > 0) {
+ cache.emplace(key, node);
+ return node;
}
}
- return nullptr;
- }});
+ }
+ return nullptr;
+ };
+
+ function._pipeline.context.put<ov::npuw::v1::subgraphs::PartitioningCallbacks>(
+ {std::move(find_tagged_model), std::move(find_node_with_rt_info)});
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.
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
index 7b5d4e8d664..0cd6e52cf04 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/moe.cpp
@@ -4,6 +4,8 @@
#include "moe.hpp"
+#include <optional>
+
#include "../../logging.hpp"
#include "openvino/op/ops.hpp"
#include "openvino/pass/pattern/op/optional.hpp"
@@ -47,20 +49,6 @@ bool is_decoding_stage(const std::shared_ptr<ov::Node>& output_multiply) {
return true; // all middle dims are 1 → decoding
}
-// Find the first consumer of `node` satisfying `pred`. Returns nullptr if not found.
-template <typename Pred>
-std::shared_ptr<ov::Node> find_consumer_by_type(const std::shared_ptr<ov::Node>& node, Pred&& pred) {
- 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;
-}
-
// After output_multiply, find the first ReduceSum consumer and isolate it.
void isolate_reduce_sum_after(const std::shared_ptr<ov::Node>& output_multiply,
const std::string& isol_tag,
@@ -87,6 +75,38 @@ void isolate_reduce_sum_after(const std::shared_ptr<ov::Node>& output_multiply,
}
}
+// Extract K from a TopK node's constant second input and write it to rt_info
+// under the RT_INFO_MOE_K key so that PartitioningCallbacks::find_node_with_rt_info
+// can retrieve it during the partition stage. Returns true on success.
+// Both GPTOSSRouter and Qwen3Router call this after validating the TopK node.
+// expected_k is updated on first call and checked for consistency on subsequent calls;
+// OPENVINO_THROW is raised if two matched layers carry different K values.
+static bool tag_topk_k(const std::shared_ptr<ov::Node>& topk_node, std::optional<size_t>& expected_k) {
+ auto k_input = topk_node->input_value(1);
+ auto k_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(k_input.get_node_shared_ptr());
+ if (!k_const) {
+ return false;
+ }
+ auto k_data = k_const->cast_vector<int64_t>();
+ if (k_data.empty() || k_data[0] <= 0) {
+ LOG_WARN("Router TopK K value is non-positive or empty (" << (k_data.empty() ? 0 : k_data[0])
+ << "); skipping tag");
+ return false;
+ }
+ const size_t k_value = static_cast<size_t>(k_data[0]);
+ if (expected_k.has_value() && expected_k.value() != k_value) {
+ OPENVINO_THROW("NPUW: Inconsistent MoE K values across layers: ",
+ expected_k.value(),
+ " vs ",
+ k_value,
+ ". All MoE layers in a model must share the same K.");
+ }
+ expected_k = k_value;
+ topk_node->get_rt_info()[RT_INFO_MOE_K] = k_value;
+ LOG_DEBUG("Router: tagged TopK '" << topk_node->get_friendly_name() << "' with K=" << k_value);
+ return true;
+}
+
} // namespace
/*
@@ -127,7 +147,6 @@ void isolate_reduce_sum_after(const std::shared_ptr<ov::Node>& output_multiply,
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()});
@@ -152,7 +171,7 @@ GPTOSSExpert::GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
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 - awq_multiply will be Swish if not matched, or AWQ Multiply if matched
+ // awq_multiply aliases Swish when not matched.
auto multiply1 = opp::wrap_type<ov::op::v1::Multiply>({add2, awq_multiply});
// Second MatMul (down projection) - weights path: Multiply -> Convert -> MatMul
@@ -161,7 +180,6 @@ GPTOSSExpert::GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
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()});
@@ -245,16 +263,15 @@ GPTOSSExpert::GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
Slice -> ScatterElementsUpdate -> Transpose -> Reshape -> Unsqueeze
Broadcast (zero base for Scatter, shape fed by folded Const)
- Pattern-matched (6): Multiply, Convert, MatMul, Add, TopK, Softmax, Slice
- Manually retrieved (4): topk_convert (indices Convert), Broadcast, Scatter,
- Transpose, Reshape, Unsqueeze
+ Pattern root is ScatterElementsUpdate to avoid matching other TopK+Slice subgraphs.
+ No isolation; only TopK K value is extracted via RT_INFO_MOE_K.
*/
-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);
+GPTOSSRouter::GPTOSSRouter([[maybe_unused]] const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot,
+ [[maybe_unused]] const std::string& isol_tag) {
+ LOG_DEBUG("GPTOSSRouter pattern matcher registered (K-extraction only, no isolation)");
- // Pattern-matched nodes (7): Multiply, Convert, MatMul, Add, TopK, Softmax, Slice
- // topk_convert (indices Convert) is retrieved manually - TopK has two outputs and
- // wrap_type always binds output(0), so output(1)->Convert cannot be expressed inline.
+ // TopK output(1)->Convert (indices) cannot be expressed in wrap_type
+ // (always binds output(0)), so Scatter port 1 uses any_input().
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});
@@ -262,13 +279,16 @@ GPTOSSRouter::GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
auto topk = opp::wrap_type<ov::op::v11::TopK>({add, opp::any_input()});
auto softmax = opp::wrap_type<ov::op::v8::Softmax>({topk}); // connects to topk->output(0)
- // Pattern root: Slice data input is Softmax output; all shape inputs are any_input()
- // because ShapeOf nodes are constant-folded before this pattern runs.
+ // Shape inputs use any_input(): ShapeOf nodes are constant-folded.
auto slice = opp::wrap_type<ov::op::v8::Slice>(
{softmax, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});
- auto node_to_gptr = snapshot->getNodeToGroupMap();
+ // Pattern root. port 1: TopK indices (any_input() — wrap_type binds output(0) only).
+ auto scatter = opp::wrap_type<ov::op::v12::ScatterElementsUpdate>(
+ {opp::any_input(), opp::any_input(), slice, opp::any_input()});
+ // Shared across layers to detect inconsistent K values.
+ auto expected_k = std::make_shared<std::optional<size_t>>();
auto callback = [=](ov::pass::pattern::Matcher& m) {
auto& node_to_output = m.get_pattern_value_map();
@@ -287,89 +307,18 @@ GPTOSSRouter::GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
return false;
}
- LOG_DEBUG("GPT-OSS Router pattern matched: " << topk_name);
-
- // Get pattern-matched nodes needed for manual retrieval
- auto matched_slice = node_to_output.at(slice).get_node_shared_ptr();
-
- // topk_convert: Convert on TopK indices output (output(1)). Not in the formal
- // pattern because TopK has two outputs and wrap_type always binds output(0).
- std::shared_ptr<ov::Node> matched_topk_convert = nullptr;
- for (auto& target : matched_topk->output(1).get_target_inputs()) {
- auto consumer = target.get_node()->shared_from_this();
- if (std::dynamic_pointer_cast<ov::op::v0::Convert>(consumer)) {
- matched_topk_convert = consumer;
- break;
- }
- }
-
- // Manual retrieval (7 nodes): helper function
- 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;
- }
-
- // 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;
+ // Extract K from the TopK constant input and tag the node so that
+ // PartitioningCallbacks::find_node_with_rt_info can retrieve it later.
+ if (!tag_topk_k(matched_topk, *expected_k)) {
+ LOG_WARN("GPTOSSRouter: failed to extract K from TopK '" << matched_topk->get_friendly_name()
+ << "'; MoE transformation will be skipped");
}
- // Isolate all 16 nodes
- auto isolate = [&](const std::shared_ptr<ov::Node>& pattern_node) {
- isolate_node(node_to_output.at(pattern_node).get_node_shared_ptr(), isol_tag, node_to_gptr);
- };
-
- isolate(weights_multiply);
- isolate(weights_convert2);
- isolate(matmul);
- isolate(add);
- isolate_node(matched_topk, isol_tag, node_to_gptr);
- isolate(softmax);
- isolate_node(matched_topk_convert, isol_tag, node_to_gptr);
- isolate_node(matched_slice, isol_tag, node_to_gptr);
- isolate_node(matched_broadcast, isol_tag, node_to_gptr);
- isolate_node(matched_scatter, isol_tag, node_to_gptr);
- isolate_node(matched_transpose, isol_tag, node_to_gptr);
- isolate_node(matched_reshape, isol_tag, node_to_gptr);
- isolate_node(matched_unsqueeze, isol_tag, node_to_gptr);
-
- LOG_DEBUG("Router pattern isolated");
+ // Router stays in the upstream subgraph — no isolation.
return false;
};
- register_matcher(std::make_shared<opp::Matcher>(slice, "TagGPTOSSRouter"), std::move(callback));
+ register_matcher(std::make_shared<opp::Matcher>(scatter, "TagGPTOSSRouter"), std::move(callback));
}
/*
@@ -394,11 +343,9 @@ GPTOSSRouter::GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
Reshape2 * router_score -> Multiply_output <-- pattern root
(router_score = opp::any_input(), produced entirely by Qwen3Router)
- Isolation boundary:
- - Expert claims: Tile, Reshape1, gate/up/down MatMuls+weights, SwiGLU Multiply, Reshape2, output Multiply
- - Router claims: Softmax, TopK, ReduceSum, Divide, ScatterElementsUpdate, Transpose, Reshape_score, Unsqueeze_score
- - Shared shape-compute nodes (ShapeOf->Gather->Unsqueeze->Concat chains) stay outside both,
- becoming parameter inputs at subgraph boundaries.
+ Expert isolates: Tile, Reshape1, weight-dequant nodes, MatMuls, SwiGLU Multiply, Reshape2, output Multiply.
+ Router isolates: Softmax, TopK, ReduceSum, Divide, Scatter, Transpose, Reshape, Unsqueeze.
+ Shape-compute chains (ShapeOf->Gather->...) stay outside both as subgraph parameters.
*/
Qwen3Expert::Qwen3Expert(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag) {
LOG_DEBUG("Qwen3Expert pattern matcher registered with tag: " << isol_tag);
@@ -498,12 +445,11 @@ Qwen3Expert::Qwen3Expert(const std::shared_ptr<ov::npuw::online::Snapshot>& snap
Shape to [num_experts, token_count, 1, 1] for expert broadcast:
ScatterElementsUpdate -> Transpose -> Reshape -> Unsqueeze <-- pattern root
- Note: The Unsqueeze output is consumed by Qwen3Expert's Multiply_output node.
- Key difference from GPT-OSS: Softmax is BEFORE TopK (not after),
- requiring explicit renormalization via ReduceSum->Divide.
+ Key difference from GPT-OSS: Softmax is BEFORE TopK (not after).
*/
-Qwen3Router::Qwen3Router(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag) {
- LOG_DEBUG("Qwen3Router pattern matcher registered with tag: " << isol_tag);
+Qwen3Router::Qwen3Router([[maybe_unused]] const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot,
+ [[maybe_unused]] const std::string& isol_tag) {
+ LOG_DEBUG("Qwen3Router pattern matcher registered (K-extraction only, no isolation)");
// Router weights: Convert(weight) -> Multiply(weight, scale) -> Convert -> MatMul
auto weights_convert_in = opp::wrap_type<ov::op::v0::Convert>({opp::any_input()});
@@ -526,8 +472,8 @@ Qwen3Router::Qwen3Router(const std::shared_ptr<ov::npuw::online::Snapshot>& snap
auto reshape = opp::wrap_type<ov::op::v1::Reshape>({transpose, opp::any_input()});
auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({reshape, opp::any_input()});
- auto node_to_gptr = snapshot->getNodeToGroupMap();
-
+ // Shared across layers to detect inconsistent K values.
+ auto expected_k = std::make_shared<std::optional<size_t>>();
auto callback = [=](ov::pass::pattern::Matcher& m) {
auto& node_to_output = m.get_pattern_value_map();
@@ -538,32 +484,14 @@ Qwen3Router::Qwen3Router(const std::shared_ptr<ov::npuw::online::Snapshot>& snap
return false;
}
- LOG_DEBUG("Qwen3Router pattern matched: " << matched_topk->get_friendly_name());
-
- auto matched_scatter = node_to_output.at(scatter).get_node_shared_ptr();
-
- // Also isolate Broadcast node that provides zero-filled base for ScatterElementsUpdate
- 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);
-
- auto isolate = [&](const std::shared_ptr<ov::Node>& pattern_node) {
- isolate_node(node_to_output.at(pattern_node).get_node_shared_ptr(), isol_tag, node_to_gptr);
- };
-
- isolate(weights_convert_in);
- isolate(weights_multiply);
- isolate(weights_convert_out);
- isolate(matmul);
- isolate(softmax);
- isolate_node(matched_topk, isol_tag, node_to_gptr);
- isolate(reduce_sum);
- isolate(divide);
- isolate_node(matched_broadcast, isol_tag, node_to_gptr);
- isolate_node(matched_scatter, isol_tag, node_to_gptr);
- isolate(transpose);
- isolate(reshape);
- isolate(unsqueeze);
+ // Extract K from the TopK constant input and tag the node so that
+ // PartitioningCallbacks::find_node_with_rt_info can retrieve it later.
+ if (!tag_topk_k(matched_topk, *expected_k)) {
+ LOG_WARN("Qwen3Router: failed to extract K from TopK '" << matched_topk->get_friendly_name()
+ << "'; MoE transformation will be skipped");
+ }
+ // Router stays in the upstream subgraph — no isolation.
return false;
};
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 8c369075966..d69004cfbf8 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
@@ -26,6 +26,11 @@ constexpr const char* EXPERT_TAG = "expert";
constexpr const char* MLP_ROUTER_NAME = ".mlp.router";
constexpr const char* MLP_EXPERT_NAME = ".mlp.expert";
+// RT info key used to propagate the Router's K value from pattern-matching
+// callbacks to the partition stage (written by Router matchers, read by
+// PartitioningCallbacks::find_node_with_rt_info).
+constexpr const char* RT_INFO_MOE_K = "npuw_moe_k";
+
class GPTOSSExpert : public ov::pass::MatcherPass {
public:
OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::moe::GPTOSSExpert");
@@ -47,13 +52,19 @@ public:
static constexpr const char* pattern_name() {
return "GPTOSSRouter";
}
+ // NOTE: GPTOSSRouter does NOT isolate any nodes. It only tags the matched
+ // TopK with RT_INFO_MOE_K. This tag is the ISOL_PRESETS lookup key used by
+ // the pattern registry ("P:GPTOSSRouter/router") — not an isolation target.
static constexpr const char* isolation_tag() {
return ROUTER_TAG;
}
static constexpr const char* group_name() {
return "moe";
}
- GPTOSSRouter(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);
+ // NOTE: isol_tag is accepted for macro-call uniformity but is intentionally unused
+ // (Router nodes are not isolated; only K is extracted via RT_INFO_MOE_K).
+ GPTOSSRouter([[maybe_unused]] const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot,
+ [[maybe_unused]] const std::string& isol_tag);
};
class Qwen3Expert : public ov::pass::MatcherPass {
@@ -77,13 +88,19 @@ public:
static constexpr const char* pattern_name() {
return "Qwen3Router";
}
+ // NOTE: Qwen3Router does NOT isolate any nodes. It only tags the matched
+ // TopK with RT_INFO_MOE_K. This tag is the ISOL_PRESETS lookup key used by
+ // the pattern registry ("P:Qwen3Router/router") — not an isolation target.
static constexpr const char* isolation_tag() {
return ROUTER_TAG;
}
static constexpr const char* group_name() {
return "moe";
}
- Qwen3Router(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);
+ // NOTE: isol_tag is accepted for macro-call uniformity but is intentionally unused
+ // (Router nodes are not isolated; only K is extracted via RT_INFO_MOE_K).
+ Qwen3Router([[maybe_unused]] const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot,
+ [[maybe_unused]] const std::string& isol_tag);
};
} // namespace moe
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 05436febf9b..d1e43371f8a 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
@@ -121,6 +121,9 @@ struct CompiledPipeline;
struct InferContext;
struct PartitioningCallbacks {
std::function<std::shared_ptr<ov::Model>(const std::string&)> find_tagged_model;
+ // Find the first node carrying the given rt_info key, searching across all
+ // registered function models. Returns nullptr when the key is not found.
+ std::function<std::shared_ptr<ov::Node>(const std::string&)> find_node_with_rt_info;
};
struct CompileContext {
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index 0d754b05bcc..02379cfd6dc 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -162,4 +162,5 @@ target_sources(${TARGET_NAME} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/stateful_to_stateless_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/pyramid_attention_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/sdpa_pattern_matcher_test.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe_k_tag_test.cpp
)
diff --git a/src/plugins/intel_npu/tests/unit/npuw/moe_k_tag_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/moe_k_tag_test.cpp
new file mode 100644
index 00000000000..bb19a8b1d02
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/moe_k_tag_test.cpp
@@ -0,0 +1,333 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+
+#include "openvino/op/ops.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+#include "partitioning/online/group.hpp"
+#include "partitioning/online/snapshot.hpp"
+#include "partitioning/patterns/moe.hpp"
+
+namespace {
+
+using namespace ov;
+
+// ============================================================================
+// Per-layer graph helpers
+// ============================================================================
+
+// Build one GPT-OSS Router layer attached to router_input and return its
+// ScatterElementsUpdate output (the pattern root).
+// extra_params: when non-null and k_param_as_input is true, the K Parameter is appended here.
+std::shared_ptr<Node> build_gptoss_router_layer(const std::shared_ptr<op::v0::Parameter>& router_input,
+ int64_t k_value,
+ int layer_idx,
+ size_t num_experts,
+ bool k_param_as_input = false,
+ ParameterVector* extra_params = nullptr) {
+ const size_t hidden_dim = router_input->get_shape()[1];
+ const std::string prefix = "__module.model.layer" + std::to_string(layer_idx) + ".mlp.router/aten::";
+
+ auto w_i4 = op::v0::Constant::create(element::i4,
+ Shape{num_experts, hidden_dim},
+ std::vector<int8_t>(num_experts * hidden_dim, 1));
+ auto w_fp16 = std::make_shared<op::v0::Convert>(w_i4, element::f16);
+ auto scale = op::v0::Constant::create(element::f16, Shape{num_experts, 1}, std::vector<float>(num_experts, 1.0f));
+ auto w_scaled = std::make_shared<op::v1::Multiply>(w_fp16, scale);
+ auto w_fp32 = std::make_shared<op::v0::Convert>(w_scaled, element::f32);
+
+ auto matmul = std::make_shared<op::v0::MatMul>(router_input, w_fp32, false, true);
+ matmul->set_friendly_name(prefix + "linear/MatMul");
+
+ auto bias = op::v0::Constant::create(element::f32, Shape{1, num_experts}, std::vector<float>(num_experts, 0.0f));
+ auto add = std::make_shared<op::v1::Add>(matmul, bias);
+ add->set_friendly_name(prefix + "linear/Add");
+
+ Output<Node> k_input;
+ if (k_param_as_input) {
+ auto k_param = std::make_shared<op::v0::Parameter>(element::i64, Shape{});
+ k_param->set_friendly_name("k_param");
+ if (extra_params)
+ extra_params->push_back(k_param);
+ k_input = k_param->output(0);
+ } else {
+ k_input = op::v0::Constant::create(element::i64, Shape{}, std::vector<int64_t>{k_value})->output(0);
+ }
+
+ auto topk =
+ std::make_shared<op::v11::TopK>(add, k_input, -1, op::v11::TopK::Mode::MAX, op::v11::TopK::SortType::NONE);
+ topk->set_friendly_name(prefix + "topk/TopK");
+
+ auto softmax = std::make_shared<op::v8::Softmax>(topk->output(0), 1);
+
+ auto begin_c = op::v0::Constant::create(element::i64, Shape{1}, {0LL});
+ auto end_c = op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{k_value});
+ auto step_c = op::v0::Constant::create(element::i64, Shape{1}, {1LL});
+ auto axes_c = op::v0::Constant::create(element::i64, Shape{1}, {1LL});
+ auto slice = std::make_shared<op::v8::Slice>(softmax, begin_c, end_c, step_c, axes_c);
+
+ // ScatterElementsUpdate is the GPTOSSRouter pattern root.
+ auto zero_base =
+ op::v0::Constant::create(element::f32, Shape{1, num_experts}, std::vector<float>(num_experts, 0.0f));
+ auto scatter_axis = op::v0::Constant::create(element::i64, Shape{}, {1LL});
+ return std::make_shared<op::v12::ScatterElementsUpdate>(zero_base, topk->output(1), slice, scatter_axis);
+}
+
+std::shared_ptr<Model> build_gptoss_router_graph(int64_t k_value,
+ bool k_param_as_input = false,
+ size_t hidden_dim = 16,
+ size_t num_experts = 8) {
+ auto router_input = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, hidden_dim});
+ router_input->set_friendly_name("router_input");
+ ParameterVector params{router_input};
+ auto out = build_gptoss_router_layer(router_input, k_value, 0, num_experts, k_param_as_input, &params);
+ return std::make_shared<Model>(ResultVector{std::make_shared<op::v0::Result>(out)}, params);
+}
+
+std::shared_ptr<Model> build_two_gptoss_router_model(int64_t k0,
+ int64_t k1,
+ size_t hidden_dim = 16,
+ size_t num_experts = 8) {
+ auto router_input = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, hidden_dim});
+ router_input->set_friendly_name("router_input");
+ ResultVector results;
+ for (int i = 0; i < 2; ++i) {
+ auto out = build_gptoss_router_layer(router_input, i == 0 ? k0 : k1, i, num_experts);
+ results.push_back(std::make_shared<op::v0::Result>(out));
+ }
+ return std::make_shared<Model>(results, ParameterVector{router_input});
+}
+
+// Build one Qwen3 Router layer attached to router_input and return its
+// Unsqueeze output (the pattern root).
+std::shared_ptr<Node> build_qwen3_router_layer(const std::shared_ptr<op::v0::Parameter>& router_input,
+ int64_t k_value,
+ int layer_idx,
+ size_t num_experts) {
+ const size_t hidden_dim = router_input->get_shape()[1];
+ const std::string prefix = "__module.model.layer" + std::to_string(layer_idx) + ".mlp.router/";
+
+ auto w_const = op::v0::Constant::create(element::f16,
+ Shape{num_experts, hidden_dim},
+ std::vector<float>(num_experts * hidden_dim, 1.0f));
+ auto w_convert_in = std::make_shared<op::v0::Convert>(w_const, element::f32);
+ auto scale = op::v0::Constant::create(element::f32, Shape{num_experts, 1}, std::vector<float>(num_experts, 1.0f));
+ auto w_multiply = std::make_shared<op::v1::Multiply>(w_convert_in, scale);
+ auto w_convert_out = std::make_shared<op::v0::Convert>(w_multiply, element::f32);
+
+ auto matmul = std::make_shared<op::v0::MatMul>(router_input, w_convert_out, false, true);
+ matmul->set_friendly_name(prefix + "MatMul");
+
+ auto softmax = std::make_shared<op::v8::Softmax>(matmul, 1);
+
+ auto k_const = op::v0::Constant::create(element::i64, Shape{}, std::vector<int64_t>{k_value});
+ auto topk =
+ std::make_shared<op::v11::TopK>(softmax, k_const, -1, op::v11::TopK::Mode::MAX, op::v11::TopK::SortType::NONE);
+ topk->set_friendly_name(prefix + "TopK");
+
+ auto reduce_axes = op::v0::Constant::create(element::i64, Shape{1}, {1LL});
+ auto reduce_sum = std::make_shared<op::v1::ReduceSum>(topk->output(0), reduce_axes, true);
+ auto divide = std::make_shared<op::v1::Divide>(topk->output(0), reduce_sum);
+
+ auto base = op::v0::Constant::create(element::f32, Shape{1, num_experts}, std::vector<float>(num_experts, 0.0f));
+ auto scatter_axis = op::v0::Constant::create(element::i64, Shape{}, {1LL});
+ auto scatter = std::make_shared<op::v12::ScatterElementsUpdate>(base, topk->output(1), divide, scatter_axis);
+
+ auto t_order = op::v0::Constant::create(element::i32, Shape{2}, std::vector<int32_t>{1, 0});
+ auto transpose = std::make_shared<op::v1::Transpose>(scatter, t_order);
+
+ auto reshape_shape =
+ op::v0::Constant::create(element::i64, Shape{3}, std::vector<int64_t>{static_cast<int64_t>(num_experts), 1, 1});
+ auto reshape = std::make_shared<op::v1::Reshape>(transpose, reshape_shape, false);
+
+ auto unsqueeze_axis = op::v0::Constant::create(element::i64, Shape{}, {3LL});
+ return std::make_shared<op::v0::Unsqueeze>(reshape, unsqueeze_axis);
+}
+
+std::shared_ptr<Model> build_qwen3_router_graph(int64_t k_value, size_t hidden_dim = 16, size_t num_experts = 8) {
+ auto router_input = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, hidden_dim});
+ router_input->set_friendly_name("router_input");
+ auto out = build_qwen3_router_layer(router_input, k_value, 0, num_experts);
+ return std::make_shared<Model>(ResultVector{std::make_shared<op::v0::Result>(out)}, ParameterVector{router_input});
+}
+
+std::shared_ptr<Model> build_two_qwen3_router_model(int64_t k0,
+ int64_t k1,
+ size_t hidden_dim = 16,
+ size_t num_experts = 8) {
+ auto router_input = std::make_shared<op::v0::Parameter>(element::f32, Shape{1, hidden_dim});
+ router_input->set_friendly_name("router_input");
+ ResultVector results;
+ for (int i = 0; i < 2; ++i) {
+ auto out = build_qwen3_router_layer(router_input, i == 0 ? k0 : k1, i, num_experts);
+ results.push_back(std::make_shared<op::v0::Result>(out));
+ }
+ return std::make_shared<Model>(results, ParameterVector{router_input});
+}
+
+// Find all TopK nodes in a model.
+std::vector<std::shared_ptr<op::v11::TopK>> find_all_topk(const std::shared_ptr<Model>& model) {
+ std::vector<std::shared_ptr<op::v11::TopK>> result;
+ for (const auto& node : model->get_ordered_ops()) {
+ if (auto topk = std::dynamic_pointer_cast<op::v11::TopK>(node))
+ result.push_back(topk);
+ }
+ return result;
+}
+
+// ============================================================================
+// Test fixtures — one per router type
+// ============================================================================
+
+class GPTOSSRouterTest : public ::testing::Test {
+protected:
+ void run_pass(const std::shared_ptr<Model>& model) {
+ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(model);
+ ov::pass::GraphRewrite rewr;
+ rewr.add_matcher<ov::npuw::patterns::moe::GPTOSSRouter>(snapshot, "router");
+ rewr.run_on_model(model);
+ }
+};
+
+class Qwen3RouterTest : public ::testing::Test {
+protected:
+ void run_pass(const std::shared_ptr<Model>& model) {
+ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(model);
+ ov::pass::GraphRewrite rewr;
+ rewr.add_matcher<ov::npuw::patterns::moe::Qwen3Router>(snapshot, "router");
+ rewr.run_on_model(model);
+ }
+};
+
+// ============================================================================
+// GPTOSSRouter tests
+// ============================================================================
+
+TEST_F(GPTOSSRouterTest, TagsTopKWithCorrectK) {
+ constexpr int64_t K = 4;
+ auto model = build_gptoss_router_graph(K);
+ run_pass(model);
+
+ auto topks = find_all_topk(model);
+ ASSERT_EQ(topks.size(), 1u);
+ const auto& rt = topks[0]->get_rt_info();
+ ASSERT_NE(rt.find(ov::npuw::patterns::moe::RT_INFO_MOE_K), rt.end());
+ EXPECT_EQ(rt.at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), static_cast<size_t>(K));
+}
+
+TEST_F(GPTOSSRouterTest, NonConstKNotTagged) {
+ // When K is a runtime Parameter, tag_topk_k() returns false — no rt_info entry.
+ constexpr int64_t K = 4;
+ auto model = build_gptoss_router_graph(K, /*k_param_as_input=*/true);
+ run_pass(model);
+
+ auto topks = find_all_topk(model);
+ ASSERT_EQ(topks.size(), 1u);
+ EXPECT_EQ(topks[0]->get_rt_info().find(ov::npuw::patterns::moe::RT_INFO_MOE_K), topks[0]->get_rt_info().end())
+ << "rt_info K must NOT be set when K input is a Parameter";
+}
+
+TEST_F(GPTOSSRouterTest, ZeroKNotTagged) {
+ // K=0 is invalid; tag_topk_k() must return false without tagging.
+ auto model = build_gptoss_router_graph(/*k_value=*/0);
+ run_pass(model);
+
+ auto topks = find_all_topk(model);
+ ASSERT_EQ(topks.size(), 1u);
+ EXPECT_EQ(topks[0]->get_rt_info().find(ov::npuw::patterns::moe::RT_INFO_MOE_K), topks[0]->get_rt_info().end())
+ << "rt_info K must NOT be set when K=0";
+}
+
+TEST_F(GPTOSSRouterTest, RouterNodesNotIsolated) {
+ // Callback must return false without isolating any node.
+ constexpr int64_t K = 4;
+ auto model = build_gptoss_router_graph(K);
+ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(model);
+ snapshot->buildGraph();
+
+ ov::pass::GraphRewrite rewr;
+ rewr.add_matcher<ov::npuw::patterns::moe::GPTOSSRouter>(snapshot, "router");
+ rewr.run_on_model(model);
+
+ for (const auto& [node, group] : *snapshot->getNodeToGroupMap()) {
+ EXPECT_NE(group->isolatedTag(), "router")
+ << "Node \"" << node->get_friendly_name() << "\" was unexpectedly isolated";
+ }
+}
+
+TEST_F(GPTOSSRouterTest, ConsistentKAcrossLayersTagsBothNodes) {
+ constexpr int64_t K = 2;
+ auto model = build_two_gptoss_router_model(K, K);
+ ASSERT_NO_THROW(run_pass(model));
+
+ auto topks = find_all_topk(model);
+ ASSERT_EQ(topks.size(), 2u);
+ for (const auto& topk : topks) {
+ const auto& rt = topk->get_rt_info();
+ ASSERT_NE(rt.find(ov::npuw::patterns::moe::RT_INFO_MOE_K), rt.end())
+ << "TopK \"" << topk->get_friendly_name() << "\" was not tagged";
+ EXPECT_EQ(rt.at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), static_cast<size_t>(K));
+ }
+}
+
+TEST_F(GPTOSSRouterTest, InconsistentKAcrossLayersThrows) {
+ auto model = build_two_gptoss_router_model(/*k0=*/2, /*k1=*/4);
+ EXPECT_THROW(run_pass(model), ov::Exception) << "Inconsistent K values across MoE layers must throw";
+}
+
+// ============================================================================
+// Qwen3Router tests
+// ============================================================================
+
+TEST_F(Qwen3RouterTest, TagsTopKWithCorrectK) {
+ constexpr int64_t K = 2;
+ auto model = build_qwen3_router_graph(K);
+ run_pass(model);
+
+ auto topks = find_all_topk(model);
+ ASSERT_EQ(topks.size(), 1u);
+ const auto& rt = topks[0]->get_rt_info();
+ ASSERT_NE(rt.find(ov::npuw::patterns::moe::RT_INFO_MOE_K), rt.end());
+ EXPECT_EQ(rt.at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), static_cast<size_t>(K));
+}
+
+TEST_F(Qwen3RouterTest, RouterNodesNotIsolated) {
+ // Callback must return false without isolating any node.
+ constexpr int64_t K = 2;
+ auto model = build_qwen3_router_graph(K);
+ auto snapshot = std::make_shared<ov::npuw::online::Snapshot>(model);
+ snapshot->buildGraph();
+
+ ov::pass::GraphRewrite rewr;
+ rewr.add_matcher<ov::npuw::patterns::moe::Qwen3Router>(snapshot, "router");
+ rewr.run_on_model(model);
+
+ for (const auto& [node, group] : *snapshot->getNodeToGroupMap()) {
+ EXPECT_NE(group->isolatedTag(), "router")
+ << "Node \"" << node->get_friendly_name() << "\" was unexpectedly isolated";
+ }
+}
+
+TEST_F(Qwen3RouterTest, ConsistentKAcrossLayersTagsBothNodes) {
+ constexpr int64_t K = 3;
+ auto model = build_two_qwen3_router_model(K, K);
+ ASSERT_NO_THROW(run_pass(model));
+
+ auto topks = find_all_topk(model);
+ ASSERT_EQ(topks.size(), 2u);
+ for (const auto& topk : topks) {
+ const auto& rt = topk->get_rt_info();
+ ASSERT_NE(rt.find(ov::npuw::patterns::moe::RT_INFO_MOE_K), rt.end())
+ << "TopK \"" << topk->get_friendly_name() << "\" was not tagged";
+ EXPECT_EQ(rt.at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), static_cast<size_t>(K));
+ }
+}
+
+TEST_F(Qwen3RouterTest, InconsistentKAcrossLayersThrows) {
+ auto model = build_two_qwen3_router_model(/*k0=*/2, /*k1=*/3);
+ EXPECT_THROW(run_pass(model), ov::Exception) << "Inconsistent K values across MoE layers must throw";
+}
+
+} // namespace