Skip to content

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

[NPUW]Patch for GPT-OSS AWQ pattern support. (#33924)

intelgaoxiong267df5f50905
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 2eb6932183a..a0ff1e2b584 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
@@ -803,8 +803,12 @@ std::shared_ptr<ov::Model> MoEModelTransformer::unroll_expert_dimension(const st
if (full_optimization) {
manager.register_pass<ov::npuw::pass::MoEExpertUnrolling>(unrolled_model);
} else {
+ // Weight-only optimizations
manager.register_pass<ov::npuw::pass::MoEExpertUnrollingWeightsOnly>(unrolled_model);
+ // AWQ parameter multiply unrolling with cleanup
+ manager.register_pass<ov::npuw::pass::UnrollAWQParameterMultiply>(unrolled_model);
}
+
manager.run_passes(unrolled_model);
unrolled_model->validate_nodes_and_infer_types();
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.cpp
index d7b08d63b48..3bece991c8d 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.cpp
@@ -775,6 +775,173 @@ PushScalarElementwiseBeforeConcat::PushScalarElementwiseBeforeConcat() {
register_matcher(m, callback);
}
+// =============================================================================
+// UnrollParameterMultiply
+// =============================================================================
+// Transforms: Multiply(Param[N,...], NonConcat) => Concat([Multiply(Param[0], Slice(NonConcat,0)), ...])
+// Handles cases like Multiply(k_parameter, Swish) where Swish is not unrolled
+// The parameter must be unrolled for correct weight loading in partial unroll scenarios
+
+UnrollParameterMultiply::UnrollParameterMultiply(std::shared_ptr<ov::Model> model) : model_(model) {
+ MATCHER_SCOPE(UnrollParameterMultiply);
+
+ auto multiply_pattern = ov::pass::pattern::wrap_type<ov::opset1::Multiply>();
+
+ auto callback = [this](ov::pass::pattern::Matcher& m) {
+ auto multiply = m.get_match_root();
+ LOG_INFO("UnrollParameterMultiply: Checking Multiply " << multiply->get_friendly_name());
+
+ auto multiply_op = std::dynamic_pointer_cast<ov::opset1::Multiply>(multiply);
+ if (!multiply_op) {
+ return false;
+ }
+
+ auto input0 = multiply_op->input_value(0);
+ auto input1 = multiply_op->input_value(1);
+
+ // Check if either input is a Concat - if so, skip (handled by PushMultiplyBeforeConcat)
+ auto input0_concat = std::dynamic_pointer_cast<ov::opset1::Concat>(input0.get_node_shared_ptr());
+ auto input1_concat = std::dynamic_pointer_cast<ov::opset1::Concat>(input1.get_node_shared_ptr());
+
+ if (input0_concat || input1_concat) {
+ LOG_DEBUG("UnrollParameterMultiply: One input is Concat, skipping (handled by PushMultiplyBeforeConcat)");
+ return false;
+ }
+
+ // Try to find a parameter input (possibly through Convert)
+ ov::Output<ov::Node> param_input, other_input;
+ std::shared_ptr<ov::op::v0::Parameter> param_node;
+
+ auto param0 = get_param_node(input0);
+ auto param1 = get_param_node(input1);
+
+ if (param0 && !param1) {
+ param_node = param0;
+ param_input = input0;
+ other_input = input1;
+ } else if (param1 && !param0) {
+ param_node = param1;
+ param_input = input1;
+ other_input = input0;
+ } else {
+ // Either no parameter or both are parameters - skip
+ return false;
+ }
+
+ // Check parameter shape: first dimension must be > 1 for unrolling
+ auto param_shape = param_node->get_partial_shape();
+
+ if (!param_shape.rank().is_static() || !param_shape[0].is_static()) {
+ LOG_DEBUG("UnrollParameterMultiply: Parameter shape not static, skipping");
+ return false;
+ }
+
+ int64_t num_branches = param_shape[0].get_length();
+
+ if (num_branches <= 1) {
+ LOG_DEBUG("UnrollParameterMultiply: Parameter first dimension <= 1, no need to unroll");
+ return false;
+ }
+
+ // Check other input shape compatibility for slicing
+ auto other_shape = other_input.get_partial_shape();
+
+ if (!other_shape.rank().is_static() || !other_shape[0].is_static()) {
+ LOG_DEBUG("UnrollParameterMultiply: Other input shape not static, cannot slice");
+ return false;
+ }
+
+ int64_t other_dim0 = other_shape[0].get_length();
+
+ if (other_dim0 != num_branches) {
+ LOG_DEBUG("UnrollParameterMultiply: Shape mismatch - param[0]=" << num_branches
+ << " vs other[0]=" << other_dim0);
+ return false;
+ }
+
+ LOG_INFO("UnrollParameterMultiply: Unrolling Multiply with parameter");
+ LOG_INFO(" Parameter: " << param_node->get_friendly_name() << ", shape: " << param_shape);
+ LOG_INFO(" Other input type: " << other_input.get_node()->get_type_name());
+ LOG_INFO(" Number of branches: " << num_branches);
+
+ // Create new per-branch parameters
+ auto orig_shape = param_shape.to_shape();
+ ov::Shape new_param_shape = orig_shape;
+ new_param_shape[0] = 1; // Change first dimension from N to 1
+
+ ov::NodeVector new_multiply_outputs;
+ ov::ParameterVector new_params;
+
+ // Check if there's a Convert between parameter and multiply
+ auto param_source = param_input;
+ std::shared_ptr<ov::opset1::Convert> param_convert;
+ if (auto conv = std::dynamic_pointer_cast<ov::opset1::Convert>(param_input.get_node_shared_ptr())) {
+ param_convert = conv;
+ }
+
+ for (size_t i = 0; i < static_cast<size_t>(num_branches); ++i) {
+ // Create new parameter for this branch
+ auto new_param = std::make_shared<ov::op::v0::Parameter>(param_node->get_element_type(),
+ ov::PartialShape(new_param_shape));
+ new_param->set_friendly_name(param_node->get_friendly_name() + "/branch_" + std::to_string(i));
+ new_param->get_rt_info()["moe_original_param"] = param_node->get_friendly_name();
+ new_param->get_rt_info()["moe_expert_index"] = static_cast<int64_t>(i);
+ new_params.push_back(new_param);
+
+ ov::Output<ov::Node> param_for_multiply = new_param->output(0);
+
+ // Apply Convert if original had one
+ if (param_convert) {
+ auto new_convert =
+ std::make_shared<ov::opset1::Convert>(param_for_multiply, param_convert->get_destination_type());
+ new_convert->set_friendly_name(param_convert->get_friendly_name() + "/branch_" + std::to_string(i));
+ param_for_multiply = new_convert->output(0);
+ }
+
+ // Slice other input for this branch
+ // Create Slice: other_input[i:i+1, ...]
+ auto start = ov::opset1::Constant::create(ov::element::i64, {1}, {static_cast<int64_t>(i)});
+ auto stop = ov::opset1::Constant::create(ov::element::i64, {1}, {static_cast<int64_t>(i + 1)});
+ auto step = ov::opset1::Constant::create(ov::element::i64, {1}, {1});
+ auto axes = ov::opset1::Constant::create(ov::element::i64, {1}, {0});
+
+ auto slice = std::make_shared<ov::op::v8::Slice>(other_input, start, stop, step, axes);
+ slice->set_friendly_name(other_input.get_node()->get_friendly_name() + "/slice_" + std::to_string(i));
+
+ // Create Multiply for this branch
+ ov::Output<ov::Node> multiply_input0, multiply_input1;
+ if (param_input == multiply->input_value(0)) {
+ multiply_input0 = param_for_multiply;
+ multiply_input1 = slice->output(0);
+ } else {
+ multiply_input0 = slice->output(0);
+ multiply_input1 = param_for_multiply;
+ }
+
+ auto new_multiply = std::make_shared<ov::opset1::Multiply>(multiply_input0, multiply_input1);
+ new_multiply->set_friendly_name(multiply->get_friendly_name() + "/branch_" + std::to_string(i));
+ new_multiply_outputs.push_back(new_multiply);
+ }
+
+ // Concat all branch outputs
+ auto new_concat = std::make_shared<ov::opset1::Concat>(new_multiply_outputs, 0);
+ new_concat->set_friendly_name(multiply->get_friendly_name() + "/concat");
+
+ // Register new parameters with model
+ model_->add_parameters(new_params);
+
+ ov::copy_runtime_info(multiply, new_concat);
+ ov::replace_node(multiply, new_concat);
+
+ LOG_INFO(" Successfully unrolled Multiply into " << num_branches << " branches with " << new_params.size()
+ << " new parameters");
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(multiply_pattern, matcher_name);
+ register_matcher(m, callback);
+}
+
// =============================================================================
// PushMultiplyBeforeConcat
// =============================================================================
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.hpp
index 787fbc4edfb..efa92181faf 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.hpp
@@ -123,6 +123,38 @@ public:
PushScalarElementwiseBeforeConcat();
};
+// =============================================================================
+// UnrollParameterMultiply: Unroll Multiply with parameter when other input is not Concat
+// =============================================================================
+/**
+ * @brief Unrolls Multiply operation when one input is a batched Parameter and the other is not Concat (e.g., AWQ
+ * Multiply where Swish is the other input)
+ *
+ * Handles cases like: Multiply(k_parameter[N,...], Swish) where Swish is not unrolled
+ * The parameter must be unrolled for correct weight loading in partial unroll scenarios.
+ *
+ * Transforms: Multiply(Param[N,...], NonConcat) → Concat([Multiply(Param[0], Slice(NonConcat,0)),
+ * Multiply(Param[1], Slice(NonConcat,1)),
+ * ...,
+ * Multiply(Param[N-1], Slice(NonConcat,N-1))])
+ *
+ * Requirements:
+ * - One input must be a Parameter with first dimension N > 1 (possibly through Convert)
+ * - Other input must NOT be a Concat (to avoid conflicts with PushMultiplyBeforeConcat)
+ * - Other input must have compatible shape for slicing on axis 0
+ *
+ * @param model Model to register split parameters with
+ */
+
+class UnrollParameterMultiply : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::pass::UnrollParameterMultiply");
+ explicit UnrollParameterMultiply(std::shared_ptr<ov::Model> model);
+
+private:
+ std::shared_ptr<ov::Model> model_;
+};
+
// =============================================================================
// PushMultiplyBeforeConcat: Push Multiply before Concat
// =============================================================================
@@ -285,6 +317,35 @@ public:
}
};
+/**
+ * @brief AWQ parameter multiply unrolling with cleanup
+ *
+ * Unrolls Multiply operations with batched parameters (e.g., AWQ quantization scales)
+ * and removes unused parameters after unrolling. This is specifically designed for
+ * handling AWQ multiply nodes where one input is a batched parameter and the other
+ * is not a Concat (e.g., Swish activation).
+ *
+ * Included patterns:
+ * - UnrollParameterMultiply: Unroll Multiply with batched parameter
+ * - RemoveUnusedParameters: Clean up unused batched parameters
+ *
+ * Use cases:
+ * - Used in combination with MoEExpertUnrollingWeightsOnly for AWQ quantized models
+ * - Not needed with MoEExpertUnrolling (already handles all patterns comprehensively)
+ *
+ * @param model Model instance for parameter registration and cleanup
+ */
+
+class UnrollAWQParameterMultiply : public ov::pass::GraphRewrite {
+public:
+ OPENVINO_GRAPH_REWRITE_RTTI("npuw::pass::UnrollAWQParameterMultiply");
+
+ explicit UnrollAWQParameterMultiply(std::shared_ptr<ov::Model> model) {
+ add_matcher<UnrollParameterMultiply>(model);
+ add_matcher<RemoveUnusedParameters>(model);
+ }
+};
+
} // namespace pass
} // namespace npuw
} // namespace ov
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 4ace2fd0eb3..32358073fd9 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
@@ -6,6 +6,7 @@
#include "../../logging.hpp"
#include "openvino/op/ops.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
#include "openvino/util/common_util.hpp"
@@ -64,20 +65,23 @@ GPTOSSExpert::GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
auto matmul1 = opp::wrap_type<ov::op::v0::MatMul>({reshape1, weights_convert1});
auto add1 = opp::wrap_type<ov::op::v1::Add>({matmul1, opp::any_input()});
- // Activation branch: Slice -> Minimum -> Swish
+ // Activation branch: Slice -> Minimum -> Swish -> (optional AWQ Multiply)
auto slice = opp::wrap_type<ov::op::v8::Slice>(
{add1, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});
auto minimum = opp::wrap_type<ov::op::v1::Minimum>({slice, opp::any_input()});
auto swish = opp::wrap_type<ov::op::v4::Swish>({minimum, opp::any_input()});
+ // AWQ quantization may add an optional Multiply after Swish
+ auto awq_multiply = opp::optional<ov::op::v1::Multiply>({swish, opp::any_input()});
+
// Gate branch: Slice -> Clamp -> Add2
auto other_slice = opp::wrap_type<ov::op::v8::Slice>(
{add1, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});
auto clamp = opp::wrap_type<ov::op::v0::Clamp>({other_slice});
auto add2 = opp::wrap_type<ov::op::v1::Add>({clamp, opp::any_input()});
- // Merge branches
- auto multiply1 = opp::wrap_type<ov::op::v1::Multiply>({add2, swish});
+ // Merge branches - awq_multiply will be Swish if not matched, or AWQ Multiply if matched
+ auto multiply1 = opp::wrap_type<ov::op::v1::Multiply>({add2, awq_multiply});
// Second MatMul (down projection) - weights path: Multiply -> Convert -> MatMul
auto weights_multiply2 = opp::wrap_type<ov::op::v1::Multiply>({opp::any_input(), opp::any_input()});
@@ -103,6 +107,20 @@ GPTOSSExpert::GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
auto matched_slice = node_to_output.at(slice).get_node_shared_ptr();
auto matched_minimum = node_to_output.at(minimum).get_node_shared_ptr();
auto matched_swish = node_to_output.at(swish).get_node_shared_ptr();
+
+ // Check if optional AWQ multiply was matched
+ std::shared_ptr<ov::Node> matched_awq_multiply = nullptr;
+ if (node_to_output.count(awq_multiply) > 0) {
+ auto awq_multiply_value = node_to_output.at(awq_multiply);
+ if (awq_multiply_value.get_node_shared_ptr() != matched_swish) {
+ // AWQ multiply exists and is different from swish
+ matched_awq_multiply = awq_multiply_value.get_node_shared_ptr();
+ LOG_DEBUG("AWQ multiply detected after Swish: " << matched_awq_multiply->get_friendly_name());
+ }
+ } else {
+ LOG_DEBUG("Normal model: No AWQ multiply after Swish");
+ }
+
auto matched_other_slice = node_to_output.at(other_slice).get_node_shared_ptr();
auto matched_clamp = node_to_output.at(clamp).get_node_shared_ptr();
auto matched_add2 = node_to_output.at(add2).get_node_shared_ptr();
@@ -141,6 +159,13 @@ GPTOSSExpert::GPTOSSExpert(const std::shared_ptr<ov::npuw::online::Snapshot>& sn
node_to_gptr->at(matched_slice)->isolate(isol_tag);
node_to_gptr->at(matched_minimum)->isolate(isol_tag);
node_to_gptr->at(matched_swish)->isolate(isol_tag);
+
+ // Isolate AWQ multiply if it exists
+ if (matched_awq_multiply && node_to_gptr->count(matched_awq_multiply)) {
+ node_to_gptr->at(matched_awq_multiply)->isolate(isol_tag);
+ LOG_DEBUG("AWQ multiply after Swish isolated");
+ }
+
node_to_gptr->at(matched_other_slice)->isolate(isol_tag);
node_to_gptr->at(matched_clamp)->isolate(isol_tag);
node_to_gptr->at(matched_add2)->isolate(isol_tag);
diff --git a/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/moe_transformation_test.cpp
index 1321f5809cd..5f9cb677bc5 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
@@ -56,6 +56,184 @@ protected:
// Synthetic Test Graph Builders
// ============================================================================
+// Create MoE expert graph with full GPT-OSS pattern including dual branches
+// Pattern matches GPTOSSExpert in moe.cpp:
+// Tile -> Reshape -> MatMul (gate+up) -> Add -> Slice (activation) -> Minimum -> Swish
+// \-> Slice (gate) -> Clamp -> Add2
+// Then: Swish + Add2 -> Multiply1 -> MatMul (down) -> Add3 -> Reshape -> Multiply (output)
+std::shared_ptr<Model> create_gpt_oss_expert_graph(size_t num_experts,
+ size_t hidden_dim = 2880,
+ size_t token_count = 1,
+ bool with_awq_multiply = false) {
+ ov::ParameterVector params;
+
+ // 1. Expert input: [token_count, hidden_dim]
+ auto expert_input = std::make_shared<op::v0::Parameter>(element::f32, Shape{token_count, hidden_dim});
+ expert_input->set_friendly_name("expert_input");
+ params.push_back(expert_input);
+
+ // 2. Tile to replicate for experts
+ auto repeats =
+ op::v0::Constant::create(element::i64, Shape{2}, std::vector<int64_t>{static_cast<int64_t>(num_experts), 1});
+ auto tile = std::make_shared<op::v0::Tile>(expert_input, repeats);
+ tile->set_friendly_name("expert_tile");
+
+ // 3. Reshape to 3D: [num_experts, token_count, hidden_dim]
+ auto reshape_shape1 = op::v0::Constant::create(element::i64,
+ Shape{3},
+ std::vector<int64_t>{static_cast<int64_t>(num_experts),
+ static_cast<int64_t>(token_count),
+ static_cast<int64_t>(hidden_dim)});
+ auto reshape1 = std::make_shared<op::v1::Reshape>(tile, reshape_shape1, false);
+ reshape1->set_friendly_name("expert_reshape1");
+
+ // 4. First MatMul (gate + up projections) with quantized weights
+ // Weight parameter: [num_experts, hidden_dim*2, hidden_dim] (NF4)
+ auto weights_nf4_1 =
+ std::make_shared<op::v0::Parameter>(element::nf4, Shape{num_experts, hidden_dim * 2, hidden_dim});
+ weights_nf4_1->set_friendly_name("weights_nf4_1");
+ params.push_back(weights_nf4_1);
+
+ // Convert NF4 to FP16
+ auto weights_fp16_1 = std::make_shared<op::v0::Convert>(weights_nf4_1, element::f16);
+ weights_fp16_1->set_friendly_name("weights_convert_fp16_1");
+
+ // Scale parameter: [num_experts, hidden_dim*2, 1] (FP16)
+ auto weights_scale_1 = std::make_shared<op::v0::Parameter>(element::f16, Shape{num_experts, hidden_dim * 2, 1});
+ weights_scale_1->set_friendly_name("weights_scale_1");
+ params.push_back(weights_scale_1);
+
+ // Multiply with scale (dequantization)
+ auto weights_mult1 = std::make_shared<op::v1::Multiply>(weights_fp16_1, weights_scale_1);
+ weights_mult1->set_friendly_name("weights_multiply1");
+
+ // Convert FP16 to FP32 for MatMul
+ auto weights_conv1 = std::make_shared<op::v0::Convert>(weights_mult1, element::f32);
+ weights_conv1->set_friendly_name("weights_convert1");
+
+ auto matmul1 = std::make_shared<op::v0::MatMul>(reshape1, weights_conv1, false, true);
+ matmul1->set_friendly_name("matmul1");
+
+ // Biases: [num_experts, 1, hidden_dim*2]
+ auto biases1 = std::make_shared<op::v0::Parameter>(element::f32, Shape{num_experts, 1, hidden_dim * 2});
+ biases1->set_friendly_name("biases1");
+ params.push_back(biases1);
+
+ auto add1 = std::make_shared<op::v1::Add>(matmul1, biases1);
+ add1->set_friendly_name("add1");
+
+ // 5. Dual branches from Add1
+ // Activation branch: Slice -> Minimum -> Swish [-> AWQ Multiply if enabled]
+ auto slice_start1 = op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{0});
+ auto slice_stop1 =
+ op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{static_cast<int64_t>(hidden_dim)});
+ auto slice_step1 = op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{1});
+ auto slice_axis1 = op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{2});
+ auto slice1 = std::make_shared<op::v8::Slice>(add1, slice_start1, slice_stop1, slice_step1, slice_axis1);
+ slice1->set_friendly_name("slice_activation");
+
+ auto minimum_const = op::v0::Constant::create(element::f32, Shape{1}, std::vector<float>{20.0f});
+ auto minimum = std::make_shared<op::v1::Minimum>(slice1, minimum_const);
+ minimum->set_friendly_name("minimum");
+
+ auto swish_beta = op::v0::Constant::create(element::f32, Shape{}, std::vector<float>{1.0f});
+ auto swish = std::make_shared<op::v4::Swish>(minimum, swish_beta);
+ swish->set_friendly_name("swish");
+
+ // Optional AWQ multiply after Swish
+ std::shared_ptr<ov::Node> activation_output = swish;
+ if (with_awq_multiply) {
+ auto awq_scale = std::make_shared<op::v0::Parameter>(element::f32, Shape{num_experts, token_count, hidden_dim});
+ awq_scale->set_friendly_name("awq_activation_scale");
+ params.push_back(awq_scale);
+
+ auto awq_mult = std::make_shared<op::v1::Multiply>(swish, awq_scale);
+ awq_mult->set_friendly_name("awq_activation_multiply");
+ activation_output = awq_mult;
+ }
+
+ // Gate branch: Slice -> Clamp -> Add2
+ auto slice_start2 =
+ op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{static_cast<int64_t>(hidden_dim)});
+ auto slice_stop2 =
+ op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{static_cast<int64_t>(hidden_dim * 2)});
+ auto slice_step2 = op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{1});
+ auto slice_axis2 = op::v0::Constant::create(element::i64, Shape{1}, std::vector<int64_t>{2});
+ auto slice2 = std::make_shared<op::v8::Slice>(add1, slice_start2, slice_stop2, slice_step2, slice_axis2);
+ slice2->set_friendly_name("slice_gate");
+
+ auto clamp = std::make_shared<op::v0::Clamp>(slice2, -20.0f, 20.0f);
+ clamp->set_friendly_name("clamp");
+
+ auto add2_const = op::v0::Constant::create(element::f32, Shape{1}, std::vector<float>{0.0f});
+ auto add2 = std::make_shared<op::v1::Add>(clamp, add2_const);
+ add2->set_friendly_name("add2");
+
+ // 6. Merge branches: Multiply1
+ auto multiply1 = std::make_shared<op::v1::Multiply>(activation_output, add2);
+ multiply1->set_friendly_name("multiply1_merge");
+
+ // 7. Second MatMul (down projection) with quantized weights
+ // Weight parameter: [num_experts, hidden_dim, hidden_dim] (NF4)
+ auto weights_nf4_2 = std::make_shared<op::v0::Parameter>(element::nf4, Shape{num_experts, hidden_dim, hidden_dim});
+ weights_nf4_2->set_friendly_name("weights_nf4_2");
+ params.push_back(weights_nf4_2);
+
+ // Convert NF4 to FP16
+ auto weights_fp16_2 = std::make_shared<op::v0::Convert>(weights_nf4_2, element::f16);
+ weights_fp16_2->set_friendly_name("weights_convert_fp16_2");
+
+ // Scale parameter: [num_experts, hidden_dim, 1] (FP16)
+ auto weights_scale_2 = std::make_shared<op::v0::Parameter>(element::f16, Shape{num_experts, hidden_dim, 1});
+ weights_scale_2->set_friendly_name("weights_scale_2");
+ params.push_back(weights_scale_2);
+
+ // Multiply with scale (dequantization)
+ auto weights_mult2 = std::make_shared<op::v1::Multiply>(weights_fp16_2, weights_scale_2);
+ weights_mult2->set_friendly_name("weights_multiply2");
+
+ // Convert FP16 to FP32 for MatMul
+ auto weights_conv2 = std::make_shared<op::v0::Convert>(weights_mult2, element::f32);
+ weights_conv2->set_friendly_name("weights_convert2");
+
+ auto matmul2 = std::make_shared<op::v0::MatMul>(multiply1, weights_conv2, false, true);
+ matmul2->set_friendly_name("matmul2");
+
+ // Biases: [num_experts, 1, hidden_dim]
+ auto biases2 = std::make_shared<op::v0::Parameter>(element::f32, Shape{num_experts, 1, hidden_dim});
+ biases2->set_friendly_name("biases2");
+ params.push_back(biases2);
+
+ auto add3 = std::make_shared<op::v1::Add>(matmul2, biases2);
+ add3->set_friendly_name("add3");
+
+ // 8. Output reshape
+ auto reshape_shape2 = op::v0::Constant::create(element::i64,
+ Shape{3},
+ std::vector<int64_t>{static_cast<int64_t>(num_experts),
+ static_cast<int64_t>(token_count),
+ static_cast<int64_t>(hidden_dim)});
+ auto reshape2 = std::make_shared<op::v1::Reshape>(add3, reshape_shape2, false);
+ reshape2->set_friendly_name("expert_reshape2");
+
+ // 9. Router scores multiply
+ auto router_scores = std::make_shared<op::v0::Parameter>(element::f32, Shape{num_experts, token_count, 1});
+ router_scores->set_friendly_name("router_scores");
+ params.push_back(router_scores);
+
+ auto output_multiply = std::make_shared<op::v1::Multiply>(reshape2, router_scores);
+ output_multiply->set_friendly_name("output_multiply");
+
+ // 10. Result
+ auto result = std::make_shared<op::v0::Result>(output_multiply);
+ result->set_friendly_name("output");
+
+ auto model = std::make_shared<Model>(ResultVector{result}, params);
+ model->set_friendly_name("gpt_oss_expert_" + std::to_string(num_experts) + (with_awq_multiply ? "_awq" : ""));
+
+ return model;
+}
+
// Create MoE graph with complete structure required by apply_expert_transformation
// Pattern: Parameter -> Tile -> Reshape -> MatMul -> Add -> Reshape -> Multiply -> Result
std::shared_ptr<Model> create_transformable_moe_graph(size_t num_experts,
@@ -258,4 +436,125 @@ TEST_F(MoETransformationTest, ExpertIterativeMode) {
EXPECT_EQ(shape[2], hidden_dim * 2) << "Hidden dimension should remain unchanged";
}
+// Test AWQ multiply unrolling: Verify that AWQ quantization multiply nodes are correctly unrolled
+TEST_F(MoETransformationTest, AWQMultiplyUnrolling) {
+ constexpr size_t num_total_experts = 8;
+ constexpr size_t num_active_experts = 4;
+ constexpr size_t hidden_dim = 2880;
+ constexpr size_t token_count = 1;
+ constexpr bool with_awq = true;
+
+ // Create GPT-OSS expert graph with AWQ multiply after Swish
+ auto model = create_gpt_oss_expert_graph(num_total_experts, hidden_dim, token_count, with_awq);
+ save_model(model, "moe_expert_awq_before");
+
+ auto structure_info = analyze_moe_structure(model);
+ ASSERT_TRUE(structure_info.has_value()) << "Failed to analyze MoE structure with AWQ multiply";
+ EXPECT_EQ(structure_info->num_experts, num_total_experts);
+ EXPECT_EQ(structure_info->input_token_count, token_count);
+ EXPECT_TRUE(structure_info->is_expert_batch_mode());
+
+ // Transform to K active experts
+ MoETransformConfig config;
+ config.num_target_experts = num_active_experts;
+ config.chunk_size = 0;
+
+ MoEModelTransformer transformer(*structure_info);
+ auto transformed = transformer.apply_expert_transformation(model, config);
+
+ ASSERT_NE(transformed, nullptr) << "AWQ multiply unrolling transformation failed";
+ EXPECT_NO_THROW(transformed->validate_nodes_and_infer_types());
+
+ save_model(transformed, "moe_expert_awq_after");
+
+ // Verify that AWQ multiply nodes were unrolled
+ size_t awq_multiply_count = 0;
+ for (const auto& node : transformed->get_ordered_ops()) {
+ if (auto mult = std::dynamic_pointer_cast<op::v1::Multiply>(node)) {
+ std::string name = mult->get_friendly_name();
+ if (name.find("awq_activation_multiply") != std::string::npos) {
+ awq_multiply_count++;
+ }
+ }
+ }
+
+ // Should have num_active_experts AWQ multiply nodes after unrolling
+ EXPECT_EQ(awq_multiply_count, num_active_experts)
+ << "Expected " << num_active_experts << " AWQ multiply nodes after unrolling, found " << awq_multiply_count;
+
+ // Verify AWQ scale parameters were unrolled
+ size_t awq_param_count = 0;
+ for (const auto& param : transformed->get_parameters()) {
+ std::string name = param->get_friendly_name();
+ if (name.find("awq_activation_scale") != std::string::npos) {
+ awq_param_count++;
+ }
+ }
+
+ // Should have num_active_experts AWQ scale parameters after unrolling
+ EXPECT_EQ(awq_param_count, num_active_experts)
+ << "Expected " << num_active_experts << " AWQ scale parameters after unrolling, found " << awq_param_count;
+
+ // Verify output shape is correct
+ auto result = transformed->get_results()[0];
+ auto output_shape = result->get_input_partial_shape(0);
+ ASSERT_TRUE(output_shape.is_static()) << "Output shape should be static";
+
+ auto shape = output_shape.to_shape();
+ EXPECT_EQ(shape.size(), 3) << "Output should be 3D tensor";
+ EXPECT_EQ(shape[0], num_active_experts) << "Expert dimension should be " << num_active_experts;
+ EXPECT_EQ(shape[1], token_count) << "Token dimension should be 1";
+ EXPECT_EQ(shape[2], hidden_dim) << "Hidden dimension should remain unchanged";
+}
+
+// Test comparison: Verify AWQ and non-AWQ models have similar structure after unrolling
+TEST_F(MoETransformationTest, AWQvsNonAWQComparison) {
+ constexpr size_t num_total_experts = 8;
+ constexpr size_t num_active_experts = 2;
+ constexpr size_t hidden_dim = 2880;
+ constexpr size_t token_count = 1;
+
+ // Create both AWQ and non-AWQ models
+ auto model_awq = create_gpt_oss_expert_graph(num_total_experts, hidden_dim, token_count, true);
+ auto model_non_awq = create_gpt_oss_expert_graph(num_total_experts, hidden_dim, token_count, false);
+
+ // Transform both
+ MoETransformConfig config;
+ config.num_target_experts = num_active_experts;
+ config.chunk_size = 0;
+
+ auto structure_awq = analyze_moe_structure(model_awq);
+ auto structure_non_awq = analyze_moe_structure(model_non_awq);
+
+ ASSERT_TRUE(structure_awq.has_value());
+ ASSERT_TRUE(structure_non_awq.has_value());
+
+ MoEModelTransformer transformer_awq(*structure_awq);
+ MoEModelTransformer transformer_non_awq(*structure_non_awq);
+
+ auto transformed_awq = transformer_awq.apply_expert_transformation(model_awq, config);
+ auto transformed_non_awq = transformer_non_awq.apply_expert_transformation(model_non_awq, config);
+
+ ASSERT_NE(transformed_awq, nullptr);
+ ASSERT_NE(transformed_non_awq, nullptr);
+
+ // AWQ model should have more operations due to additional multiply nodes
+ EXPECT_GT(transformed_awq->get_ordered_ops().size(), transformed_non_awq->get_ordered_ops().size())
+ << "AWQ model should have more operations (includes AWQ multiply nodes)";
+
+ // AWQ model should have more parameters due to AWQ scale parameters
+ EXPECT_GT(transformed_awq->get_parameters().size(), transformed_non_awq->get_parameters().size())
+ << "AWQ model should have more parameters (includes AWQ scale parameters)";
+
+ // Both should have same number of results
+ EXPECT_EQ(transformed_awq->get_results().size(), transformed_non_awq->get_results().size());
+
+ // Both should have same output shape
+ auto result_awq = transformed_awq->get_results()[0];
+ auto result_non_awq = transformed_non_awq->get_results()[0];
+
+ EXPECT_EQ(result_awq->get_input_partial_shape(0), result_non_awq->get_input_partial_shape(0))
+ << "AWQ and non-AWQ models should have identical output shapes";
+}
+
} // namespace