OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
NPUW: Introduce a pattern to handle SDPA (#32283)
Dmitry Matveev36a8f092d325
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cppindex cdf886efbbc..acc18994029 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@@ -20,6 +20,7 @@#include "openvino/runtime/iasync_infer_request.hpp"#include "openvino/runtime/properties.hpp"#include "partitioning/patterns/pre_compute.hpp"+#include "partitioning/patterns/sdpa.hpp"#include "serialization.hpp"#include "transformations/convert_precision.hpp"#include "util.hpp"@@ -990,6 +991,15 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m}}+ // Regularize models for the better partitioning assuming it is a transformer+ {+ ov::pass::GraphRewrite rewr;+ rewr.add_matcher<ov::npuw::patterns::regularize::AttentionBroadcast>();+ rewr.add_matcher<ov::npuw::patterns::regularize::ShapeOfParameter>();+ rewr.run_on_model(kvcache_model);+ rewr.run_on_model(prefill_model);+ }+m_kvcache_compiled = std::dynamic_pointer_cast<ov::npuw::CompiledModel>(ov::npuw::ICompiledModel::create(kvcache_model, plugin, generate_config));NPUW_ASSERT(m_kvcache_compiled && "Can't create ov::npuw::CompiledModel for passed kvcache "diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/compiler.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/compiler.cppindex 61bf46ebeae..908b6267f49 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/compiler.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/compiler.cpp@@ -94,7 +94,7 @@ class Compiler {REP, // Repeated blocks pipeline - combination of repeatedBlocks and RemnantsREG, // Regularized repeated blocks pipeline - same as REP, but with some strong hints firstCOMPUTE, // Separates non-foldable compute subgraphs from the model based on predefined rules + REP- SPATIAL // Similar to COMPUTE but allows folding+ SPATIAL // Similar to COMPUTE but allows folding & dynamic chunk submission for FFN/QKV (LLM)};template <class C>@@ -129,9 +129,13 @@ class Compiler {}}- std::vector<Isolate> getAllIsolates() {- auto isolates = ov::npuw::online::util::getIsolates(ov::npuw::online::util::ISOL_PRESETS.at("COMPUTE"));- for (const auto& isol : ov::npuw::online::util::getIsolates(ov::npuw::online::util::ISOL_PRESETS.at("FAKE"))) {+ std::vector<Isolate> getComputeIsolates() {+ // NB: Think twice before adding any new patterns here!+ // In the most cases, you don't - this is a very specific+ // type of patterns to isolate compute-intense parts ONLY!+ namespace ou = ov::npuw::online::util;+ auto isolates = ou::getIsolates(ou::ISOL_PRESETS.at("COMPUTE"));+ for (const auto& isol : ou::getIsolates(ou::ISOL_PRESETS.at("FAKE"))) {isolates.push_back(isol);}return isolates;@@ -206,6 +210,7 @@ class Compiler {m_snapshot->earlyRegroup();m_snapshot->repeatedBlocks([&]() {// This callback is called when repeatingBlocks algorithm thinks it is done+ // NB: the "fake" tag is stripped elsewhere, that's how it worksm_snapshot->stripTag("compute");});m_snapshot->repeat([&] {@@ -257,17 +262,18 @@ public:// Only get isolates here.// NB: We ignore NO_FOLD everywhere except pipeline COMPUTE - this needs// to be aligned in the future- ctx.isolates = getAllIsolates();+ ctx.isolates = getComputeIsolates();m_snapshot->setCtx(ctx);reg();break;case Pipeline::COMPUTE:+ // FIXME: It is probably the time to retire this pipelinewarn_unused<::intel_npu::NPUW_ONLINE_ISOLATE>();warn_unused<::intel_npu::NPUW_ONLINE_NO_FOLD>();// Manually set predefined isolates and nofolds then do rep() pipeline// FIXME: initialize via a dedicated function instead of parsing- ctx.isolates = getAllIsolates();+ ctx.isolates = getComputeIsolates();ctx.nofolds = ov::npuw::online::util::getNoFolds("compute");m_snapshot->setCtx(ctx);rep();@@ -278,7 +284,7 @@ public:// Manually set predefined isolates and nofolds then do rep() pipeline// FIXME: initialize via a dedicated function instead of parsing- ctx.isolates = getAllIsolates();+ ctx.isolates = getComputeIsolates();m_snapshot->setCtx(ctx);rep();break;diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cppindex a6d45ee887c..4ea70b69c5c 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/snapshot.cpp@@ -8,6 +8,7 @@#include "../../util.hpp"#include "../patterns/avoid.hpp"#include "../patterns/compute.hpp"+#include "../patterns/sdpa.hpp"#include "group.hpp"#include "openvino/op/util/op_types.hpp"#include "openvino/opsets/opset1.hpp"@@ -506,6 +507,11 @@ void Snapshot::earlyRegroup() {if (isolate.pattern == #p) { \rewr_fake.add_matcher<ov::npuw::patterns::compute::p>(shared_from_this(), isolate.tag); \handle_patterns = true; \+ }+#define HNDL_ATTN(p) \+ if (isolate.pattern == #p) { \+ rewr.add_matcher<ov::npuw::patterns::attn::p>(shared_from_this(), isolate.tag); \+ handle_patterns = true; \}HNDL(RMSNorm);HNDL(RMSNorm2);@@ -520,11 +526,16 @@ void Snapshot::earlyRegroup() {HNDL(VariadicSplit);HNDL_FAKE(FakeConvert);HNDL_FAKE(FakeQuantize);+ HNDL_ATTN(SDPA);+#undef HNDL_SPDA#undef HNDL_FAKE#undef HNDL}}}+ // FIXME: No warning here if the pattern is unknown?+ // FIXME: High coupling, known patterns mnemonics are listed in utils+ // (see ISOL_PRESETS), but actual passes handled here!if (handle_patterns) {// Check the model for all specified patternsdiff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hppindex f3b870b1c19..84ec271bd32 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp@@ -96,7 +96,8 @@ static const std::map<std::string, std::string> ISOL_PRESETS = {{"COMPUTE","P:RMSNorm/compute,P:RMSNorm2/compute,""P:RMSNorm3/compute,P:RMSNorm4/compute,""P:VariadicSplit/compute"},- {"FAKE", "P:FakeConvert/fake,P:FakeQuantize/fake"}};+ {"FAKE", "P:FakeConvert/fake,P:FakeQuantize/fake"},+ {"ATTN", "P:SDPA/attn"}};} // namespace util} // namespace onlinediff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.cppnew file mode 100644index 00000000000..506bd1b6f2a--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.cpp@@ -0,0 +1,152 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "sdpa.hpp"++#include <iostream>++#include "../../logging.hpp"+#include "../online/group.hpp" // online::Group+#include "../online/snapshot.hpp" // online::Snapshot+#include "openvino/op/ops.hpp"+#include "openvino/pass/pattern/op/label.hpp" // any_input+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "openvino/util/common_util.hpp"++namespace ov {+namespace npuw {+namespace patterns {+namespace attn {++namespace opp = ov::pass::pattern;++SDPA::SDPA(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag) {+ auto past_k_in = opp::wrap_type<ov::op::v0::Parameter>();+ auto past_k_cvt = opp::optional<ov::op::v0::Convert>({past_k_in->output(0)});+ auto past_k_cat = opp::wrap_type<ov::op::v0::Concat>({past_k_cvt, opp::any_input()});++ auto past_v_in = opp::wrap_type<ov::op::v0::Parameter>();+ auto past_v_cvt = opp::optional<ov::op::v0::Convert>({past_v_in->output(0)});+ auto past_v_cat = opp::wrap_type<ov::op::v0::Concat>({past_v_cvt, opp::any_input()});++ // Optional part, probably one of many. Replace by graph traversal!+ auto opt_unsq_k = opp::optional<ov::op::v0::Unsqueeze>({past_k_cat->output(0), opp::any_input()});+ auto opt_bcast_k = opp::optional<ov::op::v3::Broadcast>({opt_unsq_k->output(0), opp::any_input()});+ auto opt_rshp_k = opp::optional<ov::op::v1::Reshape>({opt_bcast_k->output(0), opp::any_input()});++ auto opt_unsq_v = opp::optional<ov::op::v0::Unsqueeze>({past_v_cat->output(0), opp::any_input()});+ auto opt_bcast_v = opp::optional<ov::op::v3::Broadcast>({opt_unsq_v->output(0), opp::any_input()});+ auto opt_rshp_v = opp::optional<ov::op::v1::Reshape>({opt_bcast_v->output(0), opp::any_input()});++ auto sdpa = opp::wrap_type<ov::op::v13::ScaledDotProductAttention>(+ {opp::any_input(), opt_rshp_k, opt_rshp_v, opp::any_input(), opp::any_input()});+ auto trans = opp::wrap_type<ov::op::v1::Transpose>({sdpa, opp::any_input()});+ auto reshape = opp::wrap_type<ov::op::v1::Reshape>({trans, opp::any_input()});++ auto node_to_gptr = snapshot->getNodeToGroupMap();++ // Note: Use [=] to make sure the above objects stay alive in the callback+ auto callback = [=](ov::pass::pattern::Matcher& m) {+ auto& node_to_output = m.get_pattern_value_map();+ auto pattern_nodes = std::vector<std::shared_ptr<ov::Node>>{past_k_in,+ past_k_cvt,+ past_k_cat,+ past_v_in,+ past_v_cvt,+ past_v_cat,+ opt_unsq_k,+ opt_bcast_k,+ opt_rshp_k,+ opt_unsq_v,+ opt_bcast_v,+ opt_rshp_v,+ sdpa,+ trans,+ reshape};+ for (auto&& pattern_node : pattern_nodes) {+ if (auto match_iter = node_to_output.find(pattern_node); match_iter != node_to_output.end()) {+ auto matched_node = match_iter->second.get_node_shared_ptr();+ if (auto group_iter = node_to_gptr->find(matched_node); group_iter != node_to_gptr->end()) {+ group_iter->second->isolate(isol_tag);+ }+ }+ }+ return false; // root hasn't changed+ };+ register_matcher(std::make_shared<opp::Matcher>(reshape, "TagSDPA"), std::move(callback));+}++} // namespace attn++namespace regularize {++namespace opp = ov::pass::pattern;++AttentionBroadcast::AttentionBroadcast() {+ // NB(dm): We've seen cases where this dynamic subgraph is placed on the K-path,+ // but I'd expect it could be on the V-path as well - so _kv in the name+ auto past_kv_in = opp::wrap_type<ov::op::v0::Parameter>();+ auto past_kv_cvt = opp::optional<ov::op::v0::Convert>({past_kv_in->output(0)});+ auto past_kv_cat = opp::wrap_type<ov::op::v0::Concat>({past_kv_cvt, opp::any_input()});++ // The dynamic shape calculation to be eliminated+ // NB: It only works in static shape graphs+ auto shape_of = opp::wrap_type<ov::op::v3::ShapeOf>({past_kv_cat});+ auto gather = opp::wrap_type<ov::op::v8::Gather>({shape_of, opp::any_input(), opp::any_input()});+ auto concat = opp::wrap_type<ov::op::v0::Concat>({gather, opp::any_input(), opp::any_input(), opp::any_input()});++ // Broadcast - the consumer+ auto unsq_kv = opp::wrap_type<ov::op::v0::Unsqueeze>({past_kv_cat, opp::any_input()});+ auto bcast_kv = opp::wrap_type<ov::op::v3::Broadcast>({unsq_kv, concat});++ // Note: Use [=] to make sure the above objects stay alive in the callback+ auto callback = [=](ov::pass::pattern::Matcher& m) {+ auto& node_to_output = m.get_pattern_value_map();+ auto matched_concat_out = node_to_output.at(concat);+ auto& matched_concat_tensor = matched_concat_out.get_tensor();+ if (matched_concat_tensor.has_and_set_bound()) {+ // Replace the dynamic shape calculation with a static constant+ // This is bad but it in the current realm it is what it is+ auto new_const = std::make_shared<ov::op::v0::Constant>(matched_concat_tensor.get_upper_value());+ new_const->set_friendly_name("NPUW/Precalculated/" ++ matched_concat_out.get_node_shared_ptr()->get_friendly_name());+ for (auto&& input : matched_concat_out.get_target_inputs()) {+ input.replace_source_output(new_const);+ }+ }+ return false; // root hasn't changed+ };+ register_matcher(std::make_shared<opp::Matcher>(bcast_kv, "AttentionBroadcast"), std::move(callback));+}++ShapeOfParameter::ShapeOfParameter() {+ auto param_in = opp::wrap_type<ov::op::v0::Parameter>();+ auto param_cvt = opp::wrap_type<ov::op::v0::Convert>({param_in});+ auto param_shp = opp::wrap_type<ov::op::v3::ShapeOf>({param_cvt});++ // Note: Use [=] to make sure the above objects stay alive in the callback+ auto callback = [=](ov::pass::pattern::Matcher& m) {+ auto& node_to_output = m.get_pattern_value_map();+ // Replace the path with a known constant too+ auto matched_shape_out = node_to_output.at(param_shp);+ auto& matched_shape_tensor = matched_shape_out.get_tensor();+ if (matched_shape_tensor.has_and_set_bound()) {+ auto new_const = std::make_shared<ov::op::v0::Constant>(matched_shape_tensor.get_upper_value());+ new_const->set_friendly_name("NPUW/Precalculated/" ++ matched_shape_out.get_node_shared_ptr()->get_friendly_name());+ for (auto&& input : matched_shape_out.get_target_inputs()) {+ input.replace_source_output(new_const);+ }+ }+ return false; // root hasn't changed (?)+ };+ register_matcher(std::make_shared<opp::Matcher>(param_shp, "ShapeOfParameter"), std::move(callback));+}++} // namespace regularize++} // namespace patterns+} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.hppnew file mode 100644index 00000000000..83fba08b9d2--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.hpp@@ -0,0 +1,51 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <string>++#include "openvino/openvino.hpp"+#include "openvino/pass/graph_rewrite.hpp"++namespace ov {+namespace npuw {++namespace online {+class Snapshot; // Forward declaration+} // namespace online++namespace patterns {++// Note: the patterns below are only utilized by the online partitioner+namespace attn {++class SDPA : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::attn::SDPA");+ SDPA(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);+};++} // namespace attn++namespace regularize {++class AttentionBroadcast : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::attn::AttentionBroadcast");+ AttentionBroadcast();+};++class ShapeOfParameter : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::attn::ShapeOfParameter");+ ShapeOfParameter();+};++} // namespace regularize++} // namespace patterns+} // namespace npuw+} // namespace ov