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
[MOE] Fix issues with batch, use postponed_const when fusing expert weights (#32546)
Mateusz Mikolajczyk4135e53897ee
diff --git a/.github/workflows/job_pytorch_models_tests.yml b/.github/workflows/job_pytorch_models_tests.ymlindex ca25451feda..1bc87ff7616 100644--- a/.github/workflows/job_pytorch_models_tests.yml+++ b/.github/workflows/job_pytorch_models_tests.yml@@ -155,6 +155,16 @@ jobs:env:TEST_DEVICE: CPU+ - name: MoE Fusion Test+ if: ${{ inputs.model_scope == 'precommit' }}+ run: |+ export PYTHONPATH=${MODEL_HUB_TESTS_INSTALL_DIR}:$PYTHONPATH+ python3 -m pip install optimum-intel==1.25.2 transformers==4.53.3 --upgrade+ python3 -m pytest ${MODEL_HUB_TESTS_INSTALL_DIR}/transformation_tests/test_moe_transformation.py -m precommit --html=${INSTALL_TEST_DIR}/TEST-torch_moe_tests.html --self-contained-html -vvv -s --tb=short -n 2+ env:+ TEST_DEVICE: CPU+ HF_HUB_OFFLINE: 0+- name: Reformat unsupported ops fileif: ${{ inputs.model_scope != 'precommit' && !cancelled()}}run: |diff --git a/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cpp b/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cppindex cbe4b036cc0..a7bc778bc23 100644--- a/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cpp@@ -395,7 +395,8 @@ ov::pass::FuseMOEExperts::FuseMOEExperts() : MultiMatcher("FuseMOEExperts") {inputs.emplace_back(ov::op::util::make_try_fold<ov::op::v0::Unsqueeze>(original_weight, const_0));}- auto fused = ov::op::util::make_try_fold<ov::op::v0::Concat>(inputs, 0);+ auto fused = std::make_shared<ov::op::v0::Concat>(inputs, 0);+ fused->get_rt_info()["postponed_constant"] = true;if (needs_decompress) {auto convert = std::make_shared<ov::op::v0::Convert>(fused, target_type);ov::mark_as_decompression(convert);@@ -418,6 +419,7 @@ ov::pass::FuseMOEExperts::FuseMOEExperts() : MultiMatcher("FuseMOEExperts") {// Extract input and residual nodes from the pattern matchauto view_reshape_node = last_add_match.at(view_Reshape).get_node_shared_ptr();auto residual_input_node = last_add_match.at(residual_input).get_node_shared_ptr();+ auto original_shape_node = last_add_match.at(original_shape).get_node_shared_ptr();// Build the fused MoE computationconst size_t num_experts = experts.size();@@ -489,8 +491,7 @@ ov::pass::FuseMOEExperts::FuseMOEExperts() : MultiMatcher("FuseMOEExperts") {auto final_output = std::make_shared<ov::op::v1::ReduceSum>(weighted_outputs, const_0, false);// Reshape back to original shape and add residual connection- auto target_shape = std::make_shared<ov::op::v3::ShapeOf>(view_reshape_node, element::i64);- auto final_reshape = std::make_shared<ov::op::v1::Reshape>(final_output, target_shape, false);+ auto final_reshape = std::make_shared<ov::op::v1::Reshape>(final_output, original_shape_node, false);auto final_add = std::make_shared<ov::op::v1::Add>(residual_input_node, final_reshape);if (last_reshape_node && !last_reshape_node->get_friendly_name().empty()) {diff --git a/src/common/transformations/tests/common_optimizations/fuse_moe_test.cpp b/src/common/transformations/tests/common_optimizations/fuse_moe_test.cppindex 6baaf9e794a..bf0bc8d528d 100644--- a/src/common/transformations/tests/common_optimizations/fuse_moe_test.cpp+++ b/src/common/transformations/tests/common_optimizations/fuse_moe_test.cpp@@ -27,6 +27,7 @@ using namespace ov;std::shared_ptr<ov::Model> BuildMOE(int expert_num, int topk) {ov::element::Type inType = ov::element::f32;// param1: [batch*seq, 2048]+ // auto hidden_states_original_shape =auto final_hidden_states_ = std::make_shared<ov::opset1::Parameter>(inType, ov::PartialShape{-1, 2048});// f32[?,128]auto router_logits = std::make_shared<ov::opset1::Parameter>(inType, ov::PartialShape{-1, expert_num});@@ -77,64 +78,51 @@ std::shared_ptr<ov::Model> BuildMOE(int expert_num, int topk) {auto routing_weights = index_Reshape;auto residual_input = makeOP<opset1::Convert>({final_hidden_states_}, {{"destination_type", "f32"}});- std::shared_ptr<ov::Node> final_hidden_states = residual_input;- std::shared_ptr<ov::Node> original_shape_node;+ auto target_shape_for_zeros = makeOP<opset3::ShapeOf>({residual_input}, {{"output_type", "i32"}});+ auto zero_scalar = makeConst(ov::element::f32, ov::Shape{}, std::vector<float>{0.0f});+ auto zeros_like = makeOP<opset3::Broadcast>({zero_scalar, target_shape_for_zeros}, {{"mode", "numpy"}});+ std::shared_ptr<ov::Node> expert_outputs_accumulator = zeros_like;++ // Original shape should be the shape of the input hidden_states_ for final reshape+ auto original_shape_node = target_shape;for (int i = 0; i < expert_num; i++) {- // expert_mask[expert_idx]std::shared_ptr<Node> select_Gather_2;select_Gather_2 = makeOP<opset8::Gather>({expert_mask, i, 0}, {{"batch_dims", 0}});- auto squeeze_Squeeze_7 = makeOP<opset1::Squeeze>(- {select_Gather_2,- squeeze_axis_const}); // tensor_array<i64[2,?]>- // __module.model.layers.1.mlp/aten::squeeze/Squeeze_7(__module.model.layers.1.mlp/aten::select/Gather_7,- // 60)+ auto squeeze_Squeeze_7 = makeOP<opset1::Squeeze>({select_Gather_2, squeeze_axis_const});- // x = torch.where(expert_mask[expert_idx]), x shape: [2, nonzero], dim0: topk, dim1: batchauto ListUnpack_NonZero_2 = makeOP<opset3::NonZero>({squeeze_Squeeze_7}, {{"output_type", "i64"}});- // topk, batch = torch.where(expert_mask[expert_idx])auto ListUnpack_Split_2 = makeOP<opset1::Split>({ListUnpack_NonZero_2, 0}, {{"num_splits", 2}});- // batchauto ListUnpack_Squeeze_0_2 =makeOP<opset1::Squeeze>({ListUnpack_Split_2->output(1), squeeze_axis_const}, {{"special_zero", false}});auto index_add__Convert_2 = makeOP<opset1::Convert>({ListUnpack_Squeeze_0_2}, {{"destination_type", "i32"}});auto index_add__Reshape_2 = makeOP<opset1::Reshape>({index_add__Convert_2, {-1, 1}}, {{"special_zero", false}});- auto index_add__Slice_2 = makeOP<opset8::Slice>({final_hidden_states, {0, 0}, {1, INT_MAX}, {1, 1}, {0, 1}});+ auto index_add__Slice_2 =+ makeOP<opset8::Slice>({expert_outputs_accumulator, {0, 0}, {1, INT_MAX}, {1, 1}, {0, 1}});auto index_add__ShapeOf_22 = makeOP<opset3::ShapeOf>({index_add__Slice_2}, {{"output_type", "i32"}});- original_shape_node = index_add__ShapeOf_22;auto index_add__Broadcast_25 =makeOP<opset3::Broadcast>({index_add__Reshape_2, index_add__ShapeOf_22}, {{"mode", "bidirectional"}});auto index_Gather_4 =- makeOP<opset8::Gather>({hidden_states_reshaped /*unsqueeze_Unsqueeze_reshape*/, index_add__Convert_2, 0},- {{"batch_dims", 0}});+ makeOP<opset8::Gather>({hidden_states_reshaped, index_add__Convert_2, 0}, {{"batch_dims", 0}});auto reshape_Reshape_2_0 = makeOP<opset1::Reshape>({index_Gather_4, {-1, 2048}}, {{"special_zero", true}});auto reshape_Reshape_2_1 = makeOP<opset1::Reshape>({reshape_Reshape_2_0, {-1, 2048}}, {{"special_zero", true}});auto reshape_Reshape_2_2 = makeOP<opset1::Reshape>({reshape_Reshape_2_1, {-1, 2048}}, {{"special_zero", true}});auto reshape_Reshape_2 = makeOP<opset1::Reshape>({reshape_Reshape_2_2, {-1, 2048}}, {{"special_zero", true}});std::shared_ptr<ov::Node> gate_linear_Convert, up_linear_Convert, down_linear_Convert;- // FP16 weights onlyauto self_model_model_layers_0_mlp_experts_2_gate_proj_weight =makeConst(element::f16, ov::Shape({768, 16 * 128}), {0});gate_linear_Convert = makeOP<opset1::Convert>({self_model_model_layers_0_mlp_experts_2_gate_proj_weight},{{"destination_type", "f32"}});ov::mark_as_decompression(gate_linear_Convert);- auto self_model_model_layers_0_mlp_experts_2_up_proj_weight = makeConst(element::f16,- ov::Shape({- 768,- 16 * 128,- }),- {0});+ auto self_model_model_layers_0_mlp_experts_2_up_proj_weight =+ makeConst(element::f16, ov::Shape({768, 16 * 128}), {0});up_linear_Convert = makeOP<opset1::Convert>({self_model_model_layers_0_mlp_experts_2_up_proj_weight},{{"destination_type", "f32"}});ov::mark_as_decompression(up_linear_Convert);- auto self_model_model_layers_0_mlp_experts_2_down_proj_weight = makeConst(element::f16,- ov::Shape({- 2048,- 6 * 128,- }),- {0});+ auto self_model_model_layers_0_mlp_experts_2_down_proj_weight =+ makeConst(element::f16, ov::Shape({2048, 6 * 128}), {0});down_linear_Convert = makeOP<opset1::Convert>({self_model_model_layers_0_mlp_experts_2_down_proj_weight},{{"destination_type", "f32"}});ov::mark_as_decompression(down_linear_Convert);@@ -151,28 +139,22 @@ std::shared_ptr<ov::Model> BuildMOE(int expert_num, int topk) {auto ListUnpack_Squeeze_2 =makeOP<opset1::Squeeze>({ListUnpack_Split_2->output(0), squeeze_axis_const}, {{"special_zero", false}});auto index_Convert_6 = makeOP<opset1::Convert>({ListUnpack_Squeeze_2}, {{"destination_type", "i32"}});- // self.topk * batch, index_split=shapeof(routing_weights), shape: [batch, self.topk, 1]auto index_Multiply_2 =makeOP<opset1::Multiply>({index_add__Convert_2, index_Split->output(1)}, {{"auto_broadcast", "numpy"}});- // self.topk * batch + topkauto index_Add_2 = makeOP<opset1::Add>({index_Convert_6, index_Multiply_2}, {{"auto_broadcast", "numpy"}});- // routing_weights', shape[self.topk * batch, 1]- auto index_Gather_5 =- makeOP<opset8::Gather>({routing_weights /*index_Reshape*/, index_Add_2, 0}, {{"batch_dims", 0}});+ auto index_Gather_5 = makeOP<opset8::Gather>({routing_weights, index_Add_2, 0}, {{"batch_dims", 0}});auto index_Reshape_8_2 = makeOP<opset1::Reshape>({index_Gather_5, {0, 1}}, {{"special_zero", true}});auto mul_Multiply_3 =makeOP<opset1::Multiply>({down_linear_MatMul, index_Reshape_8_2}, {{"auto_broadcast", "numpy"}});auto index_add__Broadcast_26 =makeOP<opset3::Broadcast>({mul_Multiply_3, index_add__ShapeOf_22}, {{"mode", "bidirectional"}});- auto index_add__ScatterElementsUpdate_8 =- makeOP<opset12::ScatterElementsUpdate>({final_hidden_states /*index_add__ScatterElementsUpdate_5*/,- index_add__Broadcast_25,- index_add__Broadcast_26,- 0},- {{"reduction", "sum"}, {"use_init_val", true}});- final_hidden_states = index_add__ScatterElementsUpdate_8;+ auto index_add__ScatterElementsUpdate_8 = makeOP<opset12::ScatterElementsUpdate>(+ {expert_outputs_accumulator, index_add__Broadcast_25, index_add__Broadcast_26, 0},+ {{"reduction", "sum"}, {"use_init_val", true}});+ expert_outputs_accumulator = index_add__ScatterElementsUpdate_8;}- auto final_reshape = makeOP<opset1::Reshape>({final_hidden_states, original_shape_node}, {{"special_zero", false}});+ auto final_reshape =+ makeOP<opset1::Reshape>({expert_outputs_accumulator, original_shape_node}, {{"special_zero", false}});auto final_add = makeOP<opset1::Add>({residual_input, final_reshape}, {{"auto_broadcast", "numpy"}});return std::make_shared<ov::Model>(ov::OutputVector{final_add},@@ -209,35 +191,41 @@ static std::shared_ptr<ov::Model> BuildFusedMOE(const int expert_num, const intauto target_shape = makeOP<opset3::ShapeOf>({hidden_states_}, {{"output_type", "i64"}});- // Create fused weights with f16 constants and decompression Converts to match transformation output- auto fused_gate_weights_f16 = makeConst(ov::element::f16,- ov::Shape{static_cast<size_t>(expert_num),- static_cast<size_t>(intermediate_size),- static_cast<size_t>(hidden_size)},- {0});+ auto axis0_const = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0});++ auto build_fused_weight = [&](ov::element::Type elem_type,+ const ov::Shape& single_expert_shape) -> std::shared_ptr<ov::Node> {+ ov::OutputVector expert_weights;+ for (int i = 0; i < expert_num; i++) {+ auto weight_const = makeConst(elem_type, single_expert_shape, {0});+ expert_weights.push_back(weight_const);+ }+ auto concat = std::make_shared<ov::op::v0::Concat>(expert_weights, 0);+ concat->get_rt_info()["postponed_constant"] = true;+ return concat;+ };++ auto fused_gate_weights_f16 =+ build_fused_weight(ov::element::f16,+ ov::Shape{1, static_cast<size_t>(intermediate_size), static_cast<size_t>(hidden_size)});auto fused_gate_weights_convert = std::make_shared<ov::op::v0::Convert>(fused_gate_weights_f16, ov::element::f32);ov::mark_as_decompression(fused_gate_weights_convert);auto fused_gate_weights = fused_gate_weights_convert;- auto fused_up_weights_f16 = makeConst(ov::element::f16,- ov::Shape{static_cast<size_t>(expert_num),- static_cast<size_t>(intermediate_size),- static_cast<size_t>(hidden_size)},- {0});+ auto fused_up_weights_f16 =+ build_fused_weight(ov::element::f16,+ ov::Shape{1, static_cast<size_t>(intermediate_size), static_cast<size_t>(hidden_size)});auto fused_up_weights_convert = std::make_shared<ov::op::v0::Convert>(fused_up_weights_f16, ov::element::f32);ov::mark_as_decompression(fused_up_weights_convert);auto fused_up_weights = fused_up_weights_convert;- auto fused_down_weights_f16 = makeConst(ov::element::f16,- ov::Shape{static_cast<size_t>(expert_num),- static_cast<size_t>(hidden_size),- static_cast<size_t>(intermediate_size)},- {0});+ auto fused_down_weights_f16 =+ build_fused_weight(ov::element::f16,+ ov::Shape{1, static_cast<size_t>(hidden_size), static_cast<size_t>(intermediate_size)});auto fused_down_weights_convert = std::make_shared<ov::op::v0::Convert>(fused_down_weights_f16, ov::element::f32);ov::mark_as_decompression(fused_down_weights_convert);auto fused_down_weights = fused_down_weights_convert;- // Create simple batched computationauto axis0_scalar = makeConst(ov::element::i64, ov::Shape{}, std::vector<int64_t>{0});auto axis1_scalar = makeConst(ov::element::i64, ov::Shape{}, std::vector<int64_t>{1});auto axis0_vector = makeConst(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0});@@ -267,7 +255,6 @@ static std::shared_ptr<ov::Model> BuildFusedMOE(const int expert_num, const intmakeOP<opset1::Concat>({num_experts_unsqueeze, batch_dim_unsqueeze, hidden_dim_unsqueeze}, {{"axis", 0}});auto batched_input = makeOP<opset1::Reshape>({repeated_input, batched_shape}, {{"special_zero", false}});- // Apply fused expert computationauto gate_bmm = makeOP<opset1::MatMul>({batched_input, fused_gate_weights->output(0)},{{"transpose_a", false}, {"transpose_b", true}});auto gate_swish = makeOP<opset4::Swish>({gate_bmm});@@ -282,7 +269,6 @@ static std::shared_ptr<ov::Model> BuildFusedMOE(const int expert_num, const int{{"axis", 0}});auto expert_outputs = makeOP<opset1::Reshape>({down_bmm, expert_output_shape}, {{"special_zero", false}});- // Create routing weights via scatter to match 3-GEMM patternauto topk_values = topk_TopK->output(0);auto sum_reduce = makeOP<opset1::ReduceSum>({topk_values, axis_minus_one}, {{"keep_dims", true}});auto normalized_topk =@@ -302,7 +288,6 @@ static std::shared_ptr<ov::Model> BuildFusedMOE(const int expert_num, const intauto router_reshape = std::make_shared<ov::op::v1::Reshape>(router_transpose, router_shape, true);auto routing_unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(router_reshape, axis_minus_one_vector);- // Apply routing and sumauto weighted_outputs = std::make_shared<ov::op::v1::Multiply>(expert_outputs, routing_unsqueeze);auto final_output = std::make_shared<ov::op::v1::ReduceSum>(weighted_outputs, axis0_vector, false);@@ -371,27 +356,33 @@ static std::shared_ptr<ov::Model> BuildFusedMOEWithInternalOp(const int expert_nauto router_reshape = std::make_shared<ov::op::v1::Reshape>(router_transpose, router_shape, true);auto routing_weights = std::make_shared<ov::op::v0::Unsqueeze>(router_reshape, axis_minus_one_vector);- auto fused_gate_weights_f16 = makeConst(ov::element::f16,- ov::Shape{static_cast<size_t>(expert_num),- static_cast<size_t>(intermediate_size),- static_cast<size_t>(hidden_size)},- {0});+ auto build_fused_weight = [&](ov::element::Type elem_type,+ const ov::Shape& single_expert_shape) -> std::shared_ptr<ov::Node> {+ ov::OutputVector expert_weights;+ for (int i = 0; i < expert_num; i++) {+ auto weight_const = makeConst(elem_type, single_expert_shape, {0});+ expert_weights.push_back(weight_const);+ }+ auto concat = std::make_shared<ov::op::v0::Concat>(expert_weights, 0);+ concat->get_rt_info()["postponed_constant"] = true;+ return concat;+ };++ auto fused_gate_weights_f16 =+ build_fused_weight(ov::element::f16,+ ov::Shape{1, static_cast<size_t>(intermediate_size), static_cast<size_t>(hidden_size)});auto fused_gate_weights = makeOP<opset1::Convert>({fused_gate_weights_f16}, {{"destination_type", "f32"}});ov::mark_as_decompression(fused_gate_weights);- auto fused_up_weights_f16 = makeConst(ov::element::f16,- ov::Shape{static_cast<size_t>(expert_num),- static_cast<size_t>(intermediate_size),- static_cast<size_t>(hidden_size)},- {0});+ auto fused_up_weights_f16 =+ build_fused_weight(ov::element::f16,+ ov::Shape{1, static_cast<size_t>(intermediate_size), static_cast<size_t>(hidden_size)});auto fused_up_weights = makeOP<opset1::Convert>({fused_up_weights_f16}, {{"destination_type", "f32"}});ov::mark_as_decompression(fused_up_weights);- auto fused_down_weights_f16 = makeConst(ov::element::f16,- ov::Shape{static_cast<size_t>(expert_num),- static_cast<size_t>(hidden_size),- static_cast<size_t>(intermediate_size)},- {0});+ auto fused_down_weights_f16 =+ build_fused_weight(ov::element::f16,+ ov::Shape{1, static_cast<size_t>(hidden_size), static_cast<size_t>(intermediate_size)});auto fused_down_weights = makeOP<opset1::Convert>({fused_down_weights_f16}, {{"destination_type", "f32"}});ov::mark_as_decompression(fused_down_weights);diff --git a/tests/model_hub_tests/transformation_tests/test_moe_transformation.py b/tests/model_hub_tests/transformation_tests/test_moe_transformation.pyindex 8b6200081f5..d49e396e62f 100644--- a/tests/model_hub_tests/transformation_tests/test_moe_transformation.py+++ b/tests/model_hub_tests/transformation_tests/test_moe_transformation.py@@ -125,7 +125,8 @@ def create_synthetic_moe_model(tmp_path, num_layers, num_experts, dtype="float32def run_moe(tmp_path,model_id,model_link,- ie_device):+ ie_device,+ batch_size=1):"""Test that MoE models are loaded with fused expert subgraphs.@@ -134,6 +135,9 @@ def run_moe(tmp_path,contains the characteristic fused MoE pattern.Additionally verifies output correctness by comparing with original PyTorch model.++ Args:+ batch_size: Number of sequences to process in parallel (default: 1)"""model_cached = snapshot_download(model_id) # required to avoid HF rate limits@@ -141,9 +145,13 @@ def run_moe(tmp_path,pt_model = AutoModelForCausalLM.from_pretrained(model_cached, trust_remote_code=True)tokenizer = AutoTokenizer.from_pretrained(model_cached, trust_remote_code=True)- # Prepare test input- test_text = "Test input for MoE model verification"- inputs = tokenizer(test_text, return_tensors="pt")+ # Prepare test input with specified batch size+ if batch_size == 1:+ test_text = "Test input for MoE model verification"+ else:+ # Create a list of different texts for batch processing+ test_text = [f"Test input {i} for MoE model batch verification" for i in range(batch_size)]+ inputs = tokenizer(test_text, return_tensors="pt", padding=True)# Get PyTorch outputwith torch.no_grad():@@ -173,12 +181,12 @@ def run_moe(tmp_path,max_diff = np.abs(pt_logits - ov_logits).max()mean_diff = np.abs(pt_logits - ov_logits).mean()- print(f"Output comparison: max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")+ print(f"Output comparison (batch_size={batch_size}): max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")# Verify outputs are close# Tolerances: rtol=1e-3, atol=1e-3 account for OpenVINO IR conversion and execution differencesassert np.allclose(pt_logits, ov_logits, rtol=1e-3, atol=1e-3), \- f"Output mismatch between PyTorch and OpenVINO fused model: max_diff={max_diff}, mean_diff={mean_diff}"+ f"Output mismatch between PyTorch and OpenVINO fused model (batch_size={batch_size}): max_diff={max_diff}, mean_diff={mean_diff}"@retry(3, exceptions=(OSError,), delay=1)@@ -186,7 +194,8 @@ def run_moe_synthetic(tmp_path,num_layers,num_experts,dtype,- ie_device):+ ie_device,+ batch_size=1):"""Test MoE fusion on synthetically generated models.@@ -194,6 +203,9 @@ def run_moe_synthetic(tmp_path,that MoE fusion produces the expected fused pattern.Additionally verifies output correctness by comparing with original PyTorch model.++ Args:+ batch_size: Number of sequences to process in parallel (default: 1)"""model_path = create_synthetic_moe_model(tmp_path, num_layers, num_experts, dtype)@@ -203,9 +215,13 @@ def run_moe_synthetic(tmp_path,tokenizer_cache = snapshot_download("optimum-internal-testing/tiny-random-qwen3_moe")tokenizer = AutoTokenizer.from_pretrained(tokenizer_cache, trust_remote_code=True)- # Prepare test input- test_text = "Test input for synthetic MoE model"- inputs = tokenizer(test_text, return_tensors="pt")+ # Prepare test input with specified batch size+ if batch_size == 1:+ test_text = "Test input for synthetic MoE model"+ else:+ # Create a list of different texts for batch processing+ test_text = [f"Synthetic test input {i} for MoE batch validation" for i in range(batch_size)]+ inputs = tokenizer(test_text, return_tensors="pt", padding=True)# Get PyTorch outputwith torch.no_grad():@@ -240,7 +256,7 @@ def run_moe_synthetic(tmp_path,max_diff = np.abs(pt_logits - ov_logits).max()mean_diff = np.abs(pt_logits - ov_logits).mean()- print(f"Synthetic ({num_layers}L, {num_experts}E, {dtype}): max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")+ print(f"Synthetic ({num_layers}L, {num_experts}E, {dtype}, batch={batch_size}): max_diff={max_diff:.6f}, mean_diff={mean_diff:.6f}")# Adjust tolerances based on dtype# FP16/BF16 have lower precision, so allow larger numerical differences@@ -248,7 +264,7 @@ def run_moe_synthetic(tmp_path,atol = 1e-2 if dtype in ["float16", "bfloat16"] else 1e-3assert np.allclose(pt_logits, ov_logits, rtol=rtol, atol=atol), \- f"Output mismatch for {num_layers}L, {num_experts}E, {dtype}: max_diff={max_diff}, mean_diff={mean_diff}"+ f"Output mismatch for {num_layers}L, {num_experts}E, {dtype}, batch={batch_size}: max_diff={max_diff}, mean_diff={mean_diff}"MOE_PRECOMMIT_TEST_CASES = [@@ -270,10 +286,15 @@ def moe_test_idfn(entry):return retval+# Batch sizes to test+BATCH_SIZES = [1, 2, 4]++@pytest.mark.precommit@pytest.mark.parametrize("model_info_tuple", MOE_PRECOMMIT_TEST_CASES, ids=moe_test_idfn)-def test_moe_precommit(tmp_path, model_info_tuple, ie_device):- """Test MoE fusion transformation on precommit models."""[email protected]("batch_size", BATCH_SIZES)+def test_moe_precommit(tmp_path, model_info_tuple, ie_device, batch_size):+ """Test MoE fusion transformation on precommit models with different batch sizes."""model_class, model_name, model_link, mark, reason = model_info_tupleassert mark is None or mark == 'skip' or mark == 'xfail', \"Incorrect test case: {}, {}".format(model_name, model_link)@@ -282,36 +303,51 @@ def test_moe_precommit(tmp_path, model_info_tuple, ie_device):elif mark == 'xfail':pytest.xfail(reason)- run_moe(tmp_path, model_name, model_link, ie_device)+ run_moe(tmp_path, model_name, model_link, ie_device, batch_size)# Synthetic test cases with different configurationsMOE_SYNTHETIC_TEST_CASES = [- # (num_layers, num_experts, dtype)- # Test different numbers of MoE layers- (1, 4, "float32"), # Single MoE layer- (2, 4, "float32"), # Two MoE layers- (3, 4, "float32"), # Three MoE layers-- # Test different numbers of experts- (1, 2, "float32"), # Minimal: 2 experts- (1, 8, "float32"), # More experts: 8- (1, 16, "float32"), # Many experts: 16-- # Test different dtypes (important for decompression pattern testing)- (1, 4, "float16"), # FP16 - may have decompression- (1, 4, "bfloat16"), # BF16 - may have decompression-- # Combined variations- (2, 8, "float16"), # Multiple layers + more experts + FP16- (3, 16, "bfloat16"), # Multiple layers + many experts + BF16+ # (num_layers, num_experts, dtype, batch_size)+ # Test different numbers of MoE layers with varying batch sizes+ (1, 4, "float32", 1), # Single MoE layer, single batch+ (1, 4, "float32", 2), # Single MoE layer, small batch+ (1, 4, "float32", 4), # Single MoE layer, larger batch+ (2, 4, "float32", 1), # Two MoE layers, single batch+ (2, 4, "float32", 4), # Two MoE layers, larger batch+ (3, 4, "float32", 1), # Three MoE layers, single batch+ (3, 4, "float32", 2), # Three MoE layers, small batch++ # Test different numbers of experts with batch processing+ (1, 2, "float32", 1), # Minimal: 2 experts, single batch+ (1, 2, "float32", 4), # Minimal: 2 experts, larger batch+ (1, 8, "float32", 1), # More experts: 8, single batch+ (1, 8, "float32", 2), # More experts: 8, small batch+ (1, 16, "float32", 1), # Many experts: 16, single batch+ (1, 16, "float32", 4), # Many experts: 16, larger batch++ # Test different dtypes with batch processing (important for decompression pattern testing)+ (1, 4, "float16", 1), # FP16 - may have decompression, single batch+ (1, 4, "float16", 4), # FP16 - may have decompression, larger batch+ (1, 4, "bfloat16", 1), # BF16 - may have decompression, single batch+ (1, 4, "bfloat16", 2), # BF16 - may have decompression, small batch++ # Combined variations with batch processing+ (2, 8, "float16", 1), # Multiple layers + more experts + FP16, single batch+ (2, 8, "float16", 4), # Multiple layers + more experts + FP16, larger batch+ (3, 16, "bfloat16", 1), # Multiple layers + many experts + BF16, single batch+ (3, 16, "bfloat16", 2), # Multiple layers + many experts + BF16, small batch++ # Edge cases: larger batch sizes+ (1, 4, "float32", 8), # Large batch size+ (2, 8, "float32", 8), # Large batch with more complex model]def synthetic_test_idfn(entry):"""Generate test ID for synthetic test cases."""- num_layers, num_experts, dtype = entry- return f"synthetic-l{num_layers}-e{num_experts}-{dtype}"+ num_layers, num_experts, dtype, batch_size = entry+ return f"synthetic-l{num_layers}-e{num_experts}-{dtype}-b{batch_size}"@pytest.mark.precommit@@ -324,6 +360,7 @@ def test_moe_synthetic(tmp_path, test_params, ie_device):- Different numbers of MoE layers (1, 2, 3)- Different numbers of experts (2, 4, 8, 16)- Different dtypes (float32, float16, bfloat16) to validate decompression handling+ - Different batch sizes (1, 2, 4, 8) to ensure fusion works correctly with batched inputs"""- num_layers, num_experts, dtype = test_params- run_moe_synthetic(tmp_path, num_layers, num_experts, dtype, ie_device)+ num_layers, num_experts, dtype, batch_size = test_params+ run_moe_synthetic(tmp_path, num_layers, num_experts, dtype, ie_device, batch_size)