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]MoE optimization - RoPE cache and unfold infer request. (#36887)
intelgaoxiong337f0f63bf5b
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cppindex 53b9059d03f..5af19d54c9f 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp@@ -502,7 +502,7 @@ void apply_moe_config(ov::AnyMap& stage_config,"DEVICE_ROUTED mode uses in-graph gather-based expert selection which is only ""optimized for GENERATE stage. Please use HOST_ROUTED or DENSE for PREFILL.");}- stage_config["NPUW_UNFOLD_IREQS"] = "NO";+ stage_config["NPUW_UNFOLD_IREQS"] = "YES";} else if (moe_hint == ::intel_npu::npuw::llm::MoEHint::DENSE) {LOG_INFO("MoE config for " << stage_name << " stage: DENSE (all experts active)");// DENSE mode requires CPU-only device due to extremely long NPU compilation time and high resource consumption@@ -736,14 +736,6 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m// Auto-detect MoE model by scanning for router/expert nodesconst bool is_moe = is_moe_model(model);if (is_moe) {- // Only apply MoE defaults if not explicitly set in external config- if (npuw_llm_props.find("NPUW_LLM_SHARED_HEAD") == npuw_llm_props.end()) {- m_cfg.update({{"NPUW_LLM_SHARED_HEAD", "NO"}});- }- if (npuw_llm_props.find("NPUW_LLM_GENERATE_HINT") == npuw_llm_props.end()) {- m_cfg.update({{"NPUW_LLM_GENERATE_HINT", "BEST_PERF"}});- }-// Enable DEVICE_ROUTED mode by default for MoE models on newer compiler versions, as it's more efficient than// HOST_ROUTEDif (npuw_llm_props.find("NPUW_LLM_GENERATE_MOE_HINT") == npuw_llm_props.end() && npudesc->arch == "5010" &&@@ -1069,32 +1061,6 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mgenerate_config["NPUW_FALLBACK_EXEC"] = "NO";}- if (is_moe) {- // Apply MoE configuration for prefill stage- const auto prefill_moe_hint = m_cfg.get<::intel_npu::NPUW_LLM_PREFILL_MOE_HINT>();- apply_moe_config(prefill_config, prefill_moe_hint, "PREFILL");-- // Apply MoE configuration for generate stage- const auto generate_moe_hint = m_cfg.get<::intel_npu::NPUW_LLM_GENERATE_MOE_HINT>();- apply_moe_config(generate_config, generate_moe_hint, "GENERATE");-- // Fold shape-compute chains (ShapeOf→Gather→Concat etc.) in the prefill model before- // online partitioning runs pattern matching (e.g. GPTOSSRouter). Must run after- // ReshapeToStatic has made all shapes static so that ShapeOf bounds are resolvable.- ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(prefill_model);- for (auto&& model_variant : generate_model_variants) {- ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(model_variant);- }-- if (generate_moe_hint == ::intel_npu::npuw::llm::MoEHint::DEVICE_ROUTED) {- // Apply model transformations only to GENERATE stage (PREFILL doesn't support DEVICE_ROUTED- // transformations)- for (auto&& model_variant : generate_model_variants) {- ov::npuw::ApplyMoEDeviceRoutedTransforms().run_on_model(model_variant);- }- }- }-if (m_is_whisper) {update_config_for_whisper(prefill_config);if (is_int8_compressed(model)) {@@ -1140,6 +1106,33 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m}}}++ if (is_moe) {+ // Apply MoE configuration for prefill stage+ const auto prefill_moe_hint = m_cfg.get<::intel_npu::NPUW_LLM_PREFILL_MOE_HINT>();+ apply_moe_config(prefill_config, prefill_moe_hint, "PREFILL");++ // Apply MoE configuration for generate stage+ const auto generate_moe_hint = m_cfg.get<::intel_npu::NPUW_LLM_GENERATE_MOE_HINT>();+ apply_moe_config(generate_config, generate_moe_hint, "GENERATE");++ // Fold shape-compute chains (ShapeOf→Gather→Concat etc.) in the prefill model before+ // online partitioning runs pattern matching (e.g. GPTOSSRouter). Must run after+ // ReshapeToStatic has made all shapes static so that ShapeOf bounds are resolvable.+ ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(prefill_model);+ for (auto&& model_variant : generate_model_variants) {+ ov::npuw::patterns::util::FoldShapeComputeChain().run_on_model(model_variant);+ }++ if (generate_moe_hint == ::intel_npu::npuw::llm::MoEHint::DEVICE_ROUTED) {+ // Apply model transformations only to GENERATE stage (PREFILL doesn't support DEVICE_ROUTED+ // transformations)+ for (auto&& model_variant : generate_model_variants) {+ ov::npuw::ApplyMoEDeviceRoutedTransforms().run_on_model(model_variant);+ }+ }+ }+// Regularize models for the better partitioning assuming it is a transformer// Apply these transformations to all variant models{diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cppindex 5f6bfb7fc2c..448ab9cdf7b 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp@@ -17,10 +17,16 @@ namespace pre_compute = ov::npuw::patterns::pre_compute;namespace {// TODO: copied from common tests+// Builds a [1, max_position_embeddings, rotary_ndims] sin/cos LUT.+// When duplicate=true (LLama2-style rotate_half), rotary_ndims = inv_freq_size*2+// and the second half mirrors the first (torch.cat([freqs, freqs], dim=-1)).+// When duplicate=false (GPT-style), rotary_ndims = inv_freq_size with no mirroring.static ov::OutputVector makeCosSinCache(const size_t max_position_embeddings,- const std::shared_ptr<ov::Node> inverse_frequencies) {+ const std::shared_ptr<ov::Node> inverse_frequencies,+ bool duplicate = true) {const auto inverse_freq_fp32 = ov::as_type_ptr<ov::op::v0::Constant>(inverse_frequencies)->cast_vector<float>();- const size_t rotary_ndims = ov::shape_size(inverse_frequencies->get_shape()) * 2;+ const size_t inv_freq_size = ov::shape_size(inverse_frequencies->get_shape());+ const size_t rotary_ndims = duplicate ? inv_freq_size * 2 : inv_freq_size;std::vector<ov::float16> lut_sin(max_position_embeddings * rotary_ndims, 0.0f);std::vector<ov::float16> lut_cos(max_position_embeddings * rotary_ndims, 0.0f);@@ -29,18 +35,17 @@ static ov::OutputVector makeCosSinCache(const size_t max_position_embeddings,// y1 = cos(m*xita_i) * x1 - sin(m*xita_i) * x2// y2 = cos(m*xita_i) * x2 + sin(m*xita_i) * x1//- for (size_t i = 0, k = 0; i < rotary_ndims; i += 2, k++) {- auto xita_i = inverse_freq_fp32[i >> 1];+ for (size_t k = 0; k < inv_freq_size; k++) {+ auto xita_i = inverse_freq_fp32[k];ov::float16* psin = lut_sin.data();ov::float16* pcos = lut_cos.data();for (size_t m = 0; m < max_position_embeddings; m++, psin += rotary_ndims, pcos += rotary_ndims) {- auto vsin = std::sin(xita_i * m);- auto vcos = std::cos(xita_i * m);- pcos[k] = ov::float16{vcos};- pcos[k + rotary_ndims / 2] = pcos[k];-- psin[k] = ov::float16{vsin};- psin[k + rotary_ndims / 2] = psin[k];+ pcos[k] = ov::float16{std::cos(xita_i * static_cast<float>(m))};+ psin[k] = ov::float16{std::sin(xita_i * static_cast<float>(m))};+ if (duplicate) {+ pcos[k + inv_freq_size] = pcos[k];+ psin[k + inv_freq_size] = psin[k];+ }}}@@ -120,6 +125,7 @@ void replaceSinCosByCache(int max_prompt_len, const ov::OutputVector& cache, conauto gather_input_to_concat = rpe->matched_concat->input(0);gather_input_to_concat.get_source_output().remove_target_input(gather_input_to_concat);}+} // namespaceov::npuw::patterns::pre_compute::RopePatternLLama2::RopePatternLLama2() : matcher("sin-cos-matcher") {@@ -135,7 +141,9 @@ ov::npuw::patterns::pre_compute::RopePatternLLama2::RopePatternLLama2() : matcheauto convert = opp::wrap_type<ov::op::v0::Convert>({unsqueeze});auto matmul = opp::wrap_type<ov::op::v0::MatMul>({broadcast, convert});auto transpose = opp::wrap_type<ov::op::v1::Transpose>({matmul, opp::any_input()});- auto concat_2 = opp::wrap_type<ov::op::v0::Concat>({transpose, opp::any_input()});+ // Optional Concat between Transpose and Sin/Cos: present in LLama2-style RoPE+ // (torch.cat([freqs, freqs], dim=-1)), absent in GPT-style RoPE (inv_freq shape [1, n, 1]).+ auto concat_2 = opp::optional<ov::op::v0::Concat>({transpose->output(0), opp::any_input()});auto output_sin = opp::wrap_type<ov::op::v0::Sin>({concat_2});auto output_cos = opp::wrap_type<ov::op::v0::Cos>({concat_2});@@ -150,7 +158,13 @@ ov::npuw::patterns::pre_compute::RopePatternLLama2::RopePatternLLama2() : matchethis->matched_cos = map_cos.at(output_cos).get_node_shared_ptr();this->matched_sin = map_sin.at(output_sin).get_node_shared_ptr();- LOG_VERB("Rope found : sin=" << matched_sin->get_name() << ", cos=" << matched_cos->get_name());+ // Determine if freq duplication was applied by inspecting the actual graph:+ // sin's direct input is Concat (LLama2-style) or Transpose (GPT-style, no dup).+ auto sin_input = this->matched_sin->input_value(0).get_node_shared_ptr();+ this->duplicate_freqs = ov::is_type<ov::op::v0::Concat>(sin_input);++ LOG_VERB("Rope found : sin=" << matched_sin->get_name() << ", cos=" << matched_cos->get_name()+ << " (duplicate_freqs=" << duplicate_freqs << ")");return true;};@@ -341,7 +355,7 @@ ov::npuw::patterns::pre_compute::RopeCacheMatcher::RopeCacheMatcher(const uint32auto rpe = std::make_shared<RopePatternLLama2>();rpe->transform_cb = [&]() {- auto cache = makeCosSinCache(max_prompt_len, rpe->matched_inv_freq);+ auto cache = makeCosSinCache(max_prompt_len, rpe->matched_inv_freq, rpe->duplicate_freqs);replaceSinCosByCache(max_prompt_len, cache, rpe.get());};rpe->run_on_model(model);diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hppindex 7af37ab027b..57840741663 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp@@ -22,6 +22,7 @@ public:std::shared_ptr<ov::Node> matched_sin;std::shared_ptr<ov::Node> matched_cos;std::shared_ptr<ov::Node> matched_concat;+ bool duplicate_freqs = false;std::function<void()> transform_cb;diff --git a/src/plugins/intel_npu/tests/unit/npuw/pre_compute_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pre_compute_test.cppindex 2690cd52d4d..ff58e5a593b 100644--- a/src/plugins/intel_npu/tests/unit/npuw/pre_compute_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/pre_compute_test.cpp@@ -2,6 +2,8 @@// SPDX-License-Identifier: Apache-2.0//+#include "partitioning/patterns/pre_compute.hpp"+#include <gtest/gtest.h>#include <algorithm>@@ -11,26 +13,22 @@#include "openvino/core/except.hpp"#include "openvino/op/ops.hpp"-#include "partitioning/patterns/pre_compute.hpp"namespace {std::shared_ptr<ov::Model> make_longrope_v5_model(const std::vector<float>& short_factor_values,- const std::vector<float>& long_factor_values,- const std::vector<float>& multiply_values,- const std::vector<float>& power_values) {+ const std::vector<float>& long_factor_values,+ const std::vector<float>& multiply_values,+ const std::vector<float>& power_values) {auto data = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4, 2});auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::Shape{2, 1});- auto short_factor = ov::op::v0::Constant::create(ov::element::f32,- ov::Shape{short_factor_values.size()},- short_factor_values);- auto long_factor = ov::op::v0::Constant::create(ov::element::f32,- ov::Shape{long_factor_values.size()},- long_factor_values);- auto multiply_const = ov::op::v0::Constant::create(ov::element::f32,- ov::Shape{multiply_values.size()},- multiply_values);+ auto short_factor =+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{short_factor_values.size()}, short_factor_values);+ auto long_factor =+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{long_factor_values.size()}, long_factor_values);+ auto multiply_const =+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{multiply_values.size()}, multiply_values);auto power_const = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{power_values.size()}, power_values);auto reduce_axes = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, 1});@@ -79,6 +77,50 @@ std::shared_ptr<ov::Model> make_longrope_v5_model(const std::vector<float>& shor"longrope_v5_test_model");}+// Builds a minimal RoPE model matching RopePatternLLama2.+// When with_concat2=true (LLama2 style): Transpose → Concat_2 → Sin/Cos, duplicate_freqs=true.+// When with_concat2=false (GPT style): Transpose → Sin/Cos directly, duplicate_freqs=false.+std::shared_ptr<ov::Model> make_rope_model(bool with_concat2) {+ auto data = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::Shape{1, 4, 4});+ auto position_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1, 4});++ // inv_freq: constant [1, half_dim=2, 1]+ auto inv_freq = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 2, 1}, {0.5f, 0.1f});++ // ShapeOf → Gather(batch dim) → Concat_1 (broadcast target shape)+ auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(data);+ auto gather_idx = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});+ auto gather_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});+ auto gather = std::make_shared<ov::op::v8::Gather>(shape_of, gather_idx, gather_axis);+ auto ndims_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});+ auto one_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});+ auto concat_1 = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{gather, ndims_const, one_const}, 0);++ // Broadcast inv_freq to [1,2,1], MatMul with position_ids → Transpose+ auto broadcast = std::make_shared<ov::op::v3::Broadcast>(inv_freq, concat_1);+ auto unsq_axis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});+ auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(position_ids, unsq_axis);+ auto convert = std::make_shared<ov::op::v0::Convert>(unsqueeze, ov::element::f32);+ auto matmul = std::make_shared<ov::op::v0::MatMul>(broadcast, convert); // [1,2,4]+ auto perm = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{0, 2, 1});+ auto transpose = std::make_shared<ov::op::v1::Transpose>(matmul, perm); // [1,4,2]++ // Sin/Cos either via Concat_2 (LLama2) or directly (GPT)+ ov::Output<ov::Node> sin_cos_input = transpose->output(0);+ if (with_concat2) {+ auto zeros = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1, 4, 2}, std::vector<float>(8, 0.f));+ sin_cos_input = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{transpose, zeros}, -1)->output(0);+ }++ auto sin = std::make_shared<ov::op::v0::Sin>(sin_cos_input);+ auto cos = std::make_shared<ov::op::v0::Cos>(sin_cos_input);++ return std::make_shared<ov::Model>(+ ov::ResultVector{std::make_shared<ov::op::v0::Result>(sin), std::make_shared<ov::op::v0::Result>(cos)},+ ov::ParameterVector{data, position_ids},+ with_concat2 ? "llama2_rope_test_model" : "gpt_rope_test_model");+}+bool has_input_name(const std::shared_ptr<ov::Model>& model, const std::string& name) {const auto inputs = model->inputs();return std::any_of(inputs.begin(), inputs.end(), [&name](const auto& input) {@@ -113,16 +155,54 @@ TEST(PreComputeTest, RopeCacheThrowsOnMismatchedFactorSizesInLongRopeV5) {auto model = make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {1.0f}, {1.0f});ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16, "longrope_input");- EXPECT_THROW(pass.run_on_model(model),- ov::AssertFailure);+ EXPECT_THROW(pass.run_on_model(model), ov::AssertFailure);}TEST(PreComputeTest, RopeCacheThrowsOnNonScalarPowerInLongRopeV5) {auto model = make_longrope_v5_model({1.0f, 2.0f}, {4.0f, 5.0f}, {1.0f, 2.0f}, {1.0f, 2.0f});ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16, "longrope_input");- EXPECT_THROW(pass.run_on_model(model),- ov::AssertFailure);+ EXPECT_THROW(pass.run_on_model(model), ov::AssertFailure);+}++// Verifies that the merged RopePatternLLama2 correctly detects and removes the+// LLama2-style sin/cos subgraph (with Concat_2 present, duplicate_freqs=true).+TEST(PreComputeTest, RopeCacheTransformsLLama2Pattern) {+ auto model = make_rope_model(/*with_concat2=*/true);++ ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16, /*longrope_input_name=*/{});+ ASSERT_NO_THROW(pass.run_on_model(model));++ const auto& ops = model->get_ops();+ const auto sin_count = std::count_if(ops.begin(), ops.end(), [](const auto& op) {+ return ov::is_type<ov::op::v0::Sin>(op);+ });+ const auto cos_count = std::count_if(ops.begin(), ops.end(), [](const auto& op) {+ return ov::is_type<ov::op::v0::Cos>(op);+ });++ EXPECT_EQ(sin_count, 0) << "Sin should be replaced by Gather from the duplicated LUT";+ EXPECT_EQ(cos_count, 0) << "Cos should be replaced by Gather from the duplicated LUT";+}++// Verifies that the merged RopePatternLLama2 correctly detects and removes the+// GPT-style sin/cos subgraph (Concat_2 absent, duplicate_freqs=false).+TEST(PreComputeTest, RopeCacheTransformsGPTPattern) {+ auto model = make_rope_model(/*with_concat2=*/false);++ ov::npuw::patterns::pre_compute::RopeCache pass(/*max_prompt_len=*/16, /*longrope_input_name=*/{});+ ASSERT_NO_THROW(pass.run_on_model(model));++ const auto& ops = model->get_ops();+ const auto sin_count = std::count_if(ops.begin(), ops.end(), [](const auto& op) {+ return ov::is_type<ov::op::v0::Sin>(op);+ });+ const auto cos_count = std::count_if(ops.begin(), ops.end(), [](const auto& op) {+ return ov::is_type<ov::op::v0::Cos>(op);+ });++ EXPECT_EQ(sin_count, 0) << "Sin should be replaced by Gather from the non-duplicated LUT";+ EXPECT_EQ(cos_count, 0) << "Cos should be replaced by Gather from the non-duplicated LUT";}} // namespace