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] Support Cross-Attention for optimization v tensors (#37649)
Ding Zhang5a5711183383
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 d1d25bcb7fa..cc3d4589021 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@@ -183,19 +183,6 @@ bool is_cw_compressed(const std::shared_ptr<ov::Model>& model) {return false;}-bool is_int8_compressed(const std::shared_ptr<ov::Model>& model) {- std::vector<std::string> rt_info_path = {"nncf", "weight_compression", "mode"};- if (!model->has_rt_info(rt_info_path)) {- // NB: Model isn't compressed by NNCF - skip- return false;- }- auto mode = model->get_rt_info<std::string>(rt_info_path);- if (mode.find("int8") != std::string::npos) {- return true;- }- return false;-}-struct NPUDesc {std::string arch;int64_t max_tiles = 0;@@ -813,7 +800,6 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mm_cfg.update({{"NPUW_LLM_SHARED_HEAD", "NO"}});m_cfg.update({{"NPUW_LLM_PREFILL_CHUNK_SIZE", "0"}});m_cfg.update({{"NPUW_LLM_CACHE_ROPE", "NO"}});- m_cfg.update({{"NPUW_LLM_OPTIMIZE_V_TENSORS", "NO"}});m_eos_token_id = m_cfg.get<::intel_npu::NPUW_WHISPER_EOS_TOKEN>();}@@ -1148,7 +1134,7 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m// Apply optimization to all variants and track resultssize_t optimized_count = 0;for (auto& model_variant : generate_model_variants) {- if (ov::npuw::util::OptimizeValueTensors(false).run_on_model(model_variant)) {+ if (ov::npuw::util::OptimizeValueTensors(false, m_is_whisper).run_on_model(model_variant)) {++optimized_count;}}@@ -1170,7 +1156,7 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m" variants were optimized, which is not allowed.");}}- if (!prefill_attn_dyn && ov::npuw::util::OptimizeValueTensors(true).run_on_model(prefill_model)) {+ if (!prefill_attn_dyn && ov::npuw::util::OptimizeValueTensors(true, m_is_whisper).run_on_model(prefill_model)) {LOG_DEBUG("V-tensors tranposed in prefill model");m_kvcache_desc.v_tensors_transposed_pre = true;}@@ -1303,11 +1289,9 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mif (m_is_whisper) {update_config_for_whisper(prefill_config);- if (is_int8_compressed(model)) {- disable_ws_for_whisper(prefill_config);- disable_ws_for_whisper(generate_config);- LOG_INFO(" WS is disabled for Whisper int8 model!");- }+ disable_ws_for_whisper(prefill_config);+ disable_ws_for_whisper(generate_config);+ LOG_INFO("NPUW_FOLD and NPUW_FUNCALL_FOR_ALL are disabled for Whisper model.");}if (m_is_embedding) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cppindex 58efe06a54c..9f5fc91cc37 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cpp@@ -75,6 +75,78 @@ protected:}};+class TransposeDirectValueTensorsPrefill : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::TransposeDirectValueTensorsPrefill");+ explicit TransposeDirectValueTensorsPrefill(TransposeValueTensors::Context::Ref ctx) {+ auto transpose = opp::wrap_type<ov::op::v1::Transpose>({opp::any_input(), opp::any_input()});+ auto softmax = opp::wrap_type<ov::op::v8::Softmax>({opp::any_input()});+ auto matmul = opp::wrap_type<ov::op::v0::MatMul>({softmax, transpose});++ auto callback = [=](ov::pass::pattern::Matcher& m) {+ const auto& node_to_output = m.get_pattern_value_map();+ const auto matched_transpose =+ ov::as_type_ptr<ov::op::v1::Transpose>(node_to_output.at(transpose).get_node_shared_ptr());+ const auto matched_matmul =+ ov::as_type_ptr<ov::op::v0::MatMul>(node_to_output.at(matmul).get_node_shared_ptr());++ if (matched_transpose == nullptr || matched_matmul == nullptr) {+ return false;+ }++ const auto shape = matched_transpose->get_output_partial_shape(0);+ if (shape.rank().is_dynamic() || shape.rank().get_length() != 4) {+ return false;+ }++ const auto order = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{4}, {0, 2, 3, 1});+ matched_transpose->set_argument(1, order);+ matched_matmul->set_transpose_b(true);+ ctx.get().bTransposed = true;+ LOG_DEBUG("vtensors transposed: Whisper cross-attention prefill pattern");+ return true;+ };+ register_matcher(std::make_shared<opp::Matcher>(matmul, "TransposeDirectValueTensorsPrefill"),+ std::move(callback));+ }+};++class TransposeDirectValueTensorsGenerate : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::TransposeDirectValueTensorsGenerate");+ explicit TransposeDirectValueTensorsGenerate(TransposeValueTensors::Context::Ref ctx) {+ auto param = opp::wrap_type<ov::op::v0::Parameter>();+ auto convert = opp::optional<ov::op::v0::Convert>({param->output(0)});+ auto softmax = opp::wrap_type<ov::op::v8::Softmax>({opp::any_input()});+ auto matmul = opp::wrap_type<ov::op::v0::MatMul>({softmax, convert});++ auto callback = [=](ov::pass::pattern::Matcher& m) {+ const auto& node_to_output = m.get_pattern_value_map();+ const auto matched_param =+ ov::as_type_ptr<ov::op::v0::Parameter>(node_to_output.at(param).get_node_shared_ptr());+ const auto matched_matmul =+ ov::as_type_ptr<ov::op::v0::MatMul>(node_to_output.at(matmul).get_node_shared_ptr());++ if (matched_param == nullptr || matched_matmul == nullptr) {+ return false;+ }++ auto shape = matched_param->get_partial_shape();+ if (shape.rank().is_dynamic() || shape.rank().get_length() != 4) {+ return false;+ }++ std::swap(shape[2], shape[3]);+ matched_param->set_partial_shape(shape);+ matched_matmul->set_transpose_b(true);+ ctx.get().bTransposed = true;+ return true;+ };+ register_matcher(std::make_shared<opp::Matcher>(matmul, "TransposeDirectValueTensorsGenerate"),+ std::move(callback));+ }+};+// MHA (Multi-Head Attention) pattern for value tensor concatenationclass TransposeValueTensors_MHA : public TransposeValueTensors {public:@@ -370,6 +442,13 @@ bool ov::npuw::util::OptimizeValueTensors::run_on_model(const std::shared_ptr<ovTransposeValueTensors::Context ctx;rewr.add_matcher<TransposeValueTensors_MHA>(std::ref(ctx));rewr.add_matcher<TransposeValueTensors_GQA>(std::ref(ctx));+ if (m_is_whisper) {+ if (m_is_prefill) {+ rewr.add_matcher<TransposeDirectValueTensorsPrefill>(std::ref(ctx));+ } else {+ rewr.add_matcher<TransposeDirectValueTensorsGenerate>(std::ref(ctx));+ }+ }rewr.run_on_model(model);diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.hppindex e893d398d24..4369bb6d521 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.hpp@@ -13,10 +13,13 @@ namespace util {// SDPA-unroll and transpose transformationsclass OptimizeValueTensors : public ov::pass::ModelPass {bool m_is_prefill;+ bool m_is_whisper;public:OPENVINO_MODEL_PASS_RTTI("ov::npuw::OptimizeValueTensors");- explicit OptimizeValueTensors(bool is_prefill) : m_is_prefill(is_prefill) {}+ explicit OptimizeValueTensors(bool is_prefill, bool is_whisper = false)+ : m_is_prefill(is_prefill),+ m_is_whisper(is_whisper) {}bool run_on_model(const std::shared_ptr<ov::Model>& model) override;};diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cppindex c91ad8f3f99..23ea9b35268 100644--- a/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_compiled_model_factory_options_test.cpp@@ -17,6 +17,7 @@#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"#include "openvino/op/gather.hpp"+#include "openvino/op/matmul.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/parameter.hpp"#include "openvino/op/subtract.hpp"@@ -30,6 +31,17 @@ using ov::test::npuw::CompileCall;using ov::test::npuw::NullPlugin;using ov::test::npuw::RecordingFactory;+bool has_transposed_value_matmul(const std::shared_ptr<ov::Model>& model, std::string_view attention_kind) {+ for (const auto& op : model->get_ops()) {+ const auto matmul = ov::as_type_ptr<ov::op::v0::MatMul>(op);+ if (matmul != nullptr && matmul->get_transpose_b() &&+ matmul->get_friendly_name().find(attention_kind) != std::string::npos) {+ return true;+ }+ }+ return false;+}+class ArchAwarePlugin final : public NullPlugin {public:ArchAwarePlugin(std::string arch, int64_t max_tiles) : m_arch(std::move(arch)), m_max_tiles(max_tiles) {}@@ -902,6 +914,60 @@ TEST_F(LLMCompiledModelFactoryOptionsTest, WhisperOptionCompilesSyntheticDecoderEXPECT_EQ(recorder.count_contains("_kv"), 1u);}+TEST_F(LLMCompiledModelFactoryOptionsTest, WhisperOptionOptimizesSelfAndCrossAttentionValueTensors) {+ RecordingFactory recorder;+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;++ ASSERT_NO_THROW(compiled = create_compiled_model(build_whisper_decoder_model(),+ {{"NPUW_WHISPER", "YES"}, {"NPUW_WHISPER_EOS_TOKEN", "42"}},+ recorder));+ ASSERT_NE(compiled, nullptr);++ const auto* prefill = recorder.find_suffix("_prefill");+ const auto& generate = require_call_containing(recorder, "_kv");+ ASSERT_NE(prefill, nullptr);++ EXPECT_TRUE(has_transposed_value_matmul(prefill->model, "self_attn"));+ EXPECT_TRUE(has_transposed_value_matmul(prefill->model, "encoder_attn"));+ EXPECT_TRUE(has_transposed_value_matmul(generate.model, "self_attn"));+ EXPECT_TRUE(has_transposed_value_matmul(generate.model, "encoder_attn"));++ const auto whisper_config = ov::test::npuw::make_test_model_config<ov::test::npuw::WhisperConfig>();+ const auto& decoder_value = generate.model->input("past_key_values.0.decoder.value");+ const auto& decoder_value_shape = decoder_value.get_shape();+ ASSERT_EQ(decoder_value_shape.size(), 4u);+ EXPECT_EQ(decoder_value_shape[2], whisper_config.head_dim);++ const auto& encoder_value = generate.model->input("past_key_values.0.encoder.value");+ const auto& encoder_value_shape = encoder_value.get_shape();+ ASSERT_EQ(encoder_value_shape.size(), 4u);+ EXPECT_EQ(encoder_value_shape[2], whisper_config.head_dim);+ EXPECT_EQ(encoder_value_shape[3], whisper_config.get_encoder_seq_len());+}++TEST_F(LLMCompiledModelFactoryOptionsTest, WhisperDisablesFoldAndFuncallStageOptions) {+ RecordingFactory recorder;+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;++ ASSERT_NO_THROW(compiled = create_compiled_model(build_whisper_decoder_model(),+ {{"NPUW_WHISPER", "YES"},+ {"NPUW_WHISPER_EOS_TOKEN", "42"},+ {"NPUW_FOLD", "YES"},+ {"NPUW_FUNCALL_FOR_ALL", "YES"},+ {"NPUW_WEIGHTS_BANK", "whisper-shared"}},+ recorder));+ ASSERT_NE(compiled, nullptr);++ const auto& prefill = require_call(recorder, "_prefill");+ const auto& generate = require_call_containing(recorder, "_kv");+ expect_missing_prop(prefill.props, "NPUW_FOLD");+ expect_missing_prop(prefill.props, "NPUW_FUNCALL_FOR_ALL");+ expect_prop(prefill.props, "NPUW_WEIGHTS_BANK", "whisper-shared");+ expect_missing_prop(generate.props, "NPUW_FOLD");+ expect_missing_prop(generate.props, "NPUW_FUNCALL_FOR_ALL");+ expect_prop(generate.props, "NPUW_WEIGHTS_BANK", "whisper-shared");+}+TEST_F(LLMCompiledModelFactoryOptionsTest, WhisperPreparationAddsKvCacheInputsAndPresentOutputs) {auto model = build_whisper_decoder_model();ov::pass::StatefulToStateless().run_on_model(model);diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/optimize_value_tensors_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/optimize_value_tensors_test.cppindex 405d7b87484..4a08ca2e6e5 100644--- a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/optimize_value_tensors_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/optimize_value_tensors_test.cpp@@ -2,12 +2,17 @@// SPDX-License-Identifier: Apache-2.0//+#include "npuw_transformations/optimize_value_tensors.hpp"+#include <gtest/gtest.h>#include "llm_pass_test_fixture.hpp"+#include "openvino/op/constant.hpp"#include "openvino/op/matmul.hpp"+#include "openvino/op/parameter.hpp"#include "openvino/op/scaled_dot_product_attention.hpp"#include "openvino/op/softmax.hpp"+#include "openvino/op/transpose.hpp"namespace {@@ -34,14 +39,14 @@ class OptimizeValueTensorsNoSDPATest : public ov::test::npuw::LLMPassTestFixturepublic ::testing::WithParamInterface<std::string> {};INSTANTIATE_TEST_SUITE_P(SubModels,- OptimizeValueTensorsNoSDPATest,- ::testing::Values(std::string{"_prefill"}, std::string{"_kv"}),- [](const ::testing::TestParamInfo<std::string>& info) {- auto name = info.param;- if (!name.empty() && name[0] == '_')- name = name.substr(1);- return name;- });+ OptimizeValueTensorsNoSDPATest,+ ::testing::Values(std::string{"_prefill"}, std::string{"_kv"}),+ [](const ::testing::TestParamInfo<std::string>& info) {+ auto name = info.param;+ if (!name.empty() && name[0] == '_')+ name = name.substr(1);+ return name;+ });TEST_P(OptimizeValueTensorsNoSDPATest, NoSDPAOpsAfterOptimization) {const auto& fragment = GetParam();@@ -132,4 +137,30 @@ TEST_F(OptimizeValueTensorsPassTest, AtLeastOneMatMulHasTransposeBSet_GQA) {EXPECT_TRUE(any_matmul_has_transpose_b(generate.model));}+TEST_F(OptimizeValueTensorsPassTest, DirectValuePatternsDoNotDependOnNodeNames) {+ auto generate_value = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 2, 3, 4});+ auto generate_scores = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 2, 5, 3});+ auto generate_softmax = std::make_shared<ov::op::v8::Softmax>(generate_scores);+ auto generate_matmul = std::make_shared<ov::op::v0::MatMul>(generate_softmax, generate_value);+ auto generate_model = std::make_shared<ov::Model>(ov::OutputVector{generate_matmul},+ ov::ParameterVector{generate_value, generate_scores});++ EXPECT_TRUE(ov::npuw::util::OptimizeValueTensors(false, true).run_on_model(generate_model));+ EXPECT_TRUE(generate_matmul->get_transpose_b());+ EXPECT_EQ(generate_value->get_partial_shape(), ov::PartialShape({1, 2, 4, 3}));++ auto prefill_value = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 3, 2, 4});+ auto prefill_order = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3});+ auto prefill_transpose = std::make_shared<ov::op::v1::Transpose>(prefill_value, prefill_order);+ auto prefill_scores = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 2, 5, 3});+ auto prefill_softmax = std::make_shared<ov::op::v8::Softmax>(prefill_scores);+ auto prefill_matmul = std::make_shared<ov::op::v0::MatMul>(prefill_softmax, prefill_transpose);+ auto prefill_model = std::make_shared<ov::Model>(ov::OutputVector{prefill_matmul},+ ov::ParameterVector{prefill_value, prefill_scores});++ EXPECT_TRUE(ov::npuw::util::OptimizeValueTensors(true, true).run_on_model(prefill_model));+ EXPECT_TRUE(prefill_matmul->get_transpose_b());+ EXPECT_EQ(prefill_transpose->get_output_partial_shape(0), ov::PartialShape({1, 2, 4, 3}));+}+} // namespace