Skip to content

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

[NPUW][MoE]Support 3D router output shape. (#36914)

intelgaoxiong2853fcc1f05a
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
index 87ab92f1339..6ec861aba6b 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
@@ -489,14 +489,21 @@ void apply_moe_config(ov::AnyMap& stage_config,
const std::string& stage_name) {
if (moe_hint == ::intel_npu::npuw::llm::MoEHint::HOST_ROUTED) {
LOG_INFO("MoE config for " << stage_name << " stage: HOST_ROUTED (host-side expert routing)");
- // MoE expert and router pattern isolation options
+ // Set NPUW_ONLINE_ISOLATE separately: append "MOE" to any existing preset (e.g. "ATTN")
+ // instead of using merge_config_with, which would silently overwrite it.
const ov::AnyMap expert_opts = {
{"NPUW_ONLINE_PIPELINE", "REP"},
- {"NPUW_ONLINE_ISOLATE", "MOE"},
{"NPUW_ONLINE_KEEP_BLOCK_SIZE", "4"},
{"NPUW_UNFOLD_IREQS", "NO"},
};
merge_config_with(stage_config, expert_opts);
+ auto isol_it = stage_config.find("NPUW_ONLINE_ISOLATE");
+ if (isol_it != stage_config.end() && !isol_it->second.as<std::string>().empty()) {
+ isol_it->second = isol_it->second.as<std::string>() + ",MOE";
+ LOG_INFO("MoE config: appended MOE to NPUW_ONLINE_ISOLATE -> " << isol_it->second.as<std::string>());
+ } else {
+ stage_config["NPUW_ONLINE_ISOLATE"] = "MOE";
+ }
} else if (moe_hint == ::intel_npu::npuw::llm::MoEHint::DEVICE_ROUTED) {
if (stage_name == "PREFILL") {
NPUW_ASSERT(false && "MoE DEVICE_ROUTED is not supported for PREFILL stage. "
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 c307f6bda64..c539f97695c 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
@@ -347,9 +347,17 @@ void MoEExecutor::run_expert_iterative(size_t idx) {
auto expert_input_source = io.expert_input;
- // Output embedding dimension
- const auto output_shape = m_config.compiled_models.begin()->second->outputs()[0].get_shape();
- const size_t embed_dim = (output_shape.size() == 4) ? output_shape[3] : output_shape[1];
+ // Use the embed_dim already validated against the accumulator buffer during prepare().
+ // Defensively assert that the compiled model's output last-dim agrees, so any future
+ // layout change (2D/3D/4D) is caught immediately at runtime instead of producing
+ // silently wrong scatter results.
+ const size_t embed_dim = m_config.expert_hidden_dim;
+ {
+ const auto output_shape = m_config.compiled_models.begin()->second->outputs()[0].get_shape();
+ NPUW_ASSERT(!output_shape.empty() && output_shape.back() == embed_dim &&
+ "Chunk model output last-dim does not match expert_hidden_dim — "
+ "layout may have changed, update embed_dim derivation");
+ }
// num_tokens and num_experts come from config, validated once during prepare().
// The router tensor's token dimension is guaranteed to match input_token_count because
@@ -676,32 +684,20 @@ void MoEExecutor::unpack_single_expert_closure(std::size_t idx, RqPtr request, s
// Slice expert weight using view (no copy) - returns ov::Tensor object
auto sliced_weight_tensor = ov::npuw::moe::slice_expert_weight(closure, expert_id, num_experts);
- // Get impl pointer for use in unpacking/setting
+ // Get impl pointer for use in setting
auto sliced_weight = ov::get_tensor_impl(sliced_weight_tensor);
- // Handle unpacking if needed
- if (m_accessor.unpack_required(idx, cidx)) {
- auto clparam = request->get_tensor(iport);
+ // Unpack is not expected for MoE sliced weights — assert to catch if this changes.
+ NPUW_ASSERT(!m_accessor.unpack_required(idx, cidx) &&
+ "EXPERT_ITERATIVE: unpack of sliced MoE weight is not supported");
- if (!comp_model_desc.scales.empty() && comp_model_desc.scales[cidx] && comp_model_desc.zerops[cidx]) {
- ov::npuw::util::unpack(sliced_weight,
- ov::get_tensor_impl(comp_model_desc.zerops[cidx]),
- ov::get_tensor_impl(comp_model_desc.scales[cidx]),
- clparam);
- } else if (!comp_model_desc.scales.empty() && comp_model_desc.scales[cidx]) {
- ov::npuw::util::unpack(sliced_weight, ov::get_tensor_impl(comp_model_desc.scales[cidx]), clparam);
- } else {
- ov::npuw::util::unpack(sliced_weight, clparam);
- }
+ // Direct set (no unpacking needed)
+ // When cache is enabled: Use direct set_tensor to avoid polluting shared input tensors
+ // When cache is disabled: Use set_tensor_optimized for better performance (copies small tensors)
+ if (m_resources.request_cache) {
+ request->set_tensor(iport, sliced_weight);
} else {
- // Direct set (no unpacking needed)
- // When cache is enabled: Use direct set_tensor to avoid polluting shared input tensors
- // When cache is disabled: Use set_tensor_optimized for better performance (copies small tensors)
- if (m_resources.request_cache) {
- request->set_tensor(iport, sliced_weight);
- } else {
- ov::npuw::moe::set_tensor_optimized(request, iport, sliced_weight);
- }
+ ov::npuw::moe::set_tensor_optimized(request, iport, sliced_weight);
}
} else {
// This closure parameter doesn't need slicing, use original logic
@@ -767,18 +763,24 @@ void MoEExecutor::unpack_multiple_experts_closure(std::size_t idx,
// Calculate original parameter index in the model
const size_t original_param_idx = comp_model_desc.param_base + closure_idx;
+ auto& batched_closure = desc_closure[closure_idx];
+ const auto& closure_shape = batched_closure.get_shape();
+
// Check if this parameter has unrolled variants (is in param_mapping)
auto mapping_it = param_mapping.find(original_param_idx);
if (mapping_it == param_mapping.end()) {
- continue; // Not unrolled
+ // If the closure is batched [num_experts,...] but has no param_mapping entry, the
+ // expert-dimension unrolling (UnrollMoEMatMul) failed to fire for this weight.
+ // This is a transformation bug — assert to surface it early.
+ const bool is_batched_nounroll = !closure_shape.empty() && closure_shape[0] == num_experts;
+ NPUW_ASSERT(!is_batched_nounroll &&
+ "Batched closure has no param_mapping entry — UnrollMoEMatMul did not fire");
+ continue; // Non-batched shared param not in mapping — skip silently
}
const auto& unrolled_indices = mapping_it->second;
NPUW_ASSERT(unrolled_indices.size() == K);
- auto& batched_closure = desc_closure[closure_idx];
- const auto& closure_shape = batched_closure.get_shape();
-
// Verify this is a batched parameter [num_experts, ...]
const bool is_batched = !closure_shape.empty() && closure_shape[0] == num_experts;
if (!is_batched) {
@@ -799,53 +801,27 @@ void MoEExecutor::unpack_multiple_experts_closure(std::size_t idx,
// ========== Step 3: Process batched parameters (K experts) ==========
- // Pre-determine unpack configuration (same for all K experts)
+ // Unpack is not expected for MoE unrolled weights — assert to catch if this changes.
const auto batched_elem_type = batched_closure.get_element_type();
const auto target_elem_type = request->get_tensor(compiled_inputs[unrolled_indices[0]])->get_element_type();
- const bool needs_unpack = (batched_elem_type != target_elem_type);
-
- ov::SoPtr<ov::ITensor> scales_impl, zerops_impl;
- if (needs_unpack) {
- if (!comp_model_desc.scales.empty() && comp_model_desc.scales[closure_idx]) {
- scales_impl = ov::get_tensor_impl(comp_model_desc.scales[closure_idx]);
- }
- if (!comp_model_desc.zerops.empty() && comp_model_desc.zerops[closure_idx]) {
- zerops_impl = ov::get_tensor_impl(comp_model_desc.zerops[closure_idx]);
- }
- }
+ NPUW_ASSERT(batched_elem_type == target_elem_type &&
+ "EXPERT_BATCH: dtype mismatch in MoE closure, unpack path is not supported");
- // Process K experts
+ // Process K experts (direct set, no unpacking)
for (size_t position = 0; position < K; ++position) {
const size_t expert_id = expert_ids[position];
const auto& iport = compiled_inputs[unrolled_indices[position]];
- // Slice expert weight (zero-copy view)
+ // Slice expert weight (zero-copy view) and bind directly to the request port.
ov::Tensor sliced_expert = ov::npuw::moe::slice_expert_weight(batched_closure, expert_id, num_experts);
+ auto sliced_impl = ov::get_tensor_impl(sliced_expert);
- if (needs_unpack) {
- // Unpack path (dtype mismatch)
- auto sliced_impl = ov::get_tensor_impl(sliced_expert);
- auto clparam = request->get_tensor(iport);
-
- if (scales_impl && zerops_impl) {
- ov::npuw::util::unpack(sliced_impl, zerops_impl, scales_impl, clparam);
- } else if (scales_impl) {
- ov::npuw::util::unpack(sliced_impl, scales_impl, clparam);
- } else if (zerops_impl) {
- ov::npuw::util::unpack(sliced_impl, zerops_impl, clparam);
- } else {
- ov::npuw::util::unpack(sliced_impl, clparam);
- }
+ // When cache is enabled: use set_tensor to avoid polluting shared input tensors.
+ // When cache is disabled: use set_tensor_optimized (copies small tensors, faster).
+ if (m_resources.request_cache) {
+ request->set_tensor(iport, sliced_impl);
} else {
- auto sliced_impl = ov::get_tensor_impl(sliced_expert);
- // Direct set (no unpacking needed)
- // When cache is enabled: Use direct set_tensor to avoid polluting shared input tensors
- // When cache is disabled: Use set_tensor_optimized for better performance (copies small tensors)
- if (m_resources.request_cache) {
- request->set_tensor(iport, sliced_impl);
- } else {
- ov::npuw::moe::set_tensor_optimized(request, iport, sliced_impl);
- }
+ ov::npuw::moe::set_tensor_optimized(request, iport, sliced_impl);
}
} // for each expert
} // for each closure parameter
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp
index 789cdc253a6..6b729d9ebbb 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe/moe_infer_utils.cpp
@@ -66,19 +66,20 @@ ov::Tensor slice_expert_weight(const ov::Tensor& batched_weight, size_t expert_i
}
namespace {
-// Returns the token-count dimension from a 4-D router output shape.
-// Two layout variants exist depending on the opset version used during model export:
-// Layout A: [num_experts, 1, token_num, 1] → returns shape[2]
-// Layout B: [num_experts, token_num, 1, 1] → returns shape[1]
-// ASSERTs if neither layout is recognised.
+// Returns the token-count dimension from a router output shape.
+// All supported layouts have a trailing singleton dim:
+// [N, token, 1] (3-D) → token at dim 1
+// [N, 1, token, 1] (4-D, dim1=1) → token at dim 2
+// [N, token, 1, 1] (4-D, dim1≠1) → token at dim 1
+// ASSERTs if rank ∉ {3, 4} or trailing dim ≠ 1.
static size_t get_router_token_count(const ov::Shape& router_shape) {
- NPUW_ASSERT(router_shape.size() == 4);
- if (router_shape[1] == 1 && router_shape[3] == 1)
- return router_shape[2]; // Layout A
- if (router_shape[2] == 1 && router_shape[3] == 1)
- return router_shape[1]; // Layout B
- NPUW_ASSERT(false && "Unexpected router output shape - cannot determine token dimension!");
- return 0; // unreachable, suppress warning
+ const auto rank = router_shape.size();
+ NPUW_ASSERT((rank == 3 || rank == 4) && router_shape.back() == 1 &&
+ "Router shape must be 3-D or 4-D with trailing singleton");
+ // [N, 1, token, 1] is the only layout where dim 1 is a singleton rather than the token dim.
+ if (rank == 4 && router_shape[1] == 1)
+ return router_shape[2]; // [N, 1, token, 1]
+ return router_shape[1]; // [N, token, 1, 1] or [N, token, 1]
}
} // namespace
@@ -95,7 +96,7 @@ std::vector<size_t> parse_selected_experts_from_router(const ov::SoPtr<ov::ITens
expert_to_tokens.clear();
auto shape = router_output->get_shape();
- if (shape.size() != 4 || shape[0] != num_experts) {
+ if ((shape.size() != 4 && shape.size() != 3) || shape[0] != num_experts) {
NPUW_ASSERT(false && "Unexpected router output shape!");
}
@@ -164,16 +165,7 @@ void gather_router_scores(const ov::SoPtr<ov::ITensor>& router_source,
size_t chunk_start,
size_t chunk_size) {
const auto router_source_shape = router_source->get_shape();
-
- size_t expert_offset;
- if (router_source_shape.size() == 4) {
- expert_offset = expert_id * get_router_token_count(router_source_shape);
- } else if (router_source_shape.size() == 2) {
- expert_offset = expert_id * router_source_shape[1]; // [num_experts, token_num]
- } else {
- NPUW_ASSERT(false && "Unexpected router source shape");
- expert_offset = 0; // unreachable, suppress uninitialized warning
- }
+ const size_t expert_offset = expert_id * get_router_token_count(router_source_shape);
auto gather = [&](const auto* src_base, auto* dst_base) {
const size_t* ids = token_ids.data() + chunk_start;
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 d6102c19da4..2f7abb5eccf 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
@@ -385,38 +385,32 @@ std::optional<MoEDownstream> detect_and_transform_moe_downstream(const std::shar
LOG_DEBUG("Detecting MoE downstream pattern...");
LOG_BLOCK();
- // Pattern to match: Parameter -> [Convert] -> ReduceSum
- // Looking for a parameter with shape [N, ..., W] where:
- // dim 0 = N (total experts, > 1)
- // dim n-1 = W (hidden_dim)
- // at least one of dims 1..n-2 equals 1 (singleton "batch" dimension)
- // Both [N, 1, H, W] (GPT-OSS) and [N, H, 1, W] (Qwen) are accepted.
+ // Pattern: Parameter -> [Convert] -> ReduceSum, shape [N, ..., W] where:
+ // rank 3: [N, token, W]
+ // rank 4: [N, 1, H, W] or [N, H, 1, W]
+ // shape[0] = N > 1 (num_experts).
const auto& params = model->get_parameters();
for (size_t param_idx = 0; param_idx < params.size(); ++param_idx) {
const auto& param = params[param_idx];
- // Validate shape: must be 4-D with dim 0 > 1
- auto param_shape = param->get_partial_shape();
- if (!param_shape.rank().is_static() || param_shape.rank().get_length() != 4) {
- continue;
- }
-
- auto shape = param_shape.to_shape();
- if (shape[0] <= 1) {
- continue;
- }
-
- // At least one of dims 1..2 must be 1 (singleton expansion dim)
- bool has_singleton_dim = (shape[1] == 1 || shape[2] == 1);
- if (!has_singleton_dim) {
+ auto shape_opt = [&]() -> std::optional<ov::Shape> {
+ const auto ps = param->get_partial_shape();
+ if (!ps.rank().is_static())
+ return std::nullopt;
+ const auto rank = ps.rank().get_length();
+ if (rank < 3 || rank > 4)
+ return std::nullopt;
+ const auto s = ps.to_shape();
+ if (s[0] <= 1)
+ return std::nullopt;
+ if (rank == 4 && s[1] != 1 && s[2] != 1)
+ return std::nullopt;
+ return s;
+ }();
+ if (!shape_opt || !check_downstream_pattern(param))
continue;
- }
-
- // Check pattern: Parameter -> Convert -> ReduceSum
- if (!check_downstream_pattern(param)) {
- continue;
- }
+ const auto& shape = *shape_opt;
LOG_DEBUG(" Found downstream pattern for Parameter: " << param->get_friendly_name());
LOG_DEBUG(" Pattern matched: Parameter -> Convert -> ReduceSum");
@@ -872,14 +866,14 @@ std::optional<MoEExperts> MoEExperts::from(const std::shared_ptr<ov::Model>& mod
LOG_INFO("Using K=" << k_value << " active experts");
- // Step 2: Analyze model structure
+ // Step 1: Analyze model structure
auto structure_info = analyze_moe_structure(model);
if (!structure_info || !structure_info->is_valid()) {
LOG_WARN("Model structure analysis failed for MoE expert pattern");
return std::nullopt;
}
- // Step 3: Determine chunk sizes based on processing mode and configuration
+ // Step 2: Determine chunk sizes based on processing mode and configuration
std::vector<size_t> chunk_sizes;
if (structure_info->is_expert_batch_mode()) {
// EXPERT_BATCH mode: single model with K active experts, no chunking
@@ -895,7 +889,7 @@ std::optional<MoEExperts> MoEExperts::from(const std::shared_ptr<ov::Model>& mod
}
}
- // Tag activation parameters before transformation so we can re-locate them afterwards
+ // Step 3: Tag activation parameters before transformation so we can re-locate them afterwards
// (transformations may shift parameter indices).
constexpr const char* expert_input_tag = "npuw_moe_expert_input";
constexpr const char* router_scores_tag = "npuw_moe_router_scores";
@@ -946,7 +940,44 @@ std::optional<MoEExperts> MoEExperts::from(const std::shared_ptr<ov::Model>& mod
// For EXPERT_BATCH mode (K experts), unrolling creates the same mapping structure
auto param_mapping = build_parameter_mapping_from_rtinfo(model, transformed_models.begin()->second);
- // Step 6: Populate and validate MoEExperts structure
+ // Step 6: EXPERT_BATCH guard — every param with shape[0]==num_experts must appear in
+ // param_mapping with exactly K entries; a missing entry means UnrollMoEMatMul did not
+ // recognise the weight chain and inference would produce silently wrong results.
+ if (structure_info->is_expert_batch_mode()) {
+ const auto& orig_params = model->get_parameters();
+ for (size_t pi = 0; pi < orig_params.size(); ++pi) {
+ const auto& pshape = orig_params[pi]->get_partial_shape();
+ if (!pshape.rank().is_static() || !pshape[0].is_static())
+ continue;
+ if (static_cast<size_t>(pshape[0].get_length()) != structure_info->num_experts)
+ continue;
+ // This parameter is batched over the expert dimension and must be unrolled.
+ auto it = param_mapping.find(pi);
+ if (it == param_mapping.end()) {
+ OPENVINO_THROW("MoE EXPERT_BATCH: parameter '",
+ orig_params[pi]->get_friendly_name(),
+ "' (index=",
+ pi,
+ ", shape=",
+ pshape,
+ ") has shape[0]==num_experts but was not unrolled. "
+ "UnrollMoEMatMul did not recognise its weight chain. "
+ "Inspect the weight graph topology and add the missing chain variant.");
+ }
+ if (it->second.size() != static_cast<size_t>(k_value)) {
+ OPENVINO_THROW("MoE EXPERT_BATCH: parameter '",
+ orig_params[pi]->get_friendly_name(),
+ "' was unrolled into ",
+ it->second.size(),
+ " entries but expected K=",
+ k_value);
+ }
+ }
+ LOG_DEBUG("Compile-time unroll validation passed: all "
+ << param_mapping.size() << " batched parameters are correctly mapped (K=" << k_value << ")");
+ }
+
+ // Step 7: Populate and validate MoEExperts structure
MoEExperts moe_experts;
moe_experts._num_experts = structure_info->num_experts;
moe_experts._expert_hidden_dim = structure_info->expert_hidden_dim;
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 11dac1004c4..6b3f7567adf 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
@@ -465,9 +465,13 @@ Qwen3Router::Qwen3Router([[maybe_unused]] const std::shared_ptr<ov::npuw::online
auto reduce_sum = opp::wrap_type<ov::op::v1::ReduceSum>({topk, opp::any_input()});
auto divide = opp::wrap_type<ov::op::v1::Divide>({topk, reduce_sum});
+ auto topk_to_scatter = opp::optional<ov::op::v0::Convert>({topk});
+ auto divide_to_scatter = opp::optional<ov::op::v8::Slice>(
+ {divide, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});
+
// Scatter to full expert shape (pattern root = Unsqueeze)
- auto scatter =
- opp::wrap_type<ov::op::v12::ScatterElementsUpdate>({opp::any_input(), topk, divide, opp::any_input()});
+ auto scatter = opp::wrap_type<ov::op::v12::ScatterElementsUpdate>(
+ {opp::any_input(), topk_to_scatter, divide_to_scatter, opp::any_input()});
auto transpose = opp::wrap_type<ov::op::v1::Transpose>({scatter, opp::any_input()});
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()});
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
index bb19a8b1d02..cdeedbdf2fa 100644
--- 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
@@ -105,7 +105,8 @@ std::shared_ptr<Model> build_two_gptoss_router_model(int64_t k0,
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) {
+ size_t num_experts,
+ bool with_convert_and_slice = false) {
const size_t hidden_dim = router_input->get_shape()[1];
const std::string prefix = "__module.model.layer" + std::to_string(layer_idx) + ".mlp.router/";
@@ -131,9 +132,24 @@ std::shared_ptr<Node> build_qwen3_router_layer(const std::shared_ptr<op::v0::Par
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);
+ Output<Node> scatter_indices = topk->output(1);
+ Output<Node> scatter_scores = divide->output(0);
+ if (with_convert_and_slice) {
+ // Convert on TopK indices (i64 -> i32)
+ scatter_indices = std::make_shared<op::v0::Convert>(topk->output(1), element::i32)->output(0);
+ // Slice on renormalized scores (no-op [0:1] along axis 0)
+ auto slice_begin = op::v0::Constant::create(element::i64, Shape{1}, {0LL});
+ auto slice_end = op::v0::Constant::create(element::i64, Shape{1}, {1LL});
+ auto slice_step = op::v0::Constant::create(element::i64, Shape{1}, {1LL});
+ auto slice_axes = op::v0::Constant::create(element::i64, Shape{1}, {0LL});
+ scatter_scores =
+ std::make_shared<op::v8::Slice>(divide, slice_begin, slice_end, slice_step, slice_axes)->output(0);
+ }
+
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 scatter =
+ std::make_shared<op::v12::ScatterElementsUpdate>(base, scatter_indices, scatter_scores, 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);
@@ -153,6 +169,15 @@ std::shared_ptr<Model> build_qwen3_router_graph(int64_t k_value, size_t hidden_d
return std::make_shared<Model>(ResultVector{std::make_shared<op::v0::Result>(out)}, ParameterVector{router_input});
}
+std::shared_ptr<Model> build_qwen3_router_graph_with_convert_and_slice(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, /*with_convert_and_slice=*/true);
+ 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,
@@ -330,4 +355,35 @@ TEST_F(Qwen3RouterTest, InconsistentKAcrossLayersThrows) {
EXPECT_THROW(run_pass(model), ov::Exception) << "Inconsistent K values across MoE layers must throw";
}
+TEST_F(Qwen3RouterTest, TagsTopKWithCorrectK_WithConvertAndSlice) {
+ // Verifies that the optional Convert(indices) + Slice(scores) path still tags K correctly.
+ constexpr int64_t K = 2;
+ auto model = build_qwen3_router_graph_with_convert_and_slice(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())
+ << "K must be tagged in the prefill variant (Convert+Slice between TopK/Divide and Scatter)";
+ EXPECT_EQ(rt.at(ov::npuw::patterns::moe::RT_INFO_MOE_K).as<size_t>(), static_cast<size_t>(K));
+}
+
+TEST_F(Qwen3RouterTest, RouterNodesNotIsolated_WithConvertAndSlice) {
+ // Verifies that the callback returns false (no isolation) for the with_convert_and_slice variant too.
+ constexpr int64_t K = 2;
+ auto model = build_qwen3_router_graph_with_convert_and_slice(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 in with_convert_and_slice variant";
+ }
+}
+
} // namespace