OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[NPUW] Add Qwen3 MoE to the test model builder (#36646)
Dylan Nevef4edad2cc349
diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cppindex 0db83393bd7..c0202f1dba1 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp@@ -678,6 +678,7 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {config.norm = LayerNorm(config.hidden_size, config.precision);if (!config.ffn) {if (config.num_experts > 0) {+ // Build the FFN from the config's MoE fields; moe_factory selects the topology (empty = GPT-OSS).size_t moe_inter = config.moe_intermediate_size > 0? config.moe_intermediate_size: config.intermediate_size;@@ -687,8 +688,10 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {OPENVINO_ASSERT(moe_k >= 1 && moe_k <= config.num_experts,"Invalid MoE config: num_experts_per_tok (",moe_k, ") must be in [1, num_experts (", config.num_experts, ")]");- config.ffn = MoEFFN(config.hidden_size, moe_inter, config.num_experts,- moe_k, config.precision);+ if (!config.moe_factory) {+ config.moe_factory = make_gptoss_moe_ffn;+ }+ config.ffn = config.moe_factory(config.hidden_size, moe_inter, config.num_experts, moe_k, config.precision);} else {config.ffn = SwiGLU(config.hidden_size, config.intermediate_size, config.precision, config.weight);}diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hppindex cffe3323691..9a494f7a617 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp@@ -12,6 +12,7 @@#include "model_builder_attention.hpp"#include "model_builder_ffn.hpp"#include "model_builder_masks.hpp"+#include "model_builder_moe.hpp"#include "model_builder_norm.hpp"#include "model_builder_rope.hpp"#include "model_builder_types.hpp"@@ -179,6 +180,7 @@ struct LLMConfig : public BaseModelConfig {size_t num_experts = 0; ///< Total experts. 0 = dense model.size_t num_experts_per_tok = 0; ///< Top-K. 0 = default to 2.size_t moe_intermediate_size = 0; ///< Expert FFN intermediate size. 0 = use intermediate_size.+ MoEFactoryFn moe_factory; ///< MoE topology (num_experts>0). Empty = GPT-OSS; make_qwen3_moe_ffn for Qwen3.size_t sliding_window_size = 0; ///< 0 = no sliding window. >0 = window size (Phi-3, Gemma 2/3)/// 0 = uniform: every layer gets the same mask (all sliding if sliding_window_size > 0,diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_ffn.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_ffn.cppindex 6c9d83c8239..e626eeee015 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_ffn.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_ffn.cpp@@ -42,158 +42,6 @@ ov::Output<ov::Node> GELU::operator()(const ov::Output<ov::Node>& input, const sreturn down;}-MoEFFN::MoEFFN(size_t hs, size_t is, size_t ne, size_t k, ov::element::Type prec, WeightFn wf)- : hidden_size(hs),- intermediate_size(is),- num_experts(ne),- num_experts_per_tok(k),- precision(prec),- weight_fn(std::move(wf)) {- // Default to i4 CompressedWeight if no weight function provided.- // i4 (not nf4) because NPUW's nf4 unpack doesn't handle 3D batched scales.- if (!weight_fn) {- weight_fn = CompressedWeight{ov::element::i4, 0, DCOffPattern::SYMM_NO_ZP};- }- using C = ov::opset11::Constant;- int32_t is_i = static_cast<int32_t>(is);- int32_t ne_i = static_cast<int32_t>(ne);- int32_t k_i = static_cast<int32_t>(k);-- // Use i32 for shape/axis/step constants matching real GPT-OSS HuggingFace export.- tile_repeats = C::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{ne_i, 1});- slice_step = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{1});- slice_axis2 = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{2});- slice_start_0 = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{0});- slice_stop_is = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{is_i});- slice_start_is = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{is_i});- slice_stop_2is = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{static_cast<int32_t>(2 * is_i)});- min_const = C::create(prec, ov::Shape{1}, std::vector<float>{20.0f});- swish_beta = C::create(prec, ov::Shape{}, std::vector<float>{1.0f});- clamp_add_zero = C::create(prec, ov::Shape{1}, std::vector<float>{0.0f});- topk_k_const = C::create(ov::element::i32, ov::Shape{}, std::vector<int32_t>{k_i});- sl_start = C::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{0, 0});- sl_step_r = C::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{1, 1});- sl_axes = C::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{0, 1});- scatter_axis = C::create(ov::element::i32, ov::Shape{}, std::vector<int32_t>{1});- tp_order = C::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{1, 0});- unsq_axis = C::create(ov::element::i32, ov::Shape{}, std::vector<int32_t>{3});- reduce_axis = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{0});-}--ov::Output<ov::Node> MoEFFN::operator()(const ov::Output<ov::Node>& input, const std::string& name) const {- using C = ov::opset11::Constant;- const auto prec = precision;- const int32_t ne_i = static_cast<int32_t>(num_experts);- const int32_t hs_i = static_cast<int32_t>(hidden_size);- auto mk = [](std::vector<int32_t> v) {- ov::OutputVector p;- for (auto x : v)- p.push_back(C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{x})->output(0));- return std::make_shared<ov::opset11::Concat>(p, 0);- };-- auto original_shape = std::make_shared<ov::opset11::ShapeOf>(input, ov::element::i32);- original_shape->set_friendly_name(name + ".original_shape");-- auto input_2d = std::make_shared<ov::opset11::Reshape>(input, mk({-1, hs_i}), false);- input_2d->set_friendly_name(name + ".input_2d");-- // Router uses i8 weights matching real GPT-OSS two-pass quantization- // (router excluded from 4-bit, gets 8-bit instead).- static const CompressedWeight router_wt{ov::element::i8, 0, DCOffPattern::SYMM_NO_ZP};- auto rw = router_wt(name + ".expert.router.weight", ov::Shape{num_experts, hidden_size}, prec);- auto r_mm = std::make_shared<ov::opset11::MatMul>(input_2d, rw, false, true);- r_mm->set_friendly_name(name + ".expert.router.matmul");- auto r_bias = C::create(prec, ov::Shape{1, num_experts}, std::vector<float>(num_experts, 0.0f));- r_bias->set_friendly_name(name + ".expert.router.bias");- auto r_add = std::make_shared<ov::opset11::Add>(r_mm, r_bias);- r_add->set_friendly_name(name + ".expert.router.add");-- auto topk = std::make_shared<ov::opset11::TopK>(r_add, topk_k_const, 1, "max", "value", ov::element::i64);- topk->set_friendly_name(name + ".expert.router.topk");- auto softmax = std::make_shared<ov::op::v8::Softmax>(topk->output(0), 1);- softmax->set_friendly_name(name + ".expert.router.softmax");- auto topk_cvt = std::make_shared<ov::opset11::Convert>(topk->output(1), ov::element::i32);- topk_cvt->set_friendly_name(name + ".expert.router.topk_convert");- auto topk_shape = std::make_shared<ov::op::v3::ShapeOf>(topk_cvt, ov::element::i32);- topk_shape->set_friendly_name(name + ".expert.router.topk_shapeof");-- auto r_slice = std::make_shared<ov::op::v8::Slice>(softmax, sl_start, topk_shape, sl_step_r, sl_axes);- r_slice->set_friendly_name(name + ".expert.router.slice");- auto add_shape = std::make_shared<ov::op::v3::ShapeOf>(r_add, ov::element::i32);- add_shape->set_friendly_name(name + ".expert.router.add_shapeof");- auto zeros = std::make_shared<ov::op::v3::Broadcast>(C::create(prec, ov::Shape{}, std::vector<float>{0.0f}),- add_shape,- ov::op::BroadcastType::NUMPY);- zeros->set_friendly_name(name + ".expert.router.zeros");- auto scatter = std::make_shared<ov::op::v3::ScatterElementsUpdate>(zeros, topk_cvt, r_slice, scatter_axis);- scatter->set_friendly_name(name + ".expert.router.scatter");-- auto r_tp = std::make_shared<ov::opset11::Transpose>(scatter, tp_order);- r_tp->set_friendly_name(name + ".expert.router.transpose");- auto r_reshape = std::make_shared<ov::opset11::Reshape>(r_tp, mk({ne_i, 1, -1}), false);- r_reshape->set_friendly_name(name + ".expert.router.reshape");- auto router_scores = std::make_shared<ov::opset11::Unsqueeze>(r_reshape, unsq_axis);- router_scores->set_friendly_name(name + ".expert.router.unsqueeze");-- // Expert: Tile → Reshape → MatMul → Add → dual-branch → MatMul → Add → Reshape → Multiply → ReduceSum- auto tiled = std::make_shared<ov::op::v0::Tile>(input_2d, tile_repeats);- tiled->set_friendly_name(name + ".expert.tile");- auto expert_3d = std::make_shared<ov::opset11::Reshape>(tiled, mk({ne_i, -1, hs_i}), false);- expert_3d->set_friendly_name(name + ".expert.reshape_in");-- auto gu_w = weight_fn(name + ".expert.gate_up_proj.weight",- ov::Shape{num_experts, 2 * intermediate_size, hidden_size},- prec);- auto gu_mm = std::make_shared<ov::opset11::MatMul>(expert_3d, gu_w, false, true);- gu_mm->set_friendly_name(name + ".expert.gate_up_matmul");- auto gu_bias = C::create(prec,- ov::Shape{num_experts, 1, 2 * intermediate_size},- std::vector<float>(num_experts * 2 * intermediate_size, 0.0f));- gu_bias->set_friendly_name(name + ".expert.gate_up_bias");- auto gu_add = std::make_shared<ov::opset11::Add>(gu_mm, gu_bias);- gu_add->set_friendly_name(name + ".expert.gate_up_add");-- auto act_slice = std::make_shared<ov::op::v8::Slice>(gu_add, slice_start_0, slice_stop_is, slice_step, slice_axis2);- act_slice->set_friendly_name(name + ".expert.slice_act");- auto act_min = std::make_shared<ov::opset11::Minimum>(act_slice, min_const);- act_min->set_friendly_name(name + ".expert.minimum");- auto act_swish = std::make_shared<ov::op::v4::Swish>(act_min, swish_beta);- act_swish->set_friendly_name(name + ".expert.swish");-- auto gate_slice =- std::make_shared<ov::op::v8::Slice>(gu_add, slice_start_is, slice_stop_2is, slice_step, slice_axis2);- gate_slice->set_friendly_name(name + ".expert.slice_gate");- auto gate_clamp = std::make_shared<ov::op::v0::Clamp>(gate_slice, -20.0f, 20.0f);- gate_clamp->set_friendly_name(name + ".expert.clamp");- auto gate_add = std::make_shared<ov::opset11::Add>(gate_clamp, clamp_add_zero);- gate_add->set_friendly_name(name + ".expert.gate_add");-- auto merged = std::make_shared<ov::opset11::Multiply>(act_swish, gate_add);- merged->set_friendly_name(name + ".expert.merge");-- auto dn_w =- weight_fn(name + ".expert.down_proj.weight", ov::Shape{num_experts, hidden_size, intermediate_size}, prec);- auto dn_mm = std::make_shared<ov::opset11::MatMul>(merged, dn_w, false, true);- dn_mm->set_friendly_name(name + ".expert.down_matmul");- auto dn_bias =- C::create(prec, ov::Shape{num_experts, 1, hidden_size}, std::vector<float>(num_experts * hidden_size, 0.0f));- dn_bias->set_friendly_name(name + ".expert.down_bias");- auto dn_add = std::make_shared<ov::opset11::Add>(dn_mm, dn_bias);- dn_add->set_friendly_name(name + ".expert.down_add");-- auto expert_out = std::make_shared<ov::opset11::Reshape>(dn_add, mk({ne_i, 1, -1, hs_i}), false);- expert_out->set_friendly_name(name + ".expert.reshape_out");- auto weighted = std::make_shared<ov::opset11::Multiply>(expert_out, router_scores);- weighted->set_friendly_name(name + ".expert.weighted");- auto reduced = std::make_shared<ov::opset11::ReduceSum>(weighted, reduce_axis, false);- reduced->set_friendly_name(name + ".expert.reduced");-- auto output = std::make_shared<ov::opset11::Reshape>(reduced, original_shape, false);- output->set_friendly_name(name + ".output");- return output->output(0);-}-} // namespace npuw} // namespace test} // namespace ovdiff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_ffn.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_ffn.hppindex 905e11e7eb9..78bf01ac057 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_ffn.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_ffn.hpp@@ -47,30 +47,6 @@ struct GELU {ov::Output<ov::Node> operator()(const ov::Output<ov::Node>& input, const std::string& name) const;};-/// GPT-OSS style batched MoE FFN matching NPUW's GPTOSSExpert + GPTOSSRouter patterns.-/// All experts compute on all tokens via Tile + 3D batched MatMul (no NonZero).-/// Weight function must produce a Multiply→Convert→MatMul chain (default: i4 CompressedWeight)-/// for the isolation patterns to match. Shared constants across layers enable repeating-/// block detection. Conforms to FFNFn for drop-in use in transformer layer templates.-struct MoEFFN {- size_t hidden_size, intermediate_size, num_experts, num_experts_per_tok;- ov::element::Type precision;- WeightFn weight_fn;-- /// Default weight_fn: CompressedWeight{i4, 0, SYMM_NO_ZP}.- MoEFFN(size_t hs, size_t is, size_t ne, size_t k, ov::element::Type prec, WeightFn wf = {});-- ov::Output<ov::Node> operator()(const ov::Output<ov::Node>& input, const std::string& name) const;--private:- // Shared across layers for matchRepeatedSubgraphs (created once in ctor)- std::shared_ptr<ov::Node> tile_repeats, topk_k_const;- std::shared_ptr<ov::Node> slice_step, slice_axis2, slice_start_0, slice_stop_is, slice_start_is, slice_stop_2is;- std::shared_ptr<ov::Node> min_const, swish_beta, clamp_add_zero;- std::shared_ptr<ov::Node> sl_start, sl_step_r, sl_axes, scatter_axis;- std::shared_ptr<ov::Node> tp_order, unsq_axis, reduce_axis;-};-} // namespace npuw} // namespace test} // namespace ovdiff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.cppnew file mode 100644index 00000000000..b96b1481e4a--- /dev/null+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.cpp@@ -0,0 +1,336 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "model_builder_moe.hpp"++#include <utility>+#include <vector>++#include "model_builder_weights.hpp"+#include "openvino/op/ops.hpp"+#include "openvino/opsets/opset11.hpp"++namespace ov {+namespace test {+namespace npuw {++namespace {++// Reshape target shape as a Concat of per-element i32 constants — the pre-folding form+// GPT-OSS reshapes arrive in.+std::shared_ptr<ov::Node> concat_shape(const std::vector<int32_t>& v) {+ ov::OutputVector parts;+ for (auto x : v) {+ parts.push_back(+ ov::opset11::Constant::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{x})->output(0));+ }+ return std::make_shared<ov::opset11::Concat>(parts, 0);+}++// Reshape target shape as a single literal i32 Constant. This matches the real+// Qwen3-30B-A3B IR — every reshape there feeds a literal Const shape — and, critically,+// is the form DeviceRoutedMoETransform can rewrite: it only collects Reshapes whose shape+// input is a Constant, and rewires each to a new Constant with entry [0] changed from+// num_experts to K. A Concat shape input would not be collected, leaving the expert+// dimension un-rewritten and the transformed graph invalid.+std::shared_ptr<ov::Node> const_shape(const std::vector<int32_t>& v) {+ return ov::opset11::Constant::create(ov::element::i32, ov::Shape{v.size()}, v);+}++} // namespace++BatchedMoEFFN::BatchedMoEFFN(size_t hs,+ size_t is,+ size_t ne,+ size_t k,+ ov::element::Type prec,+ WeightFn wf,+ ShapeFn shape_fn)+ : hidden_size(hs),+ intermediate_size(is),+ num_experts(ne),+ num_experts_per_tok(k),+ precision(prec),+ weight_fn(std::move(wf)),+ mk(shape_fn) {+ // Default to i4 CompressedWeight if no weight function provided.+ // i4 (not nf4) because NPUW's nf4 unpack doesn't handle 3D batched scales.+ if (!weight_fn) {+ weight_fn = CompressedWeight{ov::element::i4, 0, DCOffPattern::SYMM_NO_ZP};+ }+ using C = ov::opset11::Constant;+ const int32_t ne_i = static_cast<int32_t>(ne);+ const int32_t k_i = static_cast<int32_t>(k);++ // i32 shape/axis constants, shared across layers so matchRepeatedSubgraphs sees identical blocks.+ tile_repeats = C::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{ne_i, 1});+ topk_k_const = C::create(ov::element::i32, ov::Shape{}, std::vector<int32_t>{k_i});+ scatter_axis = C::create(ov::element::i32, ov::Shape{}, std::vector<int32_t>{1});+ tp_order = C::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{1, 0});+ unsq_axis = C::create(ov::element::i32, ov::Shape{}, std::vector<int32_t>{3});+ reduce_axis = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{0});+}++std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> BatchedMoEFFN::flatten_input(const ov::Output<ov::Node>& input,+ const std::string& name) const {+ auto original_shape = std::make_shared<ov::opset11::ShapeOf>(input, ov::element::i32);+ original_shape->set_friendly_name(name + ".original_shape");++ auto input_2d = std::make_shared<ov::opset11::Reshape>(input, mk({-1, static_cast<int32_t>(hidden_size)}), false);+ input_2d->set_friendly_name(name + ".input_2d");+ return {original_shape, input_2d};+}++ov::Output<ov::Node> BatchedMoEFFN::router_zeros(const ov::Output<ov::Node>& logits,+ const std::string& shapeof_name,+ const std::string& zeros_name) const {+ auto logits_shape = std::make_shared<ov::opset11::ShapeOf>(logits, ov::element::i32);+ logits_shape->set_friendly_name(shapeof_name);+ auto zeros = std::make_shared<ov::op::v3::Broadcast>(+ ov::opset11::Constant::create(precision, ov::Shape{}, std::vector<float>{0.0f}),+ logits_shape,+ ov::op::BroadcastType::NUMPY);+ zeros->set_friendly_name(zeros_name);+ return zeros;+}++ov::Output<ov::Node> BatchedMoEFFN::broadcast_router_scores(const ov::Output<ov::Node>& scattered,+ const std::string& name) const {+ auto r_tp = std::make_shared<ov::opset11::Transpose>(scattered, tp_order);+ r_tp->set_friendly_name(name + ".expert.router.transpose");+ auto r_reshape =+ std::make_shared<ov::opset11::Reshape>(r_tp, mk({static_cast<int32_t>(num_experts), 1, -1}), false);+ r_reshape->set_friendly_name(name + ".expert.router.reshape");+ auto router_scores = std::make_shared<ov::opset11::Unsqueeze>(r_reshape, unsq_axis);+ router_scores->set_friendly_name(name + ".expert.router.unsqueeze");+ return router_scores;+}++ov::Output<ov::Node> BatchedMoEFFN::tile_to_experts(const ov::Output<ov::Node>& input_2d,+ const std::string& name) const {+ auto tiled = std::make_shared<ov::op::v0::Tile>(input_2d, tile_repeats);+ tiled->set_friendly_name(name + ".expert.tile");+ auto expert_3d = std::make_shared<ov::opset11::Reshape>(+ tiled,+ mk({static_cast<int32_t>(num_experts), -1, static_cast<int32_t>(hidden_size)}),+ false);+ expert_3d->set_friendly_name(name + ".expert.reshape_in");+ return expert_3d;+}++ov::Output<ov::Node> BatchedMoEFFN::weighted_expert_sum(const ov::Output<ov::Node>& expert_out_3d,+ const ov::Output<ov::Node>& router_scores,+ const ov::Output<ov::Node>& original_shape,+ const std::string& name) const {+ auto expert_out = std::make_shared<ov::opset11::Reshape>(+ expert_out_3d,+ mk({static_cast<int32_t>(num_experts), 1, -1, static_cast<int32_t>(hidden_size)}),+ false);+ expert_out->set_friendly_name(name + ".expert.reshape_out");+ auto weighted = std::make_shared<ov::opset11::Multiply>(expert_out, router_scores);+ weighted->set_friendly_name(name + ".expert.weighted");+ auto reduced = std::make_shared<ov::opset11::ReduceSum>(weighted, reduce_axis, false);+ reduced->set_friendly_name(name + ".expert.reduced");++ auto output = std::make_shared<ov::opset11::Reshape>(reduced, original_shape, false);+ output->set_friendly_name(name + ".output");+ return output->output(0);+}++GPTOSSMoEFFN::GPTOSSMoEFFN(size_t hs, size_t is, size_t ne, size_t k, ov::element::Type prec, WeightFn wf)+ : BatchedMoEFFN(hs, is, ne, k, prec, std::move(wf), concat_shape) {+ using C = ov::opset11::Constant;+ int32_t is_i = static_cast<int32_t>(is);++ // Use i32 for shape/axis/step constants matching real GPT-OSS HuggingFace export.+ slice_step = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{1});+ slice_axis2 = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{2});+ slice_start_0 = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{0});+ slice_stop_is = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{is_i});+ slice_start_is = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{is_i});+ slice_stop_2is = C::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{static_cast<int32_t>(2 * is_i)});+ min_const = C::create(prec, ov::Shape{1}, std::vector<float>{20.0f});+ swish_beta = C::create(prec, ov::Shape{}, std::vector<float>{1.0f});+ clamp_add_zero = C::create(prec, ov::Shape{1}, std::vector<float>{0.0f});+ sl_start = C::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{0, 0});+ sl_step_r = C::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{1, 1});+ sl_axes = C::create(ov::element::i32, ov::Shape{2}, std::vector<int32_t>{0, 1});+}++ov::Output<ov::Node> GPTOSSMoEFFN::operator()(const ov::Output<ov::Node>& input, const std::string& name) const {+ using C = ov::opset11::Constant;+ const auto prec = precision;++ auto [original_shape, input_2d] = flatten_input(input, name);++ // Router uses i8 weights matching real GPT-OSS two-pass quantization+ // (router excluded from 4-bit, gets 8-bit instead).+ static const CompressedWeight router_wt{ov::element::i8, 0, DCOffPattern::SYMM_NO_ZP};+ auto rw = router_wt(name + ".expert.router.weight", ov::Shape{num_experts, hidden_size}, prec);+ auto r_mm = std::make_shared<ov::opset11::MatMul>(input_2d, rw, false, true);+ r_mm->set_friendly_name(name + ".expert.router.matmul");+ auto r_bias = C::create(prec, ov::Shape{1, num_experts}, std::vector<float>(num_experts, 0.0f));+ r_bias->set_friendly_name(name + ".expert.router.bias");+ auto r_add = std::make_shared<ov::opset11::Add>(r_mm, r_bias);+ r_add->set_friendly_name(name + ".expert.router.add");++ auto topk = std::make_shared<ov::opset11::TopK>(r_add, topk_k_const, 1, "max", "value", ov::element::i64);+ topk->set_friendly_name(name + ".expert.router.topk");+ auto softmax = std::make_shared<ov::op::v8::Softmax>(topk->output(0), 1);+ softmax->set_friendly_name(name + ".expert.router.softmax");+ auto topk_cvt = std::make_shared<ov::opset11::Convert>(topk->output(1), ov::element::i32);+ topk_cvt->set_friendly_name(name + ".expert.router.topk_convert");+ auto topk_shape = std::make_shared<ov::op::v3::ShapeOf>(topk_cvt, ov::element::i32);+ topk_shape->set_friendly_name(name + ".expert.router.topk_shapeof");++ auto r_slice = std::make_shared<ov::op::v8::Slice>(softmax, sl_start, topk_shape, sl_step_r, sl_axes);+ r_slice->set_friendly_name(name + ".expert.router.slice");+ auto zeros = router_zeros(r_add, name + ".expert.router.add_shapeof", name + ".expert.router.zeros");+ auto scatter = std::make_shared<ov::op::v3::ScatterElementsUpdate>(zeros, topk_cvt, r_slice, scatter_axis);+ scatter->set_friendly_name(name + ".expert.router.scatter");++ auto router_scores = broadcast_router_scores(scatter, name);++ // Expert: Tile → Reshape → MatMul → Add → dual-branch → MatMul → Add → Reshape → Multiply → ReduceSum+ auto expert_3d = tile_to_experts(input_2d, name);++ auto gu_w = weight_fn(name + ".expert.gate_up_proj.weight",+ ov::Shape{num_experts, 2 * intermediate_size, hidden_size},+ prec);+ auto gu_mm = std::make_shared<ov::opset11::MatMul>(expert_3d, gu_w, false, true);+ gu_mm->set_friendly_name(name + ".expert.gate_up_matmul");+ auto gu_bias = C::create(prec,+ ov::Shape{num_experts, 1, 2 * intermediate_size},+ std::vector<float>(num_experts * 2 * intermediate_size, 0.0f));+ gu_bias->set_friendly_name(name + ".expert.gate_up_bias");+ auto gu_add = std::make_shared<ov::opset11::Add>(gu_mm, gu_bias);+ gu_add->set_friendly_name(name + ".expert.gate_up_add");++ auto act_slice = std::make_shared<ov::op::v8::Slice>(gu_add, slice_start_0, slice_stop_is, slice_step, slice_axis2);+ act_slice->set_friendly_name(name + ".expert.slice_act");+ auto act_min = std::make_shared<ov::opset11::Minimum>(act_slice, min_const);+ act_min->set_friendly_name(name + ".expert.minimum");+ auto act_swish = std::make_shared<ov::op::v4::Swish>(act_min, swish_beta);+ act_swish->set_friendly_name(name + ".expert.swish");++ auto gate_slice =+ std::make_shared<ov::op::v8::Slice>(gu_add, slice_start_is, slice_stop_2is, slice_step, slice_axis2);+ gate_slice->set_friendly_name(name + ".expert.slice_gate");+ auto gate_clamp = std::make_shared<ov::op::v0::Clamp>(gate_slice, -20.0f, 20.0f);+ gate_clamp->set_friendly_name(name + ".expert.clamp");+ auto gate_add = std::make_shared<ov::opset11::Add>(gate_clamp, clamp_add_zero);+ gate_add->set_friendly_name(name + ".expert.gate_add");++ auto merged = std::make_shared<ov::opset11::Multiply>(act_swish, gate_add);+ merged->set_friendly_name(name + ".expert.merge");++ auto dn_w =+ weight_fn(name + ".expert.down_proj.weight", ov::Shape{num_experts, hidden_size, intermediate_size}, prec);+ auto dn_mm = std::make_shared<ov::opset11::MatMul>(merged, dn_w, false, true);+ dn_mm->set_friendly_name(name + ".expert.down_matmul");+ auto dn_bias =+ C::create(prec, ov::Shape{num_experts, 1, hidden_size}, std::vector<float>(num_experts * hidden_size, 0.0f));+ dn_bias->set_friendly_name(name + ".expert.down_bias");+ auto dn_add = std::make_shared<ov::opset11::Add>(dn_mm, dn_bias);+ dn_add->set_friendly_name(name + ".expert.down_add");++ return weighted_expert_sum(dn_add, router_scores, original_shape, name);+}++Qwen3MoEFFN::Qwen3MoEFFN(size_t hs, size_t is, size_t ne, size_t k, ov::element::Type prec, WeightFn wf)+ // const_shape: literal Const reshape shapes, required by DeviceRoutedMoETransform (see const_shape).+ : BatchedMoEFFN(hs, is, ne, k, prec, std::move(wf), const_shape) {+ // Router renormalization sums the K selected probabilities (last axis), keepdims.+ reduce_axis_k = ov::opset11::Constant::create(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{1});+}++ov::Output<ov::Node> Qwen3MoEFFN::operator()(const ov::Output<ov::Node>& input, const std::string& name) const {+ // Qwen3-style batched MoE matching NPUW's Qwen3Router + Qwen3Expert patterns.+ //+ // Router (Softmax BEFORE TopK, then renormalize over the K selected experts):+ // input_2d -> MatMul(router_w) -> Softmax -> TopK(MAX)+ // -> ReduceSum(values) -> Divide(values, sum)+ // -> ScatterElementsUpdate(zeros, indices, scores)+ // -> Transpose -> Reshape([N,1,-1]) -> Unsqueeze(axis 3) = router_scores+ //+ // Expert (separate gate/up MatMuls — SwiGLU = Swish(gate) * up):+ // input_2d -> Tile -> Reshape([N,-1,H])+ // -> MatMul(gate_w) -> Swish+ // -> MatMul(up_w)+ // -> Multiply(swish, up) -> MatMul(down_w) -> Reshape([N,1,-1,H])+ // -> Multiply(router_scores) -> ReduceSum(axis 0) -> Reshape(original)+ //+ // The expert weight chain is CompressedWeight's Multiply->Convert->MatMul, which is+ // exactly what Qwen3Expert/Qwen3Router bind to. Unlike GPT-OSS this uses Softmax->TopK+ // (not TopK->Softmax) and has no gate_up fusion / Clamp / Minimum branches.+ const auto prec = precision;++ auto [original_shape, input_2d] = flatten_input(input, name);++ // --- Router ---+ // i4 router weights: real Qwen3-30B-A3B quantizes the gate to int4 like the rest of the+ // model (verified against the OpenVINO IR; the GPT-OSS "router stays 8-bit" rule does not+ // apply here). The Convert->Multiply->Convert chain matches Qwen3Router's weight pattern.+ static const CompressedWeight router_wt{ov::element::i4, 0, DCOffPattern::SYMM_NO_ZP};+ auto rw = router_wt(name + ".expert.router.weight", ov::Shape{num_experts, hidden_size}, prec);+ auto r_mm = std::make_shared<ov::opset11::MatMul>(input_2d, rw, false, true);+ r_mm->set_friendly_name(name + ".expert.router.matmul");++ // Softmax over experts, THEN select top-K (Qwen3 order).+ auto softmax = std::make_shared<ov::op::v8::Softmax>(r_mm, 1);+ softmax->set_friendly_name(name + ".expert.router.softmax");+ auto topk = std::make_shared<ov::opset11::TopK>(softmax, topk_k_const, 1, "max", "value", ov::element::i64);+ topk->set_friendly_name(name + ".expert.router.topk");++ // Renormalize the K selected probabilities so they sum to 1.+ auto reduce_router = std::make_shared<ov::opset11::ReduceSum>(topk->output(0), reduce_axis_k, true);+ reduce_router->set_friendly_name(name + ".expert.router.reduce");+ auto divide = std::make_shared<ov::opset11::Divide>(topk->output(0), reduce_router);+ divide->set_friendly_name(name + ".expert.router.divide");++ // Scatter the renormalized scores back to the full expert dimension. The TopK indices+ // (output(1)) feed the scatter directly — no intermediate Convert — matching Qwen3Router.+ auto zeros = router_zeros(r_mm, name + ".expert.router.shapeof", name + ".expert.router.zeros");+ auto scatter =+ std::make_shared<ov::op::v12::ScatterElementsUpdate>(zeros, topk->output(1), divide, scatter_axis);+ scatter->set_friendly_name(name + ".expert.router.scatter");++ auto router_scores = broadcast_router_scores(scatter, name);++ // --- Expert ---+ auto expert_3d = tile_to_experts(input_2d, name);++ // Gate projection -> Swish.+ auto gate_w = weight_fn(name + ".expert.gate_proj.weight",+ ov::Shape{num_experts, intermediate_size, hidden_size},+ prec);+ auto gate_mm = std::make_shared<ov::opset11::MatMul>(expert_3d, gate_w, false, true);+ gate_mm->set_friendly_name(name + ".expert.gate_matmul");+ // Single-input Swish (no beta) — matches real Qwen3 aten::silu and the Qwen3Expert+ // matcher's wrap_type<Swish>({matmul_gate}). A 2-input Swish would not bind.+ auto gate_swish = std::make_shared<ov::op::v4::Swish>(gate_mm);+ gate_swish->set_friendly_name(name + ".expert.swish");++ // Up projection.+ auto up_w =+ weight_fn(name + ".expert.up_proj.weight", ov::Shape{num_experts, intermediate_size, hidden_size}, prec);+ auto up_mm = std::make_shared<ov::opset11::MatMul>(expert_3d, up_w, false, true);+ up_mm->set_friendly_name(name + ".expert.up_matmul");++ // SwiGLU merge.+ auto merged = std::make_shared<ov::opset11::Multiply>(gate_swish, up_mm);+ merged->set_friendly_name(name + ".expert.merge");++ // Down projection.+ auto dn_w =+ weight_fn(name + ".expert.down_proj.weight", ov::Shape{num_experts, hidden_size, intermediate_size}, prec);+ auto dn_mm = std::make_shared<ov::opset11::MatMul>(merged, dn_w, false, true);+ dn_mm->set_friendly_name(name + ".expert.down_matmul");++ return weighted_expert_sum(dn_mm, router_scores, original_shape, name);+}++} // namespace npuw+} // namespace test+} // namespace ovdiff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.hppnew file mode 100644index 00000000000..84516b12a2e--- /dev/null+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.hpp@@ -0,0 +1,129 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstdint>+#include <memory>+#include <string>+#include <utility>+#include <vector>++#include "model_builder_types.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/type/element_type.hpp"++namespace ov {+namespace test {+namespace npuw {++/// Builds a MoE FFN from the params build_llm resolves out of LLMConfig, keeping the config the+/// single source of truth. Empty = GPTOSSMoEFFN; assign make_qwen3_moe_ffn for Qwen3.+using MoEFactoryFn = std::function<FFNFn(size_t hidden_size,+ size_t intermediate_size,+ size_t num_experts,+ size_t num_experts_per_tok,+ ov::element::Type precision)>;++/// Scaffolding shared by the Tile-batched MoE FFN topologies (GPT-OSS, Qwen3, ...):+/// all experts compute on all tokens via Tile + 3D batched MatMul (no NonZero), and the+/// router scores are scattered to the full expert dimension, broadcast over the expert+/// outputs, and reduced back. Derived functors assemble operator() from these pieces;+/// only the router score computation and the expert body differ per topology.+///+/// Weight function must produce a Multiply→Convert→MatMul chain (default: i4 CompressedWeight)+/// for the isolation patterns to match. Shared constants across layers enable repeating+/// block detection. Derived types conform to FFNFn for drop-in use in transformer layer+/// templates. New topologies: derive a functor + add a MoEFactoryFn wrapper (see+/// make_qwen3_moe_ffn), no central dispatch.+struct BatchedMoEFFN {+ size_t hidden_size, intermediate_size, num_experts, num_experts_per_tok;+ ov::element::Type precision;+ WeightFn weight_fn;++protected:+ /// How reshape target shapes are emitted: concat_shape (GPT-OSS) or const_shape (Qwen3)+ /// — see those functions in model_builder_moe.cpp for why the form matters.+ using ShapeFn = std::shared_ptr<ov::Node> (*)(const std::vector<int32_t>&);++ /// Defaults weight_fn to CompressedWeight{i4, 0, SYMM_NO_ZP} when wf is empty.+ BatchedMoEFFN(size_t hs, size_t is, size_t ne, size_t k, ov::element::Type prec, WeightFn wf, ShapeFn shape_fn);++ /// [B,S,H] input -> {".original_shape" ShapeOf, ".input_2d" [-1,H] Reshape}.+ std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> flatten_input(const ov::Output<ov::Node>& input,+ const std::string& name) const;++ /// Zero base for the router scatter: ShapeOf(logits) -> Broadcast(0).+ /// The ShapeOf friendly name differs per topology, so it is passed in full.+ ov::Output<ov::Node> router_zeros(const ov::Output<ov::Node>& logits,+ const std::string& shapeof_name,+ const std::string& zeros_name) const;++ /// Scattered per-expert scores [N,ne] -> [ne,1,N,1] for broadcasting over the expert+ /// outputs: Transpose -> Reshape -> Unsqueeze (the Qwen3Router/GPTOSSRouter tail).+ ov::Output<ov::Node> broadcast_router_scores(const ov::Output<ov::Node>& scattered,+ const std::string& name) const;++ /// 2D input [N,H] -> all-expert batch [ne,N,H]: Tile -> Reshape.+ ov::Output<ov::Node> tile_to_experts(const ov::Output<ov::Node>& input_2d, const std::string& name) const;++ /// Expert outputs [ne,N,H] -> Reshape [ne,1,N,H] -> * router_scores -> ReduceSum over+ /// experts -> Reshape back to the original input shape. Returns the FFN output.+ ov::Output<ov::Node> weighted_expert_sum(const ov::Output<ov::Node>& expert_out_3d,+ const ov::Output<ov::Node>& router_scores,+ const ov::Output<ov::Node>& original_shape,+ const std::string& name) const;++ ShapeFn mk;+ // Shared across layers for matchRepeatedSubgraphs (created once in ctor)+ std::shared_ptr<ov::Node> tile_repeats, topk_k_const, scatter_axis, tp_order, unsq_axis, reduce_axis;+};++/// GPT-OSS style batched MoE FFN matching NPUW's GPTOSSExpert + GPTOSSRouter patterns:+/// fused gate_up MatMul with Slice/Minimum/Swish + Clamp branches and a TopK→Softmax router.+struct GPTOSSMoEFFN : BatchedMoEFFN {+ /// Default weight_fn: CompressedWeight{i4, 0, SYMM_NO_ZP}.+ GPTOSSMoEFFN(size_t hs, size_t is, size_t ne, size_t k, ov::element::Type prec, WeightFn wf = {});++ ov::Output<ov::Node> operator()(const ov::Output<ov::Node>& input, const std::string& name) const;++private:+ // GPT-OSS-specific constants: fused gate_up slicing, Clamp/Minimum, router Slice+ std::shared_ptr<ov::Node> slice_step, slice_axis2, slice_start_0, slice_stop_is, slice_start_is, slice_stop_2is;+ std::shared_ptr<ov::Node> min_const, swish_beta, clamp_add_zero;+ std::shared_ptr<ov::Node> sl_start, sl_step_r, sl_axes;+};++/// Qwen3 style batched MoE FFN matching NPUW's Qwen3Expert + Qwen3Router patterns+/// (real Qwen3-30B-A3B). Differs from GPTOSSMoEFFN in two ways: the expert uses separate gate/up+/// MatMuls (SwiGLU = Swish(gate) * up, single-input Swish) instead of a fused gate_up with+/// Clamp/Minimum branches, and the router is Softmax→TopK with an explicit ReduceSum→Divide+/// renormalization over the K selected experts (vs GPT-OSS's TopK→Softmax). The expert weight+/// chain is the same Multiply→Convert→MatMul the matchers bind to. Note: the shipped model+/// fuses gate_up via VariadicSplit; the matcher (and this builder) use the separate gate/up+/// form the partitioning pass keys on. Select via LLMConfig::moe_factory = make_qwen3_moe_ffn+/// (build_llm builds it from the config's MoE fields).+struct Qwen3MoEFFN : BatchedMoEFFN {+ /// Default weight_fn: CompressedWeight{i4, 0, SYMM_NO_ZP}.+ Qwen3MoEFFN(size_t hs, size_t is, size_t ne, size_t k, ov::element::Type prec, WeightFn wf = {});++ ov::Output<ov::Node> operator()(const ov::Output<ov::Node>& input, const std::string& name) const;++private:+ std::shared_ptr<ov::Node> reduce_axis_k; ///< router renormalization axis (over K)+};++/// MoEFactoryFn for the GPT-OSS topology — build_llm's default when LLMConfig::moe_factory is empty.+inline FFNFn make_gptoss_moe_ffn(size_t hs, size_t is, size_t ne, size_t k, ov::element::Type prec) {+ return GPTOSSMoEFFN(hs, is, ne, k, prec);+}++/// MoEFactoryFn for the Qwen3 topology. Assign to LLMConfig::moe_factory to select it.+inline FFNFn make_qwen3_moe_ffn(size_t hs, size_t is, size_t ne, size_t k, ov::element::Type prec) {+ return Qwen3MoEFFN(hs, is, ne, k, prec);+}++} // namespace npuw+} // namespace test+} // namespace ovdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 849d41dbaab..ce81e70a0ac 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -117,6 +117,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_attention.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_ffn.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_moe.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_masks.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_norm.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder_rope.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hppindex 418802f2fda..6c4097bbef7 100644--- a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp@@ -155,6 +155,21 @@ inline std::shared_ptr<ov::Model> build_moe_llm_test_model() {return mb.build_llm(cfg);}+/// Qwen3-style MoE: separate gate/up expert MatMuls (SwiGLU) and a Softmax->TopK router+/// with ReduceSum->Divide renormalization, matching NPUW's Qwen3Expert + Qwen3Router+/// patterns (real Qwen3-30B-A3B). Contrast build_moe_llm_test_model, which emits the+/// GPT-OSS topology (fused gate_up, TopK->Softmax router). Stateful (KV cache) like the+/// real model; consumers that need static shapes run StatefulToStateless + reshape, the+/// same way production prepares an LLM.+inline std::shared_ptr<ov::Model> build_qwen3_moe_llm_test_model() {+ ModelBuilder mb;+ auto cfg = make_test_model_config();+ cfg.num_experts = 8;+ cfg.num_experts_per_tok = 2;+ cfg.moe_factory = make_qwen3_moe_ffn;+ return mb.build_llm(cfg);+}+inline std::shared_ptr<ov::Model> build_sliding_window_test_model(size_t window_size = 512,size_t sliding_to_full_ratio = 0,const SlidingMaskFn& sliding_mask_fn = {},diff --git a/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cppindex fa5bc7bd05a..8b525cb52b6 100644--- a/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cpp@@ -6,12 +6,22 @@#include <gtest/gtest.h>+#include <algorithm>+#include <map>+#include <common_test_utils/test_common.hpp>+#include "intel_npu/config/config.hpp"+#include "intel_npu/config/npuw.hpp"#include "llm_test_helpers.hpp"#include "model_builder.hpp"+#include "moe_transformations/apply_moe_device_routed_transforms.hpp"#include "openvino/op/ops.hpp"+#include "openvino/pass/manager.hpp"#include "openvino/pass/serialize.hpp"+#include "openvino/pass/stateful_to_stateless.hpp"+#include "partitioning/online/compiler.hpp"+#include "partitioning/partitioning.hpp"/** Test suite for MoE Expert Transformation@@ -560,7 +570,7 @@ TEST_F(MoETransformationTest, AWQvsNonAWQComparison) {}// ============================================================================-// MoEFFN + build_llm E2E Tests (uses build_moe_llm_test_model from llm_test_helpers.hpp)+// GPTOSSMoEFFN + build_llm E2E Tests (uses build_moe_llm_test_model from llm_test_helpers.hpp)// ============================================================================TEST_F(MoETransformationTest, BuildMoELLM_HasExpertAndRouterNodes) {@@ -601,5 +611,189 @@ TEST_F(MoETransformationTest, BuildMoELLM_HasExpertAndRouterNodes) {EXPECT_EQ(scatter_count, 2u) << "One ScatterElementsUpdate per layer";}+// Qwen3 MoE topology: separate gate/up MatMuls (SwiGLU) and a Softmax->TopK router with+// ReduceSum->Divide renormalization, matching NPUW's Qwen3Expert + Qwen3Router patterns.+TEST_F(MoETransformationTest, BuildQwen3MoELLM_HasExpertAndRouterNodes) {+ auto model = ov::test::npuw::build_qwen3_moe_llm_test_model();+ ASSERT_NE(model, nullptr);++ bool has_tile = false, has_topk = false, has_softmax = false;+ size_t topk_router_count = 0, softmax_router_count = 0, scatter_count = 0;+ size_t router_reduce_count = 0, router_divide_count = 0, swish_count = 0;++ for (const auto& op : model->get_ordered_ops()) {+ const auto& fname = op->get_friendly_name();+ const bool is_router = fname.find("router") != std::string::npos;+ if (std::dynamic_pointer_cast<ov::op::v0::Tile>(op))+ has_tile = true;+ if (std::dynamic_pointer_cast<ov::op::v4::Swish>(op))+ swish_count++;+ if (auto topk = std::dynamic_pointer_cast<ov::op::v11::TopK>(op)) {+ has_topk = true;+ if (is_router) {+ EXPECT_EQ(topk->get_mode(), ov::op::v11::TopK::Mode::MAX);+ topk_router_count++;+ }+ }+ if (std::dynamic_pointer_cast<ov::op::v8::Softmax>(op)) {+ has_softmax = true;+ if (is_router)+ softmax_router_count++;+ }+ if (std::dynamic_pointer_cast<ov::op::v3::ScatterElementsUpdate>(op) ||+ std::dynamic_pointer_cast<ov::op::v12::ScatterElementsUpdate>(op))+ scatter_count++;+ if (is_router && std::dynamic_pointer_cast<ov::op::v1::ReduceSum>(op))+ router_reduce_count++;+ if (is_router && std::dynamic_pointer_cast<ov::op::v1::Divide>(op))+ router_divide_count++;+ }++ EXPECT_TRUE(has_tile) << "Missing Tile (expert)";+ EXPECT_TRUE(has_topk) << "Missing TopK (router)";+ EXPECT_TRUE(has_softmax) << "Missing Softmax (router)";+ // Two layers, separate gate/up -> one Swish per gate projection per layer.+ EXPECT_EQ(swish_count, 2u) << "One expert Swish (gate activation) per layer";+ EXPECT_EQ(topk_router_count, 2u) << "One router TopK per layer";+ EXPECT_EQ(softmax_router_count, 2u) << "One router Softmax per layer";+ EXPECT_EQ(scatter_count, 2u) << "One ScatterElementsUpdate per layer";+ // Qwen3-specific renormalization: ReduceSum + Divide on the router scores per layer.+ EXPECT_EQ(router_reduce_count, 2u) << "One router ReduceSum (renormalization) per layer";+ EXPECT_EQ(router_divide_count, 2u) << "One router Divide (renormalization) per layer";+}++// Minimal Qwen3 MoE config: num_experts + moe_factory, everything else defaulted.+TEST_F(MoETransformationTest, Qwen3MoE_MinimalConfigBuildsFromFactory) {+ ov::test::npuw::ModelBuilder mb;+ ov::test::npuw::LLMConfig cfg;+ cfg.num_experts = 8;+ cfg.moe_factory = ov::test::npuw::make_qwen3_moe_ffn;++ std::shared_ptr<ov::Model> model;+ ASSERT_NO_THROW(model = mb.build_llm(cfg));+ ASSERT_NE(model, nullptr);++ bool has_tile = false, has_swish = false, has_softmax = false, has_topk = false;+ for (const auto& op : model->get_ordered_ops()) {+ if (std::dynamic_pointer_cast<ov::op::v0::Tile>(op))+ has_tile = true;+ if (std::dynamic_pointer_cast<ov::op::v4::Swish>(op))+ has_swish = true;+ if (std::dynamic_pointer_cast<ov::op::v8::Softmax>(op))+ has_softmax = true;+ if (std::dynamic_pointer_cast<ov::op::v11::TopK>(op))+ has_topk = true;+ }+ EXPECT_TRUE(has_tile && has_swish && has_softmax && has_topk);+}++inline ::intel_npu::Config make_moe_isolate_cfg() {+ auto opt_desc = std::make_shared<::intel_npu::OptionsDesc>();+ ::intel_npu::registerNPUWOptions(*opt_desc);+ ::intel_npu::Config cfg(opt_desc);+ cfg.update({{"NPUW_ONLINE_PIPELINE", "REP"}, {"NPUW_ONLINE_ISOLATE", "MOE"}});+ return cfg;+}++inline size_t count_groups_with_tag(const ov::npuw::Ensemble& ens, const std::string& tag) {+ return static_cast<size_t>(+ std::count_if(ens.groups.begin(), ens.groups.end(), [&tag](const ov::npuw::Group& g) {+ return g.gettag() == tag;+ }));+}++// The builder model is stateful (KV cache) like a real LLM; the partitioner and the+// device-routed transform need static shapes, so prepare it the way production prepares+// an LLM: StatefulToStateless, then a static reshape (query_len tokens, past_len cached).+inline std::shared_ptr<ov::Model> make_static_qwen3_moe_model(int64_t query_len, int64_t past_len) {+ auto model = ov::test::npuw::build_qwen3_moe_llm_test_model();+ ov::pass::StatefulToStateless().run_on_model(model);+ model = model->clone();++ std::map<std::string, ov::PartialShape> new_shapes;+ for (const auto& input : model->inputs()) {+ const auto& name = input.get_any_name();+ auto shape = input.get_partial_shape();+ if (name.find("input_ids") != std::string::npos || name.find("position_ids") != std::string::npos) {+ new_shapes[name] = {1, query_len};+ } else if (name.find("attention_mask") != std::string::npos) {+ new_shapes[name] = {1, query_len + past_len};+ } else { // past KV inputs: [batch, kv_heads, past_len, head_dim]+ shape[0] = 1;+ shape[2] = past_len;+ new_shapes[name] = shape;+ }+ }+ model->reshape(new_shapes);+ return model;+}++// The online partitioner with the MOE preset must isolate an expert group from the builder's+// output. Only the expert is asserted: since #36427 Qwen3Router isolates nothing (it only tags+// K on the TopK), so router coverage lives in the device-routed-transform test and moe_k_tag_test.+TEST_F(MoETransformationTest, Qwen3MoE_OnlinePartitionerIsolatesExpert) {+ auto model = make_static_qwen3_moe_model(/*query_len=*/8, /*past_len=*/8);+ ASSERT_NE(model, nullptr);++ auto cfg = make_moe_isolate_cfg();+ auto ens = ov::npuw::online::buildPartitioning(model, cfg);++ // Qwen3Expert bound -> at least one expert group. (Exact count depends on the+ // partitioner's fusion heuristics, so we don't couple the assertion to layer count.)+ EXPECT_GE(count_groups_with_tag(ens, "expert"), 1u) << "Qwen3Expert did not isolate any expert group";+}++// End-to-end against the *production* MoE pipeline (not just the matchers): the full+// ApplyMoEDeviceRoutedTransforms pass — DeviceRoutedMoETransform followed by GatherTo2DGather,+// exactly what production runs — must accept the builder's Qwen3 MoE and rewrite it into the+// gathered (K-active-expert) form. detect_router_by_topology requires the decoding stage+// (TopK indices batch dim == 1), so the model is shaped to a single token. This proves the+// builder output agrees with the hand-rolled create_qwen3_moe_graph that the transform's own+// unit tests use.+TEST_F(MoETransformationTest, Qwen3MoE_DeviceRoutedTransformRewritesBuilderOutput) {+ // Decoding shape: single token so the router TopK indices have batch dim 1.+ auto model = make_static_qwen3_moe_model(/*query_len=*/1, /*past_len=*/8);+ ASSERT_NE(model, nullptr);++ // Count expert-weight Gathers only (the MoE region), not the embedding Gather that any+ // LLM has. The transform names its inserted gathers under the expert/mlp scope.+ auto count_expert_gathers = [](const std::shared_ptr<ov::Model>& m) {+ size_t n = 0;+ for (const auto& op : m->get_ordered_ops()) {+ if (ov::as_type_ptr<ov::op::v8::Gather>(op) &&+ op->get_friendly_name().find("expert") != std::string::npos) {+ ++n;+ }+ }+ return n;+ };+ EXPECT_EQ(count_expert_gathers(model), 0u) << "No expert Gather before the device-routed transform";++ ov::pass::Manager manager;+ manager.register_pass<ov::npuw::ApplyMoEDeviceRoutedTransforms>();+ manager.run_passes(model);+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());++ // The transform replaces the batched all-expert MatMuls with per-active-expert Gathers+ // (weight + scale Gather for each of gate/up/down -> 6 per layer). If it fired at all,+ // expert Gathers appear and every Tile's repeat[0] is rewritten from num_experts to k.+ EXPECT_GT(count_expert_gathers(model), 0u)+ << "ApplyMoEDeviceRoutedTransforms did not rewrite the builder's Qwen3 MoE";++ constexpr int64_t kTopK = 2;+ size_t checked_tiles = 0;+ for (const auto& op : model->get_ordered_ops()) {+ auto tile = ov::as_type_ptr<ov::op::v0::Tile>(op);+ if (!tile || tile->get_friendly_name().find("expert") == std::string::npos) {+ continue; // skip non-MoE tiles (masks/embeddings)+ }+ auto rep = ov::as_type_ptr<ov::op::v0::Constant>(tile->input_value(1).get_node_shared_ptr());+ ASSERT_NE(rep, nullptr);+ EXPECT_EQ(rep->cast_vector<int64_t>()[0], kTopK) << "expert Tile repeat[0] should be rewritten to k";+ ++checked_tiles;+ }+ EXPECT_GT(checked_tiles, 0u) << "no expert Tile found to verify";+}+} // namespace