Skip to content

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

[NPUW] Moving passes from llm_compiled_model to separate files (#34934)

Alexander Kalistratov0919a5bfd4f0
diff --git a/src/plugins/intel_npu/src/plugin/npuw/embedding_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/embedding/embedding_infer_request.cpp
similarity index 99%
rename from src/plugins/intel_npu/src/plugin/npuw/embedding_infer_request.cpp
rename to src/plugins/intel_npu/src/plugin/npuw/embedding/embedding_infer_request.cpp
index e0d90c0095f..0282e5c0c2b 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/embedding_infer_request.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/embedding/embedding_infer_request.cpp
@@ -4,8 +4,8 @@
#include "embedding_infer_request.hpp"
-#include "infer_request_utils.hpp"
-#include "logging.hpp"
+#include "../infer_request_utils.hpp"
+#include "../logging.hpp"
ov::SoPtr<ov::ITensor> ov::npuw::EmbeddingInferRequest::create_prefill_output_tensor() {
const auto& out_port = m_prefill_request->get_outputs()[0];
diff --git a/src/plugins/intel_npu/src/plugin/npuw/embedding_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/embedding/embedding_infer_request.hpp
similarity index 92%
rename from src/plugins/intel_npu/src/plugin/npuw/embedding_infer_request.hpp
rename to src/plugins/intel_npu/src/plugin/npuw/embedding/embedding_infer_request.hpp
index 86129a94a33..c3e45d597d8 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/embedding_infer_request.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/embedding/embedding_infer_request.hpp
@@ -4,9 +4,9 @@
#pragma once
-#include "base_sync_infer_request.hpp"
-#include "llm_compiled_model.hpp"
-#include "llm_infer_base_request.hpp"
+#include "../base_sync_infer_request.hpp"
+#include "../llm_compiled_model.hpp"
+#include "../llm_infer_base_request.hpp"
#include "openvino/core/descriptor/output.hpp"
namespace ov {
diff --git a/src/plugins/intel_npu/src/plugin/npuw/embedding_model_utils.cpp b/src/plugins/intel_npu/src/plugin/npuw/embedding/prepare_embedding_model.cpp
similarity index 99%
rename from src/plugins/intel_npu/src/plugin/npuw/embedding_model_utils.cpp
rename to src/plugins/intel_npu/src/plugin/npuw/embedding/prepare_embedding_model.cpp
index 6d25376ce69..34db293875f 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/embedding_model_utils.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/embedding/prepare_embedding_model.cpp
@@ -2,13 +2,13 @@
// SPDX-License-Identifier: Apache-2.0
//
-#include "embedding_model_utils.hpp"
+#include "prepare_embedding_model.hpp"
#include <cfloat>
#include <optional>
#include <regex>
-#include "logging.hpp"
+#include "../logging.hpp"
#include "openvino/op/ops.hpp"
#include "openvino/openvino.hpp"
#include "openvino/opsets/opset13.hpp"
diff --git a/src/plugins/intel_npu/src/plugin/npuw/embedding_model_utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/embedding/prepare_embedding_model.hpp
similarity index 100%
rename from src/plugins/intel_npu/src/plugin/npuw/embedding_model_utils.hpp
rename to src/plugins/intel_npu/src/plugin/npuw/embedding/prepare_embedding_model.hpp
diff --git a/src/plugins/intel_npu/src/plugin/npuw/embedding/redirect_new_kv_to_output.cpp b/src/plugins/intel_npu/src/plugin/npuw/embedding/redirect_new_kv_to_output.cpp
new file mode 100644
index 00000000000..20f0a51378c
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/embedding/redirect_new_kv_to_output.cpp
@@ -0,0 +1,120 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "redirect_new_kv_to_output.hpp"
+
+#include "../logging.hpp"
+#include "openvino/op/ops.hpp"
+#include "openvino/pass/manager.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+
+namespace opp = ov::pass::pattern;
+
+namespace {
+
+// specific function that match subgraph appeared as result of lpt transformations
+auto match_down_up_convert_subgraph_after_lpt = [](const ov::Output<ov::Node>& input) {
+ auto upconvert = opp::wrap_type<ov::op::v0::Convert>({input}, opp::type_matches(ov::element::f32));
+
+ auto upscale = opp::wrap_type<ov::op::v0::Constant>(opp::rank_equals(0));
+ auto upmul = opp::wrap_type<ov::op::v1::Multiply>({upconvert, upscale});
+
+ auto downscale = opp::wrap_type<ov::op::v0::Constant>(opp::rank_equals(0));
+ auto downmul = opp::wrap_type<ov::op::v1::Multiply>({upmul, downscale});
+
+ auto downconvert =
+ opp::wrap_type<ov::op::v0::Convert>({downmul},
+ opp::type_matches_any({ov::element::f8e4m3, ov::element::f8e5m2}));
+
+ return downconvert;
+};
+
+// diagnostics warnings on OPENVINO_MATCHER_PASS_RTTI() definition: visibility hidden
+#ifdef __GNUC__
+# pragma GCC diagnostic push
+# pragma GCC diagnostic ignored "-Wattributes"
+#endif
+
+class RedirectNewKvToOutputMatcher : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::RedirectNewKvToOutputMatcher");
+
+ RedirectNewKvToOutputMatcher() {
+ // example of fp8 inputs to concat
+ // input0 : float8e4m3[1,32,1151,96]
+ // input1 : float8e4m3[1,32,1,96]
+
+ // parameter, or down_up subgraph case always works for current models-set
+ // with both with fp8-optimisation flag enabled and without it
+ // TODO: this matcher logic better to cover with unit-tests
+ auto input0 = opp::wrap_type<ov::op::v0::Parameter>();
+ auto input0_or =
+ std::make_shared<opp::op::Or>(ov::OutputVector{input0, match_down_up_convert_subgraph_after_lpt(input0)});
+
+ auto input1 = opp::any_input();
+
+ auto kv_concat = opp::wrap_type<ov::op::v0::Concat>({input0_or, input1});
+ auto result1 = opp::wrap_type<ov::op::v0::Result>(kv_concat);
+ auto result2 = opp::wrap_type<ov::op::v0::Result>(match_down_up_convert_subgraph_after_lpt(kv_concat));
+
+ auto result_or = std::make_shared<opp::op::Or>(ov::OutputVector{result1, result2});
+
+ ov::matcher_pass_callback callback = [=](opp::Matcher& m) {
+ auto& pattern_to_output = m.get_pattern_value_map();
+ auto matched_concat = pattern_to_output.at(kv_concat).get_node_shared_ptr();
+
+ auto c0 = matched_concat->input(0).get_source_output();
+ auto c1 = matched_concat->input(1).get_source_output();
+
+ LOG_DEBUG(m.get_name() << ": input0.shape=" << c0.get_shape());
+ LOG_DEBUG(m.get_name() << ": input1.shape=" << c1.get_shape());
+ LOG_DEBUG(m.get_name() << ": concat=" << matched_concat->get_friendly_name());
+ LOG_DEBUG(m.get_name() << ": new_kv=" << c1.get_node_shared_ptr()->get_friendly_name());
+
+ std::shared_ptr<ov::Node> matched_result;
+ if (pattern_to_output.count(result1)) {
+ matched_result = pattern_to_output.at(result1).get_node_shared_ptr();
+ } else if (pattern_to_output.count(result2)) {
+ matched_result = pattern_to_output.at(result2).get_node_shared_ptr();
+ // TODO: need to check that upscale * downscale = 1
+ // TODO: need to check input type is f8e5m2 or f8e4m3 if we use this version of concat
+ } else {
+ OPENVINO_THROW("One of result1 or result2 should be matched");
+ }
+
+ LOG_DEBUG(m.get_name() << ": matched_result=" << matched_result->get_friendly_name());
+
+ matched_result->inputs()[0].replace_source_output(c1);
+
+ return true;
+ };
+
+ register_matcher(std::make_shared<opp::Matcher>(result_or, "RedirectNewKvToOutputMatcher"), callback);
+ }
+};
+
+#ifdef __GNUC__
+# pragma GCC diagnostic pop
+#endif
+
+bool redirect_new_kv_to_output(const std::shared_ptr<ov::Model>& model) {
+ ov::pass::Manager manager("redirect_new_kv_to_output");
+ manager.register_pass<RedirectNewKvToOutputMatcher>();
+ bool result = manager.run_passes(model);
+ model->validate_nodes_and_infer_types();
+
+ return result;
+}
+
+} // namespace
+
+namespace ov::npuw {
+
+bool RedirectNewKvToOutput::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ return redirect_new_kv_to_output(model);
+}
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/embedding/redirect_new_kv_to_output.hpp b/src/plugins/intel_npu/src/plugin/npuw/embedding/redirect_new_kv_to_output.hpp
new file mode 100644
index 00000000000..8c121bcd4fb
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/embedding/redirect_new_kv_to_output.hpp
@@ -0,0 +1,18 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+class RedirectNewKvToOutput : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::RedirectNewKvToOutput");
+ RedirectNewKvToOutput() = default;
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/embedding/remove_empty_kv_inputs.cpp b/src/plugins/intel_npu/src/plugin/npuw/embedding/remove_empty_kv_inputs.cpp
new file mode 100644
index 00000000000..93c2c53b3dd
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/embedding/remove_empty_kv_inputs.cpp
@@ -0,0 +1,127 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "remove_empty_kv_inputs.hpp"
+
+#include "openvino/core/graph_util.hpp"
+#include "openvino/op/ops.hpp"
+#include "openvino/op/util/node_util.hpp"
+#include "openvino/opsets/opset13.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "openvino/pass/validate.hpp"
+
+namespace opp = ov::pass::pattern;
+
+namespace {
+
+// specific function that match subgraph appeared as result of lpt transformations
+auto match_down_up_convert_subgraph_after_lpt = [](const ov::Output<ov::Node>& input) {
+ auto upconvert = opp::wrap_type<ov::op::v0::Convert>({input}, opp::type_matches(ov::element::f32));
+
+ auto upscale = opp::wrap_type<ov::op::v0::Constant>(opp::rank_equals(0));
+ auto upmul = opp::wrap_type<ov::op::v1::Multiply>({upconvert, upscale});
+
+ auto downscale = opp::wrap_type<ov::op::v0::Constant>(opp::rank_equals(0));
+ auto downmul = opp::wrap_type<ov::op::v1::Multiply>({upmul, downscale});
+
+ auto downconvert =
+ opp::wrap_type<ov::op::v0::Convert>({downmul},
+ opp::type_matches_any({ov::element::f8e4m3, ov::element::f8e5m2}));
+
+ return downconvert;
+};
+
+// diagnostics warnings on OPENVINO_MATCHER_PASS_RTTI() definition: visibility hidden
+#ifdef __GNUC__
+# pragma GCC diagnostic push
+# pragma GCC diagnostic ignored "-Wattributes"
+#endif
+
+class RemoveEmptyKVTensors : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::RemoveEmptyKVTensors");
+
+ struct Context {
+ std::vector<std::shared_ptr<ov::opset13::Parameter>> old_params;
+ using Ref = std::reference_wrapper<Context>;
+ };
+
+ RemoveEmptyKVTensors(Context::Ref ctx) {
+ auto param = opp::wrap_type<ov::op::v0::Parameter>();
+ auto param_or =
+ std::make_shared<opp::op::Or>(ov::OutputVector{param, match_down_up_convert_subgraph_after_lpt(param)});
+
+ auto concat = opp::wrap_type<ov::op::v0::Concat>({param_or, opp::any_input()});
+
+ auto callback = [=](opp::Matcher& m) {
+ auto& node_to_output = m.get_pattern_value_map();
+ auto matched_param = ov::as_type_ptr<ov::op::v0::Parameter>(node_to_output.at(param).get_node_shared_ptr());
+ auto matched_node_concat = node_to_output.at(concat).get_node_shared_ptr();
+
+ ctx.get().old_params.push_back(matched_param);
+
+ // Use concat's first input source node to find ShapeOf users.
+ // This works universally for both plain parameter and down_up_convert subgraph cases,
+ // because in the subgraph case matched_param->get_users() would return the Convert
+ // node (first node of the subgraph), not the ShapeOf.
+ auto concat_input0_node = matched_node_concat->input(0).get_source_output().get_node_shared_ptr();
+ auto users = concat_input0_node->get_users();
+
+ // In subgraph case the parameter itself may also have a ShapeOf user,
+ // so check both the concat input node and the parameter.
+ if (concat_input0_node != matched_param) {
+ auto param_users = matched_param->get_users();
+ users.insert(users.end(), param_users.begin(), param_users.end());
+ }
+
+ // Find and replace ShapeOf nodes with constants
+ for (auto& user : users) {
+ if (ov::is_type<ov::op::v3::ShapeOf>(user)) {
+ auto cst_node =
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, matched_param->get_shape());
+ ov::replace_node(user, cst_node);
+ }
+ }
+
+ // Redirect second concat input to every node which reads from concat
+ auto curr_kv_tensor = matched_node_concat->input(1).get_source_output();
+ for (auto target_input : matched_node_concat->output(0u).get_target_inputs()) {
+ target_input.replace_source_output(curr_kv_tensor);
+ }
+
+ return true;
+ };
+ register_matcher(std::make_shared<opp::Matcher>(concat, "RemoveEmptyKVTensors"), std::move(callback));
+ }
+};
+
+#ifdef __GNUC__
+# pragma GCC diagnostic pop
+#endif
+
+bool remove_empty_kv_inputs(std::shared_ptr<ov::Model> model) {
+ ov::pass::GraphRewrite rewr;
+ RemoveEmptyKVTensors::Context ctx;
+ rewr.add_matcher<RemoveEmptyKVTensors>(std::ref(ctx));
+ rewr.run_on_model(model);
+ for (auto old_param : ctx.old_params) {
+ model->remove_parameter(old_param);
+ }
+ ov::pass::Validate().run_on_model(model);
+ // NB: if old_params is not empty - pass has been applied
+ return !ctx.old_params.empty();
+}
+
+} // namespace
+
+namespace ov::npuw {
+
+bool RemoveEmptyKVInputs::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ return remove_empty_kv_inputs(model);
+}
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/embedding/remove_empty_kv_inputs.hpp b/src/plugins/intel_npu/src/plugin/npuw/embedding/remove_empty_kv_inputs.hpp
new file mode 100644
index 00000000000..37ff6a91025
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/embedding/remove_empty_kv_inputs.hpp
@@ -0,0 +1,18 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+class RemoveEmptyKVInputs : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::RemoveEmptyKVInputs");
+ RemoveEmptyKVInputs() = default;
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace ov::npuw
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.cpp
index 4130494938b..4dbbe065fec 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
@@ -3,24 +3,28 @@
//
#include "llm_compiled_model.hpp"
-#include "embedding_infer_request.hpp"
-#include "embedding_model_utils.hpp"
+#include "embedding/embedding_infer_request.hpp"
+#include "embedding/prepare_embedding_model.hpp"
+#include "embedding/redirect_new_kv_to_output.hpp"
+#include "embedding/remove_empty_kv_inputs.hpp"
+#include "llm_compiled_model_utils.hpp"
#include "llm_infer_request.hpp"
#include "logging.hpp"
-#include "low_precision/concat.hpp"
-#include "low_precision/kv_cache_concat.hpp"
-#include "low_precision/low_precision.hpp"
-#include "low_precision/move_fake_convert_up_through_kv_cache_concat.hpp"
-#include "moe_transformations/device_routed_moe_transform.hpp"
-#include "moe_transformations/gather_to_2d_gather.hpp"
+#include "moe_transformations/apply_moe_device_routed_transforms.hpp"
+#include "npuw_transformations/convert_kvcache_to_precision.hpp"
+#include "npuw_transformations/decompose_gqa.hpp"
+#include "npuw_transformations/lora_stateful_to_stateless.hpp"
+#include "npuw_transformations/optimize_value_tensors.hpp"
+#include "npuw_transformations/patch_phi3_sliding_mask.hpp"
+#include "npuw_transformations/reshape_sliced_head_to_static.hpp"
+#include "npuw_transformations/reshape_to_static.hpp"
+#include "npuw_transformations/slice_out_embeds.hpp"
#include "openvino/op/convert.hpp"
#include "openvino/op/greater.hpp"
-#include "openvino/op/group_query_attention.hpp"
#include "openvino/op/ops.hpp"
#include "openvino/op/range.hpp"
#include "openvino/op/util/node_util.hpp"
#include "openvino/openvino.hpp"
-#include "openvino/opsets/opset13.hpp"
#include "openvino/pass/graph_rewrite.hpp"
#include "openvino/pass/manager.hpp"
#include "openvino/pass/matcher_pass.hpp"
@@ -31,807 +35,17 @@
#include "openvino/pass/validate.hpp"
#include "openvino/runtime/iasync_infer_request.hpp"
#include "openvino/runtime/properties.hpp"
-#include "ov_ops/type_relaxed.hpp"
#include "partitioning/patterns/moe.hpp"
#include "partitioning/patterns/pre_compute.hpp"
#include "partitioning/patterns/sdpa.hpp"
#include "serialization.hpp"
#include "transformations/convert_precision.hpp"
-#include "transformations/op_conversions/fake_convert_decomposition.hpp"
#include "util.hpp"
-#include "whisper_infer_request.hpp"
+#include "whisper/prepare_whisper_model.hpp"
+#include "whisper/whisper_infer_request.hpp"
namespace opp = ov::pass::pattern;
-// specific function that match subgraph appeared as result of lpt transformations
-auto match_down_up_convert_subgraph_after_lpt = [](const ov::Output<ov::Node>& input) {
- auto upconvert = opp::wrap_type<ov::op::v0::Convert>({input}, opp::type_matches(ov::element::f32));
-
- auto upscale = opp::wrap_type<ov::op::v0::Constant>(opp::rank_equals(0));
- auto upmul = opp::wrap_type<ov::op::v1::Multiply>({upconvert, upscale});
-
- auto downscale = opp::wrap_type<ov::op::v0::Constant>(opp::rank_equals(0));
- auto downmul = opp::wrap_type<ov::op::v1::Multiply>({upmul, downscale});
-
- auto downconvert =
- opp::wrap_type<ov::op::v0::Convert>({downmul},
- opp::type_matches_any({ov::element::f8e4m3, ov::element::f8e5m2}));
-
- return downconvert;
-};
-
-class RemoveEmptyKVTensors : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::RemoveEmptyKVTensors");
-
- struct Context {
- std::vector<std::shared_ptr<ov::opset13::Parameter>> old_params;
- using Ref = std::reference_wrapper<Context>;
- };
-
- RemoveEmptyKVTensors(Context::Ref ctx) {
- auto param = opp::wrap_type<ov::op::v0::Parameter>();
- auto param_or =
- std::make_shared<opp::op::Or>(ov::OutputVector{param, match_down_up_convert_subgraph_after_lpt(param)});
-
- auto concat = opp::wrap_type<ov::op::v0::Concat>({param_or, opp::any_input()});
-
- auto callback = [=](opp::Matcher& m) {
- auto& node_to_output = m.get_pattern_value_map();
- auto matched_param = ov::as_type_ptr<ov::op::v0::Parameter>(node_to_output.at(param).get_node_shared_ptr());
- auto matched_node_concat = node_to_output.at(concat).get_node_shared_ptr();
-
- ctx.get().old_params.push_back(matched_param);
-
- // Use concat's first input source node to find ShapeOf users.
- // This works universally for both plain parameter and down_up_convert subgraph cases,
- // because in the subgraph case matched_param->get_users() would return the Convert
- // node (first node of the subgraph), not the ShapeOf.
- auto concat_input0_node = matched_node_concat->input(0).get_source_output().get_node_shared_ptr();
- auto users = concat_input0_node->get_users();
-
- // In subgraph case the parameter itself may also have a ShapeOf user,
- // so check both the concat input node and the parameter.
- if (concat_input0_node != matched_param) {
- auto param_users = matched_param->get_users();
- users.insert(users.end(), param_users.begin(), param_users.end());
- }
-
- // Find and replace ShapeOf nodes with constants
- for (auto& user : users) {
- if (ov::is_type<ov::op::v3::ShapeOf>(user)) {
- auto cst_node =
- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{4}, matched_param->get_shape());
- ov::replace_node(user, cst_node);
- }
- }
-
- // Redirect second concat input to every node which reads from concat
- auto curr_kv_tensor = matched_node_concat->input(1).get_source_output();
- for (auto target_input : matched_node_concat->output(0u).get_target_inputs()) {
- target_input.replace_source_output(curr_kv_tensor);
- }
-
- return true;
- };
- register_matcher(std::make_shared<opp::Matcher>(concat, "RemoveEmptyKVTensors"), std::move(callback));
- }
-};
-
-class GroupQueryAttentionDecomposition : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::GroupQueryAttentionDecomposition");
- GroupQueryAttentionDecomposition(bool is_prefill_model) {
- auto pattern_node = opp::wrap_type<ov::op::internal::GroupQueryAttention>();
-
- ov::matcher_pass_callback callback = [=](opp::Matcher& m) {
- auto& pattern_to_output = m.get_pattern_value_map();
- auto node = ov::as_type_ptr<ov::op::internal::GroupQueryAttention>(
- pattern_to_output.at(pattern_node).get_node_shared_ptr());
-
- if (node == nullptr || transformation_callback(node)) {
- return false;
- }
-
- auto new_output_node = decompose(node, is_prefill_model);
- ov::replace_node(node, new_output_node);
- return true;
- };
-
- auto m = std::make_shared<opp::Matcher>(pattern_node, "GroupQueryAttentionDecomposition");
- register_matcher(m, std::move(callback));
- }
-
- ov::OutputVector decompose(std::shared_ptr<ov::op::internal::GroupQueryAttention> node, bool is_prefill_model) {
- using namespace ov::op;
- using namespace ov;
-
- const auto num_heads = node->get_num_heads();
- const auto kv_num_heads = node->get_kv_num_heads();
- const auto scale = node->get_scale();
- const auto do_rotary = node->get_do_rotary();
- const auto rotary_interleaved = node->get_rotary_interleaved();
- // TODO: add softcap support
-
- auto Q = node->input_value(0);
- auto K = node->input_value(1);
- auto V = node->input_value(2);
- auto past_key = node->input_value(3);
- auto past_value = node->input_value(4);
- auto seqlens_k = node->input_value(5);
- auto total_sequence_length = node->input_value(6);
- auto cos_cache = node->input_value(7);
- auto sin_cache = node->input_value(8);
-
- // The length of all tokens (past + current) is `seqlens_k` + 1.
- // current = Q.shape[2], past = `seqlens_k` + 1 - current
-
- const auto T = Q.get_element_type();
- const auto q_shape = register_new_node<v3::ShapeOf>(Q);
- const auto current_seqlen = get_dimensions(q_shape, {2});
- const auto head_size_node = get_dimensions(q_shape, {3});
-
- const auto zero = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}));
- const auto zero_without_shape = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {0}));
- const auto one = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}));
- const auto one_without_shape = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {1}));
- const auto two = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));
- const auto seqlens_elemi64 = register_new_node<v0::Convert>(seqlens_k, ov::element::i64);
- const auto real_seqlens = register_new_node<v1::Add>(seqlens_elemi64, one);
-
- // Only consider batch is 1
- const auto seqlens_1d = register_new_node<v1::Reshape>(real_seqlens, one, false);
- const auto past_seqlen = register_new_node<v1::Subtract>(seqlens_1d, current_seqlen);
- const auto curr_seqlen_scalar = register_new_node<v0::Squeeze>(current_seqlen);
-
- if (do_rotary) {
- ov::Output<ov::Node> position_ids = register_new_node<v4::Range>(zero_without_shape,
- curr_seqlen_scalar,
- one_without_shape,
- ov::element::i64);
- position_ids = register_new_node<v1::Add>(position_ids, past_seqlen);
-
- const auto cos = register_new_node<v8::Gather>(cos_cache, position_ids, zero);
- const auto sin = register_new_node<v8::Gather>(sin_cache, position_ids, zero);
- Q = rotaryEmbedding(Q, cos, sin, rotary_interleaved);
- K = rotaryEmbedding(K, cos, sin, rotary_interleaved);
- }
-
- auto construct_kv_cache = [&](const ov::Output<ov::Node>& past, const ov::Output<ov::Node>& current) {
- return register_new_node<v0::Concat>(ov::OutputVector{past, current}, 2);
- };
- K = construct_kv_cache(past_key, K);
- V = construct_kv_cache(past_value, V);
-
- ov::Output<ov::Node> present_k = K;
- ov::Output<ov::Node> present_v = V;
-
- const auto concat_kv_len = get_dimensions(K.get_node_shared_ptr(), {2});
- const auto concat_kv_len_scalar = register_new_node<v0::Squeeze>(concat_kv_len);
-
- // Broadcast KV if grouped query attention
- const size_t kv_num_heads_factor = num_heads / kv_num_heads;
- if (kv_num_heads_factor > 1) {
- const auto kv_shape = register_new_node<v3::ShapeOf>(K);
- const auto kv_shape_prev_2 = get_dimensions(kv_shape, {0, 1});
- const auto kv_shape_last_2 = get_dimensions(kv_shape, {2, 3});
- auto new_kv_shape = register_new_node<v0::Concat>(ov::NodeVector{kv_shape_prev_2, one, kv_shape_last_2}, 0);
- K = register_new_node<v1::Reshape>(K, new_kv_shape, false);
- V = register_new_node<v1::Reshape>(V, new_kv_shape, false);
- K = register_new_node<v0::Concat>(ov::OutputVector(kv_num_heads_factor, K), 2);
- V = register_new_node<v0::Concat>(ov::OutputVector(kv_num_heads_factor, V), 2);
- const auto q_shape = register_new_node<v3::ShapeOf>(Q);
- const auto q_shape_prev_2 = get_dimensions(q_shape, {0, 1});
- auto extended_kv_shape = register_new_node<v0::Concat>(ov::NodeVector{q_shape_prev_2, kv_shape_last_2}, 0);
- K = register_new_node<v1::Reshape>(K, extended_kv_shape, false);
- V = register_new_node<v1::Reshape>(V, extended_kv_shape, false);
- }
-
- // Make attention mask
- std::shared_ptr<ov::Node> mask;
-
- std::shared_ptr<ov::Node> hori_range =
- register_new_node<v4::Range>(zero_without_shape, concat_kv_len_scalar, one_without_shape, ov::element::i64);
- hori_range = register_new_node<v0::Unsqueeze>(hori_range, zero);
-
- std::shared_ptr<ov::Node> vert_range =
- register_new_node<v4::Range>(zero_without_shape, curr_seqlen_scalar, one_without_shape, ov::element::i64);
- vert_range = register_new_node<v0::Unsqueeze>(vert_range, one);
- const auto past_k_node_len = get_dimensions(past_key.get_node_shared_ptr(), {2});
- vert_range = register_new_node<v1::Add>(vert_range, past_k_node_len);
-
- const auto triu = register_new_node<v1::Greater>(hori_range, vert_range);
- const auto typed_zero = register_new_node(v0::Constant::create(T, ov::Shape{}, {0}));
- // cf. make_attention_mask@src\plugins\intel_gpu\tests\common\subgraphs_builders.hpp
- std::shared_ptr<ov::Node> minus_inf = nullptr;
- if (T == ov::element::f32)
- minus_inf =
- register_new_node(v0::Constant::create(T, ov::Shape{}, {-std::numeric_limits<float>::infinity()}));
- else if (T == ov::element::f16)
- minus_inf =
- register_new_node(v0::Constant::create(T, ov::Shape{}, {std::numeric_limits<ov::float16>::lowest()}));
- mask = register_new_node<v1::Select>(triu, minus_inf, typed_zero);
-
- if (is_prefill_model) {
- // prefill model
- const auto padding_len = register_new_node<v1::Subtract>(concat_kv_len, seqlens_1d);
- const auto padding_mask_vert_shape = register_new_node<v0::Concat>(ov::NodeVector{current_seqlen, one}, 0);
- const auto padding_mask_vert = register_new_node<v3::Broadcast>(padding_len, padding_mask_vert_shape);
- const auto padding_mask = register_new_node<v1::GreaterEqual>(hori_range, padding_mask_vert);
- mask = register_new_node<v1::Select>(padding_mask, mask, minus_inf);
- } else {
- // kv cache model
- const auto left_mask = register_new_node<v1::Less>(hori_range, seqlens_elemi64); // first N
- const auto righ_mask = register_new_node<v1::GreaterEqual>(hori_range, vert_range); // last 1
- const auto atte_mask = register_new_node<v1::LogicalOr>(left_mask, righ_mask); // [1,1,1,..., 0,0,0,1]
- mask = register_new_node<v1::Select>(atte_mask, mask, minus_inf);
- }
-
- std::shared_ptr<ov::Node> qga_output;
- if (scale != 0.0f) {
- auto scale_node = register_new_node(v0::Constant::create(T, Shape{}, {scale}));
- qga_output = register_new_node<v13::ScaledDotProductAttention>(Q, K, V, mask, scale_node, false);
- } else {
- qga_output = register_new_node<v13::ScaledDotProductAttention>(Q, K, V, mask, false);
- }
-
- // transpose the result from (batch_size, num_heads, sequence_length, head_size)
- // to (batch_size, sequence_length, num_heads * head_size)
- auto perm = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3}));
- auto qga_output_transposed = register_new_node<v1::Transpose>(qga_output, perm);
- auto dim_merge_shape = register_new_node(v0::Constant::create(ov::element::i32, ov::Shape{3}, {0, 0, -1}));
- auto output = register_new_node<v1::Reshape>(qga_output_transposed, dim_merge_shape, true)->output(0);
-
- return {std::move(output), std::move(present_k), std::move(present_v)};
- }
-
- // make split functions is a copy-past from ONNX FE. TODO: move it to one place
- ov::OutputVector make_split(const ov::Output<ov::Node>& value, int64_t num_splits, int64_t axis) {
- using namespace ov::op;
- const auto axis_node = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {axis}));
- const auto split = register_new_node<v1::Split>(value, axis_node, num_splits);
-
- return split->outputs();
- }
-
- std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf>& shape,
- const std::vector<int>& dims) {
- using namespace ov::op;
- const auto zero = v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
- const auto dims_const = v0::Constant::create(ov::element::i32, ov::Shape{dims.size()}, dims);
- return register_new_node<v8::Gather>(shape, dims_const, zero);
- }
-
- std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node>& node, const std::vector<int>& dims) {
- return get_dimensions(register_new_node<ov::op::v3::ShapeOf>(node), dims);
- }
-
- std::shared_ptr<ov::Node> rotaryEmbedding(ov::Output<ov::Node> input,
- ov::Output<ov::Node> cos,
- ov::Output<ov::Node> sin,
- bool interleaved) {
- using namespace ov::op;
- auto zero = v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
- auto one = v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
-
- if (interleaved) {
- auto two = v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
- auto cos_last_dim = get_dimensions(cos.get_node_shared_ptr(), {-1});
- auto input_shape = register_new_node<v3::ShapeOf>(input);
- auto dim_bns = get_dimensions(input_shape, {0, 1, 2});
-
- auto negtive_one = v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1});
- auto split_input_shape = register_new_node<v0::Concat>(ov::NodeVector{dim_bns, cos_last_dim, two}, 0);
- auto reshaped_input = register_new_node<v1::Reshape>(input, split_input_shape, false);
-
- auto in_split = make_split(reshaped_input, 2, -1);
- split_input_shape = register_new_node<v0::Concat>(ov::NodeVector{dim_bns, cos_last_dim}, 0);
- auto in_split_0 = register_new_node<v1::Reshape>(in_split[0], split_input_shape, false);
- auto in_split_1 = register_new_node<v1::Reshape>(in_split[1], split_input_shape, false);
-
- auto res_0 = register_new_node<v1::Subtract>(register_new_node<v1::Multiply>(in_split_0, cos),
- register_new_node<v1::Multiply>(in_split_1, sin));
- auto res_1 = register_new_node<v1::Add>(register_new_node<v1::Multiply>(in_split_0, sin),
- register_new_node<v1::Multiply>(in_split_1, cos));
-
- split_input_shape = register_new_node<v0::Concat>(ov::NodeVector{dim_bns, cos_last_dim, one}, 0);
- auto res_0_5d = register_new_node<v1::Reshape>(res_0, split_input_shape, false);
- auto res_1_5d = register_new_node<v1::Reshape>(res_1, split_input_shape, false);
-
- auto concat_ret = register_new_node<v0::Concat>(ov::NodeVector{res_0_5d, res_1_5d}, -1);
- return register_new_node<v1::Reshape>(concat_ret, input_shape, false);
- } else {
- auto in_split = make_split(input, 2, -1);
- auto res_0 = register_new_node<v1::Subtract>(register_new_node<v1::Multiply>(in_split[0], cos),
- register_new_node<v1::Multiply>(in_split[1], sin));
- auto res_1 = register_new_node<v1::Add>(register_new_node<v1::Multiply>(in_split[0], sin),
- register_new_node<v1::Multiply>(in_split[1], cos));
-
- return register_new_node<v0::Concat>(ov::NodeVector{res_0, res_1}, -1);
- }
- }
-};
-
-class RedirectNewKvToOutputMatcher : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::RedirectNewKvToOutputMatcher");
-
- RedirectNewKvToOutputMatcher() {
- // example of fp8 inputs to concat
- // input0 : float8e4m3[1,32,1151,96]
- // input1 : float8e4m3[1,32,1,96]
-
- // parameter, or down_up subgraph case always works for current models-set
- // with both with fp8-optimisation flag enabled and without it
- // TODO: this matcher logic better to cover with unit-tests
- auto input0 = opp::wrap_type<ov::op::v0::Parameter>();
- auto input0_or =
- std::make_shared<opp::op::Or>(ov::OutputVector{input0, match_down_up_convert_subgraph_after_lpt(input0)});
-
- auto input1 = opp::any_input();
-
- auto kv_concat = opp::wrap_type<ov::op::v0::Concat>({input0_or, input1});
- auto result1 = opp::wrap_type<ov::op::v0::Result>(kv_concat);
- auto result2 = opp::wrap_type<ov::op::v0::Result>(match_down_up_convert_subgraph_after_lpt(kv_concat));
-
- auto result_or = std::make_shared<opp::op::Or>(ov::OutputVector{result1, result2});
-
- ov::matcher_pass_callback callback = [=](opp::Matcher& m) {
- auto& pattern_to_output = m.get_pattern_value_map();
- auto matched_concat = pattern_to_output.at(kv_concat).get_node_shared_ptr();
-
- auto c0 = matched_concat->input(0).get_source_output();
- auto c1 = matched_concat->input(1).get_source_output();
-
- LOG_DEBUG(m.get_name() << ": input0.shape=" << c0.get_shape());
- LOG_DEBUG(m.get_name() << ": input1.shape=" << c1.get_shape());
- LOG_DEBUG(m.get_name() << ": concat=" << matched_concat->get_friendly_name());
- LOG_DEBUG(m.get_name() << ": new_kv=" << c1.get_node_shared_ptr()->get_friendly_name());
-
- std::shared_ptr<ov::Node> matched_result;
- if (pattern_to_output.count(result1)) {
- matched_result = pattern_to_output.at(result1).get_node_shared_ptr();
- } else if (pattern_to_output.count(result2)) {
- matched_result = pattern_to_output.at(result2).get_node_shared_ptr();
- // TODO: need to check that upscale * downscale = 1
- // TODO: need to check input type is f8e5m2 or f8e4m3 if we use this version of concat
- } else {
- OPENVINO_THROW("One of result1 or result2 should be matched");
- }
-
- LOG_DEBUG(m.get_name() << ": matched_result=" << matched_result->get_friendly_name());
-
- matched_result->inputs()[0].replace_source_output(c1);
-
- return true;
- };
-
- register_matcher(std::make_shared<opp::Matcher>(result_or, "RedirectNewKvToOutputMatcher"), callback);
- }
-};
-
-class OldPhi3SlidingMaskMatcher : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::OldPhi3SlidingMaskMatcher");
-
- OldPhi3SlidingMaskMatcher() {
- // Search for the Phi3 old sliding mask pattern to extend it to work with right-padded
- // past tokens and left-padded present tokens.
- //
- // Mask creation is simply done via "less_equal" and "greater" operations between
- // row K range: [0,... mask_len] and column Q range: [current_pos_id,... mask_len].T
- // and sliding window length.
- // Due to broadcasting rules these two operation form two triangular masks.
- //
- // - "less_equal" forms a sliding window mask, more precisely, it has following expression:
- //
- // row range [0,... mask_len] <= column range [current_pos_id - sliding_window_size,
- // ...,
- // mask_len - sliding_window_size]
- //
- // forming, under example conditions, the mask below:
- // past tokens = 3
- // present tokens = 5 (starting with current_pos_id = 3)
- // sliding window len = 4
- // K0 K1 K2 K3 K4 K5 K6 K7
- // [ 0 1 2 3 4 5 6 7 ]
- // Q3[ 3 - 4 ] 0 0 0 0 0 0 0 0
- // Q4[ 4 - 4 ] 1 0 0 0 0 0 0 0
- // Q5[ 5 - 4 ] 1 1 0 0 0 0 0 0
- // Q6[ 6 - 4 ] 1 1 1 0 0 0 0 0
- // Q7[ 7 - 4 ] 1 1 1 1 0 0 0 0
- // where 1 at [i, j] means that j token should be forgotten as it can't fit into the sliding
- // window from the left of i-th token.
- //
- // - "greater" forms a similar to self-attention mask:
- //
- // row range [0,... mask_len] > column range [current_pos_id,
- // ...,
- // mask_len]
- //
- // forming, under example conditions, the mask below:
- // past tokens = 3
- // present tokens = 5 (starting with current_pos_id = 3)
- // K0 K1 K2 K3 K4 K5 K6 K7
- // [ 0 1 2 3 4 5 6 7 ]
- // Q3[ 3 ] 0 0 0 0 1 1 1 1
- // Q4[ 4 ] 0 0 0 0 0 1 1 1
- // Q5[ 5 ] 0 0 0 0 0 0 1 1
- // Q6[ 6 ] 0 0 0 0 0 0 0 1
- // Q7[ 7 ] 0 0 0 0 0 0 0 0
- // where 1 at [i, j] means that j token is a future token for i-th token, that we shouldn't attend to.
- //
- // Together, via "bitwise_or" this two masks forms the inverted sliding attention mask:
- // past tokens = 3
- // present tokens = 5 (starting with current_pos_id = 3)
- // sliding window len = 4
- // K0 K1 K2 K3 K4 K5 K6 K7
- // [ 0 1 2 3 4 5 6 7 ]
- // Q3[ 3 - 4 ] 0 0 0 0 1 1 1 1
- // Q4[ 4 - 4 ] 1 0 0 0 0 1 1 1
- // Q5[ 5 - 4 ] 1 1 0 0 0 0 1 1
- // Q6[ 6 - 4 ] 1 1 1 0 0 0 0 1
- // Q7[ 7 - 4 ] 1 1 1 1 0 0 0 0
- //
- // Issue with sliding attention mask appears when we work with static shapes and different
- // paddings for past and present tokens.
- // More precisely, issue appears with sliding window mask, as Q column range is created
- // from length of past key/values tensor (2175 for 2K case) as start point and the length
- // of attention mask (2176 for 2K) as an end point. This is okay for inverted
- // self-attention mask by means of "greater" operation, as our present tokens exactly
- // left-padded and located on the right in the attention mask.
- // However, for the sliding window mask created by means of "less_equal" operation, given
- // Q range will behave as if position ids of new Q tokens will start from 2175 and not from
- // 3 as in example above and therefore, 2175 - 2047 = 128 first tokens should be forgotten.
- // To fix it a new formula is suggested:
- // 1. (K range <= (Q_pos range - sliding window).T) | (K range > Q range.T)
- // 2. (K range <= (Q range - sliding window).T) & (K range >= len(past_key_values))
- // 3. Resulting mask = 1 | 2,
- // where K range and Q range are created by the same rules as before and Q_pos range is
- // a position_ids array.
- // 4. We also clean mask in places where paddings used instead of real tokens via:
- // Clean mask = 3 | !(attention_mask_input[past_kv_len:]).T
- auto past_kv_len = opp::wrap_type<ov::op::v8::Gather>({opp::any_input(), opp::any_input(), opp::any_input()});
- auto pos_ids_param = opp::wrap_type<ov::op::v0::Parameter>();
- auto pos_ids_shape_of = opp::wrap_type<ov::op::v3::ShapeOf>({pos_ids_param});
- auto pos_ids_len = opp::wrap_type<ov::op::v8::Gather>({pos_ids_shape_of, opp::any_input(), opp::any_input()});
- auto full_ctx_len = opp::wrap_type<ov::op::v1::Add>({past_kv_len, pos_ids_len});
- auto query_range = opp::wrap_type<ov::op::v4::Range>({past_kv_len, full_ctx_len, opp::any_input()});
- auto column_shape = opp::wrap_type<ov::op::v0::Constant>();
- auto query_range_column = opp::wrap_type<ov::op::v1::Reshape>({query_range, column_shape});
-
- auto zero_const = opp::wrap_type<ov::op::v0::Constant>();
- auto atten_mask_param = opp::wrap_type<ov::op::v0::Parameter>();
- auto atten_mask_shape_of = opp::wrap_type<ov::op::v3::ShapeOf>({atten_mask_param});
- auto atten_mask_len =
- opp::wrap_type<ov::op::v8::Gather>({atten_mask_shape_of, opp::any_input(), opp::any_input()});
- auto key_range = opp::wrap_type<ov::op::v4::Range>({zero_const, atten_mask_len, opp::any_input()});
- auto key_range_i64 = opp::wrap_type<ov::op::v0::Convert>({key_range});
- auto key_range_f32 = opp::wrap_type<ov::op::v0::Convert>({key_range_i64});
-
- auto neg_window_size = opp::wrap_type<ov::op::v0::Constant>();
- auto query_left_bound_range = opp::wrap_type<ov::op::v1::Add>({query_range_column, neg_window_size});
- // False in mask means that we shouldn't forget this token
- auto forget_left_tokens_mask = opp::wrap_type<ov::op::v1::LessEqual>({key_range_f32, query_left_bound_range});
- // Basically it is a reference triangle self-attention mask that
- // forbids tokens to attend to future ones, but values are inverted:
- auto look_only_future_mask = opp::wrap_type<ov::op::v1::Greater>({key_range_f32, query_range_column});
-
- auto inv_sliding_attention_mask =
- opp::wrap_type<ov::op::v13::BitwiseOr>({look_only_future_mask, forget_left_tokens_mask});
-
- auto callback = [=](opp::Matcher& m) {
- LOG_INFO("Found (4.51) pattern for Phi-3 Sliding Window Attention, will be replaced with custom for static "
- "shapes.");
- auto& node_to_output = m.get_pattern_value_map();
- auto node_past_kv_len = node_to_output.at(past_kv_len).get_node_shared_ptr();
- auto node_pos_ids_param = node_to_output.at(pos_ids_param).get_node_shared_ptr();
- auto node_atten_mask_param = node_to_output.at(atten_mask_param).get_node_shared_ptr();
- auto node_atten_mask_len = node_to_output.at(atten_mask_len).get_node_shared_ptr();
- auto node_key_range_f32 = node_to_output.at(key_range_f32).get_node_shared_ptr();
- auto node_neg_window_size = node_to_output.at(neg_window_size).get_node_shared_ptr();
- auto node_forget_left_tokens_mask = node_to_output.at(forget_left_tokens_mask).get_node_shared_ptr();
- auto node_bitwise_or = node_to_output.at(inv_sliding_attention_mask).get_node_shared_ptr();
-
- auto matched_past_kv_len = std::static_pointer_cast<ov::op::v8::Gather>(node_past_kv_len);
- auto matched_pos_ids_input = std::static_pointer_cast<ov::op::v0::Parameter>(node_pos_ids_param);
- auto matched_atten_mask_input = std::static_pointer_cast<ov::op::v0::Parameter>(node_atten_mask_param);
- auto matched_atten_mask_len = std::static_pointer_cast<ov::op::v8::Gather>(node_atten_mask_len);
- auto matched_key_range_f32 = std::static_pointer_cast<ov::op::v0::Convert>(node_key_range_f32);
- auto matched_neg_window_size = std::static_pointer_cast<ov::op::v0::Constant>(node_neg_window_size);
- auto matched_forget_left_tokens_mask =
- std::static_pointer_cast<ov::op::v1::LessEqual>(node_forget_left_tokens_mask);
- auto matched_bitwise_or = std::static_pointer_cast<ov::op::v13::BitwiseOr>(node_bitwise_or);
- OPENVINO_ASSERT(matched_neg_window_size->get_output_size() == 1,
- "Sliding window size constant must be of size 1, but got " +
- std::to_string(matched_neg_window_size->get_output_size()));
-
- // 1.(K range <= (Q_pos range - sliding window).T) | (K range > Q range.T)
- auto query_range_as_pos_ids =
- std::make_shared<ov::op::v0::Convert>(matched_pos_ids_input, ov::element::f32);
- std::vector<int64_t> vector_shape{-1, 1};
- auto vector_shape_const =
- std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{2}, vector_shape);
- auto query_range_as_pos_ids_col =
- std::make_shared<ov::op::v1::Reshape>(query_range_as_pos_ids, vector_shape_const, false);
- auto query_range_as_pos_left_bound =
- std::make_shared<ov::op::v1::Add>(query_range_as_pos_ids_col, matched_neg_window_size);
- auto forget_left_mask_for_right_padding =
- std::make_shared<ov::op::v1::LessEqual>(matched_key_range_f32, query_range_as_pos_left_bound);
- matched_bitwise_or->input(1).replace_source_output(forget_left_mask_for_right_padding);
-
- // 2. (K range <= (Q range - sliding window).T) & (K range >= shape(past_key_values, 2))
- auto past_kv_len_f32 = std::make_shared<ov::op::v0::Convert>(matched_past_kv_len, ov::element::f32);
- auto only_present_tokens_mask =
- std::make_shared<ov::op::v1::GreaterEqual>(matched_key_range_f32, past_kv_len_f32);
- auto bitwise_and =
- std::make_shared<ov::op::v13::BitwiseAnd>(matched_forget_left_tokens_mask, only_present_tokens_mask);
-
- // 3. Result = 1 | 2
- // Save target inputs first:
- auto target_inputs = matched_bitwise_or->output(0).get_target_inputs();
- auto new_inv_sliding_mask = std::make_shared<ov::op::v13::BitwiseOr>(matched_bitwise_or, bitwise_and);
-
- // 4. Removing extra padding via : 3 | !(attention_mask_input[past_kv_len:]).T
- std::vector<int64_t> shape_rank_one{1};
- auto shape_rank_one_const =
- std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, shape_rank_one);
- auto past_len_reshaped =
- std::make_shared<ov::op::v1::Reshape>(matched_past_kv_len, shape_rank_one_const, false);
- auto atten_len_reshaped =
- std::make_shared<ov::op::v1::Reshape>(matched_atten_mask_len, shape_rank_one_const, false);
- auto const_one = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, 1);
- auto present_atten_mask = std::make_shared<ov::op::v8::Slice>(matched_atten_mask_input,
- past_len_reshaped,
- atten_len_reshaped,
- const_one,
- const_one);
- auto present_atten_mask_bool =
- std::make_shared<ov::op::v0::Convert>(present_atten_mask, ov::element::boolean);
- auto inv_present_atten_mask = std::make_shared<ov::op::v1::LogicalNot>(present_atten_mask_bool);
- auto inv_present_atten_mask_col =
- std::make_shared<ov::op::v1::Reshape>(inv_present_atten_mask, vector_shape_const, false);
- auto clean_inv_sliding_mask =
- std::make_shared<ov::op::v13::BitwiseOr>(new_inv_sliding_mask, inv_present_atten_mask_col);
- for (auto&& input : target_inputs) {
- input.replace_source_output(clean_inv_sliding_mask);
- }
-
- return true;
- };
- register_matcher(std::make_shared<opp::Matcher>(inv_sliding_attention_mask, "OldPhi3SlidingMaskMatcher"),
- std::move(callback));
- }
-};
-
-class Phi3SlidingMaskMatcher : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::Phi3SlidingMaskMatcher");
-
- Phi3SlidingMaskMatcher(const std::shared_ptr<ov::Node>& attention_mask_node_ptr,
- const std::shared_ptr<ov::Node>& position_ids_node_ptr) {
- // Search for the Phi3 sliding mask pattern to extend it to work with right-padded
- // past tokens and left-padded present tokens. Logic to replace pattern is the same
- // as in Phi3SlidingMask rewriter, but adjusted to another set of operations for
- // creation of mask, obtained from transformers 4.53.
- // Pattern is the same as in GemmaSlidingMask.
- //
- // Fix is a replace of following pattern:
- // 1. (K range > (Q range - sliding window).T) & (K range <= Q range.T)
- // to
- // 1. (K range > (Q_pos range - sliding window).T) & (K range <= Q range.T)
- // 2. (K range > (Q range - sliding window).T) | (K range < len(past_key_values))
- // 3. Resulting mask = 1 & 2,
- // where K range and Q range are created by the same rules as before and Q_pos range is
- // a position_ids array.
- // 4. We also clean mask in places where paddings used instead of real tokens via:
- // Clean mask = 3 & attention_mask_input[past_kv_len:].T
- auto unsqueeze_sequence = [&](std::shared_ptr<ov::Node> range) {
- auto unsqueeze1 = opp::wrap_type<ov::op::v0::Unsqueeze>({range, opp::any_input()});
- auto unsqueeze2 = opp::wrap_type<ov::op::v0::Unsqueeze>({unsqueeze1, opp::any_input()});
- auto unsqueeze3 = opp::wrap_type<ov::op::v0::Unsqueeze>({unsqueeze2, opp::any_input()});
-
- return unsqueeze3;
- };
-
- auto past_kv_len = opp::wrap_type<ov::op::v8::Gather>({opp::any_input(), opp::any_input(), opp::any_input()});
- // TODO: ov::op::v0::Squeeze may accept or not accept optional axes input, so we need to cover both cases in
- // pattern If Squeeze accepts axes it doesn't match with pattern without axes, and if it doesn't accept axes it
- // doesn't match with pattern with axes. So we need to add two branches in pattern to cover both cases.
- auto past_kv_len_squeeze = opp::optional<ov::op::v0::Squeeze>({past_kv_len});
- auto full_ctx_len = opp::wrap_type<ov::op::v1::Add>({past_kv_len_squeeze, opp::any_input()});
- auto query_range = opp::wrap_type<ov::op::v4::Range>({past_kv_len_squeeze, full_ctx_len, opp::any_input()});
- auto query_range_column = unsqueeze_sequence(query_range);
-
- auto zero_const = opp::wrap_type<ov::op::v0::Constant>();
- auto full_ctx_len_2 = opp::wrap_type<ov::op::v1::Add>({opp::any_input(), past_kv_len_squeeze});
- auto key_range = opp::wrap_type<ov::op::v4::Range>({zero_const, full_ctx_len_2, opp::any_input()});
- auto key_range_row = unsqueeze_sequence(key_range);
- auto opt_key_range_row_f32 = opp::optional<ov::op::v0::Convert>({key_range_row->output(0)});
-
- auto neg_window_size = opp::wrap_type<ov::op::v0::Constant>();
- auto query_left_bound_range = opp::wrap_type<ov::op::v1::Add>({query_range_column, neg_window_size});
- // True in mask means that we should attend this token
- auto sliding_mask = opp::wrap_type<ov::op::v1::Greater>({opt_key_range_row_f32, query_left_bound_range});
- auto sliding_and_true = opp::wrap_type<ov::op::v13::BitwiseAnd>({opp::any_input(), sliding_mask});
- // Basically it is a reference triangle self-attention mask
- auto causal_mask = opp::wrap_type<ov::op::v1::LessEqual>({opt_key_range_row_f32, query_range_column});
-
- auto sliding_and_causal_mask = opp::wrap_type<ov::op::v13::BitwiseAnd>({sliding_and_true, causal_mask});
-
- auto callback = [=](opp::Matcher& m) {
- LOG_INFO("Found (4.53) pattern for Phi-3 Sliding Window Attention, will be replaced with custom for static "
- "shapes.");
- auto& node_to_output = m.get_pattern_value_map();
- auto optional_squeeze = node_to_output.find(past_kv_len_squeeze);
- auto matched_past_kv_len = optional_squeeze != node_to_output.end()
- ? optional_squeeze->second.get_node_shared_ptr()
- : node_to_output.at(past_kv_len).get_node_shared_ptr();
- auto matched_full_ctx_len = node_to_output.at(full_ctx_len).get_node_shared_ptr();
- auto node_neg_window_size = node_to_output.at(neg_window_size).get_node_shared_ptr();
- auto matched_sliding_mask = node_to_output.at(sliding_mask).get_node_shared_ptr();
- auto matched_sliding_and_causal_mask = node_to_output.at(sliding_and_causal_mask).get_node_shared_ptr();
-
- auto optional_convert = node_to_output.find(opt_key_range_row_f32);
- std::shared_ptr<ov::Node> matched_key_range_row =
- optional_convert != node_to_output.end() ? optional_convert->second.get_node_shared_ptr()
- : node_to_output.at(key_range_row).get_node_shared_ptr();
- auto matched_neg_window_size = std::static_pointer_cast<ov::op::v0::Constant>(node_neg_window_size);
- OPENVINO_ASSERT(matched_neg_window_size->get_output_size() == 1,
- "Sliding window size constant must be of size 1, but got " +
- std::to_string(matched_neg_window_size->get_output_size()));
-
- std::shared_ptr<ov::Node> passed_attention_mask = attention_mask_node_ptr;
- std::shared_ptr<ov::Node> passed_position_ids = position_ids_node_ptr;
- OPENVINO_ASSERT(passed_attention_mask, "Passed attention_mask node is nullptr!");
- OPENVINO_ASSERT(passed_position_ids, "Passed position_ids node is nullptr!");
-
- auto const_zero = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, 0);
- auto const_one = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, 1);
- auto const_three = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, 3);
-
- // 1.(K range > (Q_pos range - sliding window).T) & (K range <= Q range.T)
- std::shared_ptr<ov::Node> query_range_as_pos_ids = passed_position_ids;
- if (matched_neg_window_size->output(0).get_element_type() == ov::element::f32) {
- query_range_as_pos_ids = std::make_shared<ov::op::v0::Convert>(passed_position_ids, ov::element::f32);
- }
- auto query_range_as_pos_ids_unsqueezed =
- std::make_shared<ov::op::v0::Unsqueeze>(query_range_as_pos_ids, const_zero);
- auto query_range_as_pos_ids_col =
- std::make_shared<ov::op::v0::Unsqueeze>(query_range_as_pos_ids_unsqueezed, const_three);
- auto query_range_as_pos_left_bound =
- std::make_shared<ov::op::v1::Add>(query_range_as_pos_ids_col, matched_neg_window_size);
- auto sliding_mask_for_right_padding =
- std::make_shared<ov::op::v1::Greater>(matched_key_range_row, query_range_as_pos_left_bound);
- matched_sliding_and_causal_mask->input(0).replace_source_output(sliding_mask_for_right_padding);
-
- // 2. (K range > (Q range - sliding window).T) | (K range < shape(past_key_values, 2))
- std::shared_ptr<ov::Node> past_kv_len_argument = matched_past_kv_len;
- if (matched_neg_window_size->output(0).get_element_type() == ov::element::f32) {
- past_kv_len_argument = std::make_shared<ov::op::v0::Convert>(matched_past_kv_len, ov::element::f32);
- }
- auto only_past_tokens_mask =
- std::make_shared<ov::op::v1::Less>(matched_key_range_row, past_kv_len_argument);
- auto sliding_mask_for_left_padding_or_only_past =
- std::make_shared<ov::op::v13::BitwiseOr>(matched_sliding_mask, only_past_tokens_mask);
-
- // 3. Result = 1 & 2
- // Save target inputs first:
- auto target_inputs = matched_sliding_and_causal_mask->output(0).get_target_inputs();
- auto new_sliding_and_causal_mask =
- std::make_shared<ov::op::v13::BitwiseAnd>(matched_sliding_and_causal_mask,
- sliding_mask_for_left_padding_or_only_past);
-
- // 4. Removing extra padding via : 3 & attention_mask_input[past_kv_len:].T
- std::vector<int64_t> shape_rank_one{1};
- auto shape_rank_one_const =
- std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, shape_rank_one);
- auto past_len_reshaped =
- std::make_shared<ov::op::v1::Reshape>(matched_past_kv_len, shape_rank_one_const, false);
- auto full_ctx_len_reshaped =
- std::make_shared<ov::op::v1::Reshape>(matched_full_ctx_len, shape_rank_one_const, false);
- auto const_one_rank_one = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, 1);
- auto attention_mask_bool =
- std::make_shared<ov::op::v0::Convert>(passed_attention_mask, ov::element::boolean);
- auto present_atten_mask_bool = std::make_shared<ov::op::v8::Slice>(attention_mask_bool,
- past_len_reshaped,
- full_ctx_len_reshaped,
- const_one_rank_one,
- const_one_rank_one);
- std::vector<int64_t> vector_shape{-1, 1};
- auto vector_shape_const =
- std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{2}, vector_shape);
- auto present_atten_mask_bool_col =
- std::make_shared<ov::op::v1::Reshape>(present_atten_mask_bool, vector_shape_const, false);
- auto clean_sliding_and_causal_mask =
- std::make_shared<ov::op::v13::BitwiseAnd>(new_sliding_and_causal_mask, present_atten_mask_bool_col);
- for (auto&& input : target_inputs) {
- input.replace_source_output(clean_sliding_and_causal_mask);
- }
-
- return true;
- };
- register_matcher(std::make_shared<opp::Matcher>(sliding_and_causal_mask, "Phi3SlidingMaskMatcher"),
- std::move(callback));
- }
-};
-
-class FakeConvertDestinationTypeExtractor : public ov::pass::MatcherPass {
-public:
- FakeConvertDestinationTypeExtractor(std::set<ov::element::Type>& fcDestinationTypes) {
- auto fake_convert_m = opp::wrap_type<ov::op::v13::FakeConvert>();
-
- ov::matcher_pass_callback callback = [=, &fcDestinationTypes](opp::Matcher& m) {
- const auto& pattern_to_output = m.get_pattern_value_map();
- const auto fake_convert =
- ov::as_type_ptr<ov::op::v13::FakeConvert>(pattern_to_output.at(fake_convert_m).get_node_shared_ptr());
-
- if (fake_convert == nullptr) {
- return false;
- }
- fcDestinationTypes.insert(fake_convert->get_destination_element_type());
- return true;
- };
- register_matcher(std::make_shared<opp::Matcher>(fake_convert_m, "FakeConvertDestinationTypeExtractor"),
- callback);
- }
-};
-
-class ConvertTypeRelaxedToRegular : public ov::pass::MatcherPass {
-public:
- ConvertTypeRelaxedToRegular() {
- auto pattern = opp::wrap_type<ov::op::TypeRelaxed<ov::op::v1::Multiply>>();
-
- ov::matcher_pass_callback callback = [](opp::Matcher& m) {
- auto tr_mul = std::dynamic_pointer_cast<ov::op::TypeRelaxed<ov::opset1::Multiply>>(m.get_match_root());
- if (tr_mul) {
- auto new_mul = std::make_shared<ov::opset1::Multiply>(tr_mul->input_value(0), tr_mul->input_value(1));
- new_mul->set_friendly_name(tr_mul->get_friendly_name());
- ov::copy_runtime_info(tr_mul, new_mul);
- ov::replace_node(tr_mul, new_mul);
- }
- return true;
- };
-
- register_matcher(std::make_shared<opp::Matcher>(pattern, "ConvertTypeRelaxedToRegular"), callback);
- }
-};
-
-class Phi3SlidingMask : public ov::pass::ModelPass {
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::Phi3SlidingMask");
- Phi3SlidingMask() = default;
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override {
- std::shared_ptr<ov::Node> attention_mask_node_ptr = nullptr;
- std::shared_ptr<ov::Node> position_ids_node_ptr = nullptr;
- for (const auto& i : model->inputs()) {
- if (i.get_any_name() == "attention_mask") {
- attention_mask_node_ptr = i.get_node_shared_ptr();
- }
- if (i.get_any_name() == "position_ids") {
- position_ids_node_ptr = i.get_node_shared_ptr();
- }
- }
- if (attention_mask_node_ptr == nullptr || position_ids_node_ptr == nullptr) {
- return false;
- }
-
- auto pos_id_shape = position_ids_node_ptr->get_output_tensor(0).get_partial_shape();
- if (pos_id_shape.size() != 2) {
- // FIXME: Qwen2.5 VL/Omni uses 3D position_ids, which can't be directly used
- // in creation of sliding window mask.
- return false;
- }
-
- ov::pass::Manager manager;
- manager.set_per_pass_validation(true);
- const auto rewriter = manager.register_pass<ov::pass::GraphRewrite>();
- rewriter->add_matcher<Phi3SlidingMaskMatcher>(attention_mask_node_ptr, position_ids_node_ptr);
- rewriter->add_matcher<OldPhi3SlidingMaskMatcher>();
- return manager.run_passes(model);
- }
-};
-
namespace {
template <typename T, typename = std::enable_if_t<std::is_integral<T>::value>>
T align_to(T value, T alignment) {
@@ -842,158 +56,8 @@ bool is_aligned_to(T value, T alignment) {
return value % alignment == 0;
}
-std::shared_ptr<ov::Model> cvt_kvcache_to_low_precision(const std::shared_ptr<ov::Model>& model,
- const ov::element::Type lptype) {
- ov::preprocess::PrePostProcessor ppp(model);
-
- for (const auto& tensor : model->inputs()) {
- if (tensor.get_any_name().find("past_key") != std::string::npos) {
- ppp.input(tensor.get_any_name()).tensor().set_element_type(lptype);
- }
- }
-
- for (const auto& tensor : model->outputs()) {
- if (tensor.get_any_name().find("present") != std::string::npos) {
- ppp.output(tensor.get_any_name()).tensor().set_element_type(lptype);
- }
- }
-
- return ppp.build();
-}
-
-ov::element::Type optimize_kv_cache_storage(const std::shared_ptr<ov::Model>& model) {
- LOG_DEBUG("Running FP8 static quantization on model: " << model->get_name());
-
- auto kv_kache_storage_type = ov::element::f16;
-
- ov::pass::low_precision::LayerTransformation::Params params;
- std::set<ov::element::Type> fcTypesInput, fcTypesRemained;
-
- ov::pass::Manager manager("optimize_fp8");
- params.defaultPrecisions = ov::pass::low_precision::precision_set::get_fp8_support();
- manager.register_pass<FakeConvertDestinationTypeExtractor>(fcTypesInput);
- manager.register_pass<ov::pass::low_precision::MoveFakeConvertUpThroughKVCacheConcat>();
- auto graph_rewrite = manager.register_pass<ov::pass::GraphRewrite>();
- graph_rewrite->add_matcher<ov::pass::FakeConvertDecomposition>();
- graph_rewrite->add_matcher<ov::pass::low_precision::ConcatTransformation>(params);
- graph_rewrite->add_matcher<ov::pass::low_precision::KVCacheConcat>(model);
- manager.register_pass<ConvertTypeRelaxedToRegular>();
- manager.register_pass<FakeConvertDestinationTypeExtractor>(fcTypesRemained);
- manager.run_passes(model);
- if (fcTypesInput.empty()) {
- LOG_WARN("FakeConvert layers not detected - leaving kv-cache in " << kv_kache_storage_type << " precision");
- } else if (!fcTypesRemained.empty()) {
- LOG_WARN(fcTypesRemained.size() << " FakeConvert layers not decomposed - leaving kv-cache in "
- << kv_kache_storage_type << " precision");
- } else if (fcTypesInput.size() > 1) {
- auto it2 = std::next(fcTypesInput.begin(), 1);
- LOG_WARN("FakeConvert layers had several precisions (" << fcTypesInput.size() << ")-" << *fcTypesInput.begin()
- << ", " << *it2 << ", ... "
- << "supported only single precision");
- LOG_WARN("Leaving KV-cache in " << kv_kache_storage_type << " precision");
- } else {
- kv_kache_storage_type = *fcTypesInput.begin();
- LOG_DEBUG("KV cache storage precision changed to " << kv_kache_storage_type);
- }
- return kv_kache_storage_type;
-}
-
-bool redirect_new_kv_to_output(const std::shared_ptr<ov::Model>& model) {
- ov::pass::Manager manager("redirect_new_kv_to_output");
- manager.register_pass<RedirectNewKvToOutputMatcher>();
- bool result = manager.run_passes(model);
- model->validate_nodes_and_infer_types();
-
- return result;
-}
-
-bool remove_empty_kv_inputs(std::shared_ptr<ov::Model> model) {
- ov::pass::GraphRewrite rewr;
- RemoveEmptyKVTensors::Context ctx;
- rewr.add_matcher<RemoveEmptyKVTensors>(std::ref(ctx));
- rewr.run_on_model(model);
- for (auto old_param : ctx.old_params) {
- model->remove_parameter(old_param);
- }
- ov::pass::Validate().run_on_model(model);
- // NB: if old_params is not empty - pass has been applied
- return !ctx.old_params.empty();
-}
-
-bool decompose_GQA(std::shared_ptr<ov::Model> model, bool is_prefill_model) {
- ov::pass::GraphRewrite rewr;
- rewr.add_matcher<GroupQueryAttentionDecomposition>(is_prefill_model);
- return rewr.run_on_model(model);
-}
-
-bool patch_phi3_sliding_mask(const std::shared_ptr<ov::Model>& model) {
- ov::pass::Manager manager;
- manager.register_pass<Phi3SlidingMask>();
- return manager.run_passes(model);
-}
-
} // namespace
-class ConvertKVCacheToPrecision : public ov::pass::ModelPass {
- ov::element::Type m_lp_type;
-
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::ConvertKVCacheToPrecision");
- explicit ConvertKVCacheToPrecision(const ov::element::Type lptype) : m_lp_type(lptype) {}
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override {
- auto ppp_result = cvt_kvcache_to_low_precision(model, m_lp_type);
- // PrePostProcessor currently always modifies the model in-place and returns the same model pointer, but let's
- // be defensive here and check it just in case
- OPENVINO_ASSERT(ppp_result == model,
- "PrePostProcessor should not create a new model, but returned a different one.");
-
- return true;
- }
-};
-
-class RedirectNewKvToOutput : public ov::pass::ModelPass {
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::RedirectNewKvToOutput");
- RedirectNewKvToOutput() = default;
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override {
- return redirect_new_kv_to_output(model);
- }
-};
-
-class RemoveEmptyKVInputs : public ov::pass::ModelPass {
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::RemoveEmptyKVInputs");
- RemoveEmptyKVInputs() = default;
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override {
- return remove_empty_kv_inputs(model);
- }
-};
-
-class DecomposeGQA : public ov::pass::ModelPass {
- bool m_is_prefill_model;
-
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::DecomposeGQA");
- explicit DecomposeGQA(bool is_prefill_model) : m_is_prefill_model(is_prefill_model) {}
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override {
- return decompose_GQA(model, m_is_prefill_model);
- }
-};
-
-class PatchPhi3SlidingMask : public ov::pass::ModelPass {
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::PatchPhi3SlidingMask");
- explicit PatchPhi3SlidingMask() = default;
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override {
- return patch_phi3_sliding_mask(model);
- }
-};
-
class CutLMHead : public ov::pass::MatcherPass {
public:
OPENVINO_MATCHER_PASS_RTTI("ov::npuw::CutLMHead");
@@ -1092,142 +156,6 @@ std::shared_ptr<ov::Model> cut_lm_head(const std::shared_ptr<ov::Model>& model)
return lm_head_model;
}
-void reshape_to_static(std::shared_ptr<ov::Model> model,
- const uint32_t input_size,
- const uint32_t kvcache_size,
- const KVAxesPosition& kv_axes_position,
- const uint32_t lora_rank,
- const uint32_t lhs_seq_size = 0) {
- std::map<std::string, ov::PartialShape> new_shapes;
- for (const auto& input : model->inputs()) {
- const auto& input_name = input.get_any_name();
- ov::PartialShape new_shape;
- if (input_name.find("input_ids") != std::string::npos) {
- new_shape = ov::PartialShape({1, input_size});
- } else if (input_name.find("token_type_ids") != std::string::npos) {
- new_shape = ov::PartialShape({1, input_size});
- } else if (input_name.find("inputs_embeds") != std::string::npos) {
- // NB: VLMs case, model accepts inputs_embeds[BATCH, SEQ_LEN, EMB_SIZE]
- NPUW_ASSERT(input.get_partial_shape().size() == 3u);
- NPUW_ASSERT(input.get_partial_shape()[2].is_static());
- new_shape = ov::PartialShape({1, input_size, input.get_partial_shape()[2]});
- } else if (input_name.find("attention_mask") != std::string::npos) {
- new_shape = ov::PartialShape({1, kvcache_size});
- if (lhs_seq_size && kvcache_size > 4)
- // NB: for whisper kvcache model attn mask should be size + 1
- new_shape = ov::PartialShape({1, kvcache_size + 1});
- } else if (input_name.find("position_ids") != std::string::npos) {
- const auto partial_shape_size = input.get_partial_shape().size();
- // NB: Regular LLM uses 2D shapes, Qwen2.5 VL/Omni uses 3D shapes
- // The first dimension (3) represents the three components of position encoding: time, height, and width
- // enabling alignment across multimodal inputs like text, audio, and video
- NPUW_ASSERT(partial_shape_size == 3u || partial_shape_size == 2u);
- new_shape =
- partial_shape_size == 3u ? ov::PartialShape({3, 1, input_size}) : ov::PartialShape({1, input_size});
- } else if (input_name.find("cache_position") != std::string::npos) {
- // NB: Whisper case
- new_shape = ov::PartialShape({1});
- } else if (input_name.find("encoder_hidden_states") != std::string::npos) {
- // NB: Whisper case
- const auto& partial_shape = input.get_partial_shape();
- new_shape = partial_shape;
- new_shape[0] = 1; // batch_dim
- } else if (ov::npuw::matchEagle3HiddenStatesString(input_name)) {
- new_shape = ov::npuw::Eagle3Extension::get_static_input(model, input, input_size);
- } else if (ov::npuw::util::matchLoRAMatMulAString(input_name)) {
- new_shape = ov::PartialShape({lora_rank, input.get_partial_shape()[1]});
- } else if (ov::npuw::util::matchLoRAMatMulAlphaString(input_name)) {
- new_shape = ov::PartialShape({input.get_partial_shape()[0], lora_rank});
- } else if (ov::npuw::util::matchLoRAMatMulBString(input_name)) {
- new_shape = ov::PartialShape({input.get_partial_shape()[0], lora_rank});
- } else {
- const auto& partial_shape = input.get_partial_shape();
- new_shape = partial_shape;
- new_shape[kv_axes_position.batch] = 1;
- if (lhs_seq_size) { // Whisper model
- new_shape[kv_axes_position.seq_len] = (input_name.find(".decoder") != std::string::npos)
- ? kvcache_size - input_size // kv_size for decoder
- : lhs_seq_size; // sequence size for encoder hidden states
- } else { // LLM/VLM
- new_shape[kv_axes_position.seq_len] = kvcache_size - input_size;
- }
- }
- new_shapes.emplace(input_name, new_shape);
- }
- model->reshape(new_shapes);
-}
-
-void reshape_sliced_head_to_static(std::shared_ptr<ov::Model> lm_head_model,
- const uint32_t& batch_dim,
- std::size_t max_generation_token_len) {
- // We have only one input with dynamic shapes: output embeds.
- // Output embeds should have "max_generation_token_len" for dimension representing
- // number of embeddings to send to the matmul. Batch size should be equal to "1"
- // for NPU.
- const auto& input = lm_head_model->input(0);
- const auto& partial_shape = input.get_partial_shape();
- NPUW_ASSERT(partial_shape.size() == 3);
-
- ov::PartialShape new_shape = partial_shape;
- new_shape[batch_dim] = 1;
- // Left dynamic axis will be for number of embeddings
- for (auto i = 0; i < new_shape.rank().get_length(); i++) {
- if (new_shape[i].is_dynamic()) {
- new_shape[i] = max_generation_token_len;
- // Sanity check that only one left dimension is dynamic, as
- // another one should contain embedding space rank
- break;
- }
- }
-
- lm_head_model->reshape(new_shape);
-}
-
-void slice_out_embeds(std::shared_ptr<ov::Model> model,
- const uint32_t& batch_dim,
- std::size_t max_generation_token_len) {
- std::shared_ptr<ov::Node> embed_result;
- for (auto&& output : model->outputs()) {
- if (output.get_any_name() == ov::npuw::LLMCompiledModel::output_embeds) {
- embed_result = output.get_node_shared_ptr();
- }
- }
-
- if (embed_result) {
- auto shape = embed_result->input(0).get_shape();
- // If shape.size() is 3, then last axis should contain the rank of embedding dimension.
- // But 1st and 2nd axes can mean different things.
- // 1st axis can represent the batch size, while 2nd - the number of embeddings,
- // or vice-versa (in chatglm)
- if (shape.size() == 3) {
- OPENVINO_ASSERT(batch_dim <= 1, "Unexpected value of batch_dim: ", batch_dim, ", expected 0 or 1!");
- uint32_t num_embeds_dim = 1 - batch_dim;
- OPENVINO_ASSERT(shape[num_embeds_dim] >= max_generation_token_len,
- "Number of output embeddings should be greater or equal to the slicing range!");
- if (shape[num_embeds_dim] != max_generation_token_len) {
- std::vector<int32_t> start_pos{
- static_cast<int32_t>(batch_dim * (shape[num_embeds_dim] - max_generation_token_len)),
- static_cast<int32_t>(num_embeds_dim * (shape[num_embeds_dim] - max_generation_token_len)),
- 0};
- std::vector<int32_t> stop_pos{static_cast<int32_t>(batch_dim * (shape[num_embeds_dim] - 1)) + 1,
- static_cast<int32_t>(num_embeds_dim * (shape[num_embeds_dim] - 1)) + 1,
- static_cast<int32_t>(shape[2])};
- auto start = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{3}, start_pos);
- auto stop = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{3}, stop_pos);
- auto step = std::make_shared<ov::op::v0::Constant>(ov::element::i32,
- ov::Shape{3},
- std::vector<int32_t>{1, 1, 1});
-
- auto slice = std::make_shared<ov::op::v8::Slice>(embed_result->input_value(0), start, stop, step);
-
- embed_result->input(0).replace_source_output(slice);
- embed_result->validate_and_infer_types();
- model->validate_nodes_and_infer_types();
- }
- }
- }
-}
-
bool is_cw_compressed(const std::shared_ptr<ov::Model>& model) {
std::vector<std::string> rt_info_path = {"nncf", "weight_compression", "group_size"};
if (!model->has_rt_info(rt_info_path)) {
@@ -1540,18 +468,6 @@ void apply_moe_config(ov::AnyMap& stage_config,
}
// Apply DEVICE_ROUTED MoE transformations to models
-void apply_moe_device_routed_transforms(const std::shared_ptr<ov::Model>& model) {
- ov::npuw::pass::DeviceRoutedMoETransform moe_transform;
- ov::npuw::pass::GatherTo2DGather gather_transform;
-
- moe_transform.run_on_model(model);
- LOG_DEBUG(" Applied DEVICE_ROUTED transformations to model variant");
-
- // Apply Gather to 2D Gather transformation for HW optimization
- gather_transform.run_on_model(model);
- LOG_DEBUG(" Applied GatherTo2DGather transformation to model variant");
-}
-
ov::element::Type choose_kv_cache_storage_type(const std::shared_ptr<ov::Model>& model,
const ::intel_npu::Config& cfg,
ov::AnyMap& other_props) {
@@ -1559,7 +475,7 @@ ov::element::Type choose_kv_cache_storage_type(const std::shared_ptr<ov::Model>&
// kv-cache-precision changes to fp8 does make sense unconditionally only if LPT passes succesfully applied
if (cfg.get<::intel_npu::NPUW_LLM_OPTIMIZE_FP8>()) {
- kv_kache_storage_type = optimize_kv_cache_storage(model);
+ kv_kache_storage_type = ov::npuw::optimize_kv_cache_storage(model);
}
auto kv_cache_precision_hint = pop_option(other_props, ov::hint::kv_cache_precision.name());
@@ -1576,49 +492,6 @@ ov::element::Type choose_kv_cache_storage_type(const std::shared_ptr<ov::Model>&
return kv_kache_storage_type;
}
-void convert_stateful_lora_to_stateless(const std::shared_ptr<ov::Model>& model) {
- typedef std::shared_ptr<ov::op::util::AssignBase> PAssign;
- typedef std::shared_ptr<ov::op::util::ReadValueBase> PReadValue;
- std::vector<PReadValue> readValues;
- std::vector<PAssign> assigns;
- auto sinks = model->get_sinks();
- for (size_t i = 0; i < sinks.size(); ++i) {
- if (auto assign = ov::as_type_ptr<ov::op::util::AssignBase>(sinks[i])) {
- auto variable_name = assign->get_variable_id();
- if (!ov::npuw::util::matchLoRAMatMulAString(variable_name) &&
- !ov::npuw::util::matchLoRAMatMulBString(variable_name) &&
- !ov::npuw::util::matchLoRAMatMulAlphaString(variable_name)) {
- continue;
- }
-
- auto read_value = ov::as_type_ptr<ov::op::util::ReadValueBase>(assign->get_input_node_shared_ptr(0));
- OPENVINO_ASSERT(read_value, "Can't find ReadValue");
- readValues.push_back(read_value);
- assigns.push_back(assign);
- }
- }
-
- ov::ParameterVector new_parameters;
- new_parameters.reserve(readValues.size());
- for (size_t i = 0; i < readValues.size(); ++i) {
- auto read_value = readValues[i];
- auto variable_name = read_value->get_variable_id();
- const auto element_type = read_value->get_output_element_type(0);
- const auto shape = read_value->get_output_partial_shape(0);
-
- auto parameter = std::make_shared<ov::op::v0::Parameter>(element_type, shape);
- ov::op::util::set_name(*parameter, variable_name);
- replace_node(read_value, parameter);
-
- auto assign = assigns[i];
- model->remove_sink(assign);
- model->remove_variable(model->get_variable_by_id(variable_name));
- new_parameters.push_back(parameter);
- }
-
- model->add_parameters(new_parameters);
-}
-
std::shared_ptr<ov::Model> check_and_cut_lm_head(const std::shared_ptr<ov::Model>& m, const ::intel_npu::Config& cfg) {
bool shared_head_enabled = cfg.get<::intel_npu::NPUW_LLM_SHARED_HEAD>();
std::shared_ptr<ov::Model> lm_head_model = nullptr;
@@ -1640,93 +513,7 @@ std::shared_ptr<ov::Model> check_and_cut_lm_head(const std::shared_ptr<ov::Model
} // namespace
-class ReshapeToStatic : public ov::pass::ModelPass {
- uint32_t m_input_size;
- uint32_t m_kvcache_size;
- KVAxesPosition m_kv_axes_position;
- uint32_t m_lora_rank;
- uint32_t m_lhs_seq_size;
-
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::ReshapeToStatic");
- explicit ReshapeToStatic(const uint32_t input_size,
- const uint32_t kvcache_size,
- const KVAxesPosition& kv_axes_position,
- const uint32_t lora_rank,
- const uint32_t lhs_seq_size = 0)
- : m_input_size(input_size),
- m_kvcache_size(kvcache_size),
- m_kv_axes_position(kv_axes_position),
- m_lora_rank(lora_rank),
- m_lhs_seq_size(lhs_seq_size) {}
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override {
- reshape_to_static(model, m_input_size, m_kvcache_size, m_kv_axes_position, m_lora_rank, m_lhs_seq_size);
-
- return true;
- }
-};
-
-class ReshapeSlicedHeadToStatic : public ov::pass::ModelPass {
- uint32_t m_batch_dim;
- std::size_t m_max_generation_token_len;
-
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::ReshapeSlicedHeadToStatic");
- explicit ReshapeSlicedHeadToStatic(uint32_t batch_dim, std::size_t max_generation_token_len)
- : m_batch_dim(batch_dim),
- m_max_generation_token_len(max_generation_token_len) {}
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override {
- reshape_sliced_head_to_static(model, m_batch_dim, m_max_generation_token_len);
-
- return true;
- }
-};
-
-class SliceOutEmbeds : public ov::pass::ModelPass {
- uint32_t m_batch_dim;
- std::size_t m_max_generation_token_len;
-
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::SliceOutEmbeds");
- explicit SliceOutEmbeds(uint32_t batch_dim, std::size_t max_generation_token_len)
- : m_batch_dim(batch_dim),
- m_max_generation_token_len(max_generation_token_len) {}
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override {
- slice_out_embeds(model, m_batch_dim, m_max_generation_token_len);
-
- return true;
- }
-};
-
// Apply DEVICE_ROUTED MoE transformations to models
-class ApplyMoEDeviceRoutedTransforms : public ov::pass::ModelPass {
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::ApplyMoEDeviceRoutedTransforms");
- ApplyMoEDeviceRoutedTransforms() = default;
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override {
- apply_moe_device_routed_transforms(model);
-
- return true;
- }
-};
-
-class LoraStatefulToStatelessPass : public ov::pass::ModelPass {
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::LoraStatefulToStatelessPass");
-
- explicit LoraStatefulToStatelessPass() = default;
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override {
- convert_stateful_lora_to_stateless(model);
-
- return true;
- }
-};
-
std::vector<std::shared_ptr<ov::Model>> ov::npuw::LLMCompiledModel::create_generate_model_variants(
const std::shared_ptr<ov::Model>& generate_model,
const KVAxesPosition& axes,
@@ -1779,7 +566,7 @@ std::vector<std::shared_ptr<ov::Model>> ov::npuw::LLMCompiledModel::create_gener
<< "): reshaping to static");
// Reshape to target size
- ReshapeToStatic(max_generation_token_len, kv_size, axes, m_max_lora_rank, whisper_lhs_seq_size)
+ ov::npuw::ReshapeToStatic(max_generation_token_len, kv_size, axes, m_max_lora_rank, whisper_lhs_seq_size)
.run_on_model(generate_variant);
// Set unique name for this variant
@@ -1983,7 +770,7 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
ov::pass::StatefulToStateless().run_on_model(kvcache_model);
}
- LoraStatefulToStatelessPass().run_on_model(kvcache_model);
+ ov::npuw::LoraStatefulToStatelessPass().run_on_model(kvcache_model);
LOG_DEBUG(" ...also convert BF16 to FP16");
// Note: we need to identify original bf16 constants for potential weightless deserialization later
@@ -1995,7 +782,7 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
if (!m_is_whisper) {
LOG_DEBUG("Try patch Phi-3 sliding window mask, if it exists.");
- PatchPhi3SlidingMask().run_on_model(kvcache_model);
+ ov::npuw::PatchPhi3SlidingMask().run_on_model(kvcache_model);
}
LOG_DEBUG("Creating prefill model as clone of transformed kvcache one.");
@@ -2021,17 +808,17 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
LOG_DEBUG("Make prefill model with static shapes");
m_max_lora_rank = m_cfg.get<::intel_npu::NPUW_LLM_MAX_LORA_RANK>();
if (m_use_chunk_prefill) {
- ReshapeToStatic(static_cast<uint32_t>(m_prefill_chunk_size),
- m_kvcache_desc.max_prompt_size,
- axes,
- m_max_lora_rank)
+ ov::npuw::ReshapeToStatic(static_cast<uint32_t>(m_prefill_chunk_size),
+ m_kvcache_desc.max_prompt_size,
+ axes,
+ m_max_lora_rank)
.run_on_model(prefill_model);
} else {
- ReshapeToStatic(m_kvcache_desc.max_prompt_size,
- m_kvcache_desc.max_prompt_size,
- axes,
- m_max_lora_rank,
- whisper_lhs_seq_size)
+ ov::npuw::ReshapeToStatic(m_kvcache_desc.max_prompt_size,
+ m_kvcache_desc.max_prompt_size,
+ axes,
+ m_max_lora_rank,
+ whisper_lhs_seq_size)
.run_on_model(prefill_model);
}
LOG_DEBUG("Make kvcache model with static shapes");
@@ -2043,15 +830,16 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
LOG_DEBUG("Shared LM head: slice the prefill output");
// KVCache model is already reshaped to [1, max_generation_token_len, embed size],
// so only apply slice to the Prefill model:
- SliceOutEmbeds(axes.batch, m_kvcache_desc.max_generation_token_len).run_on_model(prefill_model);
+ ov::npuw::SliceOutEmbeds(axes.batch, m_kvcache_desc.max_generation_token_len).run_on_model(prefill_model);
LOG_DEBUG("Make LM head model with static shapes");
- ReshapeSlicedHeadToStatic(axes.batch, m_kvcache_desc.max_generation_token_len).run_on_model(lm_head_model);
+ ov::npuw::ReshapeSlicedHeadToStatic(axes.batch, m_kvcache_desc.max_generation_token_len)
+ .run_on_model(lm_head_model);
}
LOG_DEBUG("5.1, decompose GroupQueryAttention OP");
- DecomposeGQA(true).run_on_model(prefill_model);
+ ov::npuw::DecomposeGQA(true).run_on_model(prefill_model);
for (auto& model_variant : generate_model_variants) {
- DecomposeGQA(false).run_on_model(model_variant);
+ ov::npuw::DecomposeGQA(false).run_on_model(model_variant);
}
const auto prefill_attn_hint = m_cfg.get<::intel_npu::NPUW_LLM_PREFILL_ATTENTION_HINT>();
@@ -2106,25 +894,25 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
if (!m_is_embedding) {
if (!m_use_chunk_prefill) {
- NPUW_ASSERT(RemoveEmptyKVInputs().run_on_model(prefill_model));
+ NPUW_ASSERT(ov::npuw::RemoveEmptyKVInputs().run_on_model(prefill_model));
} else {
LOG_DEBUG("Don't remove input key/values from prefill model.");
LOG_DEBUG("Ask prefill model to output key/values for prefill chunk size tokens.");
- RedirectNewKvToOutput().run_on_model(prefill_model);
+ ov::npuw::RedirectNewKvToOutput().run_on_model(prefill_model);
}
LOG_DEBUG("Optimize generate model to output key/values for new token.");
for (size_t i = 0; i < generate_model_variants.size(); ++i) {
- RedirectNewKvToOutput().run_on_model(generate_model_variants[i]);
+ ov::npuw::RedirectNewKvToOutput().run_on_model(generate_model_variants[i]);
}
}
LOG_DEBUG("Converting KV-cache in generate model to FP16.");
for (size_t i = 0; i < generate_model_variants.size(); ++i) {
- ConvertKVCacheToPrecision(kv_kache_storage_type).run_on_model(generate_model_variants[i]);
+ ov::npuw::ConvertKVCacheToPrecision(kv_kache_storage_type).run_on_model(generate_model_variants[i]);
}
LOG_DEBUG("Converting KV-cache in prefill model to FP16.");
- ConvertKVCacheToPrecision(kv_kache_storage_type).run_on_model(prefill_model);
+ ov::npuw::ConvertKVCacheToPrecision(kv_kache_storage_type).run_on_model(prefill_model);
auto prefill_config =
prefill_config_opt.value_or(get_default_prefill_config(prefill_model, npudesc)).as<ov::AnyMap>();
@@ -2189,7 +977,7 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
if (generate_moe_hint == ::intel_npu::npuw::llm::MoEHint::DEVICE_ROUTED) {
LOG_INFO("Applying DEVICE_ROUTED MoE transformations to " << generate_model_variants.size() << " variants");
for (auto&& model_variant : generate_model_variants) {
- ApplyMoEDeviceRoutedTransforms().run_on_model(model_variant);
+ ov::npuw::ApplyMoEDeviceRoutedTransforms().run_on_model(model_variant);
}
LOG_INFO("DEVICE_ROUTED MoE transformations completed");
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp
index b714b704dff..b1c13601e3b 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp
@@ -7,13 +7,7 @@
#include <memory>
#include "compiled_model.hpp"
-
-namespace {
-struct KVAxesPosition {
- uint32_t batch;
- uint32_t seq_len;
-};
-} // anonymous namespace
+#include "npuw_transformations/kv_axes_position.hpp"
namespace ov {
namespace npuw {
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.cpp
index e8f4e57668f..a68560972ed 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.cpp
@@ -4,508 +4,6 @@
#include "llm_compiled_model_utils.hpp"
-#include <regex>
-#include <transformations/op_conversions/scaled_dot_product_attention_decomposition.hpp>
-
-#include "logging.hpp"
-#include "openvino/op/ops.hpp"
-#include "openvino/openvino.hpp"
-#include "openvino/opsets/opset13.hpp"
-#include "openvino/pass/graph_rewrite.hpp"
-#include "openvino/pass/matcher_pass.hpp"
-#include "openvino/pass/pattern/op/optional.hpp"
-#include "openvino/pass/pattern/op/or.hpp"
-#include "openvino/pass/pattern/op/wrap_type.hpp"
-#include "openvino/pass/validate.hpp"
-
-namespace opp = ov::pass::pattern;
-
-// diagnostics warnings on OPENVINO_MATCHER_PASS_RTTI() definition: visibility hidden
-#ifdef __GNUC__
-# pragma GCC diagnostic push
-# pragma GCC diagnostic ignored "-Wattributes"
-#endif
-namespace {
-
-class TransposeValueTensors : public ov::pass::MatcherPass {
-public:
- struct Context {
- using Ref = std::reference_wrapper<Context>;
- bool bTransposed = false;
- };
-
-protected:
- // generic part of matchers, to transpose v-tensors, and concat, and update matmul args
- void transpose_matmul_b(Context::Ref ctx,
- const std::shared_ptr<ov::op::v0::Parameter>& matched_param,
- const std::shared_ptr<ov::op::v0::Concat>& matched_concat,
- const std::shared_ptr<ov::op::v1::Transpose>& matched_transpose,
- const std::shared_ptr<ov::op::v0::MatMul>& matched_matmul) {
- auto param_shape = matched_param->get_partial_shape();
- NPUW_ASSERT(param_shape.size() == 4u);
- // NB: Transpose Parameter that correspond to V-tensor it will
- // speed-up its multiplication with attention scores
- std::swap(param_shape[2], param_shape[3]);
-
- matched_param->set_partial_shape(param_shape);
-
- auto order_cst = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{4}, {0, 2, 3, 1});
-
- matched_transpose->set_argument(1, order_cst);
- matched_concat->set_axis(3u);
- matched_matmul->set_transpose_b(true);
- ctx.get().bTransposed = true;
- }
-
- void transpose_matmul_b(Context::Ref ctx,
- const std::shared_ptr<ov::Node>& node_param,
- const std::shared_ptr<ov::Node>& node_concat,
- const std::shared_ptr<ov::Node>& node_transpose,
- const std::shared_ptr<ov::Node>& node_matmul) {
- auto matched_param = std::static_pointer_cast<ov::op::v0::Parameter>(node_param);
- auto matched_concat = std::static_pointer_cast<ov::op::v0::Concat>(node_concat);
- auto matched_transpose = std::static_pointer_cast<ov::op::v1::Transpose>(node_transpose);
- auto matched_matmul = std::static_pointer_cast<ov::op::v0::MatMul>(node_matmul);
-
- transpose_matmul_b(ctx, matched_param, matched_concat, matched_transpose, matched_matmul);
- }
-};
-
-// MHA (Multi-Head Attention) pattern for value tensor concatenation
-class TransposeValueTensors_MHA : public TransposeValueTensors {
-public:
- OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::TransposeValueTensors_MHA");
- TransposeValueTensors_MHA(Context::Ref ctx) {
- register_matcher_mha(ctx);
- }
-
-private:
- void register_matcher_mha(Context::Ref ctx) {
- auto param = opp::wrap_type<ov::op::v0::Parameter>();
- auto transpose = opp::wrap_type<ov::op::v1::Transpose>({opp::any_input(), opp::any_input()});
- auto convert = opp::optional<ov::op::v0::Convert>({param->output(0)});
- auto concat = opp::wrap_type<ov::op::v0::Concat>({convert, transpose});
- auto softmax = opp::wrap_type<ov::op::v8::Softmax>({opp::any_input()});
- // Softmax output maybe sliced when SDPA with sink input is decomposed
- auto maybe_slice = opp::optional<ov::op::v8::Slice>(
- {softmax, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});
- auto matmul = opp::wrap_type<ov::op::v0::MatMul>({maybe_slice, concat});
-
- auto callback = [=](ov::pass::pattern::Matcher& m) {
- auto& node_to_output = m.get_pattern_value_map();
-
- auto matched_node_param = node_to_output.at(param).get_node_shared_ptr();
- auto matched_node_concat = node_to_output.at(concat).get_node_shared_ptr();
- auto matched_node_transpose = node_to_output.at(transpose).get_node_shared_ptr();
- auto matched_node_matmul = node_to_output.at(matmul).get_node_shared_ptr();
-
- transpose_matmul_b(ctx,
- matched_node_param,
- matched_node_concat,
- matched_node_transpose,
- matched_node_matmul);
- LOG_DEBUG("vtensors transposed: MHA pattern");
- return true;
- };
- register_matcher(std::make_shared<opp::Matcher>(matmul, "TransposeValueTensors_MHA"), std::move(callback));
- }
-};
-
-// GQA (Grouped Query Attention) pattern for value tensors with broadcasting
-// Used by llama3, phi3, mistral, GPT-OSS, etc.
-class TransposeValueTensors_GQA : public TransposeValueTensors {
-public:
- OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::TransposeValueTensors_GQA");
- TransposeValueTensors_GQA(Context::Ref ctx) {
- register_matcher_gqa(ctx);
- }
-
-private:
- void register_matcher_gqa(Context::Ref ctx) {
- auto param = opp::wrap_type<ov::op::v0::Parameter>();
- auto transpose = opp::wrap_type<ov::op::v1::Transpose>({opp::any_input(), opp::any_input()});
- auto convert = opp::optional<ov::op::v0::Convert>({param->output(0)});
- auto concat = opp::wrap_type<ov::op::v0::Concat>({convert, transpose});
-
- // only difference is that broadcast wrapped into unsquese/reshape, while transposed tensor didn't change
- const auto unsqueeze_axes = opp::wrap_type<ov::op::v0::Constant>();
- auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({concat, unsqueeze_axes});
- auto broadcast = opp::wrap_type<ov::op::v1::Broadcast, ov::op::v3::Broadcast>({unsqueeze, opp::any_input()});
- auto reshape = opp::wrap_type<ov::op::v1::Reshape>({broadcast, opp::any_input()});
-
- // v8 softmax? what? can be other softmaxes
- auto softmax = opp::wrap_type<ov::op::v8::Softmax>({opp::any_input()});
- // Softmax output maybe sliced when SDPA with sink input is decomposed (e.g. GPT-OSS)
- auto maybe_slice = opp::optional<ov::op::v8::Slice>(
- {softmax, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});
- auto matmul = opp::wrap_type<ov::op::v0::MatMul>({maybe_slice, reshape});
-
- auto callback = [=](ov::pass::pattern::Matcher& m) {
- auto& node_to_output = m.get_pattern_value_map();
-
- auto matched_node_param = node_to_output.at(param).get_node_shared_ptr();
- auto matched_node_concat = node_to_output.at(concat).get_node_shared_ptr();
- auto matched_node_transpose = node_to_output.at(transpose).get_node_shared_ptr();
- auto matched_node_matmul = node_to_output.at(matmul).get_node_shared_ptr();
- auto matched_node_unsqueeze = node_to_output.at(unsqueeze).get_node_shared_ptr();
- auto matched_node_unsqueeze_axes = node_to_output.at(unsqueeze_axes).get_node_shared_ptr();
- auto matched_node_broadcast = node_to_output.at(broadcast).get_node_shared_ptr();
- auto matched_node_reshape = node_to_output.at(reshape).get_node_shared_ptr();
-
- auto matched_param = std::static_pointer_cast<ov::op::v0::Parameter>(matched_node_param);
- auto matched_concat = std::static_pointer_cast<ov::op::v0::Concat>(matched_node_concat);
- auto matched_transpose = std::static_pointer_cast<ov::op::v1::Transpose>(matched_node_transpose);
- auto matched_matmul = std::static_pointer_cast<ov::op::v0::MatMul>(matched_node_matmul);
- auto matched_unsqueeze = std::static_pointer_cast<ov::op::v0::Unsqueeze>(matched_node_unsqueeze);
- auto matched_broadcast = std::static_pointer_cast<ov::op::v3::Broadcast>(matched_node_broadcast);
- auto matched_reshape = std::static_pointer_cast<ov::op::v1::Reshape>(matched_node_reshape);
-
- auto shape_broadcast = matched_broadcast->get_output_shape(0);
- NPUW_ASSERT(shape_broadcast.size() == 5u);
- std::swap(shape_broadcast[3], shape_broadcast[4]);
-
- LOG_DEBUG("shape_broadcast for: " << matched_broadcast->get_friendly_name()
- << ", shape=" << shape_broadcast);
-
- const auto broadcast_axes_node =
- std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{5}, shape_broadcast);
- broadcast_axes_node->set_friendly_name(matched_broadcast->get_friendly_name() + "/new_broadcast_shape");
- matched_broadcast->input(1).replace_source_output(broadcast_axes_node);
-
- auto shape_reshape = matched_reshape->get_output_shape(0);
- NPUW_ASSERT(shape_reshape.size() == 4u);
- std::swap(shape_reshape[2], shape_reshape[3]);
-
- LOG_DEBUG("shape_reshape for: " << matched_reshape->get_friendly_name() << ", shape=" << shape_reshape);
-
- const auto reshape_axes_node =
- std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{4}, shape_reshape);
- reshape_axes_node->set_friendly_name(matched_reshape->get_friendly_name() + "/new_reshape_shape");
- matched_reshape->input(1).replace_source_output(reshape_axes_node);
-
- transpose_matmul_b(ctx, matched_param, matched_concat, matched_transpose, matched_matmul);
- LOG_DEBUG("vtensors transposed: GQA pattern");
- return true;
- };
- register_matcher(std::make_shared<opp::Matcher>(matmul, "TransposeValueTensors_GQA"), std::move(callback));
- }
-};
-
-class ScaledDotProductAttentionDecomposition : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::ScaledDotProductAttentionDecomposition");
- explicit ScaledDotProductAttentionDecomposition(bool use_high_precision_on_add) {
- auto pattern_node = ov::pass::pattern::wrap_type<ov::op::v13::ScaledDotProductAttention>();
-
- ov::matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {
- auto& pattern_to_output = m.get_pattern_value_map();
- auto node = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(
- pattern_to_output.at(pattern_node).get_node_shared_ptr());
-
- if (node == nullptr || transformation_callback(node)) {
- return false;
- }
-
- auto new_output_node = decompose(node, use_high_precision_on_add);
- ov::replace_node(node, new_output_node);
- return true;
- };
-
- auto m = std::make_shared<ov::pass::pattern::Matcher>(pattern_node, "ScaledDotProductAttentionDecomposition");
- register_matcher(m, std::move(callback));
- }
- std::shared_ptr<ov::Node> decompose(std::shared_ptr<ov::op::v13::ScaledDotProductAttention> node,
- bool use_high_precision_on_add) {
- using namespace ov::op;
- using namespace ov;
- auto query = node->input_value(0);
- auto key = node->input_value(1);
- auto value = node->input_value(2);
- auto q_shape = register_new_node<v3::ShapeOf>(query, element::i32);
- auto k_shape = register_new_node<v3::ShapeOf>(key, element::i32);
- auto minus_one = register_new_node(v0::Constant::create(element::i32, Shape{}, {-1}));
- auto minus_two = register_new_node(v0::Constant::create(element::i32, Shape{}, {-2}));
- auto zero_i = register_new_node(v0::Constant::create(element::i32, Shape{}, {0}));
- auto one_i = register_new_node(v0::Constant::create(element::i32, Shape{}, {1}));
- auto one_f = register_new_node<v1::ConvertLike>(one_i, query);
- auto zero_f = register_new_node<v1::ConvertLike>(zero_i, query);
-
- Output<Node> scale;
- if (node->get_input_size() < 5) {
- scale = register_new_node<v8::Gather>(q_shape, minus_one, zero_i)->output(0);
- scale = register_new_node<v1::ConvertLike>(scale, query);
- auto sqrt_scale = register_new_node<v0::Sqrt>(scale);
- scale = register_new_node<v1::Divide>(one_f, sqrt_scale);
- } else {
- scale = node->input_value(4);
- }
-
- auto q_scaled = register_new_node<v1::Multiply>(query, scale);
- auto k_rank = register_new_node<v3::ShapeOf>(k_shape, element::i32)->output(0);
- auto k_last_dim = register_new_node<v1::Add>(k_rank, minus_one);
- auto k_next_dim = register_new_node<v1::Add>(k_rank, minus_two)->output(0);
- k_rank = register_new_node<v0::Squeeze>(k_rank, zero_i);
- auto minus_inf =
- register_new_node(v0::Constant::create(element::f32, Shape{}, {-std::numeric_limits<float>::infinity()}))
- ->output(0);
- auto keep_dim_last = register_new_node<v0::Squeeze>(k_next_dim, zero_i);
- auto k_dims_before_transpose = register_new_node<v4::Range>(zero_i, keep_dim_last, one_i, element::i32);
-
- auto scaled_atten = register_new_node<v0::MatMul>(q_scaled, key, false, true)->output(0);
- minus_inf = register_new_node<v1::ConvertLike>(minus_inf, scaled_atten);
-
- if (node->get_causal() || node->get_input_size() > 3) {
- Output<Node> mask;
- Output<Node> atten_mask;
- if (!node->get_causal()) {
- mask = node->input_value(3);
-
- // two types of masks are supported. A boolean mask where a value of True indicates that the element
- // should take part in attention. A float mask of the same type as query, key, value that is added to
- // the attention score.
- if (mask.get_element_type() == element::boolean) {
- atten_mask = register_new_node<v1::Select>(mask, zero_f, minus_inf);
- } else {
- atten_mask = mask;
- }
- } else {
- auto target_s_len = register_new_node<v8::Gather>(q_shape, minus_two, zero_i);
- auto source_s_len = register_new_node<v8::Gather>(k_shape, minus_two, zero_i);
- auto ssl = register_new_node<v0::Unsqueeze>(source_s_len, zero_i);
- auto tsl = register_new_node<v0::Unsqueeze>(target_s_len, zero_i);
- auto mask_shape = register_new_node<v0::Concat>(OutputVector{tsl, ssl}, 0);
- mask = register_new_node<v1::Broadcast>(minus_inf, mask_shape);
- auto horizontal_range =
- register_new_node<v4::Range>(zero_i, source_s_len, one_i, element::i32)->output(0);
- horizontal_range = register_new_node<v0::Unsqueeze>(horizontal_range, zero_i);
- auto stop = register_new_node<v1::Add>(target_s_len, one_i);
- auto vertical_range = register_new_node<v4::Range>(one_i, stop, one_i, element::i32)->output(0);
- vertical_range = register_new_node<v0::Unsqueeze>(vertical_range, one_i);
- auto triu = register_new_node<v1::GreaterEqual>(horizontal_range, vertical_range);
- atten_mask = register_new_node<v1::Select>(triu, mask, zero_f);
- }
- if (use_high_precision_on_add) {
- npuw::util::HighPrecisionAttr attr_hp;
- attr_hp.compute_precision_type = ov::element::f32;
- atten_mask.get_rt_info()[npuw::util::HighPrecisionAttr::get_type_info_static()] = attr_hp;
- }
-
- scaled_atten = register_new_node<v1::Add>(scaled_atten, atten_mask);
- }
-
- scaled_atten = register_new_node<v8::Softmax>(scaled_atten, -1);
- auto result = register_new_node<v0::MatMul>(scaled_atten, value);
- result->set_friendly_name(node->get_friendly_name());
- copy_runtime_info(node, get_new_nodes());
- return result;
- }
-};
-
-class AttentionMaskInputPast : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::AttentionMaskInputPast");
-
- AttentionMaskInputPast(std::shared_ptr<ov::Model> model) {
- auto range = opp::wrap_type<ov::op::v4::Range>();
- auto convert1 = opp::wrap_type<ov::op::v0::Convert>({range});
- auto greater = opp::wrap_type<ov::op::v1::Greater>({convert1, opp::any_input()});
- auto convert2 = opp::wrap_type<ov::op::v0::Convert>({greater});
-
- register_matcher(std::make_shared<opp::Matcher>(convert2, this->get_type_info().name),
- [model](opp::Matcher& m) {
- auto node = m.get_match_root();
- auto attention_mask =
- std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
- attention_mask->get_output_tensor(0).set_names({"attention_mask"});
- model->add_parameters({attention_mask});
-
- auto cvt =
- std::make_shared<ov::op::v0::Convert>(attention_mask->output(0), ov::element::f32);
- ov::replace_node(node, cvt);
- return false;
- });
- }
-};
-
-class AttentionMaskInputPast_2 : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::AttentionMaskInputPast_2");
-
- AttentionMaskInputPast_2(std::shared_ptr<ov::Model> model) {
- auto range = opp::wrap_type<ov::op::v4::Range>();
- auto unsqueeze1 = opp::wrap_type<ov::op::v0::Unsqueeze>({range, opp::any_input()});
- auto unsqueeze2 = opp::wrap_type<ov::op::v0::Unsqueeze>({unsqueeze1, opp::any_input()});
- auto unsqueeze3 = opp::wrap_type<ov::op::v0::Unsqueeze>({unsqueeze2, opp::any_input()});
- auto opt_convert = opp::optional<ov::op::v0::Convert>({unsqueeze3->output(0)});
- auto lessequal = opp::wrap_type<ov::op::v1::LessEqual>({opt_convert, opp::any_input()});
-
- register_matcher(
- std::make_shared<opp::Matcher>(lessequal, this->get_type_info().name),
- [model](opp::Matcher& m) {
- auto node = m.get_match_root();
- auto attention_mask =
- std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{1, -1});
- attention_mask->get_output_tensor(0).set_names({"attention_mask"});
- model->add_parameters({attention_mask});
-
- auto cst_0 = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, 0);
- auto cst_1 = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, 1);
- auto cst_2 = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, 2);
-
- auto attn_mask_shape =
- std::make_shared<ov::op::v3::ShapeOf>(attention_mask, ov::element::i64)->output(0);
- auto gather = std::make_shared<ov::op::v8::Gather>(attn_mask_shape, cst_1, cst_0)->output(0);
- auto attn_mask_size_minus_one = std::make_shared<ov::op::v1::Subtract>(gather, cst_1)->output(0);
- auto slice = std::make_shared<ov::op::v8::Slice>(attention_mask->output(0),
- cst_0,
- attn_mask_size_minus_one,
- cst_1,
- cst_1);
-
- auto unsqueeze_1 = std::make_shared<ov::op::v0::Unsqueeze>(slice->output(0), cst_1->output(0));
- auto unsqueeze_2 = std::make_shared<ov::op::v0::Unsqueeze>(unsqueeze_1->output(0), cst_2->output(0));
-
- auto equal = std::make_shared<ov::op::v1::Equal>(unsqueeze_2->output(0), cst_0->output(0));
-
- ov::replace_node(node, equal);
- return false;
- });
- }
-};
-
-class AttentionMaskInput : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::AttentionMaskInput");
-
- AttentionMaskInput(std::shared_ptr<ov::Model> model,
- const uint32_t& max_prompt_len,
- const uint32_t& lhs_seq_size,
- bool transform_cross_attn) {
- std::vector<std::shared_ptr<ov::Node>> self_attn_nodes;
- std::vector<std::shared_ptr<ov::Node>> cross_attn_nodes;
- const auto kAttnMaskPort = 3;
- for (auto node : model->get_ops()) {
- if (ov::is_type<ov::op::v13::ScaledDotProductAttention>(node)) {
- if (node->inputs().size() > kAttnMaskPort &&
- ov::is_type<ov::op::v8::Slice>(node->input(kAttnMaskPort).get_source_output().get_node())) {
- self_attn_nodes.push_back(node);
- } else {
- cross_attn_nodes.push_back(node);
- }
- }
- }
-
- // Self-attention
- OPENVINO_ASSERT(!self_attn_nodes.empty());
-
- auto attention_mask = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
- attention_mask->get_output_tensor(0).set_names({"attention_mask"});
- model->add_parameters({attention_mask});
-
- auto cst_ninf = std::make_shared<ov::op::v0::Constant>(ov::element::f32,
- ov::Shape{1},
- std::vector<float>{-std::numeric_limits<float>::max()});
- auto cst_1 = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{1}, std::vector<float>{1});
- auto cst_0 = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{1}, std::vector<float>{0});
-
- auto slice = self_attn_nodes[0]->input(kAttnMaskPort).get_source_output().get_node_shared_ptr();
- std::shared_ptr<ov::Node> slice_f32;
- if (slice->get_element_type() == ov::element::boolean) {
- slice_f32 = std::make_shared<ov::op::v1::Select>(slice->output(0), cst_0->output(0), cst_ninf->output(0));
- } else {
- slice_f32 = slice;
- }
- auto cvt = std::make_shared<ov::op::v0::Convert>(attention_mask->output(0), ov::element::f32);
- auto add = std::make_shared<ov::op::v1::Add>(slice_f32->output(0), cvt->output(0));
-
- auto trps = std::make_shared<ov::op::v1::Transpose>(
- cvt->output(0),
- ov::op::v0::Constant::create(ov::element::i32, ov::Shape{2}, std::vector<int>{1, 0}));
- auto mtpl = std::make_shared<ov::op::v1::Multiply>(trps->output(0), add->output(0));
-
- auto equal = std::make_shared<ov::op::v1::Equal>(mtpl->output(0), cst_1->output(0));
- auto select = std::make_shared<ov::op::v1::Select>(equal->output(0), cst_0->output(0), cst_ninf->output(0));
-
- for (auto self_attn : self_attn_nodes) {
- self_attn->input(3).replace_source_output(select->output(0));
- }
-
- if (transform_cross_attn) {
- // Cross attn
- OPENVINO_ASSERT(!cross_attn_nodes.empty());
- // FIXME: Should be taken from topology - don't hardcode!!!
- auto shape_cst =
- std::make_shared<ov::op::v0::Constant>(ov::element::i64,
- ov::Shape{2},
- std::vector<float>{static_cast<float>(max_prompt_len), 1});
- auto target_shape = std::make_shared<ov::op::v0::Constant>(
- ov::element::i64,
- ov::Shape{2},
- std::vector<float>{static_cast<float>(max_prompt_len), static_cast<float>(lhs_seq_size)});
- // FIXME: Must be transpose if batch present
- auto reshape = std::make_shared<ov::op::v1::Reshape>(cvt->output(0), shape_cst->output(0), false);
- auto equal = std::make_shared<ov::op::v1::Equal>(reshape->output(0), cst_1->output(0));
- auto select = std::make_shared<ov::op::v1::Select>(equal->output(0), cst_0->output(0), cst_ninf->output(0));
- auto broadcast = std::make_shared<ov::op::v3::Broadcast>(select->output(0), target_shape->output(0));
- auto unsq1 = std::make_shared<ov::op::v0::Unsqueeze>(broadcast->output(0), cst_0->output(0));
- auto unsq2 = std::make_shared<ov::op::v0::Unsqueeze>(unsq1->output(0), cst_1->output(0));
- for (auto cross_attn_node : cross_attn_nodes) {
- if (cross_attn_node->inputs().size() == 3) {
- auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(
- cross_attn_node->input(0).get_source_output(),
- cross_attn_node->input(1).get_source_output(),
- cross_attn_node->input(2).get_source_output(),
- unsq2->output(0),
- false);
- ov::replace_node(cross_attn_node, sdpa);
- } else {
- cross_attn_node->input(3).replace_source_output(unsq2->output(0));
- }
- }
- }
- }
-};
-
-class CachePositionInput : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::CachePositionInput");
-
- CachePositionInput(std::shared_ptr<ov::Model> model) {
- auto gather = opp::wrap_type<ov::op::v8::Gather>({opp::any_input(), opp::any_input(), opp::any_input()});
- auto add = opp::wrap_type<ov::op::v1::Add>({gather, opp::any_input()});
- auto range = opp::wrap_type<ov::op::v4::Range>({gather, add, opp::any_input()});
- auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({range, opp::any_input()});
- auto tile = opp::wrap_type<ov::op::v0::Tile>({unsqueeze, opp::any_input()});
-
- register_matcher(
- std::make_shared<opp::Matcher>(tile, this->get_type_info().name),
- [model, unsqueeze](opp::Matcher& m) {
- auto& node_to_output = m.get_pattern_value_map();
- auto unsqueeze_node = node_to_output.at(unsqueeze).get_node_shared_ptr();
- auto matched_unsqueeze = std::static_pointer_cast<ov::op::v0::Unsqueeze>(unsqueeze_node);
-
- auto cache_position = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1});
- cache_position->get_output_tensor(0).set_names({"cache_position"});
- cache_position->set_friendly_name("cache_position");
- model->add_parameters({cache_position});
- std::shared_ptr<ov::Node> cache_pos_unsqueeze_arg;
- if (matched_unsqueeze->input(0).get_element_type() == ov::element::f32) {
- cache_pos_unsqueeze_arg = std::make_shared<ov::op::v0::Convert>(cache_position, ov::element::f32);
- } else {
- cache_pos_unsqueeze_arg = cache_position;
- }
-
- matched_unsqueeze->input(0).replace_source_output(cache_pos_unsqueeze_arg->output(0));
- return false;
- });
- }
-};
-} // namespace
-
-#ifdef __GNUC__
-# pragma GCC diagnostic pop
-#endif
-
bool ov::npuw::util::has_input(const std::shared_ptr<ov::Model>& model, const std::string& name) {
auto inputs = model->inputs();
auto it = std::find_if(inputs.begin(), inputs.end(), [&](const auto& port) {
@@ -513,317 +11,3 @@ bool ov::npuw::util::has_input(const std::shared_ptr<ov::Model>& model, const st
});
return it != inputs.end();
}
-
-bool ov::npuw::util::OptimizeValueTensors::run_on_model(const std::shared_ptr<ov::Model>& model) {
- ov::pass::GraphRewrite rewr;
-
- // Check if any SDPA has sink input
- bool has_sdpa_with_sink = false;
- for (const auto& op : model->get_ops()) {
- if (auto sdpa = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(op)) {
- if (sdpa->get_input_size() == 6) {
- has_sdpa_with_sink = true;
- break;
- }
- }
- }
-
- if (has_sdpa_with_sink) {
- // TODO: evaluate performance by older npu-drivers
- rewr.add_matcher<ov::pass::ScaledDotProductAttentionDecomposition>();
- } else {
- rewr.add_matcher<ScaledDotProductAttentionDecomposition>(m_is_prefill);
- }
-
- TransposeValueTensors::Context ctx;
- rewr.add_matcher<TransposeValueTensors_MHA>(std::ref(ctx));
- rewr.add_matcher<TransposeValueTensors_GQA>(std::ref(ctx));
- rewr.run_on_model(model);
-
- ov::pass::Validate().run_on_model(model);
-
- // NB: matmul parameters gets transposed, if pass applied
- return ctx.bTransposed;
-}
-
-namespace {
-auto remove_encoder_attn_read_value(const std::shared_ptr<ov::Node>& rv_node,
- const ov::Output<ov::Node>& kv_out,
- const ov::Input<ov::Node>& sdpa_in) {
- // Find Assign node
- OPENVINO_ASSERT(rv_node->outputs().size() == 1);
- auto rv_out = rv_node->outputs()[0];
- ov::NodeVector rv_readers;
- for (const auto& target_in : rv_out.get_target_inputs()) {
- rv_readers.push_back(target_in.get_node()->shared_from_this());
- }
- // Assign and SDPA
- OPENVINO_ASSERT(rv_readers.size() == 2);
- auto assign_node = (strstr(rv_readers[0]->get_type_name(), "Assign") != nullptr) ? rv_readers[0] : rv_readers[1];
- OPENVINO_ASSERT(strstr(assign_node->get_type_name(), "Assign") != nullptr);
- // Redirect KV-cache tensor to SDPA
- sdpa_in.replace_source_output(kv_out);
- return std::make_pair(std::make_shared<ov::op::v0::Result>(kv_out),
- ov::as_type_ptr<ov::op::v6::Assign>(assign_node));
-}
-
-std::string transform_key_value_name(std::string input_string,
- std::string prefix,
- std::string enc_or_dec,
- std::string key_or_value) {
- std::regex pattern("[0-9]+");
- std::smatch match;
- std::regex_search(input_string, match, pattern);
-
- if (match.empty())
- OPENVINO_THROW("Input string does not match the expected pattern");
-
- auto number = std::string(match[0]);
- return prefix + "." + number + enc_or_dec + key_or_value;
-}
-
-void set_name(std::shared_ptr<ov::Node> result, const std::string& name) {
- result->set_friendly_name(name);
- result->get_output_tensor(0).set_names({name});
-}
-
-bool is_fake_cvt_to_key_tensor(const ov::Input<ov::Node>& reader) {
- auto fc_reader = reader.get_node()->outputs()[0].get_target_inputs();
- // FakeConvert node has only 1 consumer
- OPENVINO_ASSERT(fc_reader.size() == 1);
- // FakeConvert -> SDPA : 'key' tensor is input with index 1 to SDPA
- return fc_reader.begin()->get_index() == 1;
-}
-
-void expose_runtime_states_as_outputs(const std::shared_ptr<ov::Model>& model) {
- // Find all ReadValue nodes
- ov::NodeVector read_value_nodes;
- for (const auto& op : model->get_ops()) {
- if (strstr(op->get_type_name(), "ReadValue") != nullptr) {
- read_value_nodes.push_back(op);
- }
- }
-
- // Holds result layers for cross-attn KV-cache tensors
- ov::ResultVector results;
- ov::SinkVector assigns;
-
- // Go through all ReadValue nodes and remove them
- for (const auto& rv_node : read_value_nodes) {
- OPENVINO_ASSERT(rv_node->inputs().size() == 1);
- OPENVINO_ASSERT(rv_node->outputs().size() == 1);
- auto rv_in = rv_node->inputs()[0];
- auto x = rv_in.get_source_output();
- auto rv_out = rv_node->outputs()[0];
- // Gather all nodes that read from ReadValue, there must be SDPA and Assign
- auto rv_readers = rv_out.get_target_inputs();
- OPENVINO_ASSERT(rv_readers.size() == 2);
- // Input port for SDPA node
- for (const auto& reader : rv_readers) {
- bool is_fake_cvt = strstr(reader.get_node()->get_type_name(), "FakeConvert") != nullptr;
- if (strstr(reader.get_node()->get_type_name(), "ScaledDotProductAttention") != nullptr || is_fake_cvt) {
- auto sdpa_in = reader;
-
- // In case there's additional FakeConvert node(fp8): ReadValue -> FakeConvert -> SDPA
- auto is_fc_key_tensor = is_fake_cvt ? is_fake_cvt_to_key_tensor(reader) : false;
-
- // Remove ReadValue, store new Result and Assign
- auto key_or_value = (sdpa_in.get_index() == 1 || is_fc_key_tensor) ? "key" : "value";
- auto [result, assign] = remove_encoder_attn_read_value(rv_node, rv_in.get_source_output(), sdpa_in);
- auto normalized_name =
- transform_key_value_name(rv_node->inputs()[0].get_source_output().get_node()->get_friendly_name(),
- "present",
- ".encoder.",
- key_or_value);
- set_name(result, normalized_name);
- results.push_back(result);
- assigns.push_back(assign);
- }
- }
- }
-
- // Add, remove, validate
- model->add_results(results);
- for (const auto& assign : assigns) {
- model->remove_sink(assign);
- }
- model->validate_nodes_and_infer_types();
-}
-
-void remove_cache_position(const std::shared_ptr<ov::Model>& model) {
- // Build subgraph that will replace cache_pos
- auto input_ids = model->input("input_ids").get_node();
- auto shape_of_node = std::make_shared<ov::op::v3::ShapeOf>(input_ids->outputs()[0]);
-
- std::vector<int> v_0{0};
- std::vector<int> v_1{1};
-
- auto indices = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, v_1);
- indices->set_friendly_name("indices");
- auto axis = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, v_0);
- axis->set_friendly_name("axis");
-
- auto gather_node = std::make_shared<ov::op::v8::Gather>(shape_of_node->outputs()[0], indices, axis);
-
- auto cst_node = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, v_0);
- auto step = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, v_1);
- step->set_friendly_name("step");
- auto range_node = std::make_shared<ov::op::v4::Range>(cst_node->outputs()[0],
- gather_node->outputs()[0],
- step->outputs()[0],
- ov::element::i64);
- // Replace cache_position
- auto cache_pos =
- ov::as_type_ptr<ov::op::v0::Parameter>(model->input("cache_position").get_node()->shared_from_this());
- for (const auto& target_input : cache_pos->outputs()[0].get_target_inputs()) {
- target_input.replace_source_output(range_node->outputs()[0]);
- }
-
- model->remove_parameter(cache_pos);
- model->validate_nodes_and_infer_types();
-}
-
-void expose_runtime_states_as_inputs(const std::shared_ptr<ov::Model>& model) {
- // Store Assign nodes to perform remove_sink later on
- ov::SinkVector assigns;
- // To add new Params to the model
- ov::ParameterVector params;
-
- ov::NodeVector read_value_nodes;
- for (const auto& op : model->get_ops()) {
- if (strstr(op->get_type_name(), "ReadValue") != nullptr) {
- read_value_nodes.push_back(op);
- }
- }
-
- for (const auto& rv_node : read_value_nodes) {
- auto rv_out = rv_node->outputs()[0];
- auto rv_readers = rv_out.get_target_inputs();
- for (auto rv_reader : rv_readers) {
- bool is_fake_cvt = strstr(rv_reader.get_node()->get_type_name(), "FakeConvert") != nullptr;
- if (strstr(rv_reader.get_node()->get_type_name(), "Assign") != nullptr) {
- auto assign_node = ov::as_type_ptr<ov::op::v6::Assign>(rv_reader.get_node()->shared_from_this());
- assigns.push_back(assign_node);
- } else if (strstr(rv_reader.get_node()->get_type_name(), "ScaledDotProductAttention") != nullptr ||
- is_fake_cvt) {
- auto sdpa_in = rv_reader;
-
- auto shape = rv_node->get_output_partial_shape(0);
- auto new_param = std::make_shared<ov::op::v0::Parameter>(rv_node->get_output_element_type(0), shape);
-
- // In case there's additional FakeConvert node(fp8): ReadValue -> FakeConvert -> SDPA
- auto is_fc_key_tensor = is_fake_cvt ? is_fake_cvt_to_key_tensor(rv_reader) : false;
-
- auto key_or_value = (sdpa_in.get_index() == 1 || is_fc_key_tensor) ? "key" : "value";
- auto normalized_name = transform_key_value_name(sdpa_in.get_node()->get_friendly_name(),
- "past_key_values",
- ".encoder.",
- key_or_value);
- set_name(new_param, normalized_name);
-
- params.push_back(new_param);
- sdpa_in.replace_source_output(new_param->outputs()[0]);
- }
- }
- }
-
- // Remove sinks and add new params
- model->add_parameters(params);
- for (const auto& assign : assigns) {
- model->remove_sink(assign);
- }
-}
-
-void normalize_input_key_value_names(const std::shared_ptr<ov::Model>& model) {
- ov::ResultVector new_results, old_results;
- for (const auto& in : model->inputs()) {
- if (in.get_any_name().find("decoder") == std::string::npos) {
- continue;
- }
-
- auto key_or_value = (in.get_any_name().find(".key") != std::string::npos) ? "key" : "value";
- auto normalized_name =
- transform_key_value_name(in.get_any_name(), "past_key_values", ".decoder.", key_or_value);
- set_name(in.get_node_shared_ptr(), normalized_name);
- }
-
- model->validate_nodes_and_infer_types();
-}
-
-void normalize_output_key_value_names(const std::shared_ptr<ov::Model>& model) {
- ov::ResultVector new_results, old_results;
- for (const auto& out : model->outputs()) {
- if (out.get_any_name().find("decoder") == std::string::npos) {
- continue;
- }
-
- auto key_or_value = (out.get_any_name().find(".key") != std::string::npos) ? "key" : "value";
- auto normalized_name = transform_key_value_name(out.get_any_name(), "present", ".decoder.", key_or_value);
- set_name(out.get_node_shared_ptr(), normalized_name);
- }
-
- model->validate_nodes_and_infer_types();
-}
-
-void add_attention_mask_input(const std::shared_ptr<ov::Model>& model,
- const uint32_t& max_prompt_size = 0,
- const uint32_t& lhs_seq_size = 0,
- bool transform_cross_attn = false) {
- ov::pass::GraphRewrite rewr;
- if (transform_cross_attn) {
- rewr.add_matcher<AttentionMaskInput>(model, max_prompt_size, lhs_seq_size, transform_cross_attn);
- } else {
- rewr.add_matcher<AttentionMaskInputPast>(model);
- rewr.add_matcher<AttentionMaskInputPast_2>(model); // transformers>=4.53
- }
-
- rewr.run_on_model(model);
-
- ov::pass::Validate().run_on_model(model);
-}
-
-void add_cache_position_input(const std::shared_ptr<ov::Model>& model) {
- ov::pass::GraphRewrite rewr;
- rewr.add_matcher<CachePositionInput>(model);
- rewr.run_on_model(model);
-
- ov::pass::Validate().run_on_model(model);
-}
-} // namespace
-
-bool ov::npuw::util::PrepareWhisperPrefillModel::run_on_model(const std::shared_ptr<ov::Model>& model) {
- // 2) Remove all non-runtime states from inputs (they empty on first iteration)
- // remove_input_kv_tensors(model); -> Done for LLM also
- // 3) Expose all states that requires initialization on the first run as outputs
- expose_runtime_states_as_outputs(model);
- // 4) Remove cache_position input if it exists
- if (has_input(model, "cache_position")) {
- remove_cache_position(model);
- }
- // 5) Normalize output names - should be done in stateful_to_stateless_transformation
- normalize_output_key_value_names(model);
-
- add_attention_mask_input(model, m_max_prompt_size, m_lhs_seq_size, true);
-
- model->validate_nodes_and_infer_types();
-
- return true;
-}
-
-bool ov::npuw::util::PrepareWhisperKVCacheModel::run_on_model(const std::shared_ptr<ov::Model>& model) {
- normalize_input_key_value_names(model);
- normalize_output_key_value_names(model);
- expose_runtime_states_as_inputs(model);
-
- if (!has_input(model, "cache_position")) {
- add_cache_position_input(model);
- }
-
- add_attention_mask_input(model);
-
- model->reshape({{"input_ids", ov::PartialShape({-1, 1})}});
-
- model->validate_nodes_and_infer_types();
-
- return true;
-}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp
index 3ce5b9934be..e973f585c18 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp
@@ -25,38 +25,6 @@ public:
bool has_input(const std::shared_ptr<ov::Model>& model, const std::string& name);
-// SDPA-unroll and transpose transformations
-class OptimizeValueTensors : public ov::pass::ModelPass {
- bool m_is_prefill;
-
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::OptimizeValueTensors");
- explicit OptimizeValueTensors(bool is_prefill) : m_is_prefill(is_prefill) {}
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
-};
-
-class PrepareWhisperPrefillModel : public ov::pass::ModelPass {
- uint32_t m_max_prompt_size;
- uint32_t m_lhs_seq_size;
-
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::PrepareWhisperPrefillModel");
- explicit PrepareWhisperPrefillModel(uint32_t max_prompt_size, uint32_t lhs_seq_size)
- : m_max_prompt_size(max_prompt_size),
- m_lhs_seq_size(lhs_seq_size) {}
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
-};
-
-class PrepareWhisperKVCacheModel : public ov::pass::ModelPass {
-public:
- OPENVINO_MODEL_PASS_RTTI("ov::npuw::PrepareWhisperKVCacheModel");
- PrepareWhisperKVCacheModel() = default;
-
- bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
-};
-
// clang-format off
} // namespace ov
// clang-format on
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/apply_moe_device_routed_transforms.cpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/apply_moe_device_routed_transforms.cpp
new file mode 100644
index 00000000000..be2918ee7ca
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/apply_moe_device_routed_transforms.cpp
@@ -0,0 +1,36 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "apply_moe_device_routed_transforms.hpp"
+
+#include "../logging.hpp"
+#include "../moe_transformations/device_routed_moe_transform.hpp"
+#include "../moe_transformations/gather_to_2d_gather.hpp"
+
+namespace {
+
+// Apply DEVICE_ROUTED MoE transformations to models
+void apply_moe_device_routed_transforms(const std::shared_ptr<ov::Model>& model) {
+ ov::npuw::pass::DeviceRoutedMoETransform moe_transform;
+ ov::npuw::pass::GatherTo2DGather gather_transform;
+
+ moe_transform.run_on_model(model);
+ LOG_DEBUG(" Applied DEVICE_ROUTED transformations to model variant");
+
+ // Apply Gather to 2D Gather transformation for HW optimization
+ gather_transform.run_on_model(model);
+ LOG_DEBUG(" Applied GatherTo2DGather transformation to model variant");
+}
+
+} // namespace
+
+namespace ov::npuw {
+
+bool ApplyMoEDeviceRoutedTransforms::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ apply_moe_device_routed_transforms(model);
+
+ return true;
+}
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/apply_moe_device_routed_transforms.hpp b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/apply_moe_device_routed_transforms.hpp
new file mode 100644
index 00000000000..2b68e6db663
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/apply_moe_device_routed_transforms.hpp
@@ -0,0 +1,19 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+// Apply DEVICE_ROUTED MoE transformations to models
+class ApplyMoEDeviceRoutedTransforms : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::ApplyMoEDeviceRoutedTransforms");
+ ApplyMoEDeviceRoutedTransforms() = default;
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.cpp
new file mode 100644
index 00000000000..d21698635ca
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.cpp
@@ -0,0 +1,145 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "convert_kvcache_to_precision.hpp"
+
+#include "../logging.hpp"
+#include "low_precision/concat.hpp"
+#include "low_precision/kv_cache_concat.hpp"
+#include "low_precision/low_precision.hpp"
+#include "low_precision/move_fake_convert_up_through_kv_cache_concat.hpp"
+#include "openvino/core/preprocess/pre_post_process.hpp"
+#include "openvino/op/ops.hpp"
+#include "openvino/opsets/opset13.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/pass/manager.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "ov_ops/type_relaxed.hpp"
+#include "transformations/op_conversions/fake_convert_decomposition.hpp"
+
+namespace opp = ov::pass::pattern;
+
+namespace {
+
+class FakeConvertDestinationTypeExtractor : public ov::pass::MatcherPass {
+public:
+ FakeConvertDestinationTypeExtractor(std::set<ov::element::Type>& fcDestinationTypes) {
+ auto fake_convert_m = opp::wrap_type<ov::op::v13::FakeConvert>();
+
+ ov::matcher_pass_callback callback = [=, &fcDestinationTypes](opp::Matcher& m) {
+ const auto& pattern_to_output = m.get_pattern_value_map();
+ const auto fake_convert =
+ ov::as_type_ptr<ov::op::v13::FakeConvert>(pattern_to_output.at(fake_convert_m).get_node_shared_ptr());
+
+ if (fake_convert == nullptr) {
+ return false;
+ }
+ fcDestinationTypes.insert(fake_convert->get_destination_element_type());
+ return true;
+ };
+ register_matcher(std::make_shared<opp::Matcher>(fake_convert_m, "FakeConvertDestinationTypeExtractor"),
+ callback);
+ }
+};
+
+class ConvertTypeRelaxedToRegular : public ov::pass::MatcherPass {
+public:
+ ConvertTypeRelaxedToRegular() {
+ auto pattern = opp::wrap_type<ov::op::TypeRelaxed<ov::op::v1::Multiply>>();
+
+ ov::matcher_pass_callback callback = [](opp::Matcher& m) {
+ auto tr_mul = std::dynamic_pointer_cast<ov::op::TypeRelaxed<ov::opset1::Multiply>>(m.get_match_root());
+ if (tr_mul) {
+ auto new_mul = std::make_shared<ov::opset1::Multiply>(tr_mul->input_value(0), tr_mul->input_value(1));
+ new_mul->set_friendly_name(tr_mul->get_friendly_name());
+ ov::copy_runtime_info(tr_mul, new_mul);
+ ov::replace_node(tr_mul, new_mul);
+ }
+ return true;
+ };
+
+ register_matcher(std::make_shared<opp::Matcher>(pattern, "ConvertTypeRelaxedToRegular"), callback);
+ }
+};
+
+std::shared_ptr<ov::Model> cvt_kvcache_to_low_precision(const std::shared_ptr<ov::Model>& model,
+ const ov::element::Type lptype) {
+ ov::preprocess::PrePostProcessor ppp(model);
+
+ for (const auto& tensor : model->inputs()) {
+ if (tensor.get_any_name().find("past_key") != std::string::npos) {
+ ppp.input(tensor.get_any_name()).tensor().set_element_type(lptype);
+ }
+ }
+
+ for (const auto& tensor : model->outputs()) {
+ if (tensor.get_any_name().find("present") != std::string::npos) {
+ ppp.output(tensor.get_any_name()).tensor().set_element_type(lptype);
+ }
+ }
+
+ return ppp.build();
+}
+
+} // namespace
+
+namespace ov {
+namespace npuw {
+
+ov::element::Type optimize_kv_cache_storage(const std::shared_ptr<ov::Model>& model) {
+ LOG_DEBUG("Running FP8 static quantization on model: " << model->get_name());
+
+ auto kv_kache_storage_type = ov::element::f16;
+
+ ov::pass::low_precision::LayerTransformation::Params params;
+ std::set<ov::element::Type> fcTypesInput, fcTypesRemained;
+
+ ov::pass::Manager manager("optimize_fp8");
+ params.defaultPrecisions = ov::pass::low_precision::precision_set::get_fp8_support();
+ manager.register_pass<FakeConvertDestinationTypeExtractor>(fcTypesInput);
+ manager.register_pass<ov::pass::low_precision::MoveFakeConvertUpThroughKVCacheConcat>();
+ auto graph_rewrite = manager.register_pass<ov::pass::GraphRewrite>();
+ graph_rewrite->add_matcher<ov::pass::FakeConvertDecomposition>();
+ graph_rewrite->add_matcher<ov::pass::low_precision::ConcatTransformation>(params);
+ graph_rewrite->add_matcher<ov::pass::low_precision::KVCacheConcat>(model);
+ manager.register_pass<ConvertTypeRelaxedToRegular>();
+ manager.register_pass<FakeConvertDestinationTypeExtractor>(fcTypesRemained);
+ manager.run_passes(model);
+ if (fcTypesInput.empty()) {
+ LOG_WARN("FakeConvert layers not detected - leaving kv-cache in " << kv_kache_storage_type << " precision");
+ } else if (!fcTypesRemained.empty()) {
+ LOG_WARN(fcTypesRemained.size() << " FakeConvert layers not decomposed - leaving kv-cache in "
+ << kv_kache_storage_type << " precision");
+ } else if (fcTypesInput.size() > 1) {
+ auto it2 = std::next(fcTypesInput.begin(), 1);
+ LOG_WARN("FakeConvert layers had several precisions (" << fcTypesInput.size() << ")-" << *fcTypesInput.begin()
+ << ", " << *it2 << ", ... "
+ << "supported only single precision");
+ LOG_WARN("Leaving KV-cache in " << kv_kache_storage_type << " precision");
+ } else {
+ kv_kache_storage_type = *fcTypesInput.begin();
+ LOG_DEBUG("KV cache storage precision changed to " << kv_kache_storage_type);
+ }
+ return kv_kache_storage_type;
+}
+
+} // namespace npuw
+} // namespace ov
+
+namespace ov::npuw {
+
+ConvertKVCacheToPrecision::ConvertKVCacheToPrecision(const ov::element::Type lptype) : m_lp_type(lptype) {}
+
+bool ConvertKVCacheToPrecision::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ auto ppp_result = cvt_kvcache_to_low_precision(model, m_lp_type);
+ // PrePostProcessor currently always modifies the model in-place and returns the same model pointer, but let's
+ // be defensive here and check it just in case
+ OPENVINO_ASSERT(ppp_result == model,
+ "PrePostProcessor should not create a new model, but returned a different one.");
+
+ return true;
+}
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.hpp
new file mode 100644
index 00000000000..6ebb1a8a0a2
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.hpp
@@ -0,0 +1,24 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/core/model.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+ov::element::Type optimize_kv_cache_storage(const std::shared_ptr<ov::Model>& model);
+
+class ConvertKVCacheToPrecision : public ov::pass::ModelPass {
+ ov::element::Type m_lp_type;
+
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::ConvertKVCacheToPrecision");
+ explicit ConvertKVCacheToPrecision(const ov::element::Type lptype);
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/decompose_gqa.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/decompose_gqa.cpp
new file mode 100644
index 00000000000..1eae5f40887
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/decompose_gqa.cpp
@@ -0,0 +1,279 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "decompose_gqa.hpp"
+
+#include "openvino/core/graph_util.hpp"
+#include "openvino/op/group_query_attention.hpp"
+#include "openvino/op/ops.hpp"
+#include "openvino/op/range.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+
+namespace opp = ov::pass::pattern;
+
+namespace {
+
+// diagnostics warnings on OPENVINO_MATCHER_PASS_RTTI() definition: visibility hidden
+#ifdef __GNUC__
+# pragma GCC diagnostic push
+# pragma GCC diagnostic ignored "-Wattributes"
+#endif
+
+class GroupQueryAttentionDecomposition : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::GroupQueryAttentionDecomposition");
+ GroupQueryAttentionDecomposition(bool is_prefill_model) {
+ auto pattern_node = opp::wrap_type<ov::op::internal::GroupQueryAttention>();
+
+ ov::matcher_pass_callback callback = [=](opp::Matcher& m) {
+ auto& pattern_to_output = m.get_pattern_value_map();
+ auto node = ov::as_type_ptr<ov::op::internal::GroupQueryAttention>(
+ pattern_to_output.at(pattern_node).get_node_shared_ptr());
+
+ if (node == nullptr || transformation_callback(node)) {
+ return false;
+ }
+
+ auto new_output_node = decompose(node, is_prefill_model);
+ ov::replace_node(node, new_output_node);
+ return true;
+ };
+
+ auto m = std::make_shared<opp::Matcher>(pattern_node, "GroupQueryAttentionDecomposition");
+ register_matcher(m, std::move(callback));
+ }
+
+ ov::OutputVector decompose(std::shared_ptr<ov::op::internal::GroupQueryAttention> node, bool is_prefill_model) {
+ using namespace ov::op;
+ using namespace ov;
+
+ const auto num_heads = node->get_num_heads();
+ const auto kv_num_heads = node->get_kv_num_heads();
+ const auto scale = node->get_scale();
+ const auto do_rotary = node->get_do_rotary();
+ const auto rotary_interleaved = node->get_rotary_interleaved();
+ // TODO: add softcap support
+
+ auto Q = node->input_value(0);
+ auto K = node->input_value(1);
+ auto V = node->input_value(2);
+ auto past_key = node->input_value(3);
+ auto past_value = node->input_value(4);
+ auto seqlens_k = node->input_value(5);
+ auto total_sequence_length = node->input_value(6);
+ auto cos_cache = node->input_value(7);
+ auto sin_cache = node->input_value(8);
+
+ // The length of all tokens (past + current) is `seqlens_k` + 1.
+ // current = Q.shape[2], past = `seqlens_k` + 1 - current
+
+ const auto T = Q.get_element_type();
+ const auto q_shape = register_new_node<v3::ShapeOf>(Q);
+ const auto current_seqlen = get_dimensions(q_shape, {2});
+ const auto head_size_node = get_dimensions(q_shape, {3});
+
+ const auto zero = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}));
+ const auto zero_without_shape = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {0}));
+ const auto one = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}));
+ const auto one_without_shape = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {1}));
+ const auto two = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{1}, {2}));
+ const auto seqlens_elemi64 = register_new_node<v0::Convert>(seqlens_k, ov::element::i64);
+ const auto real_seqlens = register_new_node<v1::Add>(seqlens_elemi64, one);
+
+ // Only consider batch is 1
+ const auto seqlens_1d = register_new_node<v1::Reshape>(real_seqlens, one, false);
+ const auto past_seqlen = register_new_node<v1::Subtract>(seqlens_1d, current_seqlen);
+ const auto curr_seqlen_scalar = register_new_node<v0::Squeeze>(current_seqlen);
+
+ if (do_rotary) {
+ ov::Output<ov::Node> position_ids = register_new_node<v4::Range>(zero_without_shape,
+ curr_seqlen_scalar,
+ one_without_shape,
+ ov::element::i64);
+ position_ids = register_new_node<v1::Add>(position_ids, past_seqlen);
+
+ const auto cos = register_new_node<v8::Gather>(cos_cache, position_ids, zero);
+ const auto sin = register_new_node<v8::Gather>(sin_cache, position_ids, zero);
+ Q = rotaryEmbedding(Q, cos, sin, rotary_interleaved);
+ K = rotaryEmbedding(K, cos, sin, rotary_interleaved);
+ }
+
+ auto construct_kv_cache = [&](const ov::Output<ov::Node>& past, const ov::Output<ov::Node>& current) {
+ return register_new_node<v0::Concat>(ov::OutputVector{past, current}, 2);
+ };
+ K = construct_kv_cache(past_key, K);
+ V = construct_kv_cache(past_value, V);
+
+ ov::Output<ov::Node> present_k = K;
+ ov::Output<ov::Node> present_v = V;
+
+ const auto concat_kv_len = get_dimensions(K.get_node_shared_ptr(), {2});
+ const auto concat_kv_len_scalar = register_new_node<v0::Squeeze>(concat_kv_len);
+
+ // Broadcast KV if grouped query attention
+ const size_t kv_num_heads_factor = num_heads / kv_num_heads;
+ if (kv_num_heads_factor > 1) {
+ const auto kv_shape = register_new_node<v3::ShapeOf>(K);
+ const auto kv_shape_prev_2 = get_dimensions(kv_shape, {0, 1});
+ const auto kv_shape_last_2 = get_dimensions(kv_shape, {2, 3});
+ auto new_kv_shape = register_new_node<v0::Concat>(ov::NodeVector{kv_shape_prev_2, one, kv_shape_last_2}, 0);
+ K = register_new_node<v1::Reshape>(K, new_kv_shape, false);
+ V = register_new_node<v1::Reshape>(V, new_kv_shape, false);
+ K = register_new_node<v0::Concat>(ov::OutputVector(kv_num_heads_factor, K), 2);
+ V = register_new_node<v0::Concat>(ov::OutputVector(kv_num_heads_factor, V), 2);
+ const auto q_shape = register_new_node<v3::ShapeOf>(Q);
+ const auto q_shape_prev_2 = get_dimensions(q_shape, {0, 1});
+ auto extended_kv_shape = register_new_node<v0::Concat>(ov::NodeVector{q_shape_prev_2, kv_shape_last_2}, 0);
+ K = register_new_node<v1::Reshape>(K, extended_kv_shape, false);
+ V = register_new_node<v1::Reshape>(V, extended_kv_shape, false);
+ }
+
+ // Make attention mask
+ std::shared_ptr<ov::Node> mask;
+
+ std::shared_ptr<ov::Node> hori_range =
+ register_new_node<v4::Range>(zero_without_shape, concat_kv_len_scalar, one_without_shape, ov::element::i64);
+ hori_range = register_new_node<v0::Unsqueeze>(hori_range, zero);
+
+ std::shared_ptr<ov::Node> vert_range =
+ register_new_node<v4::Range>(zero_without_shape, curr_seqlen_scalar, one_without_shape, ov::element::i64);
+ vert_range = register_new_node<v0::Unsqueeze>(vert_range, one);
+ const auto past_k_node_len = get_dimensions(past_key.get_node_shared_ptr(), {2});
+ vert_range = register_new_node<v1::Add>(vert_range, past_k_node_len);
+
+ const auto triu = register_new_node<v1::Greater>(hori_range, vert_range);
+ const auto typed_zero = register_new_node(v0::Constant::create(T, ov::Shape{}, {0}));
+ // cf. make_attention_mask@src\plugins\intel_gpu\tests\common\subgraphs_builders.hpp
+ std::shared_ptr<ov::Node> minus_inf = nullptr;
+ if (T == ov::element::f32)
+ minus_inf =
+ register_new_node(v0::Constant::create(T, ov::Shape{}, {-std::numeric_limits<float>::infinity()}));
+ else if (T == ov::element::f16)
+ minus_inf =
+ register_new_node(v0::Constant::create(T, ov::Shape{}, {std::numeric_limits<ov::float16>::lowest()}));
+ mask = register_new_node<v1::Select>(triu, minus_inf, typed_zero);
+
+ if (is_prefill_model) {
+ // prefill model
+ const auto padding_len = register_new_node<v1::Subtract>(concat_kv_len, seqlens_1d);
+ const auto padding_mask_vert_shape = register_new_node<v0::Concat>(ov::NodeVector{current_seqlen, one}, 0);
+ const auto padding_mask_vert = register_new_node<v3::Broadcast>(padding_len, padding_mask_vert_shape);
+ const auto padding_mask = register_new_node<v1::GreaterEqual>(hori_range, padding_mask_vert);
+ mask = register_new_node<v1::Select>(padding_mask, mask, minus_inf);
+ } else {
+ // kv cache model
+ const auto left_mask = register_new_node<v1::Less>(hori_range, seqlens_elemi64); // first N
+ const auto righ_mask = register_new_node<v1::GreaterEqual>(hori_range, vert_range); // last 1
+ const auto atte_mask = register_new_node<v1::LogicalOr>(left_mask, righ_mask); // [1,1,1,..., 0,0,0,1]
+ mask = register_new_node<v1::Select>(atte_mask, mask, minus_inf);
+ }
+
+ std::shared_ptr<ov::Node> qga_output;
+ if (scale != 0.0f) {
+ auto scale_node = register_new_node(v0::Constant::create(T, Shape{}, {scale}));
+ qga_output = register_new_node<v13::ScaledDotProductAttention>(Q, K, V, mask, scale_node, false);
+ } else {
+ qga_output = register_new_node<v13::ScaledDotProductAttention>(Q, K, V, mask, false);
+ }
+
+ // transpose the result from (batch_size, num_heads, sequence_length, head_size)
+ // to (batch_size, sequence_length, num_heads * head_size)
+ auto perm = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{4}, {0, 2, 1, 3}));
+ auto qga_output_transposed = register_new_node<v1::Transpose>(qga_output, perm);
+ auto dim_merge_shape = register_new_node(v0::Constant::create(ov::element::i32, ov::Shape{3}, {0, 0, -1}));
+ auto output = register_new_node<v1::Reshape>(qga_output_transposed, dim_merge_shape, true)->output(0);
+
+ return {std::move(output), std::move(present_k), std::move(present_v)};
+ }
+
+ // make split functions is a copy-paste from ONNX FE. TODO: move it to one place
+ ov::OutputVector make_split(const ov::Output<ov::Node>& value, int64_t num_splits, int64_t axis) {
+ using namespace ov::op;
+ const auto axis_node = register_new_node(v0::Constant::create(ov::element::i64, ov::Shape{}, {axis}));
+ const auto split = register_new_node<v1::Split>(value, axis_node, num_splits);
+
+ return split->outputs();
+ }
+
+ std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf>& shape,
+ const std::vector<int>& dims) {
+ using namespace ov::op;
+ const auto zero = v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
+ const auto dims_const = v0::Constant::create(ov::element::i32, ov::Shape{dims.size()}, dims);
+ return register_new_node<v8::Gather>(shape, dims_const, zero);
+ }
+
+ std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node>& node, const std::vector<int>& dims) {
+ return get_dimensions(register_new_node<ov::op::v3::ShapeOf>(node), dims);
+ }
+
+ std::shared_ptr<ov::Node> rotaryEmbedding(ov::Output<ov::Node> input,
+ ov::Output<ov::Node> cos,
+ ov::Output<ov::Node> sin,
+ bool interleaved) {
+ using namespace ov::op;
+ auto zero = v0::Constant::create(ov::element::i64, ov::Shape{1}, {0});
+ auto one = v0::Constant::create(ov::element::i64, ov::Shape{1}, {1});
+
+ if (interleaved) {
+ auto two = v0::Constant::create(ov::element::i64, ov::Shape{1}, {2});
+ auto cos_last_dim = get_dimensions(cos.get_node_shared_ptr(), {-1});
+ auto input_shape = register_new_node<v3::ShapeOf>(input);
+ auto dim_bns = get_dimensions(input_shape, {0, 1, 2});
+
+ auto negtive_one = v0::Constant::create(ov::element::i64, ov::Shape{1}, {-1});
+ auto split_input_shape = register_new_node<v0::Concat>(ov::NodeVector{dim_bns, cos_last_dim, two}, 0);
+ auto reshaped_input = register_new_node<v1::Reshape>(input, split_input_shape, false);
+
+ auto in_split = make_split(reshaped_input, 2, -1);
+ split_input_shape = register_new_node<v0::Concat>(ov::NodeVector{dim_bns, cos_last_dim}, 0);
+ auto in_split_0 = register_new_node<v1::Reshape>(in_split[0], split_input_shape, false);
+ auto in_split_1 = register_new_node<v1::Reshape>(in_split[1], split_input_shape, false);
+
+ auto res_0 = register_new_node<v1::Subtract>(register_new_node<v1::Multiply>(in_split_0, cos),
+ register_new_node<v1::Multiply>(in_split_1, sin));
+ auto res_1 = register_new_node<v1::Add>(register_new_node<v1::Multiply>(in_split_0, sin),
+ register_new_node<v1::Multiply>(in_split_1, cos));
+
+ split_input_shape = register_new_node<v0::Concat>(ov::NodeVector{dim_bns, cos_last_dim, one}, 0);
+ auto res_0_5d = register_new_node<v1::Reshape>(res_0, split_input_shape, false);
+ auto res_1_5d = register_new_node<v1::Reshape>(res_1, split_input_shape, false);
+
+ auto concat_ret = register_new_node<v0::Concat>(ov::NodeVector{res_0_5d, res_1_5d}, -1);
+ return register_new_node<v1::Reshape>(concat_ret, input_shape, false);
+ } else {
+ auto in_split = make_split(input, 2, -1);
+ auto res_0 = register_new_node<v1::Subtract>(register_new_node<v1::Multiply>(in_split[0], cos),
+ register_new_node<v1::Multiply>(in_split[1], sin));
+ auto res_1 = register_new_node<v1::Add>(register_new_node<v1::Multiply>(in_split[0], sin),
+ register_new_node<v1::Multiply>(in_split[1], cos));
+
+ return register_new_node<v0::Concat>(ov::NodeVector{res_0, res_1}, -1);
+ }
+ }
+};
+
+#ifdef __GNUC__
+# pragma GCC diagnostic pop
+#endif
+
+bool decompose_GQA(std::shared_ptr<ov::Model> model, bool is_prefill_model) {
+ ov::pass::GraphRewrite rewr;
+ rewr.add_matcher<GroupQueryAttentionDecomposition>(is_prefill_model);
+ return rewr.run_on_model(model);
+}
+
+} // namespace
+
+namespace ov::npuw {
+
+DecomposeGQA::DecomposeGQA(bool is_prefill_model) : m_is_prefill_model(is_prefill_model) {}
+
+bool DecomposeGQA::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ return decompose_GQA(model, m_is_prefill_model);
+}
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/decompose_gqa.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/decompose_gqa.hpp
new file mode 100644
index 00000000000..f0c3afdb8f2
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/decompose_gqa.hpp
@@ -0,0 +1,20 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+class DecomposeGQA : public ov::pass::ModelPass {
+ bool m_is_prefill_model;
+
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::DecomposeGQA");
+ explicit DecomposeGQA(bool is_prefill_model);
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_axes_position.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_axes_position.hpp
new file mode 100644
index 00000000000..fd73fab1f25
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_axes_position.hpp
@@ -0,0 +1,18 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstdint>
+
+namespace ov {
+namespace npuw {
+
+struct KVAxesPosition {
+ uint32_t batch;
+ uint32_t seq_len;
+};
+
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.cpp
new file mode 100644
index 00000000000..d4aff31f5cc
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.cpp
@@ -0,0 +1,68 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "lora_stateful_to_stateless.hpp"
+
+#include "../util.hpp"
+#include "openvino/op/ops.hpp"
+#include "openvino/op/util/assign_base.hpp"
+#include "openvino/op/util/node_util.hpp"
+#include "openvino/op/util/read_value_base.hpp"
+
+namespace {
+
+void convert_stateful_lora_to_stateless(const std::shared_ptr<ov::Model>& model) {
+ typedef std::shared_ptr<ov::op::util::AssignBase> PAssign;
+ typedef std::shared_ptr<ov::op::util::ReadValueBase> PReadValue;
+ std::vector<PReadValue> readValues;
+ std::vector<PAssign> assigns;
+ auto sinks = model->get_sinks();
+ for (size_t i = 0; i < sinks.size(); ++i) {
+ if (auto assign = ov::as_type_ptr<ov::op::util::AssignBase>(sinks[i])) {
+ auto variable_name = assign->get_variable_id();
+ if (!ov::npuw::util::matchLoRAMatMulAString(variable_name) &&
+ !ov::npuw::util::matchLoRAMatMulBString(variable_name) &&
+ !ov::npuw::util::matchLoRAMatMulAlphaString(variable_name)) {
+ continue;
+ }
+
+ auto read_value = ov::as_type_ptr<ov::op::util::ReadValueBase>(assign->get_input_node_shared_ptr(0));
+ OPENVINO_ASSERT(read_value, "Can't find ReadValue");
+ readValues.push_back(read_value);
+ assigns.push_back(assign);
+ }
+ }
+
+ ov::ParameterVector new_parameters;
+ new_parameters.reserve(readValues.size());
+ for (size_t i = 0; i < readValues.size(); ++i) {
+ auto read_value = readValues[i];
+ auto variable_name = read_value->get_variable_id();
+ const auto element_type = read_value->get_output_element_type(0);
+ const auto shape = read_value->get_output_partial_shape(0);
+
+ auto parameter = std::make_shared<ov::op::v0::Parameter>(element_type, shape);
+ ov::op::util::set_name(*parameter, variable_name);
+ replace_node(read_value, parameter);
+
+ auto assign = assigns[i];
+ model->remove_sink(assign);
+ model->remove_variable(model->get_variable_by_id(variable_name));
+ new_parameters.push_back(parameter);
+ }
+
+ model->add_parameters(new_parameters);
+}
+
+} // namespace
+
+namespace ov::npuw {
+
+bool LoraStatefulToStatelessPass::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ convert_stateful_lora_to_stateless(model);
+
+ return true;
+}
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.hpp
new file mode 100644
index 00000000000..bc71f3e4dcc
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.hpp
@@ -0,0 +1,18 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+class LoraStatefulToStatelessPass : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::LoraStatefulToStatelessPass");
+ explicit LoraStatefulToStatelessPass() = default;
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace ov::npuw
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.cpp
new file mode 100644
index 00000000000..5bf43afe500
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cpp
@@ -0,0 +1,339 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "optimize_value_tensors.hpp"
+
+#include <transformations/op_conversions/scaled_dot_product_attention_decomposition.hpp>
+
+#include "../llm_compiled_model_utils.hpp"
+#include "../logging.hpp"
+#include "openvino/core/graph_util.hpp"
+#include "openvino/op/ops.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "openvino/pass/validate.hpp"
+
+namespace opp = ov::pass::pattern;
+
+namespace {
+
+// diagnostics warnings on OPENVINO_MATCHER_PASS_RTTI() definition: visibility hidden
+#ifdef __GNUC__
+# pragma GCC diagnostic push
+# pragma GCC diagnostic ignored "-Wattributes"
+#endif
+
+class TransposeValueTensors : public ov::pass::MatcherPass {
+public:
+ struct Context {
+ using Ref = std::reference_wrapper<Context>;
+ bool bTransposed = false;
+ };
+
+protected:
+ // generic part of matchers, to transpose v-tensors, and concat, and update matmul args
+ void transpose_matmul_b(Context::Ref ctx,
+ const std::shared_ptr<ov::op::v0::Parameter>& matched_param,
+ const std::shared_ptr<ov::op::v0::Concat>& matched_concat,
+ const std::shared_ptr<ov::op::v1::Transpose>& matched_transpose,
+ const std::shared_ptr<ov::op::v0::MatMul>& matched_matmul) {
+ auto param_shape = matched_param->get_partial_shape();
+ NPUW_ASSERT(param_shape.size() == 4u);
+ // NB: Transpose Parameter that correspond to V-tensor it will
+ // speed-up its multiplication with attention scores
+ std::swap(param_shape[2], param_shape[3]);
+
+ matched_param->set_partial_shape(param_shape);
+
+ auto order_cst = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{4}, {0, 2, 3, 1});
+
+ matched_transpose->set_argument(1, order_cst);
+ matched_concat->set_axis(3u);
+ matched_matmul->set_transpose_b(true);
+ ctx.get().bTransposed = true;
+ }
+
+ void transpose_matmul_b(Context::Ref ctx,
+ const std::shared_ptr<ov::Node>& node_param,
+ const std::shared_ptr<ov::Node>& node_concat,
+ const std::shared_ptr<ov::Node>& node_transpose,
+ const std::shared_ptr<ov::Node>& node_matmul) {
+ auto matched_param = std::static_pointer_cast<ov::op::v0::Parameter>(node_param);
+ auto matched_concat = std::static_pointer_cast<ov::op::v0::Concat>(node_concat);
+ auto matched_transpose = std::static_pointer_cast<ov::op::v1::Transpose>(node_transpose);
+ auto matched_matmul = std::static_pointer_cast<ov::op::v0::MatMul>(node_matmul);
+
+ transpose_matmul_b(ctx, matched_param, matched_concat, matched_transpose, matched_matmul);
+ }
+};
+
+// MHA (Multi-Head Attention) pattern for value tensor concatenation
+class TransposeValueTensors_MHA : public TransposeValueTensors {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::TransposeValueTensors_MHA");
+ TransposeValueTensors_MHA(Context::Ref ctx) {
+ register_matcher_mha(ctx);
+ }
+
+private:
+ void register_matcher_mha(Context::Ref ctx) {
+ auto param = opp::wrap_type<ov::op::v0::Parameter>();
+ auto transpose = opp::wrap_type<ov::op::v1::Transpose>({opp::any_input(), opp::any_input()});
+ auto convert = opp::optional<ov::op::v0::Convert>({param->output(0)});
+ auto concat = opp::wrap_type<ov::op::v0::Concat>({convert, transpose});
+ auto softmax = opp::wrap_type<ov::op::v8::Softmax>({opp::any_input()});
+ // Softmax output maybe sliced when SDPA with sink input is decomposed
+ auto maybe_slice = opp::optional<ov::op::v8::Slice>(
+ {softmax, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});
+ auto matmul = opp::wrap_type<ov::op::v0::MatMul>({maybe_slice, concat});
+
+ auto callback = [=](ov::pass::pattern::Matcher& m) {
+ auto& node_to_output = m.get_pattern_value_map();
+
+ auto matched_node_param = node_to_output.at(param).get_node_shared_ptr();
+ auto matched_node_concat = node_to_output.at(concat).get_node_shared_ptr();
+ auto matched_node_transpose = node_to_output.at(transpose).get_node_shared_ptr();
+ auto matched_node_matmul = node_to_output.at(matmul).get_node_shared_ptr();
+
+ transpose_matmul_b(ctx,
+ matched_node_param,
+ matched_node_concat,
+ matched_node_transpose,
+ matched_node_matmul);
+ LOG_DEBUG("vtensors transposed: MHA pattern");
+ return true;
+ };
+ register_matcher(std::make_shared<opp::Matcher>(matmul, "TransposeValueTensors_MHA"), std::move(callback));
+ }
+};
+
+// GQA (Grouped Query Attention) pattern for value tensors with broadcasting
+// Used by llama3, phi3, mistral, GPT-OSS, etc.
+class TransposeValueTensors_GQA : public TransposeValueTensors {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::TransposeValueTensors_GQA");
+ TransposeValueTensors_GQA(Context::Ref ctx) {
+ register_matcher_gqa(ctx);
+ }
+
+private:
+ void register_matcher_gqa(Context::Ref ctx) {
+ auto param = opp::wrap_type<ov::op::v0::Parameter>();
+ auto transpose = opp::wrap_type<ov::op::v1::Transpose>({opp::any_input(), opp::any_input()});
+ auto convert = opp::optional<ov::op::v0::Convert>({param->output(0)});
+ auto concat = opp::wrap_type<ov::op::v0::Concat>({convert, transpose});
+
+ // only difference is that broadcast wrapped into unsquese/reshape, while transposed tensor didn't change
+ const auto unsqueeze_axes = opp::wrap_type<ov::op::v0::Constant>();
+ auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({concat, unsqueeze_axes});
+ auto broadcast = opp::wrap_type<ov::op::v1::Broadcast, ov::op::v3::Broadcast>({unsqueeze, opp::any_input()});
+ auto reshape = opp::wrap_type<ov::op::v1::Reshape>({broadcast, opp::any_input()});
+
+ // v8 softmax? what? can be other softmaxes
+ auto softmax = opp::wrap_type<ov::op::v8::Softmax>({opp::any_input()});
+ // Softmax output maybe sliced when SDPA with sink input is decomposed (e.g. GPT-OSS)
+ auto maybe_slice = opp::optional<ov::op::v8::Slice>(
+ {softmax, opp::any_input(), opp::any_input(), opp::any_input(), opp::any_input()});
+ auto matmul = opp::wrap_type<ov::op::v0::MatMul>({maybe_slice, reshape});
+
+ auto callback = [=](ov::pass::pattern::Matcher& m) {
+ auto& node_to_output = m.get_pattern_value_map();
+
+ auto matched_node_param = node_to_output.at(param).get_node_shared_ptr();
+ auto matched_node_concat = node_to_output.at(concat).get_node_shared_ptr();
+ auto matched_node_transpose = node_to_output.at(transpose).get_node_shared_ptr();
+ auto matched_node_matmul = node_to_output.at(matmul).get_node_shared_ptr();
+ auto matched_node_unsqueeze = node_to_output.at(unsqueeze).get_node_shared_ptr();
+ auto matched_node_unsqueeze_axes = node_to_output.at(unsqueeze_axes).get_node_shared_ptr();
+ auto matched_node_broadcast = node_to_output.at(broadcast).get_node_shared_ptr();
+ auto matched_node_reshape = node_to_output.at(reshape).get_node_shared_ptr();
+
+ auto matched_param = std::static_pointer_cast<ov::op::v0::Parameter>(matched_node_param);
+ auto matched_concat = std::static_pointer_cast<ov::op::v0::Concat>(matched_node_concat);
+ auto matched_transpose = std::static_pointer_cast<ov::op::v1::Transpose>(matched_node_transpose);
+ auto matched_matmul = std::static_pointer_cast<ov::op::v0::MatMul>(matched_node_matmul);
+ auto matched_unsqueeze = std::static_pointer_cast<ov::op::v0::Unsqueeze>(matched_node_unsqueeze);
+ auto matched_broadcast = std::static_pointer_cast<ov::op::v3::Broadcast>(matched_node_broadcast);
+ auto matched_reshape = std::static_pointer_cast<ov::op::v1::Reshape>(matched_node_reshape);
+
+ auto shape_broadcast = matched_broadcast->get_output_shape(0);
+ NPUW_ASSERT(shape_broadcast.size() == 5u);
+ std::swap(shape_broadcast[3], shape_broadcast[4]);
+
+ LOG_DEBUG("shape_broadcast for: " << matched_broadcast->get_friendly_name()
+ << ", shape=" << shape_broadcast);
+
+ const auto broadcast_axes_node =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{5}, shape_broadcast);
+ broadcast_axes_node->set_friendly_name(matched_broadcast->get_friendly_name() + "/new_broadcast_shape");
+ matched_broadcast->input(1).replace_source_output(broadcast_axes_node);
+
+ auto shape_reshape = matched_reshape->get_output_shape(0);
+ NPUW_ASSERT(shape_reshape.size() == 4u);
+ std::swap(shape_reshape[2], shape_reshape[3]);
+
+ LOG_DEBUG("shape_reshape for: " << matched_reshape->get_friendly_name() << ", shape=" << shape_reshape);
+
+ const auto reshape_axes_node =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{4}, shape_reshape);
+ reshape_axes_node->set_friendly_name(matched_reshape->get_friendly_name() + "/new_reshape_shape");
+ matched_reshape->input(1).replace_source_output(reshape_axes_node);
+
+ transpose_matmul_b(ctx, matched_param, matched_concat, matched_transpose, matched_matmul);
+ LOG_DEBUG("vtensors transposed: GQA pattern");
+ return true;
+ };
+ register_matcher(std::make_shared<opp::Matcher>(matmul, "TransposeValueTensors_GQA"), std::move(callback));
+ }
+};
+
+class ScaledDotProductAttentionDecomposition : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::ScaledDotProductAttentionDecomposition");
+ explicit ScaledDotProductAttentionDecomposition(bool use_high_precision_on_add) {
+ auto pattern_node = ov::pass::pattern::wrap_type<ov::op::v13::ScaledDotProductAttention>();
+
+ ov::matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {
+ auto& pattern_to_output = m.get_pattern_value_map();
+ auto node = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(
+ pattern_to_output.at(pattern_node).get_node_shared_ptr());
+
+ if (node == nullptr || transformation_callback(node)) {
+ return false;
+ }
+
+ auto new_output_node = decompose(node, use_high_precision_on_add);
+ ov::replace_node(node, new_output_node);
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(pattern_node, "ScaledDotProductAttentionDecomposition");
+ register_matcher(m, std::move(callback));
+ }
+ std::shared_ptr<ov::Node> decompose(std::shared_ptr<ov::op::v13::ScaledDotProductAttention> node,
+ bool use_high_precision_on_add) {
+ using namespace ov::op;
+ using namespace ov;
+ auto query = node->input_value(0);
+ auto key = node->input_value(1);
+ auto value = node->input_value(2);
+ auto q_shape = register_new_node<v3::ShapeOf>(query, element::i32);
+ auto k_shape = register_new_node<v3::ShapeOf>(key, element::i32);
+ auto minus_one = register_new_node(v0::Constant::create(element::i32, Shape{}, {-1}));
+ auto minus_two = register_new_node(v0::Constant::create(element::i32, Shape{}, {-2}));
+ auto zero_i = register_new_node(v0::Constant::create(element::i32, Shape{}, {0}));
+ auto one_i = register_new_node(v0::Constant::create(element::i32, Shape{}, {1}));
+ auto one_f = register_new_node<v1::ConvertLike>(one_i, query);
+ auto zero_f = register_new_node<v1::ConvertLike>(zero_i, query);
+
+ Output<Node> scale;
+ if (node->get_input_size() < 5) {
+ scale = register_new_node<v8::Gather>(q_shape, minus_one, zero_i)->output(0);
+ scale = register_new_node<v1::ConvertLike>(scale, query);
+ auto sqrt_scale = register_new_node<v0::Sqrt>(scale);
+ scale = register_new_node<v1::Divide>(one_f, sqrt_scale);
+ } else {
+ scale = node->input_value(4);
+ }
+
+ auto q_scaled = register_new_node<v1::Multiply>(query, scale);
+ auto k_rank = register_new_node<v3::ShapeOf>(k_shape, element::i32)->output(0);
+ auto k_last_dim = register_new_node<v1::Add>(k_rank, minus_one);
+ auto k_next_dim = register_new_node<v1::Add>(k_rank, minus_two)->output(0);
+ k_rank = register_new_node<v0::Squeeze>(k_rank, zero_i);
+ auto minus_inf =
+ register_new_node(v0::Constant::create(element::f32, Shape{}, {-std::numeric_limits<float>::infinity()}))
+ ->output(0);
+ auto keep_dim_last = register_new_node<v0::Squeeze>(k_next_dim, zero_i);
+ auto k_dims_before_transpose = register_new_node<v4::Range>(zero_i, keep_dim_last, one_i, element::i32);
+
+ auto scaled_atten = register_new_node<v0::MatMul>(q_scaled, key, false, true)->output(0);
+ minus_inf = register_new_node<v1::ConvertLike>(minus_inf, scaled_atten);
+
+ if (node->get_causal() || node->get_input_size() > 3) {
+ Output<Node> mask;
+ Output<Node> atten_mask;
+ if (!node->get_causal()) {
+ mask = node->input_value(3);
+
+ // two types of masks are supported. A boolean mask where a value of True indicates that the element
+ // should take part in attention. A float mask of the same type as query, key, value that is added to
+ // the attention score.
+ if (mask.get_element_type() == element::boolean) {
+ atten_mask = register_new_node<v1::Select>(mask, zero_f, minus_inf);
+ } else {
+ atten_mask = mask;
+ }
+ } else {
+ auto target_s_len = register_new_node<v8::Gather>(q_shape, minus_two, zero_i);
+ auto source_s_len = register_new_node<v8::Gather>(k_shape, minus_two, zero_i);
+ auto ssl = register_new_node<v0::Unsqueeze>(source_s_len, zero_i);
+ auto tsl = register_new_node<v0::Unsqueeze>(target_s_len, zero_i);
+ auto mask_shape = register_new_node<v0::Concat>(OutputVector{tsl, ssl}, 0);
+ mask = register_new_node<v1::Broadcast>(minus_inf, mask_shape);
+ auto horizontal_range =
+ register_new_node<v4::Range>(zero_i, source_s_len, one_i, element::i32)->output(0);
+ horizontal_range = register_new_node<v0::Unsqueeze>(horizontal_range, zero_i);
+ auto stop = register_new_node<v1::Add>(target_s_len, one_i);
+ auto vertical_range = register_new_node<v4::Range>(one_i, stop, one_i, element::i32)->output(0);
+ vertical_range = register_new_node<v0::Unsqueeze>(vertical_range, one_i);
+ auto triu = register_new_node<v1::GreaterEqual>(horizontal_range, vertical_range);
+ atten_mask = register_new_node<v1::Select>(triu, mask, zero_f);
+ }
+ if (use_high_precision_on_add) {
+ npuw::util::HighPrecisionAttr attr_hp;
+ attr_hp.compute_precision_type = ov::element::f32;
+ atten_mask.get_rt_info()[npuw::util::HighPrecisionAttr::get_type_info_static()] = attr_hp;
+ }
+
+ scaled_atten = register_new_node<v1::Add>(scaled_atten, atten_mask);
+ }
+
+ scaled_atten = register_new_node<v8::Softmax>(scaled_atten, -1);
+ auto result = register_new_node<v0::MatMul>(scaled_atten, value);
+ result->set_friendly_name(node->get_friendly_name());
+ copy_runtime_info(node, get_new_nodes());
+ return result;
+ }
+};
+
+#ifdef __GNUC__
+# pragma GCC diagnostic pop
+#endif
+
+} // namespace
+
+bool ov::npuw::util::OptimizeValueTensors::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ ov::pass::GraphRewrite rewr;
+
+ // Check if any SDPA has sink input
+ bool has_sdpa_with_sink = false;
+ for (const auto& op : model->get_ops()) {
+ if (auto sdpa = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(op)) {
+ if (sdpa->get_input_size() == 6) {
+ has_sdpa_with_sink = true;
+ break;
+ }
+ }
+ }
+
+ if (has_sdpa_with_sink) {
+ // TODO: evaluate performance by older npu-drivers
+ rewr.add_matcher<ov::pass::ScaledDotProductAttentionDecomposition>();
+ } else {
+ rewr.add_matcher<ScaledDotProductAttentionDecomposition>(m_is_prefill);
+ }
+
+ TransposeValueTensors::Context ctx;
+ rewr.add_matcher<TransposeValueTensors_MHA>(std::ref(ctx));
+ rewr.add_matcher<TransposeValueTensors_GQA>(std::ref(ctx));
+ rewr.run_on_model(model);
+
+ ov::pass::Validate().run_on_model(model);
+
+ // NB: matmul parameters gets transposed, if pass applied
+ return ctx.bTransposed;
+}
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.hpp
new file mode 100644
index 00000000000..e893d398d24
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.hpp
@@ -0,0 +1,26 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov {
+namespace npuw {
+namespace util {
+
+// SDPA-unroll and transpose transformations
+class OptimizeValueTensors : public ov::pass::ModelPass {
+ bool m_is_prefill;
+
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::OptimizeValueTensors");
+ explicit OptimizeValueTensors(bool is_prefill) : m_is_prefill(is_prefill) {}
+
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace util
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.cpp
new file mode 100644
index 00000000000..01d5d78e8e1
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.cpp
@@ -0,0 +1,26 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "patch_phi3_sliding_mask.hpp"
+
+#include "openvino/pass/manager.hpp"
+#include "phi3_sliding_mask.hpp"
+
+namespace {
+
+bool patch_phi3_sliding_mask(const std::shared_ptr<ov::Model>& model) {
+ ov::pass::Manager manager;
+ manager.register_pass<ov::npuw::Phi3SlidingMask>();
+ return manager.run_passes(model);
+}
+
+} // namespace
+
+namespace ov::npuw {
+
+bool PatchPhi3SlidingMask::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ return patch_phi3_sliding_mask(model);
+}
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.hpp
new file mode 100644
index 00000000000..ba884e334a2
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.hpp
@@ -0,0 +1,18 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+class PatchPhi3SlidingMask : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::PatchPhi3SlidingMask");
+ explicit PatchPhi3SlidingMask() = default;
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.cpp
new file mode 100644
index 00000000000..85d3d661c5b
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.cpp
@@ -0,0 +1,409 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "phi3_sliding_mask.hpp"
+
+#include "../logging.hpp"
+#include "openvino/op/ops.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/pass/manager.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+
+namespace opp = ov::pass::pattern;
+
+namespace {
+
+// diagnostics warnings on OPENVINO_MATCHER_PASS_RTTI() definition: visibility hidden
+#ifdef __GNUC__
+# pragma GCC diagnostic push
+# pragma GCC diagnostic ignored "-Wattributes"
+#endif
+
+class OldPhi3SlidingMaskMatcher : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::OldPhi3SlidingMaskMatcher");
+
+ OldPhi3SlidingMaskMatcher() {
+ // Search for the Phi3 old sliding mask pattern to extend it to work with right-padded
+ // past tokens and left-padded present tokens.
+ //
+ // Mask creation is simply done via "less_equal" and "greater" operations between
+ // row K range: [0,... mask_len] and column Q range: [current_pos_id,... mask_len].T
+ // and sliding window length.
+ // Due to broadcasting rules these two operation form two triangular masks.
+ //
+ // - "less_equal" forms a sliding window mask, more precisely, it has following expression:
+ //
+ // row range [0,... mask_len] <= column range [current_pos_id - sliding_window_size,
+ // ...,
+ // mask_len - sliding_window_size]
+ //
+ // forming, under example conditions, the mask below:
+ // past tokens = 3
+ // present tokens = 5 (starting with current_pos_id = 3)
+ // sliding window len = 4
+ // K0 K1 K2 K3 K4 K5 K6 K7
+ // [ 0 1 2 3 4 5 6 7 ]
+ // Q3[ 3 - 4 ] 0 0 0 0 0 0 0 0
+ // Q4[ 4 - 4 ] 1 0 0 0 0 0 0 0
+ // Q5[ 5 - 4 ] 1 1 0 0 0 0 0 0
+ // Q6[ 6 - 4 ] 1 1 1 0 0 0 0 0
+ // Q7[ 7 - 4 ] 1 1 1 1 0 0 0 0
+ // where 1 at [i, j] means that j token should be forgotten as it can't fit into the sliding
+ // window from the left of i-th token.
+ //
+ // - "greater" forms a similar to self-attention mask:
+ //
+ // row range [0,... mask_len] > column range [current_pos_id,
+ // ...,
+ // mask_len]
+ //
+ // forming, under example conditions, the mask below:
+ // past tokens = 3
+ // present tokens = 5 (starting with current_pos_id = 3)
+ // K0 K1 K2 K3 K4 K5 K6 K7
+ // [ 0 1 2 3 4 5 6 7 ]
+ // Q3[ 3 ] 0 0 0 0 1 1 1 1
+ // Q4[ 4 ] 0 0 0 0 0 1 1 1
+ // Q5[ 5 ] 0 0 0 0 0 0 1 1
+ // Q6[ 6 ] 0 0 0 0 0 0 0 1
+ // Q7[ 7 ] 0 0 0 0 0 0 0 0
+ // where 1 at [i, j] means that j token is a future token for i-th token, that we shouldn't attend to.
+ //
+ // Together, via "bitwise_or" this two masks forms the inverted sliding attention mask:
+ // past tokens = 3
+ // present tokens = 5 (starting with current_pos_id = 3)
+ // sliding window len = 4
+ // K0 K1 K2 K3 K4 K5 K6 K7
+ // [ 0 1 2 3 4 5 6 7 ]
+ // Q3[ 3 - 4 ] 0 0 0 0 1 1 1 1
+ // Q4[ 4 - 4 ] 1 0 0 0 0 1 1 1
+ // Q5[ 5 - 4 ] 1 1 0 0 0 0 1 1
+ // Q6[ 6 - 4 ] 1 1 1 0 0 0 0 1
+ // Q7[ 7 - 4 ] 1 1 1 1 0 0 0 0
+ //
+ // Issue with sliding attention mask appears when we work with static shapes and different
+ // paddings for past and present tokens.
+ // More precisely, issue appears with sliding window mask, as Q column range is created
+ // from length of past key/values tensor (2175 for 2K case) as start point and the length
+ // of attention mask (2176 for 2K) as an end point. This is okay for inverted
+ // self-attention mask by means of "greater" operation, as our present tokens exactly
+ // left-padded and located on the right in the attention mask.
+ // However, for the sliding window mask created by means of "less_equal" operation, given
+ // Q range will behave as if position ids of new Q tokens will start from 2175 and not from
+ // 3 as in example above and therefore, 2175 - 2047 = 128 first tokens should be forgotten.
+ // To fix it a new formula is suggested:
+ // 1. (K range <= (Q_pos range - sliding window).T) | (K range > Q range.T)
+ // 2. (K range <= (Q range - sliding window).T) & (K range >= len(past_key_values))
+ // 3. Resulting mask = 1 | 2,
+ // where K range and Q range are created by the same rules as before and Q_pos range is
+ // a position_ids array.
+ // 4. We also clean mask in places where paddings used instead of real tokens via:
+ // Clean mask = 3 | !(attention_mask_input[past_kv_len:]).T
+ auto past_kv_len = opp::wrap_type<ov::op::v8::Gather>({opp::any_input(), opp::any_input(), opp::any_input()});
+ auto pos_ids_param = opp::wrap_type<ov::op::v0::Parameter>();
+ auto pos_ids_shape_of = opp::wrap_type<ov::op::v3::ShapeOf>({pos_ids_param});
+ auto pos_ids_len = opp::wrap_type<ov::op::v8::Gather>({pos_ids_shape_of, opp::any_input(), opp::any_input()});
+ auto full_ctx_len = opp::wrap_type<ov::op::v1::Add>({past_kv_len, pos_ids_len});
+ auto query_range = opp::wrap_type<ov::op::v4::Range>({past_kv_len, full_ctx_len, opp::any_input()});
+ auto column_shape = opp::wrap_type<ov::op::v0::Constant>();
+ auto query_range_column = opp::wrap_type<ov::op::v1::Reshape>({query_range, column_shape});
+
+ auto zero_const = opp::wrap_type<ov::op::v0::Constant>();
+ auto atten_mask_param = opp::wrap_type<ov::op::v0::Parameter>();
+ auto atten_mask_shape_of = opp::wrap_type<ov::op::v3::ShapeOf>({atten_mask_param});
+ auto atten_mask_len =
+ opp::wrap_type<ov::op::v8::Gather>({atten_mask_shape_of, opp::any_input(), opp::any_input()});
+ auto key_range = opp::wrap_type<ov::op::v4::Range>({zero_const, atten_mask_len, opp::any_input()});
+ auto key_range_i64 = opp::wrap_type<ov::op::v0::Convert>({key_range});
+ auto key_range_f32 = opp::wrap_type<ov::op::v0::Convert>({key_range_i64});
+
+ auto neg_window_size = opp::wrap_type<ov::op::v0::Constant>();
+ auto query_left_bound_range = opp::wrap_type<ov::op::v1::Add>({query_range_column, neg_window_size});
+ // False in mask means that we shouldn't forget this token
+ auto forget_left_tokens_mask = opp::wrap_type<ov::op::v1::LessEqual>({key_range_f32, query_left_bound_range});
+ // Basically it is a reference triangle self-attention mask that
+ // forbids tokens to attend to future ones, but values are inverted:
+ auto look_only_future_mask = opp::wrap_type<ov::op::v1::Greater>({key_range_f32, query_range_column});
+
+ auto inv_sliding_attention_mask =
+ opp::wrap_type<ov::op::v13::BitwiseOr>({look_only_future_mask, forget_left_tokens_mask});
+
+ auto callback = [=](opp::Matcher& m) {
+ LOG_INFO("Found (4.51) pattern for Phi-3 Sliding Window Attention, will be replaced with custom for static "
+ "shapes.");
+ auto& node_to_output = m.get_pattern_value_map();
+ auto node_past_kv_len = node_to_output.at(past_kv_len).get_node_shared_ptr();
+ auto node_pos_ids_param = node_to_output.at(pos_ids_param).get_node_shared_ptr();
+ auto node_atten_mask_param = node_to_output.at(atten_mask_param).get_node_shared_ptr();
+ auto node_atten_mask_len = node_to_output.at(atten_mask_len).get_node_shared_ptr();
+ auto node_key_range_f32 = node_to_output.at(key_range_f32).get_node_shared_ptr();
+ auto node_neg_window_size = node_to_output.at(neg_window_size).get_node_shared_ptr();
+ auto node_forget_left_tokens_mask = node_to_output.at(forget_left_tokens_mask).get_node_shared_ptr();
+ auto node_bitwise_or = node_to_output.at(inv_sliding_attention_mask).get_node_shared_ptr();
+
+ auto matched_past_kv_len = std::static_pointer_cast<ov::op::v8::Gather>(node_past_kv_len);
+ auto matched_pos_ids_input = std::static_pointer_cast<ov::op::v0::Parameter>(node_pos_ids_param);
+ auto matched_atten_mask_input = std::static_pointer_cast<ov::op::v0::Parameter>(node_atten_mask_param);
+ auto matched_atten_mask_len = std::static_pointer_cast<ov::op::v8::Gather>(node_atten_mask_len);
+ auto matched_key_range_f32 = std::static_pointer_cast<ov::op::v0::Convert>(node_key_range_f32);
+ auto matched_neg_window_size = std::static_pointer_cast<ov::op::v0::Constant>(node_neg_window_size);
+ auto matched_forget_left_tokens_mask =
+ std::static_pointer_cast<ov::op::v1::LessEqual>(node_forget_left_tokens_mask);
+ auto matched_bitwise_or = std::static_pointer_cast<ov::op::v13::BitwiseOr>(node_bitwise_or);
+ OPENVINO_ASSERT(matched_neg_window_size->get_output_size() == 1,
+ "Sliding window size constant must be of size 1, but got " +
+ std::to_string(matched_neg_window_size->get_output_size()));
+
+ // 1.(K range <= (Q_pos range - sliding window).T) | (K range > Q range.T)
+ auto query_range_as_pos_ids =
+ std::make_shared<ov::op::v0::Convert>(matched_pos_ids_input, ov::element::f32);
+ std::vector<int64_t> vector_shape{-1, 1};
+ auto vector_shape_const =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{2}, vector_shape);
+ auto query_range_as_pos_ids_col =
+ std::make_shared<ov::op::v1::Reshape>(query_range_as_pos_ids, vector_shape_const, false);
+ auto query_range_as_pos_left_bound =
+ std::make_shared<ov::op::v1::Add>(query_range_as_pos_ids_col, matched_neg_window_size);
+ auto forget_left_mask_for_right_padding =
+ std::make_shared<ov::op::v1::LessEqual>(matched_key_range_f32, query_range_as_pos_left_bound);
+ matched_bitwise_or->input(1).replace_source_output(forget_left_mask_for_right_padding);
+
+ // 2. (K range <= (Q range - sliding window).T) & (K range >= shape(past_key_values, 2))
+ auto past_kv_len_f32 = std::make_shared<ov::op::v0::Convert>(matched_past_kv_len, ov::element::f32);
+ auto only_present_tokens_mask =
+ std::make_shared<ov::op::v1::GreaterEqual>(matched_key_range_f32, past_kv_len_f32);
+ auto bitwise_and =
+ std::make_shared<ov::op::v13::BitwiseAnd>(matched_forget_left_tokens_mask, only_present_tokens_mask);
+
+ // 3. Result = 1 | 2
+ // Save target inputs first:
+ auto target_inputs = matched_bitwise_or->output(0).get_target_inputs();
+ auto new_inv_sliding_mask = std::make_shared<ov::op::v13::BitwiseOr>(matched_bitwise_or, bitwise_and);
+
+ // 4. Removing extra padding via : 3 | !(attention_mask_input[past_kv_len:]).T
+ std::vector<int64_t> shape_rank_one{1};
+ auto shape_rank_one_const =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, shape_rank_one);
+ auto past_len_reshaped =
+ std::make_shared<ov::op::v1::Reshape>(matched_past_kv_len, shape_rank_one_const, false);
+ auto atten_len_reshaped =
+ std::make_shared<ov::op::v1::Reshape>(matched_atten_mask_len, shape_rank_one_const, false);
+ auto const_one = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, 1);
+ auto present_atten_mask = std::make_shared<ov::op::v8::Slice>(matched_atten_mask_input,
+ past_len_reshaped,
+ atten_len_reshaped,
+ const_one,
+ const_one);
+ auto present_atten_mask_bool =
+ std::make_shared<ov::op::v0::Convert>(present_atten_mask, ov::element::boolean);
+ auto inv_present_atten_mask = std::make_shared<ov::op::v1::LogicalNot>(present_atten_mask_bool);
+ auto inv_present_atten_mask_col =
+ std::make_shared<ov::op::v1::Reshape>(inv_present_atten_mask, vector_shape_const, false);
+ auto clean_inv_sliding_mask =
+ std::make_shared<ov::op::v13::BitwiseOr>(new_inv_sliding_mask, inv_present_atten_mask_col);
+ for (auto&& input : target_inputs) {
+ input.replace_source_output(clean_inv_sliding_mask);
+ }
+
+ return true;
+ };
+ register_matcher(std::make_shared<opp::Matcher>(inv_sliding_attention_mask, "OldPhi3SlidingMaskMatcher"),
+ std::move(callback));
+ }
+};
+
+class Phi3SlidingMaskMatcher : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("ov::npuw::patterns::Phi3SlidingMaskMatcher");
+
+ Phi3SlidingMaskMatcher(const std::shared_ptr<ov::Node>& attention_mask_node_ptr,
+ const std::shared_ptr<ov::Node>& position_ids_node_ptr) {
+ // Search for the Phi3 sliding mask pattern to extend it to work with right-padded
+ // past tokens and left-padded present tokens. Logic to replace pattern is the same
+ // as in Phi3SlidingMask rewriter, but adjusted to another set of operations for
+ // creation of mask, obtained from transformers 4.53.
+ // Pattern is the same as in GemmaSlidingMask.
+ //
+ // Fix is a replace of following pattern:
+ // 1. (K range > (Q range - sliding window).T) & (K range <= Q range.T)
+ // to
+ // 1. (K range > (Q_pos range - sliding window).T) & (K range <= Q range.T)
+ // 2. (K range > (Q range - sliding window).T) | (K range < len(past_key_values))
+ // 3. Resulting mask = 1 & 2,
+ // where K range and Q range are created by the same rules as before and Q_pos range is
+ // a position_ids array.
+ // 4. We also clean mask in places where paddings used instead of real tokens via:
+ // Clean mask = 3 & attention_mask_input[past_kv_len:].T
+ auto unsqueeze_sequence = [&](std::shared_ptr<ov::Node> range) {
+ auto unsqueeze1 = opp::wrap_type<ov::op::v0::Unsqueeze>({range, opp::any_input()});
+ auto unsqueeze2 = opp::wrap_type<ov::op::v0::Unsqueeze>({unsqueeze1, opp::any_input()});
+ auto unsqueeze3 = opp::wrap_type<ov::op::v0::Unsqueeze>({unsqueeze2, opp::any_input()});
+
+ return unsqueeze3;
+ };
+
+ auto past_kv_len = opp::wrap_type<ov::op::v8::Gather>({opp::any_input(), opp::any_input(), opp::any_input()});
+ // TODO: ov::op::v0::Squeeze may accept or not accept optional axes input, so we need to cover both cases in
+ // pattern If Squeeze accepts axes it doesn't match with pattern without axes, and if it doesn't accept axes it
+ // doesn't match with pattern with axes. So we need to add two branches in pattern to cover both cases.
+ auto past_kv_len_squeeze = opp::optional<ov::op::v0::Squeeze>({past_kv_len});
+ auto full_ctx_len = opp::wrap_type<ov::op::v1::Add>({past_kv_len_squeeze, opp::any_input()});
+ auto query_range = opp::wrap_type<ov::op::v4::Range>({past_kv_len_squeeze, full_ctx_len, opp::any_input()});
+ auto query_range_column = unsqueeze_sequence(query_range);
+
+ auto zero_const = opp::wrap_type<ov::op::v0::Constant>();
+ auto full_ctx_len_2 = opp::wrap_type<ov::op::v1::Add>({opp::any_input(), past_kv_len_squeeze});
+ auto key_range = opp::wrap_type<ov::op::v4::Range>({zero_const, full_ctx_len_2, opp::any_input()});
+ auto key_range_row = unsqueeze_sequence(key_range);
+ auto opt_key_range_row_f32 = opp::optional<ov::op::v0::Convert>({key_range_row->output(0)});
+
+ auto neg_window_size = opp::wrap_type<ov::op::v0::Constant>();
+ auto query_left_bound_range = opp::wrap_type<ov::op::v1::Add>({query_range_column, neg_window_size});
+ // True in mask means that we should attend this token
+ auto sliding_mask = opp::wrap_type<ov::op::v1::Greater>({opt_key_range_row_f32, query_left_bound_range});
+ auto sliding_and_true = opp::wrap_type<ov::op::v13::BitwiseAnd>({opp::any_input(), sliding_mask});
+ // Basically it is a reference triangle self-attention mask
+ auto causal_mask = opp::wrap_type<ov::op::v1::LessEqual>({opt_key_range_row_f32, query_range_column});
+
+ auto sliding_and_causal_mask = opp::wrap_type<ov::op::v13::BitwiseAnd>({sliding_and_true, causal_mask});
+
+ auto callback = [=](opp::Matcher& m) {
+ LOG_INFO("Found (4.53) pattern for Phi-3 Sliding Window Attention, will be replaced with custom for static "
+ "shapes.");
+ auto& node_to_output = m.get_pattern_value_map();
+ auto optional_squeeze = node_to_output.find(past_kv_len_squeeze);
+ auto matched_past_kv_len = optional_squeeze != node_to_output.end()
+ ? optional_squeeze->second.get_node_shared_ptr()
+ : node_to_output.at(past_kv_len).get_node_shared_ptr();
+ auto matched_full_ctx_len = node_to_output.at(full_ctx_len).get_node_shared_ptr();
+ auto node_neg_window_size = node_to_output.at(neg_window_size).get_node_shared_ptr();
+ auto matched_sliding_mask = node_to_output.at(sliding_mask).get_node_shared_ptr();
+ auto matched_sliding_and_causal_mask = node_to_output.at(sliding_and_causal_mask).get_node_shared_ptr();
+
+ auto optional_convert = node_to_output.find(opt_key_range_row_f32);
+ std::shared_ptr<ov::Node> matched_key_range_row =
+ optional_convert != node_to_output.end() ? optional_convert->second.get_node_shared_ptr()
+ : node_to_output.at(key_range_row).get_node_shared_ptr();
+ auto matched_neg_window_size = std::static_pointer_cast<ov::op::v0::Constant>(node_neg_window_size);
+ OPENVINO_ASSERT(matched_neg_window_size->get_output_size() == 1,
+ "Sliding window size constant must be of size 1, but got " +
+ std::to_string(matched_neg_window_size->get_output_size()));
+
+ std::shared_ptr<ov::Node> passed_attention_mask = attention_mask_node_ptr;
+ std::shared_ptr<ov::Node> passed_position_ids = position_ids_node_ptr;
+ OPENVINO_ASSERT(passed_attention_mask, "Passed attention_mask node is nullptr!");
+ OPENVINO_ASSERT(passed_position_ids, "Passed position_ids node is nullptr!");
+
+ auto const_zero = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, 0);
+ auto const_one = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, 1);
+ auto const_three = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, 3);
+
+ // 1.(K range > (Q_pos range - sliding window).T) & (K range <= Q range.T)
+ std::shared_ptr<ov::Node> query_range_as_pos_ids = passed_position_ids;
+ if (matched_neg_window_size->output(0).get_element_type() == ov::element::f32) {
+ query_range_as_pos_ids = std::make_shared<ov::op::v0::Convert>(passed_position_ids, ov::element::f32);
+ }
+ auto query_range_as_pos_ids_unsqueezed =
+ std::make_shared<ov::op::v0::Unsqueeze>(query_range_as_pos_ids, const_zero);
+ auto query_range_as_pos_ids_col =
+ std::make_shared<ov::op::v0::Unsqueeze>(query_range_as_pos_ids_unsqueezed, const_three);
+ auto query_range_as_pos_left_bound =
+ std::make_shared<ov::op::v1::Add>(query_range_as_pos_ids_col, matched_neg_window_size);
+ auto sliding_mask_for_right_padding =
+ std::make_shared<ov::op::v1::Greater>(matched_key_range_row, query_range_as_pos_left_bound);
+ matched_sliding_and_causal_mask->input(0).replace_source_output(sliding_mask_for_right_padding);
+
+ // 2. (K range > (Q range - sliding window).T) | (K range < shape(past_key_values, 2))
+ std::shared_ptr<ov::Node> past_kv_len_argument = matched_past_kv_len;
+ if (matched_neg_window_size->output(0).get_element_type() == ov::element::f32) {
+ past_kv_len_argument = std::make_shared<ov::op::v0::Convert>(matched_past_kv_len, ov::element::f32);
+ }
+ auto only_past_tokens_mask =
+ std::make_shared<ov::op::v1::Less>(matched_key_range_row, past_kv_len_argument);
+ auto sliding_mask_for_left_padding_or_only_past =
+ std::make_shared<ov::op::v13::BitwiseOr>(matched_sliding_mask, only_past_tokens_mask);
+
+ // 3. Result = 1 & 2
+ // Save target inputs first:
+ auto target_inputs = matched_sliding_and_causal_mask->output(0).get_target_inputs();
+ auto new_sliding_and_causal_mask =
+ std::make_shared<ov::op::v13::BitwiseAnd>(matched_sliding_and_causal_mask,
+ sliding_mask_for_left_padding_or_only_past);
+
+ // 4. Removing extra padding via : 3 & attention_mask_input[past_kv_len:].T
+ std::vector<int64_t> shape_rank_one{1};
+ auto shape_rank_one_const =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, shape_rank_one);
+ auto past_len_reshaped =
+ std::make_shared<ov::op::v1::Reshape>(matched_past_kv_len, shape_rank_one_const, false);
+ auto full_ctx_len_reshaped =
+ std::make_shared<ov::op::v1::Reshape>(matched_full_ctx_len, shape_rank_one_const, false);
+ auto const_one_rank_one = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, 1);
+ auto attention_mask_bool =
+ std::make_shared<ov::op::v0::Convert>(passed_attention_mask, ov::element::boolean);
+ auto present_atten_mask_bool = std::make_shared<ov::op::v8::Slice>(attention_mask_bool,
+ past_len_reshaped,
+ full_ctx_len_reshaped,
+ const_one_rank_one,
+ const_one_rank_one);
+ std::vector<int64_t> vector_shape{-1, 1};
+ auto vector_shape_const =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{2}, vector_shape);
+ auto present_atten_mask_bool_col =
+ std::make_shared<ov::op::v1::Reshape>(present_atten_mask_bool, vector_shape_const, false);
+ auto clean_sliding_and_causal_mask =
+ std::make_shared<ov::op::v13::BitwiseAnd>(new_sliding_and_causal_mask, present_atten_mask_bool_col);
+ for (auto&& input : target_inputs) {
+ input.replace_source_output(clean_sliding_and_causal_mask);
+ }
+
+ return true;
+ };
+ register_matcher(std::make_shared<opp::Matcher>(sliding_and_causal_mask, "Phi3SlidingMaskMatcher"),
+ std::move(callback));
+ }
+};
+
+#ifdef __GNUC__
+# pragma GCC diagnostic pop
+#endif
+
+} // namespace
+
+namespace ov::npuw {
+
+bool Phi3SlidingMask::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ std::shared_ptr<ov::Node> attention_mask_node_ptr = nullptr;
+ std::shared_ptr<ov::Node> position_ids_node_ptr = nullptr;
+ for (const auto& i : model->inputs()) {
+ if (i.get_any_name() == "attention_mask") {
+ attention_mask_node_ptr = i.get_node_shared_ptr();
+ }
+ if (i.get_any_name() == "position_ids") {
+ position_ids_node_ptr = i.get_node_shared_ptr();
+ }
+ }
+ if (attention_mask_node_ptr == nullptr || position_ids_node_ptr == nullptr) {
+ return false;
+ }
+
+ auto pos_id_shape = position_ids_node_ptr->get_output_tensor(0).get_partial_shape();
+ if (pos_id_shape.size() != 2) {
+ // FIXME: Qwen2.5 VL/Omni uses 3D position_ids, which can't be directly used
+ // in creation of sliding window mask.
+ return false;
+ }
+
+ ov::pass::Manager manager;
+ manager.set_per_pass_validation(true);
+ const auto rewriter = manager.register_pass<ov::pass::GraphRewrite>();
+ rewriter->add_matcher<Phi3SlidingMaskMatcher>(attention_mask_node_ptr, position_ids_node_ptr);
+ rewriter->add_matcher<OldPhi3SlidingMaskMatcher>();
+ return manager.run_passes(model);
+}
+
+} // namespace ov::npuw
\ No newline at end of file
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.hpp
new file mode 100644
index 00000000000..56fca1b8bd1
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.hpp
@@ -0,0 +1,18 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+class Phi3SlidingMask : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::Phi3SlidingMask");
+ Phi3SlidingMask() = default;
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace ov::npuw
\ No newline at end of file
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_sliced_head_to_static.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_sliced_head_to_static.cpp
new file mode 100644
index 00000000000..562e8a736b6
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_sliced_head_to_static.cpp
@@ -0,0 +1,51 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "reshape_sliced_head_to_static.hpp"
+
+#include "../logging.hpp"
+
+namespace {
+
+void reshape_sliced_head_to_static(std::shared_ptr<ov::Model> lm_head_model,
+ const uint32_t& batch_dim,
+ std::size_t max_generation_token_len) {
+ // We have only one input with dynamic shapes: output embeds.
+ // Output embeds should have "max_generation_token_len" for dimension representing
+ // number of embeddings to send to the matmul. Batch size should be equal to "1"
+ // for NPU.
+ const auto& input = lm_head_model->input(0);
+ const auto& partial_shape = input.get_partial_shape();
+ NPUW_ASSERT(partial_shape.size() == 3);
+
+ ov::PartialShape new_shape = partial_shape;
+ new_shape[batch_dim] = 1;
+ // Left dynamic axis will be for number of embeddings
+ for (auto i = 0; i < new_shape.rank().get_length(); i++) {
+ if (new_shape[i].is_dynamic()) {
+ new_shape[i] = max_generation_token_len;
+ // Sanity check that only one left dimension is dynamic, as
+ // another one should contain embedding space rank
+ break;
+ }
+ }
+
+ lm_head_model->reshape(new_shape);
+}
+
+} // namespace
+
+namespace ov::npuw {
+
+ReshapeSlicedHeadToStatic::ReshapeSlicedHeadToStatic(uint32_t batch_dim, std::size_t max_generation_token_len)
+ : m_batch_dim(batch_dim),
+ m_max_generation_token_len(max_generation_token_len) {}
+
+bool ReshapeSlicedHeadToStatic::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ reshape_sliced_head_to_static(model, m_batch_dim, m_max_generation_token_len);
+
+ return true;
+}
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_sliced_head_to_static.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_sliced_head_to_static.hpp
new file mode 100644
index 00000000000..593d45b672e
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_sliced_head_to_static.hpp
@@ -0,0 +1,24 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+class ReshapeSlicedHeadToStatic : public ov::pass::ModelPass {
+ uint32_t m_batch_dim;
+ std::size_t m_max_generation_token_len;
+
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::ReshapeSlicedHeadToStatic");
+ explicit ReshapeSlicedHeadToStatic(uint32_t batch_dim, std::size_t max_generation_token_len);
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp
new file mode 100644
index 00000000000..023b991a2cd
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp
@@ -0,0 +1,100 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "reshape_to_static.hpp"
+
+#include "../llm_eagle3_extension.hpp"
+#include "../logging.hpp"
+#include "../util.hpp"
+#include "openvino/core/partial_shape.hpp"
+
+namespace {
+
+void reshape_to_static(std::shared_ptr<ov::Model> model,
+ const uint32_t input_size,
+ const uint32_t kvcache_size,
+ const ov::npuw::KVAxesPosition& kv_axes_position,
+ const uint32_t lora_rank,
+ const uint32_t lhs_seq_size = 0) {
+ std::map<std::string, ov::PartialShape> new_shapes;
+ for (const auto& input : model->inputs()) {
+ const auto& input_name = input.get_any_name();
+ ov::PartialShape new_shape;
+ if (input_name.find("input_ids") != std::string::npos) {
+ new_shape = ov::PartialShape({1, input_size});
+ } else if (input_name.find("token_type_ids") != std::string::npos) {
+ new_shape = ov::PartialShape({1, input_size});
+ } else if (input_name.find("inputs_embeds") != std::string::npos) {
+ // NB: VLMs case, model accepts inputs_embeds[BATCH, SEQ_LEN, EMB_SIZE]
+ NPUW_ASSERT(input.get_partial_shape().size() == 3u);
+ NPUW_ASSERT(input.get_partial_shape()[2].is_static());
+ new_shape = ov::PartialShape({1, input_size, input.get_partial_shape()[2]});
+ } else if (input_name.find("attention_mask") != std::string::npos) {
+ new_shape = ov::PartialShape({1, kvcache_size});
+ if (lhs_seq_size && kvcache_size > 4)
+ // NB: for whisper kvcache model attn mask should be size + 1
+ new_shape = ov::PartialShape({1, kvcache_size + 1});
+ } else if (input_name.find("position_ids") != std::string::npos) {
+ const auto partial_shape_size = input.get_partial_shape().size();
+ // NB: Regular LLM uses 2D shapes, Qwen2.5 VL/Omni uses 3D shapes
+ // The first dimension (3) represents the three components of position encoding: time, height, and width
+ // enabling alignment across multimodal inputs like text, audio, and video
+ NPUW_ASSERT(partial_shape_size == 3u || partial_shape_size == 2u);
+ new_shape =
+ partial_shape_size == 3u ? ov::PartialShape({3, 1, input_size}) : ov::PartialShape({1, input_size});
+ } else if (input_name.find("cache_position") != std::string::npos) {
+ // NB: Whisper case
+ new_shape = ov::PartialShape({1});
+ } else if (input_name.find("encoder_hidden_states") != std::string::npos) {
+ // NB: Whisper case
+ const auto& partial_shape = input.get_partial_shape();
+ new_shape = partial_shape;
+ new_shape[0] = 1; // batch_dim
+ } else if (ov::npuw::matchEagle3HiddenStatesString(input_name)) {
+ new_shape = ov::npuw::Eagle3Extension::get_static_input(model, input, input_size);
+ } else if (ov::npuw::util::matchLoRAMatMulAString(input_name)) {
+ new_shape = ov::PartialShape({lora_rank, input.get_partial_shape()[1]});
+ } else if (ov::npuw::util::matchLoRAMatMulAlphaString(input_name)) {
+ new_shape = ov::PartialShape({input.get_partial_shape()[0], lora_rank});
+ } else if (ov::npuw::util::matchLoRAMatMulBString(input_name)) {
+ new_shape = ov::PartialShape({input.get_partial_shape()[0], lora_rank});
+ } else {
+ const auto& partial_shape = input.get_partial_shape();
+ new_shape = partial_shape;
+ new_shape[kv_axes_position.batch] = 1;
+ if (lhs_seq_size) { // Whisper model
+ new_shape[kv_axes_position.seq_len] = (input_name.find(".decoder") != std::string::npos)
+ ? kvcache_size - input_size // kv_size for decoder
+ : lhs_seq_size; // sequence size for encoder hidden states
+ } else { // LLM/VLM
+ new_shape[kv_axes_position.seq_len] = kvcache_size - input_size;
+ }
+ }
+ new_shapes.emplace(input_name, new_shape);
+ }
+ model->reshape(new_shapes);
+}
+
+} // namespace
+
+namespace ov::npuw {
+
+ReshapeToStatic::ReshapeToStatic(const uint32_t input_size,
+ const uint32_t kvcache_size,
+ const KVAxesPosition& kv_axes_position,
+ const uint32_t lora_rank,
+ const uint32_t lhs_seq_size)
+ : m_input_size(input_size),
+ m_kvcache_size(kvcache_size),
+ m_kv_axes_position(kv_axes_position),
+ m_lora_rank(lora_rank),
+ m_lhs_seq_size(lhs_seq_size) {}
+
+bool ReshapeToStatic::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ reshape_to_static(model, m_input_size, m_kvcache_size, m_kv_axes_position, m_lora_rank, m_lhs_seq_size);
+
+ return true;
+}
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.hpp
new file mode 100644
index 00000000000..83aa06f4eda
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.hpp
@@ -0,0 +1,29 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "kv_axes_position.hpp"
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+class ReshapeToStatic : public ov::pass::ModelPass {
+ uint32_t m_input_size;
+ uint32_t m_kvcache_size;
+ KVAxesPosition m_kv_axes_position;
+ uint32_t m_lora_rank;
+ uint32_t m_lhs_seq_size;
+
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::ReshapeToStatic");
+ explicit ReshapeToStatic(const uint32_t input_size,
+ const uint32_t kvcache_size,
+ const KVAxesPosition& kv_axes_position,
+ const uint32_t lora_rank,
+ const uint32_t lhs_seq_size = 0);
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.cpp
new file mode 100644
index 00000000000..146ec962976
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.cpp
@@ -0,0 +1,71 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "slice_out_embeds.hpp"
+
+#include "../llm_compiled_model.hpp"
+#include "openvino/op/ops.hpp"
+
+namespace {
+
+void slice_out_embeds(std::shared_ptr<ov::Model> model,
+ const uint32_t& batch_dim,
+ std::size_t max_generation_token_len) {
+ std::shared_ptr<ov::Node> embed_result;
+ for (auto&& output : model->outputs()) {
+ if (output.get_any_name() == ov::npuw::LLMCompiledModel::output_embeds) {
+ embed_result = output.get_node_shared_ptr();
+ }
+ }
+
+ if (embed_result) {
+ auto shape = embed_result->input(0).get_shape();
+ // If shape.size() is 3, then last axis should contain the rank of embedding dimension.
+ // But 1st and 2nd axes can mean different things.
+ // 1st axis can represent the batch size, while 2nd - the number of embeddings,
+ // or vice-versa (in chatglm)
+ if (shape.size() == 3) {
+ OPENVINO_ASSERT(batch_dim <= 1, "Unexpected value of batch_dim: ", batch_dim, ", expected 0 or 1!");
+ uint32_t num_embeds_dim = 1 - batch_dim;
+ OPENVINO_ASSERT(shape[num_embeds_dim] >= max_generation_token_len,
+ "Number of output embeddings should be greater or equal to the slicing range!");
+ if (shape[num_embeds_dim] != max_generation_token_len) {
+ std::vector<int32_t> start_pos{
+ static_cast<int32_t>(batch_dim * (shape[num_embeds_dim] - max_generation_token_len)),
+ static_cast<int32_t>(num_embeds_dim * (shape[num_embeds_dim] - max_generation_token_len)),
+ 0};
+ std::vector<int32_t> stop_pos{static_cast<int32_t>(batch_dim * (shape[num_embeds_dim] - 1)) + 1,
+ static_cast<int32_t>(num_embeds_dim * (shape[num_embeds_dim] - 1)) + 1,
+ static_cast<int32_t>(shape[2])};
+ auto start = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{3}, start_pos);
+ auto stop = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{3}, stop_pos);
+ auto step = std::make_shared<ov::op::v0::Constant>(ov::element::i32,
+ ov::Shape{3},
+ std::vector<int32_t>{1, 1, 1});
+
+ auto slice = std::make_shared<ov::op::v8::Slice>(embed_result->input_value(0), start, stop, step);
+
+ embed_result->input(0).replace_source_output(slice);
+ embed_result->validate_and_infer_types();
+ model->validate_nodes_and_infer_types();
+ }
+ }
+ }
+}
+
+} // namespace
+
+namespace ov::npuw {
+
+SliceOutEmbeds::SliceOutEmbeds(uint32_t batch_dim, std::size_t max_generation_token_len)
+ : m_batch_dim(batch_dim),
+ m_max_generation_token_len(max_generation_token_len) {}
+
+bool SliceOutEmbeds::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ slice_out_embeds(model, m_batch_dim, m_max_generation_token_len);
+
+ return true;
+}
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.hpp
new file mode 100644
index 00000000000..04425524b85
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.hpp
@@ -0,0 +1,24 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov::npuw {
+
+class SliceOutEmbeds : public ov::pass::ModelPass {
+ uint32_t m_batch_dim;
+ std::size_t m_max_generation_token_len;
+
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::SliceOutEmbeds");
+ explicit SliceOutEmbeds(uint32_t batch_dim, std::size_t max_generation_token_len);
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace ov::npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/whisper/prepare_whisper_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/whisper/prepare_whisper_model.cpp
new file mode 100644
index 00000000000..35bdc392a74
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/whisper/prepare_whisper_model.cpp
@@ -0,0 +1,514 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "prepare_whisper_model.hpp"
+
+#include <regex>
+
+#include "../llm_compiled_model_utils.hpp"
+#include "openvino/op/ops.hpp"
+#include "openvino/openvino.hpp"
+#include "openvino/opsets/opset13.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "openvino/pass/validate.hpp"
+
+namespace opp = ov::pass::pattern;
+
+namespace {
+
+// diagnostics warnings on OPENVINO_MATCHER_PASS_RTTI() definition: visibility hidden
+#ifdef __GNUC__
+# pragma GCC diagnostic push
+# pragma GCC diagnostic ignored "-Wattributes"
+#endif
+
+class AttentionMaskInputPast : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::AttentionMaskInputPast");
+
+ AttentionMaskInputPast(std::shared_ptr<ov::Model> model) {
+ auto range = opp::wrap_type<ov::op::v4::Range>();
+ auto convert1 = opp::wrap_type<ov::op::v0::Convert>({range});
+ auto greater = opp::wrap_type<ov::op::v1::Greater>({convert1, opp::any_input()});
+ auto convert2 = opp::wrap_type<ov::op::v0::Convert>({greater});
+
+ register_matcher(std::make_shared<opp::Matcher>(convert2, this->get_type_info().name),
+ [model](opp::Matcher& m) {
+ auto node = m.get_match_root();
+ auto attention_mask =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
+ attention_mask->get_output_tensor(0).set_names({"attention_mask"});
+ model->add_parameters({attention_mask});
+
+ auto cvt =
+ std::make_shared<ov::op::v0::Convert>(attention_mask->output(0), ov::element::f32);
+ ov::replace_node(node, cvt);
+ return false;
+ });
+ }
+};
+
+class AttentionMaskInputPast_2 : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::AttentionMaskInputPast_2");
+
+ AttentionMaskInputPast_2(std::shared_ptr<ov::Model> model) {
+ auto range = opp::wrap_type<ov::op::v4::Range>();
+ auto unsqueeze1 = opp::wrap_type<ov::op::v0::Unsqueeze>({range, opp::any_input()});
+ auto unsqueeze2 = opp::wrap_type<ov::op::v0::Unsqueeze>({unsqueeze1, opp::any_input()});
+ auto unsqueeze3 = opp::wrap_type<ov::op::v0::Unsqueeze>({unsqueeze2, opp::any_input()});
+ auto opt_convert = opp::optional<ov::op::v0::Convert>({unsqueeze3->output(0)});
+ auto lessequal = opp::wrap_type<ov::op::v1::LessEqual>({opt_convert, opp::any_input()});
+
+ register_matcher(
+ std::make_shared<opp::Matcher>(lessequal, this->get_type_info().name),
+ [model](opp::Matcher& m) {
+ auto node = m.get_match_root();
+ auto attention_mask =
+ std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{1, -1});
+ attention_mask->get_output_tensor(0).set_names({"attention_mask"});
+ model->add_parameters({attention_mask});
+
+ auto cst_0 = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, 0);
+ auto cst_1 = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, 1);
+ auto cst_2 = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, 2);
+
+ auto attn_mask_shape =
+ std::make_shared<ov::op::v3::ShapeOf>(attention_mask, ov::element::i64)->output(0);
+ auto gather = std::make_shared<ov::op::v8::Gather>(attn_mask_shape, cst_1, cst_0)->output(0);
+ auto attn_mask_size_minus_one = std::make_shared<ov::op::v1::Subtract>(gather, cst_1)->output(0);
+ auto slice = std::make_shared<ov::op::v8::Slice>(attention_mask->output(0),
+ cst_0,
+ attn_mask_size_minus_one,
+ cst_1,
+ cst_1);
+
+ auto unsqueeze_1 = std::make_shared<ov::op::v0::Unsqueeze>(slice->output(0), cst_1->output(0));
+ auto unsqueeze_2 = std::make_shared<ov::op::v0::Unsqueeze>(unsqueeze_1->output(0), cst_2->output(0));
+
+ auto equal = std::make_shared<ov::op::v1::Equal>(unsqueeze_2->output(0), cst_0->output(0));
+
+ ov::replace_node(node, equal);
+ return false;
+ });
+ }
+};
+
+class AttentionMaskInput : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::AttentionMaskInput");
+
+ AttentionMaskInput(std::shared_ptr<ov::Model> model,
+ const uint32_t& max_prompt_len,
+ const uint32_t& lhs_seq_size,
+ bool transform_cross_attn) {
+ std::vector<std::shared_ptr<ov::Node>> self_attn_nodes;
+ std::vector<std::shared_ptr<ov::Node>> cross_attn_nodes;
+ const auto kAttnMaskPort = 3;
+ for (auto node : model->get_ops()) {
+ if (ov::is_type<ov::op::v13::ScaledDotProductAttention>(node)) {
+ if (node->inputs().size() > kAttnMaskPort &&
+ ov::is_type<ov::op::v8::Slice>(node->input(kAttnMaskPort).get_source_output().get_node())) {
+ self_attn_nodes.push_back(node);
+ } else {
+ cross_attn_nodes.push_back(node);
+ }
+ }
+ }
+
+ // Self-attention
+ OPENVINO_ASSERT(!self_attn_nodes.empty());
+
+ auto attention_mask = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});
+ attention_mask->get_output_tensor(0).set_names({"attention_mask"});
+ model->add_parameters({attention_mask});
+
+ auto cst_ninf = std::make_shared<ov::op::v0::Constant>(ov::element::f32,
+ ov::Shape{1},
+ std::vector<float>{-std::numeric_limits<float>::max()});
+ auto cst_1 = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{1}, std::vector<float>{1});
+ auto cst_0 = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{1}, std::vector<float>{0});
+
+ auto slice = self_attn_nodes[0]->input(kAttnMaskPort).get_source_output().get_node_shared_ptr();
+ std::shared_ptr<ov::Node> slice_f32;
+ if (slice->get_element_type() == ov::element::boolean) {
+ slice_f32 = std::make_shared<ov::op::v1::Select>(slice->output(0), cst_0->output(0), cst_ninf->output(0));
+ } else {
+ slice_f32 = slice;
+ }
+ auto cvt = std::make_shared<ov::op::v0::Convert>(attention_mask->output(0), ov::element::f32);
+ auto add = std::make_shared<ov::op::v1::Add>(slice_f32->output(0), cvt->output(0));
+
+ auto trps = std::make_shared<ov::op::v1::Transpose>(
+ cvt->output(0),
+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{2}, std::vector<int>{1, 0}));
+ auto mtpl = std::make_shared<ov::op::v1::Multiply>(trps->output(0), add->output(0));
+
+ auto equal = std::make_shared<ov::op::v1::Equal>(mtpl->output(0), cst_1->output(0));
+ auto select = std::make_shared<ov::op::v1::Select>(equal->output(0), cst_0->output(0), cst_ninf->output(0));
+
+ for (auto self_attn : self_attn_nodes) {
+ self_attn->input(3).replace_source_output(select->output(0));
+ }
+
+ if (transform_cross_attn) {
+ // Cross attn
+ OPENVINO_ASSERT(!cross_attn_nodes.empty());
+ // FIXME: Should be taken from topology - don't hardcode!!!
+ auto shape_cst =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64,
+ ov::Shape{2},
+ std::vector<float>{static_cast<float>(max_prompt_len), 1});
+ auto target_shape = std::make_shared<ov::op::v0::Constant>(
+ ov::element::i64,
+ ov::Shape{2},
+ std::vector<float>{static_cast<float>(max_prompt_len), static_cast<float>(lhs_seq_size)});
+ // FIXME: Must be transpose if batch present
+ auto reshape = std::make_shared<ov::op::v1::Reshape>(cvt->output(0), shape_cst->output(0), false);
+ auto equal = std::make_shared<ov::op::v1::Equal>(reshape->output(0), cst_1->output(0));
+ auto select = std::make_shared<ov::op::v1::Select>(equal->output(0), cst_0->output(0), cst_ninf->output(0));
+ auto broadcast = std::make_shared<ov::op::v3::Broadcast>(select->output(0), target_shape->output(0));
+ auto unsq1 = std::make_shared<ov::op::v0::Unsqueeze>(broadcast->output(0), cst_0->output(0));
+ auto unsq2 = std::make_shared<ov::op::v0::Unsqueeze>(unsq1->output(0), cst_1->output(0));
+ for (auto cross_attn_node : cross_attn_nodes) {
+ if (cross_attn_node->inputs().size() == 3) {
+ auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(
+ cross_attn_node->input(0).get_source_output(),
+ cross_attn_node->input(1).get_source_output(),
+ cross_attn_node->input(2).get_source_output(),
+ unsq2->output(0),
+ false);
+ ov::replace_node(cross_attn_node, sdpa);
+ } else {
+ cross_attn_node->input(3).replace_source_output(unsq2->output(0));
+ }
+ }
+ }
+ }
+};
+
+class CachePositionInput : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::LLMCompiledModel::CachePositionInput");
+
+ CachePositionInput(std::shared_ptr<ov::Model> model) {
+ auto gather = opp::wrap_type<ov::op::v8::Gather>({opp::any_input(), opp::any_input(), opp::any_input()});
+ auto add = opp::wrap_type<ov::op::v1::Add>({gather, opp::any_input()});
+ auto range = opp::wrap_type<ov::op::v4::Range>({gather, add, opp::any_input()});
+ auto unsqueeze = opp::wrap_type<ov::op::v0::Unsqueeze>({range, opp::any_input()});
+ auto tile = opp::wrap_type<ov::op::v0::Tile>({unsqueeze, opp::any_input()});
+
+ register_matcher(
+ std::make_shared<opp::Matcher>(tile, this->get_type_info().name),
+ [model, unsqueeze](opp::Matcher& m) {
+ auto& node_to_output = m.get_pattern_value_map();
+ auto unsqueeze_node = node_to_output.at(unsqueeze).get_node_shared_ptr();
+ auto matched_unsqueeze = std::static_pointer_cast<ov::op::v0::Unsqueeze>(unsqueeze_node);
+
+ auto cache_position = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1});
+ cache_position->get_output_tensor(0).set_names({"cache_position"});
+ cache_position->set_friendly_name("cache_position");
+ model->add_parameters({cache_position});
+ std::shared_ptr<ov::Node> cache_pos_unsqueeze_arg;
+ if (matched_unsqueeze->input(0).get_element_type() == ov::element::f32) {
+ cache_pos_unsqueeze_arg = std::make_shared<ov::op::v0::Convert>(cache_position, ov::element::f32);
+ } else {
+ cache_pos_unsqueeze_arg = cache_position;
+ }
+
+ matched_unsqueeze->input(0).replace_source_output(cache_pos_unsqueeze_arg->output(0));
+ return false;
+ });
+ }
+};
+
+auto remove_encoder_attn_read_value(const std::shared_ptr<ov::Node>& rv_node,
+ const ov::Output<ov::Node>& kv_out,
+ const ov::Input<ov::Node>& sdpa_in) {
+ // Find Assign node
+ OPENVINO_ASSERT(rv_node->outputs().size() == 1);
+ auto rv_out = rv_node->outputs()[0];
+ ov::NodeVector rv_readers;
+ for (const auto& target_in : rv_out.get_target_inputs()) {
+ rv_readers.push_back(target_in.get_node()->shared_from_this());
+ }
+ // Assign and SDPA
+ OPENVINO_ASSERT(rv_readers.size() == 2);
+ auto assign_node = (strstr(rv_readers[0]->get_type_name(), "Assign") != nullptr) ? rv_readers[0] : rv_readers[1];
+ OPENVINO_ASSERT(strstr(assign_node->get_type_name(), "Assign") != nullptr);
+ // Redirect KV-cache tensor to SDPA
+ sdpa_in.replace_source_output(kv_out);
+ return std::make_pair(std::make_shared<ov::op::v0::Result>(kv_out),
+ ov::as_type_ptr<ov::op::v6::Assign>(assign_node));
+}
+
+std::string transform_key_value_name(std::string input_string,
+ std::string prefix,
+ std::string enc_or_dec,
+ std::string key_or_value) {
+ std::regex pattern("[0-9]+");
+ std::smatch match;
+ std::regex_search(input_string, match, pattern);
+
+ if (match.empty())
+ OPENVINO_THROW("Input string does not match the expected pattern");
+
+ auto number = std::string(match[0]);
+ return prefix + "." + number + enc_or_dec + key_or_value;
+}
+
+void set_name(std::shared_ptr<ov::Node> result, const std::string& name) {
+ result->set_friendly_name(name);
+ result->get_output_tensor(0).set_names({name});
+}
+
+bool is_fake_cvt_to_key_tensor(const ov::Input<ov::Node>& reader) {
+ auto fc_reader = reader.get_node()->outputs()[0].get_target_inputs();
+ // FakeConvert node has only 1 consumer
+ OPENVINO_ASSERT(fc_reader.size() == 1);
+ // FakeConvert -> SDPA : 'key' tensor is input with index 1 to SDPA
+ return fc_reader.begin()->get_index() == 1;
+}
+
+void expose_runtime_states_as_outputs(const std::shared_ptr<ov::Model>& model) {
+ // Find all ReadValue nodes
+ ov::NodeVector read_value_nodes;
+ for (const auto& op : model->get_ops()) {
+ if (strstr(op->get_type_name(), "ReadValue") != nullptr) {
+ read_value_nodes.push_back(op);
+ }
+ }
+
+ // Holds result layers for cross-attn KV-cache tensors
+ ov::ResultVector results;
+ ov::SinkVector assigns;
+
+ // Go through all ReadValue nodes and remove them
+ for (const auto& rv_node : read_value_nodes) {
+ OPENVINO_ASSERT(rv_node->inputs().size() == 1);
+ OPENVINO_ASSERT(rv_node->outputs().size() == 1);
+ auto rv_in = rv_node->inputs()[0];
+ auto x = rv_in.get_source_output();
+ auto rv_out = rv_node->outputs()[0];
+ // Gather all nodes that read from ReadValue, there must be SDPA and Assign
+ auto rv_readers = rv_out.get_target_inputs();
+ OPENVINO_ASSERT(rv_readers.size() == 2);
+ // Input port for SDPA node
+ for (const auto& reader : rv_readers) {
+ bool is_fake_cvt = strstr(reader.get_node()->get_type_name(), "FakeConvert") != nullptr;
+ if (strstr(reader.get_node()->get_type_name(), "ScaledDotProductAttention") != nullptr || is_fake_cvt) {
+ auto sdpa_in = reader;
+
+ // In case there's additional FakeConvert node(fp8): ReadValue -> FakeConvert -> SDPA
+ auto is_fc_key_tensor = is_fake_cvt ? is_fake_cvt_to_key_tensor(reader) : false;
+
+ // Remove ReadValue, store new Result and Assign
+ auto key_or_value = (sdpa_in.get_index() == 1 || is_fc_key_tensor) ? "key" : "value";
+ auto [result, assign] = remove_encoder_attn_read_value(rv_node, rv_in.get_source_output(), sdpa_in);
+ auto normalized_name =
+ transform_key_value_name(rv_node->inputs()[0].get_source_output().get_node()->get_friendly_name(),
+ "present",
+ ".encoder.",
+ key_or_value);
+ set_name(result, normalized_name);
+ results.push_back(result);
+ assigns.push_back(assign);
+ }
+ }
+ }
+
+ // Add, remove, validate
+ model->add_results(results);
+ for (const auto& assign : assigns) {
+ model->remove_sink(assign);
+ }
+ model->validate_nodes_and_infer_types();
+}
+
+void remove_cache_position(const std::shared_ptr<ov::Model>& model) {
+ // Build subgraph that will replace cache_pos
+ auto input_ids = model->input("input_ids").get_node();
+ auto shape_of_node = std::make_shared<ov::op::v3::ShapeOf>(input_ids->outputs()[0]);
+
+ std::vector<int> v_0{0};
+ std::vector<int> v_1{1};
+
+ auto indices = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, v_1);
+ indices->set_friendly_name("indices");
+ auto axis = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, v_0);
+ axis->set_friendly_name("axis");
+
+ auto gather_node = std::make_shared<ov::op::v8::Gather>(shape_of_node->outputs()[0], indices, axis);
+
+ auto cst_node = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, v_0);
+ auto step = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{}, v_1);
+ step->set_friendly_name("step");
+ auto range_node = std::make_shared<ov::op::v4::Range>(cst_node->outputs()[0],
+ gather_node->outputs()[0],
+ step->outputs()[0],
+ ov::element::i64);
+ // Replace cache_position
+ auto cache_pos =
+ ov::as_type_ptr<ov::op::v0::Parameter>(model->input("cache_position").get_node()->shared_from_this());
+ for (const auto& target_input : cache_pos->outputs()[0].get_target_inputs()) {
+ target_input.replace_source_output(range_node->outputs()[0]);
+ }
+
+ model->remove_parameter(cache_pos);
+ model->validate_nodes_and_infer_types();
+}
+
+void expose_runtime_states_as_inputs(const std::shared_ptr<ov::Model>& model) {
+ // Store Assign nodes to perform remove_sink later on
+ ov::SinkVector assigns;
+ // To add new Params to the model
+ ov::ParameterVector params;
+
+ ov::NodeVector read_value_nodes;
+ for (const auto& op : model->get_ops()) {
+ if (strstr(op->get_type_name(), "ReadValue") != nullptr) {
+ read_value_nodes.push_back(op);
+ }
+ }
+
+ for (const auto& rv_node : read_value_nodes) {
+ auto rv_out = rv_node->outputs()[0];
+ auto rv_readers = rv_out.get_target_inputs();
+ for (auto rv_reader : rv_readers) {
+ bool is_fake_cvt = strstr(rv_reader.get_node()->get_type_name(), "FakeConvert") != nullptr;
+ if (strstr(rv_reader.get_node()->get_type_name(), "Assign") != nullptr) {
+ auto assign_node = ov::as_type_ptr<ov::op::v6::Assign>(rv_reader.get_node()->shared_from_this());
+ assigns.push_back(assign_node);
+ } else if (strstr(rv_reader.get_node()->get_type_name(), "ScaledDotProductAttention") != nullptr ||
+ is_fake_cvt) {
+ auto sdpa_in = rv_reader;
+
+ auto shape = rv_node->get_output_partial_shape(0);
+ auto new_param = std::make_shared<ov::op::v0::Parameter>(rv_node->get_output_element_type(0), shape);
+
+ // In case there's additional FakeConvert node(fp8): ReadValue -> FakeConvert -> SDPA
+ auto is_fc_key_tensor = is_fake_cvt ? is_fake_cvt_to_key_tensor(rv_reader) : false;
+
+ auto key_or_value = (sdpa_in.get_index() == 1 || is_fc_key_tensor) ? "key" : "value";
+ auto normalized_name = transform_key_value_name(sdpa_in.get_node()->get_friendly_name(),
+ "past_key_values",
+ ".encoder.",
+ key_or_value);
+ set_name(new_param, normalized_name);
+
+ params.push_back(new_param);
+ sdpa_in.replace_source_output(new_param->outputs()[0]);
+ }
+ }
+ }
+
+ // Remove sinks and add new params
+ model->add_parameters(params);
+ for (const auto& assign : assigns) {
+ model->remove_sink(assign);
+ }
+}
+
+void normalize_input_key_value_names(const std::shared_ptr<ov::Model>& model) {
+ ov::ResultVector new_results, old_results;
+ for (const auto& in : model->inputs()) {
+ if (in.get_any_name().find("decoder") == std::string::npos) {
+ continue;
+ }
+
+ auto key_or_value = (in.get_any_name().find(".key") != std::string::npos) ? "key" : "value";
+ auto normalized_name =
+ transform_key_value_name(in.get_any_name(), "past_key_values", ".decoder.", key_or_value);
+ set_name(in.get_node_shared_ptr(), normalized_name);
+ }
+
+ model->validate_nodes_and_infer_types();
+}
+
+void normalize_output_key_value_names(const std::shared_ptr<ov::Model>& model) {
+ ov::ResultVector new_results, old_results;
+ for (const auto& out : model->outputs()) {
+ if (out.get_any_name().find("decoder") == std::string::npos) {
+ continue;
+ }
+
+ auto key_or_value = (out.get_any_name().find(".key") != std::string::npos) ? "key" : "value";
+ auto normalized_name = transform_key_value_name(out.get_any_name(), "present", ".decoder.", key_or_value);
+ set_name(out.get_node_shared_ptr(), normalized_name);
+ }
+
+ model->validate_nodes_and_infer_types();
+}
+
+void add_attention_mask_input(const std::shared_ptr<ov::Model>& model,
+ const uint32_t& max_prompt_size = 0,
+ const uint32_t& lhs_seq_size = 0,
+ bool transform_cross_attn = false) {
+ ov::pass::GraphRewrite rewr;
+ if (transform_cross_attn) {
+ rewr.add_matcher<AttentionMaskInput>(model, max_prompt_size, lhs_seq_size, transform_cross_attn);
+ } else {
+ rewr.add_matcher<AttentionMaskInputPast>(model);
+ rewr.add_matcher<AttentionMaskInputPast_2>(model); // transformers>=4.53
+ }
+
+ rewr.run_on_model(model);
+
+ ov::pass::Validate().run_on_model(model);
+}
+
+void add_cache_position_input(const std::shared_ptr<ov::Model>& model) {
+ ov::pass::GraphRewrite rewr;
+ rewr.add_matcher<CachePositionInput>(model);
+ rewr.run_on_model(model);
+
+ ov::pass::Validate().run_on_model(model);
+}
+
+#ifdef __GNUC__
+# pragma GCC diagnostic pop
+#endif
+
+} // namespace
+
+bool ov::npuw::util::PrepareWhisperPrefillModel::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ // 2) Remove all non-runtime states from inputs (they empty on first iteration)
+ // remove_input_kv_tensors(model); -> Done for LLM also
+ // 3) Expose all states that requires initialization on the first run as outputs
+ expose_runtime_states_as_outputs(model);
+ // 4) Remove cache_position input if it exists
+ if (has_input(model, "cache_position")) {
+ remove_cache_position(model);
+ }
+ // 5) Normalize output names - should be done in stateful_to_stateless_transformation
+ normalize_output_key_value_names(model);
+
+ add_attention_mask_input(model, m_max_prompt_size, m_lhs_seq_size, true);
+
+ model->validate_nodes_and_infer_types();
+
+ return true;
+}
+
+bool ov::npuw::util::PrepareWhisperKVCacheModel::run_on_model(const std::shared_ptr<ov::Model>& model) {
+ normalize_input_key_value_names(model);
+ normalize_output_key_value_names(model);
+ expose_runtime_states_as_inputs(model);
+
+ if (!has_input(model, "cache_position")) {
+ add_cache_position_input(model);
+ }
+
+ add_attention_mask_input(model);
+
+ model->reshape({{"input_ids", ov::PartialShape({-1, 1})}});
+
+ model->validate_nodes_and_infer_types();
+
+ return true;
+}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/whisper/prepare_whisper_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/whisper/prepare_whisper_model.hpp
new file mode 100644
index 00000000000..69265be42d4
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/whisper/prepare_whisper_model.hpp
@@ -0,0 +1,39 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstdint>
+#include <memory>
+
+#include "openvino/pass/pass.hpp"
+
+namespace ov {
+namespace npuw {
+namespace util {
+
+class PrepareWhisperPrefillModel : public ov::pass::ModelPass {
+ uint32_t m_max_prompt_size;
+ uint32_t m_lhs_seq_size;
+
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::PrepareWhisperPrefillModel");
+ explicit PrepareWhisperPrefillModel(uint32_t max_prompt_size, uint32_t lhs_seq_size)
+ : m_max_prompt_size(max_prompt_size),
+ m_lhs_seq_size(lhs_seq_size) {}
+
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+class PrepareWhisperKVCacheModel : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::PrepareWhisperKVCacheModel");
+ PrepareWhisperKVCacheModel() = default;
+
+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
+};
+
+} // namespace util
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/whisper_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/whisper/whisper_infer_request.cpp
similarity index 98%
rename from src/plugins/intel_npu/src/plugin/npuw/whisper_infer_request.cpp
rename to src/plugins/intel_npu/src/plugin/npuw/whisper/whisper_infer_request.cpp
index 0b469b1c710..cc11d571560 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/whisper_infer_request.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/whisper/whisper_infer_request.cpp
@@ -6,9 +6,9 @@
#include <regex>
-#include "../../utils/include/intel_npu/utils/zero/zero_remote_tensor.hpp"
-#include "infer_request_utils.hpp"
-#include "logging.hpp"
+#include "../../../utils/include/intel_npu/utils/zero/zero_remote_tensor.hpp"
+#include "../infer_request_utils.hpp"
+#include "../logging.hpp"
#include "openvino/runtime/iasync_infer_request.hpp"
namespace {
diff --git a/src/plugins/intel_npu/src/plugin/npuw/whisper_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/whisper/whisper_infer_request.hpp
similarity index 94%
rename from src/plugins/intel_npu/src/plugin/npuw/whisper_infer_request.hpp
rename to src/plugins/intel_npu/src/plugin/npuw/whisper/whisper_infer_request.hpp
index b5ff58ffe76..766a1af6caa 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/whisper_infer_request.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/whisper/whisper_infer_request.hpp
@@ -4,7 +4,7 @@
#pragma once
-#include "llm_infer_request.hpp"
+#include "../llm_infer_request.hpp"
namespace ov {
namespace npuw {
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index 89860abe77b..95c5228ea7e 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -48,9 +48,12 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.cpp
- ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/whisper_infer_request.cpp
- ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/embedding_infer_request.cpp
- ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/embedding_model_utils.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/whisper/whisper_infer_request.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/whisper/prepare_whisper_model.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/embedding/embedding_infer_request.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/embedding/prepare_embedding_model.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/embedding/redirect_new_kv_to_output.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/embedding/remove_empty_kv_inputs.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cpp
@@ -77,6 +80,17 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/moe_unroll_patterns.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/device_routed_moe_transform.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/gather_to_2d_gather.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/moe_transformations/apply_moe_device_routed_transforms.cpp
+ # npuw_transformations
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/decompose_gqa.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_phi3_sliding_mask.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/phi3_sliding_mask.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_sliced_head_to_static.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/slice_out_embeds.cpp
# kokoro pipeline
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pipelines/kokoro/kokoro_compiled_model.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pipelines/kokoro/kokoro_infer_request.cpp
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.cpp
index 83cd18b3db2..a702b5e01b8 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
@@ -12,9 +12,8 @@
#include <utility>
#include <vector>
-#include "embedding_model_utils.hpp"
#include "llm_test_helpers.hpp"
-#include "llm_compiled_model_utils.hpp"
+#include "whisper/prepare_whisper_model.hpp"
#include "openvino/pass/stateful_to_stateless.hpp"
namespace {
diff --git a/src/plugins/intel_npu/tests/unit/npuw/transpose_vt.cpp b/src/plugins/intel_npu/tests/unit/npuw/transpose_vt.cpp
index 56ea6003299..87ecb1153fd 100644
--- a/src/plugins/intel_npu/tests/unit/npuw/transpose_vt.cpp
+++ b/src/plugins/intel_npu/tests/unit/npuw/transpose_vt.cpp
@@ -8,6 +8,7 @@
#include "llm_compiled_model_utils.hpp"
#include "partitioning/partitioning.hpp"
#include "intel_npu/config/config.hpp"
+#include "npuw_transformations/optimize_value_tensors.hpp"
/*
* conditional compilation that can be used during test regression debug