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: Refactor dynamic attention as a subgraph behavior (#35645)
Dmitry Matveeva5247d3e30ec
diff --git a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cppnew file mode 100644index 00000000000..9a51a17dd8d--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp@@ -0,0 +1,169 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "attn_subgraph.hpp"++#include "../attention.hpp"+#include "../just_sync_infer_request.hpp"+#include "../logging.hpp"+#include "../partitioning/partitioning.hpp"+#include "../partitioning/patterns/sdpa.hpp"++namespace ov {+namespace npuw {+namespace attn {+namespace {++ov::npuw::JustInferRequest& get_request(ov::npuw::v1::subgraphs::InferContext& ctx) {+ auto* request = dynamic_cast<ov::npuw::JustInferRequest*>(&ctx.infer_request);+ OPENVINO_ASSERT(request != nullptr, "Expected JustInferRequest for attention runtime behavior");+ return *request;+}++BehaviorKind get_behavior_kind(const ov::npuw::v1::subgraphs::Context& ctx) {+ if (const auto* kind = ctx.get_if<BehaviorKind>()) {+ return *kind;+ }+ OPENVINO_THROW("Attention behavior context is missing BehaviorKind");+}++ov::npuw::v1::subgraphs::RuntimeBehaviorFactory make_runtime_factory() {+ return [](const ov::npuw::v1::subgraphs::Context& ctx) -> ov::npuw::v1::subgraphs::ISubgraphBehavior::Ptr {+ class AttnBehavior final : public ov::npuw::v1::subgraphs::ISubgraphBehavior {+ public:+ explicit AttnBehavior(BehaviorKind kind) : m_kind(kind) {}++ bool bind_function_input(ov::npuw::v1::subgraphs::InferContext& ctx,+ std::size_t input_idx,+ const ov::SoPtr<ov::ITensor>& tensor) override {+ auto& request = get_request(ctx);+ switch (m_kind) {+ case BehaviorKind::Dynamic:+ return request.behavior_bind_dynamic_input(ctx.real_subgraph_idx,+ ctx.subgraph_idx,+ input_idx,+ tensor);+ case BehaviorKind::Pyramid:+ return request.behavior_bind_pyramid_input(ctx.real_subgraph_idx,+ ctx.subgraph_idx,+ input_idx,+ tensor);+ case BehaviorKind::HFA:+ return request.behavior_bind_hfa_input(ctx.subgraph_idx, input_idx, tensor);+ }+ OPENVINO_THROW("Unsupported attention behavior kind");+ }++ bool bind_function_output(ov::npuw::v1::subgraphs::InferContext& ctx,+ std::size_t output_idx,+ const ov::SoPtr<ov::ITensor>& tensor) override {+ if (m_kind != BehaviorKind::HFA) {+ return false;+ }+ auto& request = get_request(ctx);+ return request.behavior_bind_hfa_output(ctx.subgraph_idx, output_idx, tensor);+ }++ void prologue(ov::npuw::v1::subgraphs::InferContext& ctx) override {+ if (ctx.opaque_prologue) {+ ctx.opaque_prologue();+ }+ auto& request = get_request(ctx);+ switch (m_kind) {+ case BehaviorKind::Dynamic:+ request.behavior_prologue_dynamic(ctx.real_subgraph_idx, ctx.subgraph_idx);+ return;+ case BehaviorKind::Pyramid:+ request.behavior_prologue_pyramid(ctx.real_subgraph_idx, ctx.subgraph_idx);+ return;+ case BehaviorKind::HFA:+ return;+ }+ OPENVINO_THROW("Unsupported attention behavior kind");+ }++ void run(ov::npuw::v1::subgraphs::InferContext& ctx) override {+ auto& request = get_request(ctx);+ switch (m_kind) {+ case BehaviorKind::Dynamic:+ case BehaviorKind::Pyramid:+ ctx.legacy_infer();+ return;+ case BehaviorKind::HFA:+ request.behavior_run_hfa(ctx.real_subgraph_idx, ctx.subgraph_idx);+ return;+ }+ OPENVINO_THROW("Unsupported attention behavior kind");+ }++ private:+ BehaviorKind m_kind;+ };++ return std::make_unique<AttnBehavior>(get_behavior_kind(ctx));+ };+}++} // namespace++void attach_runtime_behavior(ov::npuw::v1::subgraphs::CompiledPipeline& compiled_pipeline,+ ov::npuw::v1::subgraphs::Context& compiled_context,+ BehaviorKind kind) {+ compiled_pipeline.registration.group = ov::npuw::patterns::attn::SDPA::group_name();+ compiled_pipeline.registration.name = ov::npuw::patterns::attn::SDPA::pattern_name();+ compiled_context.put<BehaviorKind>(kind);+ ov::npuw::v1::subgraphs::RuntimeBehaviorSpec spec;+ spec.registration = compiled_pipeline.registration;+ spec.context = compiled_context;+ spec.factory = make_runtime_factory();+ spec.handles_function_prologue = true;+ compiled_pipeline.runtime_behavior = std::move(spec);+}++std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> register_patterns(+ ov::npuw::v1::subgraphs::PatternRegistry& registry) {+ std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> registrations;+ registrations.reserve(3);++ // Matcher-only registrations so the registry handles SDPA/SDPADecomposed isolation+ // (replaces the legacy HNDL_ATTN fallback in snapshot.cpp)+ registrations.emplace_back(registry.on<ov::npuw::patterns::attn::SDPA>().scoped());+ registrations.emplace_back(registry.on<ov::npuw::patterns::attn::SDPADecomposed>().scoped());++ // Behavior registration: fires for any function tagged "attn" (i.e. from either SDPA+ // or SDPADecomposed pattern). The at_partition callback checks whether dynamic+ // attention was detected (f._attention set by Partitioner::attention()) and, if so,+ // stashes the compile-time descriptor in the pipeline context for later stages.+ ov::npuw::v1::subgraphs::PatternRegistration attn_behavior;+ attn_behavior.tag = ov::npuw::patterns::attn::SDPA::isolation_tag();+ attn_behavior.partition_stage = [](ov::npuw::Function& f, ov::npuw::v1::subgraphs::Context& ctx) {+ if (f._attention.has_value()) {+ ctx.put<ov::npuw::compiled::Attention>(ov::npuw::compiled::Attention(f._attention.value(), f._model));+ ctx.put<BehaviorKind>(BehaviorKind::Dynamic);+ return;+ }+ if (f._pyramid_attention.has_value()) {+ ctx.put<BehaviorKind>(BehaviorKind::Pyramid);+ return;+ }+ if (f._host_flash_attention.has_value()) {+ ctx.put<BehaviorKind>(BehaviorKind::HFA);+ }+ };+ attn_behavior.compile_stage = [](ov::npuw::v1::subgraphs::CompiledPipeline& compiled_pipeline,+ ov::npuw::v1::subgraphs::Context& compiled_context) {+ const auto* kind = compiled_context.get_if<BehaviorKind>();+ if (kind == nullptr) {+ return;+ }+ attach_runtime_behavior(compiled_pipeline, compiled_context, *kind);+ };+ registrations.emplace_back(registry.add(std::move(attn_behavior)));++ return registrations;+}++} // namespace attn+} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.hpp b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.hppnew file mode 100644index 00000000000..5876a63136c--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.hpp@@ -0,0 +1,26 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <vector>++#include "../v1/subgraph_pipeline.hpp"++namespace ov {+namespace npuw {+namespace attn {++enum class BehaviorKind { Dynamic, Pyramid, HFA };++std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> register_patterns(+ ov::npuw::v1::subgraphs::PatternRegistry& registry);++void attach_runtime_behavior(ov::npuw::v1::subgraphs::CompiledPipeline& compiled_pipeline,+ ov::npuw::v1::subgraphs::Context& compiled_context,+ BehaviorKind kind);++} // namespace attn+} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cppindex bd6f2f12037..1207e76703d 100644--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp@@ -9,6 +9,7 @@#include <string>#include "accuracy/comparator.hpp"+#include "attn/attn_subgraph.hpp"#include "intel_npu/npu_private_properties.hpp"#include "just_sync_infer_request.hpp"#include "logging.hpp"@@ -300,6 +301,13 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,ov::npuw::moe::register_patterns(*combined_subgraph_patterns,m_cfg.get<::intel_npu::NPUW_MOE_TOKEN_CHUNK_SIZE>());+ {+ auto attn_registrations = ov::npuw::attn::register_patterns(*combined_subgraph_patterns);+ for (auto& r : attn_registrations) {+ builtin_pattern_registrations.push_back(std::move(r));+ }+ }+ov::npuw::PartitioningContext ctx;// Identify based on compiler version, user config and patternctx.use_host_gather_quant = should_use_quantized_host_gather(model, npuw_props);@@ -839,6 +847,16 @@ void ov::npuw::CompiledModel::CompiledModelDesc::serialize(ov::npuw::s11n::Strea}}+ if (stream.input()) {+ if (attention.has_value()) {+ ov::npuw::attn::attach_runtime_behavior(pipeline, pipeline.context, ov::npuw::attn::BehaviorKind::Dynamic);+ } else if (pyramid_attention.has_value()) {+ ov::npuw::attn::attach_runtime_behavior(pipeline, pipeline.context, ov::npuw::attn::BehaviorKind::Pyramid);+ } else if (host_flash_attention.has_value()) {+ ov::npuw::attn::attach_runtime_behavior(pipeline, pipeline.context, ov::npuw::attn::BehaviorKind::HFA);+ }+ }+auto& closure_desc = closure.get();stream & closure_desc.is_remote & closure_desc.closure_uid;diff --git a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cppindex 21ccf7ef489..006e4bd316f 100644--- a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp@@ -466,24 +466,6 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::ComLOG_VERB("Done");}- // Handle dynamic submission- if (has_dynamic) {- if (!m_npuw_model->m_cfg.get<::intel_npu::NPUW_ATTN_DYN>()) {- // Even if the attention is detected and ready to go dynamic,- // force it on the full range- LOG_WARN("Dynamic capability is enabled, but won't be used due to user preference");- m_attention_selector.reset(new runtime::attention::All());- } else {- const auto& dyn = m_npuw_model->m_compiled_submodels.at(dynamic_sub_idx).attention.value();- m_attention_selector = runtime::attention::PositionIDs::find(dyn, *this);- if (!m_attention_selector) {- LOG_WARN("Dynamic capability is enabled, but no run-time features were found.");- m_attention_selector.reset(new runtime::attention::All());- }- }- LOG_VERB("Done");- }-// Handle pyramid attentionif (has_pyramid) {const auto& pyramid_dyn = m_npuw_model->m_compiled_submodels.at(pyramid_sub_idx).pyramid_attention.value();@@ -514,6 +496,22 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::ComLOG_VERB("Done");}+ // Initialize the dynamic-attention selector eagerly so bind_attention_inputs() can use+ // it from the pipelining (PREP-NEXT) path before DynAttnBehavior::prologue runs.+ if (has_dynamic) {+ const auto& dynamic = m_npuw_model->m_compiled_submodels.at(dynamic_sub_idx).attention.value();+ if (!m_npuw_model->m_cfg.get<::intel_npu::NPUW_ATTN_DYN>()) {+ m_attention_selector = std::make_shared<runtime::attention::All>();+ } else {+ m_attention_selector = runtime::attention::PositionIDs::find(dynamic, *this);+ if (!m_attention_selector) {+ LOG_WARN("Dynamic capability is enabled, but no run-time features were found.");+ m_attention_selector = std::make_shared<runtime::attention::All>();+ }+ }+ LOG_VERB("Done");+ }+// Initialize MoE executor if MoE was detectedif (has_moe) {initialize_moe_executor();@@ -552,23 +550,22 @@ void ov::npuw::JustInferRequest::initialize_subgraph_behaviors() {ov::npuw::v1::subgraphs::InferContext ov::npuw::JustInferRequest::make_behavior_context(std::size_t real_idx,std::size_t idx) {const bool is_function_call = m_npuw_model->m_compiled_submodels[idx].replaced_by.has_value();- return ov::npuw::v1::subgraphs::InferContext{- *m_npuw_model,- *this,- idx,- real_idx,- [this, real_idx, idx]() {- legacy_infer(real_idx, idx);- },- is_function_call ? std::function<void()>{[this, idx]() {- OPENVINO_ASSERT(m_moe_executor != nullptr, "Expected MoE executor for opaque MoE prologue");- function_prologue(idx);- }}- : std::function<void()>{},- [this, real_idx, idx]() {- OPENVINO_ASSERT(m_moe_executor != nullptr, "Expected MoE executor for opaque MoE run");- m_moe_executor->run(real_idx, idx);- }};+ return ov::npuw::v1::subgraphs::InferContext{*m_npuw_model,+ *this,+ idx,+ real_idx,+ [this, real_idx, idx]() {+ legacy_infer(real_idx, idx);+ },+ is_function_call ? std::function<void()>{[this, idx]() {+ function_prologue(idx);+ }}+ : std::function<void()>{},+ [this, real_idx, idx]() {+ OPENVINO_ASSERT(m_moe_executor != nullptr,+ "Expected MoE executor for opaque MoE run");+ m_moe_executor->run(real_idx, idx);+ }};}const ov::npuw::v1::subgraphs::RuntimeBehaviorSpec* ov::npuw::JustInferRequest::get_runtime_behavior_spec(@@ -597,6 +594,86 @@ bool ov::npuw::JustInferRequest::behavior_handles_function_prologue(std::size_treturn spec != nullptr && spec->handles_function_prologue;}+bool ov::npuw::JustInferRequest::behavior_bind_dynamic_input(std::size_t real_idx,+ std::size_t idx,+ std::size_t input_idx,+ const ov::SoPtr<ov::ITensor>& tensor) {+ auto& func_desc = m_npuw_model->m_compiled_submodels[real_idx];+ NPUW_ASSERT(func_desc.attention.has_value());++ const auto& dynamic = func_desc.attention.value();+ const bool is_non_param_mask = std::none_of(dynamic.params.begin(),+ dynamic.params.end(),+ [&](auto&& param) {+ return param.idx == input_idx;+ }) &&+ input_idx != dynamic.mask_idx;++ const auto& iport = func_desc.compiled_model->inputs()[input_idx];+ if (is_non_param_mask) {+ m_subrequests[real_idx]->set_tensor(iport, tensor);+ } else {+ m_attention_io[idx].inputs.at(input_idx) = tensor;+ }+ return true;+}++bool ov::npuw::JustInferRequest::behavior_bind_pyramid_input(std::size_t real_idx,+ std::size_t idx,+ std::size_t input_idx,+ const ov::SoPtr<ov::ITensor>& tensor) {+ auto& func_desc = m_npuw_model->m_compiled_submodels[real_idx];+ NPUW_ASSERT(func_desc.pyramid_attention.has_value());+ NPUW_ASSERT(m_pyramid_selector);++ const auto pyramid_id = m_pyramid_selector->pyramid_id();+ const auto& info = func_desc.pyramid_attention.value()._attention_infos[pyramid_id];+ const bool is_non_param_mask = std::none_of(info.params.begin(),+ info.params.end(),+ [&](auto&& param) {+ return param.idx == input_idx;+ }) &&+ input_idx != info.mask_idx;++ const auto& iport = func_desc.compiled_model->inputs()[input_idx];+ if (is_non_param_mask) {+ m_subrequests[real_idx]->set_tensor(iport, tensor);+ } else {+ m_attention_io[idx].inputs.at(input_idx) = tensor;+ }+ return true;+}++bool ov::npuw::JustInferRequest::behavior_bind_hfa_input(std::size_t idx,+ std::size_t input_idx,+ const ov::SoPtr<ov::ITensor>& tensor) {+ m_hfa_io[idx].inputs.at(input_idx) = tensor;+ return true;+}++bool ov::npuw::JustInferRequest::behavior_bind_hfa_output(std::size_t idx,+ std::size_t output_idx,+ const ov::SoPtr<ov::ITensor>& tensor) {+ m_hfa_io[idx].outputs.at(output_idx) = tensor;+ return true;+}++void ov::npuw::JustInferRequest::behavior_prologue_dynamic(std::size_t real_idx, std::size_t idx) {+ m_profile["attn(act)"] += ov::npuw::perf::ms_to_run([&]() {+ function_prologue_attn(real_idx, idx);+ });+}++void ov::npuw::JustInferRequest::behavior_prologue_pyramid(std::size_t real_idx, std::size_t idx) {+ m_profile["attn(act)"] += ov::npuw::perf::ms_to_run([&]() {+ function_prologue_pyramid_attn(real_idx, idx);+ });+}++void ov::npuw::JustInferRequest::behavior_run_hfa(std::size_t real_idx, std::size_t idx) {+ run_hfa_tiled_inference(real_idx, idx);+}+void ov::npuw::JustInferRequest::set_tensor(const ov::Output<const ov::Node>& port,const ov::SoPtr<ov::ITensor>& tensor) {std::unique_lock lock(m_io_storages_mutex);@@ -811,19 +888,12 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {auto& func_desc = m_npuw_model->m_compiled_submodels[real_idx];const bool is_spatial = func_desc.spatial.has_value();- const bool is_dynamic = func_desc.attention.has_value();- const bool is_pyramid = func_desc.pyramid_attention.has_value();- const bool is_hfa = func_desc.host_flash_attention.has_value();const bool is_moe = ov::npuw::moe::has_compiled_state(func_desc.pipeline);-- // Generalized: check if input is neither param nor mask- auto is_non_param_mask = [](const auto& info, std::size_t in_idx) {- const bool not_param = std::none_of(info.params.begin(), info.params.end(), [&](auto&& p) {- return p.idx == in_idx;- });- const bool not_mask = in_idx != info.mask_idx;- return not_param && not_mask;- };+ auto* behavior = get_subgraph_behavior(idx);+ std::optional<ov::npuw::v1::subgraphs::InferContext> behavior_ctx;+ if (behavior != nullptr) {+ behavior_ctx.emplace(make_behavior_context(real_idx, idx));+ }// Function call prologue:// 1. Walk through function dependencies and set the respective tensors@@ -855,25 +925,9 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {if (is_spatial) {// Spatial case - deferm_spatial_io[real_idx].inputs.at(i) = i_tensor;- } else if (is_dynamic) {- // Set tensor only if it is non-dynamic (dynamic are managed by the infer_dynamic)- if (is_non_param_mask(*func_desc.attention, i)) {- m_subrequests[real_idx]->set_tensor(iport, i_tensor);- } else {- m_attention_io[idx].inputs.at(i) = i_tensor;- }- } else if (is_pyramid) {- // Pyramid attention- auto pyramid_id = m_pyramid_selector->pyramid_id();- const auto& info = func_desc.pyramid_attention.value()._attention_infos[pyramid_id];- if (is_non_param_mask(info, i)) {- m_subrequests[real_idx]->set_tensor(iport, i_tensor);- } else {- m_attention_io[idx].inputs.at(i) = i_tensor;- }- } else if (is_hfa) {- // Host Flash Attention case - defer, use dedicated HFA I/O structure- m_hfa_io[idx].inputs.at(i) = i_tensor;+ } else if (behavior != nullptr && behavior_ctx.has_value() &&+ behavior->bind_function_input(*behavior_ctx, i, i_tensor)) {+ continue;} else if (is_moe) {// MoE layer: delegate to executor for input bindingif (m_moe_executor->function_prologue_moe_input(idx, real_idx, i, i_tensor)) {@@ -886,19 +940,6 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {} // if (link_iter)} // for(param_base)- // 1.5: Do attention prologue if needed- if (is_dynamic) {- m_profile["attn(act)"] += ov::npuw::perf::ms_to_run([&]() {- function_prologue_attn(real_idx, idx);- });- }-- if (is_pyramid) {- m_profile["attn(act)"] += ov::npuw::perf::ms_to_run([&]() {- function_prologue_pyramid_attn(real_idx, idx);- });- }-// 2. Unpack the function closure -- right here, if pipelining if not enabled.// If it is enabled, the flow is a little bit different - see run_subrequest_for_success()// for details.@@ -920,9 +961,9 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {if (ov::npuw::moe::has_compiled_experts(func_desc.pipeline)) {// MoE case - delegate to executor for output bindingm_moe_executor->function_prologue_moe_output(idx, i, o_tensor);- } else if (is_hfa) {- // HFA case - defer, store in dedicated HFA I/O structure- m_hfa_io[idx].outputs.at(i) = o_tensor;+ } else if (behavior != nullptr && behavior_ctx.has_value() &&+ behavior->bind_function_output(*behavior_ctx, i, o_tensor)) {+ continue;} else if (!is_spatial) {// Non-spatial case - set immediatelym_subrequests[real_idx]->set_tensor(oport, o_tensor);diff --git a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hppindex 69d7d4ff984..e5d0de39fbf 100644--- a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.hpp@@ -10,6 +10,7 @@#include <optional>#include <vector>+#include "attn/attn_subgraph.hpp"#include "base_sync_infer_request.hpp"#include "host_flash_attention.hpp"#include "moe/moe_executor.hpp"@@ -127,6 +128,22 @@ protected:ov::npuw::v1::subgraphs::ISubgraphBehavior* get_subgraph_behavior(std::size_t idx) const;bool behavior_handles_function_prologue(std::size_t idx) const;+public:+ bool behavior_bind_dynamic_input(std::size_t real_idx,+ std::size_t idx,+ std::size_t input_idx,+ const ov::SoPtr<ov::ITensor>& tensor);+ bool behavior_bind_pyramid_input(std::size_t real_idx,+ std::size_t idx,+ std::size_t input_idx,+ const ov::SoPtr<ov::ITensor>& tensor);+ bool behavior_bind_hfa_input(std::size_t idx, std::size_t input_idx, const ov::SoPtr<ov::ITensor>& tensor);+ bool behavior_bind_hfa_output(std::size_t idx, std::size_t output_idx, const ov::SoPtr<ov::ITensor>& tensor);+ void behavior_prologue_dynamic(std::size_t real_idx, std::size_t idx);+ void behavior_prologue_pyramid(std::size_t real_idx, std::size_t idx);+ void behavior_run_hfa(std::size_t real_idx, std::size_t idx);++protected:// HFA helper functionsstatic void hfa_extract_and_copy_tile(const ov::SoPtr<ov::ITensor>& source_tensor,const ov::SoPtr<ov::ITensor>& dest_tensor,diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.cppindex 708454c20d9..bb4b32525ff 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.cpp@@ -24,11 +24,14 @@ 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)});+ // Optional beam-search gather: Parameter → Gather(beam_idx) → ... (stateless LLM models)+ auto past_k_gather = opp::optional<ov::op::v8::Gather>({past_k_in->output(0), opp::any_input(), opp::any_input()});+ auto past_k_cvt = opp::optional<ov::op::v0::Convert>({past_k_gather->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_gather = opp::optional<ov::op::v8::Gather>({past_v_in->output(0), opp::any_input(), opp::any_input()});+ auto past_v_cvt = opp::optional<ov::op::v0::Convert>({past_v_gather->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!@@ -51,9 +54,11 @@ SDPA::SDPA(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const stauto 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_gather,past_k_cvt,past_k_cat,past_v_in,+ past_v_gather,past_v_cvt,past_v_cat,opt_unsq_k,diff --git a/src/plugins/intel_npu/src/plugin/npuw/v1/subgraph_pipeline.hpp b/src/plugins/intel_npu/src/plugin/npuw/v1/subgraph_pipeline.hppindex 5b23e612499..2a4905221c5 100644--- a/src/plugins/intel_npu/src/plugin/npuw/v1/subgraph_pipeline.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/v1/subgraph_pipeline.hpp@@ -18,6 +18,7 @@#include "openvino/core/except.hpp"#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/runtime/itensor.hpp"#include "openvino/runtime/so_ptr.hpp"namespace ov {@@ -142,6 +143,12 @@ class ISubgraphBehavior {public:using Ptr = std::unique_ptr<ISubgraphBehavior>;+ virtual bool bind_function_input(InferContext&, std::size_t, const ov::SoPtr<ov::ITensor>&) {+ return false;+ }+ virtual bool bind_function_output(InferContext&, std::size_t, const ov::SoPtr<ov::ITensor>&) {+ return false;+ }virtual void prologue(InferContext&) {}virtual void run(InferContext&) = 0;virtual void epilogue(InferContext&) {}diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cppindex e83048b608f..7f3810cbf51 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.cpp@@ -1794,7 +1794,7 @@ std::shared_ptr<ov::Model> ModelBuilder::build_llm(const LLMConfig& config_in) {// Shared GQA broadcast shape (embedding models only)ov::Output<ov::Node> shared_broadcast;- if (!config.use_kv_cache && !config.lm_head_weight) {+ if ((!config.use_kv_cache && !config.lm_head_weight) || config.force_gqa_broadcast) {shared_broadcast = make_shared_gqa_broadcast(attention_mask->output(0),config.get_kv_heads(),config.num_heads,diff --git a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hppindex 7c38c478a87..f6fa67ce061 100644--- a/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp+++ b/src/plugins/intel_npu/tests/functional/behavior/npuw/test_engine/models/model_builder.hpp@@ -433,6 +433,7 @@ struct LLMConfig : public BaseModelConfig {bool use_inputs_embeds = false;bool internal_position_ids = false; ///< embedding modelbool pre_norm = true;+ bool force_gqa_broadcast = false; ///< force 5-input SDPA (needed for SDPA isolation pattern matching)// MoE configuration (num_experts=0 means dense, no MoE)size_t num_experts = 0; ///< Total experts. 0 = dense model.diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 068a0304cf8..9ec82cbd11d 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -84,6 +84,8 @@ ov_add_test_target(${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+ # attn+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.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.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hppindex 25cf2050043..2c265682f42 100644--- a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp@@ -15,6 +15,7 @@#include "model_builder.hpp"#include "openvino/op/fake_convert.hpp"#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/pass/stateful_to_stateless.hpp"#include "openvino/runtime/iplugin.hpp"#include "serialization.hpp"#include "weights_bank.hpp"@@ -38,6 +39,56 @@ inline std::shared_ptr<ov::Model> build_llm_test_model() {return mb.build_llm(make_test_model_config());}+/// Build an LLM test model configured so that Attention::from() can unambiguously+/// identify the past-KV dimension in the isolated attention function body.+///+/// The default test config has num_kv_heads == kPastKvLen == 4 which makes the+/// KV-cache shape [1, 4, 4, 16] ambiguous — find_context_dim sees two dims equal+/// to past_len and returns false. By setting num_kv_heads=2 and using a past+/// length of 8, the KV shape becomes [1, 2, 8, 16] where only dim 2 equals+/// past_len=8, so Attention::from() succeeds and f._attention gets set.+inline std::shared_ptr<ov::Model> build_dynamic_attention_llm_model() {+ ov::test::npuw::LLMConfig cfg;+ cfg.num_layers = 2;+ cfg.hidden_size = 64;+ cfg.num_heads = 4;+ cfg.head_dim = 16;+ cfg.num_kv_heads = 2; // must differ from kPastKvLen so find_context_dim is unambiguous+ cfg.vocab_size = 256;+ cfg.force_gqa_broadcast = true; // produces 5-input SDPA needed by the SDPA isolation pattern++ ModelBuilder mb;+ auto model = mb.build_llm(cfg);+ ov::pass::StatefulToStateless().run_on_model(model);+ model = model->clone();++ constexpr std::size_t kSeq = 4;+ constexpr std::size_t kPast = 8; // != num_kv_heads (2), so KV shape [1,2,8,16] is unambiguous++ std::map<std::string, ov::PartialShape> new_shapes;+ for (const auto& input : model->inputs()) {+ const auto& name = input.get_any_name();+ const auto& pshape = input.get_partial_shape();+ if (name.find("input_ids") != std::string::npos ||+ name.find("token_type_ids") != std::string::npos) {+ new_shapes[name] = ov::PartialShape{1, kSeq};+ } else if (name.find("attention_mask") != std::string::npos) {+ new_shapes[name] = ov::PartialShape{1, kSeq + kPast};+ } else if (name.find("position_ids") != std::string::npos) {+ new_shapes[name] = ov::PartialShape{1, kSeq};+ } else {+ // KV cache params: fix batch=1, past_len=kPast, leave head/head_dim from pshape+ auto static_shape = pshape;+ static_shape[0] = 1;+ static_shape[2] = kPast;+ new_shapes[name] = static_shape;+ }+ }+ model->reshape(new_shapes);+ model->validate_nodes_and_infer_types();+ return model;+}+inline std::shared_ptr<ov::Model> build_llm_test_model_with_kv_fake_convert(const ov::element::Type fake_convert_type) {auto model = build_llm_test_model();auto scale = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {1.0f});diff --git a/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp b/src/plugins/intel_npu/tests/unit/npuw/serialization.cppindex 82f63beb08c..22c8d374693 100644--- a/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/serialization.cpp@@ -17,8 +17,8 @@#include "intel_npu/config/config.hpp"#include "intel_npu/config/npuw.hpp"#include "lazy_tensor.hpp"-#include "moe_transformations/moe_transformation.hpp"#include "model_builder.hpp"+#include "moe_transformations/moe_transformation.hpp"#include "openvino/core/parallel.hpp"#include "openvino/core/rt_info/weightless_caching_attributes.hpp"#include "openvino/op/constant.hpp"@@ -60,15 +60,16 @@ ov::npuw::s11n::WeightsContext::ConstsCache make_consts_cache(const std::vector<std::shared_ptr<ov::op::v0::Constant>>& constants) {ov::npuw::s11n::WeightsContext::ConstsCache cache;for (const auto& constant : constants) {- const auto attr =- constant->get_rt_info().at(ov::WeightlessCacheAttribute::get_type_info_static())- .as<ov::WeightlessCacheAttribute>();+ const auto attr = constant->get_rt_info()+ .at(ov::WeightlessCacheAttribute::get_type_info_static())+ .as<ov::WeightlessCacheAttribute>();cache[{attr.bin_offset, constant->get_byte_size()}] = constant;}return cache;}-void expect_attention_equal(const ov::npuw::compiled::Attention& expected, const ov::npuw::compiled::Attention& actual) {+void expect_attention_equal(const ov::npuw::compiled::Attention& expected,+ const ov::npuw::compiled::Attention& actual) {EXPECT_EQ(expected.query_size, actual.query_size);EXPECT_EQ(expected.context_size, actual.context_size);EXPECT_EQ(expected.params.size(), actual.params.size());@@ -674,12 +675,10 @@ TEST(SerializationTest, OVTypes_Tensor_allocator) {bool allocator_called = false;ov::Tensor res;auto input_stream = Stream::reader(ss);- transfer_tensor(input_stream,- res,- [&](const ov::element::Type& type, const ov::Shape& shape) {- allocator_called = true;- return ov::Tensor(type, shape);- });+ transfer_tensor(input_stream, res, [&](const ov::element::Type& type, const ov::Shape& shape) {+ allocator_called = true;+ return ov::Tensor(type, shape);+ });EXPECT_TRUE(allocator_called);expect_tensors_equal(var, res);@@ -780,8 +779,7 @@ TEST(SerializationTest, OVTypes_ParameterPointer_throws_on_write) {TEST(SerializationTest, OVTypes_NodePointer_throws_on_write) {using namespace ov::npuw::s11n;- std::shared_ptr<ov::Node> node =- std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1});+ std::shared_ptr<ov::Node> node = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1});std::stringstream ss;EXPECT_THROW(write(ss, node), ov::Exception);@@ -824,7 +822,8 @@ TEST(SerializationTest, OVTypes_LazyTensor_const_roundtrip) {TEST(SerializationTest, OVTypes_LazyTensor_const_with_embedded_weight_roundtrip) {using namespace ov::npuw::s11n;- auto constant = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{2}, std::vector<float>{1.0f, 2.0f});+ auto constant =+ std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{2}, std::vector<float>{1.0f, 2.0f});ov::npuw::weights::LazyTensor var(constant);ov::npuw::weights::LazyTensor res;@@ -842,11 +841,12 @@ TEST(SerializationTest, OVTypes_LazyTensor_concat_permute_convert_roundtrip) {using namespace ov::npuw::s11n;auto first = make_weightless_constant<float>(ov::element::f32, ov::Shape{1, 2}, {1.0f, 2.0f}, 0);- auto second = make_weightless_constant<float>(ov::element::f32, ov::Shape{1, 2}, {3.0f, 4.0f}, first->get_byte_size());- ov::npuw::weights::LazyTensor concat(std::vector<ov::npuw::weights::LazyTensor>{- ov::npuw::weights::LazyTensor(first),- ov::npuw::weights::LazyTensor(second)},- 0);+ auto second =+ make_weightless_constant<float>(ov::element::f32, ov::Shape{1, 2}, {3.0f, 4.0f}, first->get_byte_size());+ ov::npuw::weights::LazyTensor concat(+ std::vector<ov::npuw::weights::LazyTensor>{ov::npuw::weights::LazyTensor(first),+ ov::npuw::weights::LazyTensor(second)},+ 0);auto var = concat.permute({1, 0}).convert(ov::element::f16);ov::npuw::weights::LazyTensor res;@@ -865,7 +865,10 @@ TEST(SerializationTest, OVTypes_LazyTensor_unpack_roundtrip) {using namespace ov::npuw::s11n;auto w = make_weightless_constant<uint8_t>(ov::element::u8, ov::Shape{8}, {1, 2, 3, 4, 5, 6, 7, 8}, 0);- auto s = make_weightless_constant<ov::float16>(ov::element::f16, ov::Shape{8}, {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f}, w->get_byte_size());+ auto s = make_weightless_constant<ov::float16>(ov::element::f16,+ ov::Shape{8},+ {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f},+ w->get_byte_size());ov::npuw::weights::LazyTensor var(ov::npuw::weights::LazyTensor(w),ov::npuw::weights::LazyTensor(),ov::npuw::weights::LazyTensor(s),@@ -886,8 +889,9 @@ TEST(SerializationTest, OVTypes_LazyTensor_unpack_roundtrip) {TEST(SerializationTest, OVTypes_LazyTensor_gather_roundtrip) {using namespace ov::npuw::s11n;- auto w = make_weightless_constant<uint8_t>(ov::element::u8, ov::Shape{16}, {0, 1, 2, 3, 4, 5, 6, 7,- 8, 9, 10, 11, 12, 13, 14, 15},+ auto w = make_weightless_constant<uint8_t>(ov::element::u8,+ ov::Shape{16},+ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},0);std::vector<uint8_t> indices{0, 1, 2, 3};ov::Tensor lut(ov::element::f8e4m3, ov::Shape{4}, indices.data());diff --git a/src/plugins/intel_npu/tests/unit/npuw/subgraph_behavior_infer_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/subgraph_behavior_infer_test.cppindex 14cff900c3c..065cce5e02e 100644--- a/src/plugins/intel_npu/tests/unit/npuw/subgraph_behavior_infer_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/subgraph_behavior_infer_test.cpp@@ -19,6 +19,7 @@#include "just_sync_infer_request.hpp"#include "llm_test_helpers.hpp"#include "model_builder.hpp"+#include "partitioning/patterns/sdpa.hpp"#include "unfold_sync_infer_request.hpp"#include "openvino/op/scaled_dot_product_attention.hpp"#include "openvino/openvino.hpp"@@ -126,6 +127,23 @@ std::size_t count_runtime_behaviors(const std::shared_ptr<ov::npuw::CompiledMode});}+// Count subgraphs where the attention runtime behavior was attached. The test keys off the+// behavior's registered attn identity rather than only handles_function_prologue, since that+// callback flag is not unique to attention behaviors.+std::size_t count_dyn_attn_behaviors(const std::shared_ptr<ov::npuw::CompiledModel>& compiled_model) {+ return std::count_if(compiled_model->m_compiled_submodels.begin(),+ compiled_model->m_compiled_submodels.end(),+ [](const auto& desc) {+ if (!desc.pipeline.runtime_behavior.has_value()) {+ return false;+ }+ const auto& spec = *desc.pipeline.runtime_behavior;+ return spec.handles_function_prologue &&+ spec.registration.group == ov::npuw::patterns::attn::SDPA::group_name() &&+ spec.registration.name == ov::npuw::patterns::attn::SDPA::pattern_name();+ });+}+class FakeSubCompiledModel;class FakeSubInferRequest final : public ov::ISyncInferRequest {@@ -282,8 +300,14 @@ protected:{"NPUW_DEVICES", "CPU"},{"NPUW_UNFOLD_IREQS", "NO"},{"NPUW_ATTN", "DYNAMIC"},+ {"NPUW_FOLD", "YES"},{"NPUW_ONLINE_PIPELINE", "REP"},- {"NPUW_ONLINE_ISOLATE", "ATTN"}};+ {"NPUW_ONLINE_ISOLATE", "ATTN"},+ // The test model has only 2 layers so repeated blocks appear only twice.+ // Lower the thresholds so they survive cleanUpUniquesImpl and ens.repeated+ // stays non-empty (required for the FOLD pass to run at all).+ {"NPUW_ONLINE_KEEP_BLOCKS", "2"},+ {"NPUW_ONLINE_KEEP_BLOCK_SIZE", "1"}};}ov::AnyMap unfold_props() const {@@ -439,4 +463,68 @@ TEST_F(SubgraphBehaviorInferTest, RuntimeBehaviorForcesJustInferRequestWhenUnfolEXPECT_EQ(std::dynamic_pointer_cast<ov::npuw::UnfoldInferRequest>(behavior_request), nullptr);}+// --- Dynamic-attention behavior gating tests ---+//+// These tests verify two properties:+//+// 1. When NPUW_ATTN=DYNAMIC + NPUW_ONLINE_ISOLATE=ATTN are set and the model has SDPA nodes+// with dynamic KV-cache dimensions, the attn runtime behavior IS attached to the attention+// subgraphs.+//+// 2. When either condition is absent (STATIC mode or no isolation), NO DynAttnBehavior is+// attached. This proves the gate is working correctly.+//+// build_dynamic_llm_model() produces a stateful→stateless-converted LLM whose KV-cache+// parameters retain dynamic dimensions — the exact shape that function::Attention::from()+// requires to succeed in DYNAMIC mode.++TEST_F(SubgraphBehaviorInferTest, DynAttnBehaviorAttachedWhenDynamicAttentionRequested) {+ auto model = ov::test::npuw::build_dynamic_attention_llm_model();+ ASSERT_GT(count_sdpa_nodes(model), 0u) << "Dynamic LLM model must contain SDPA nodes";++ auto plugin = std::make_shared<TestPlugin>();+ auto core = make_core(plugin);+ plugin->set_core(core);++ // base_props() has NPUW_ATTN=DYNAMIC and NPUW_ONLINE_ISOLATE=ATTN+ auto compiled = std::make_shared<ov::npuw::CompiledModel>(model, plugin, base_props());+ EXPECT_GT(count_dyn_attn_behaviors(compiled), 0u)+ << "DynAttnBehavior must be attached when NPUW_ATTN=DYNAMIC and NPUW_ONLINE_ISOLATE=ATTN";+}++TEST_F(SubgraphBehaviorInferTest, DynAttnBehaviorNotAttachedWithStaticAttentionMode) {+ auto model = ov::test::npuw::build_dynamic_attention_llm_model();++ auto plugin = std::make_shared<TestPlugin>();+ auto core = make_core(plugin);+ plugin->set_core(core);++ auto props = base_props();+ props["NPUW_ATTN"] = std::string("STATIC");+ auto compiled = std::make_shared<ov::npuw::CompiledModel>(model, plugin, props);+ EXPECT_EQ(count_dyn_attn_behaviors(compiled), 0u)+ << "DynAttnBehavior must NOT be attached when NPUW_ATTN=STATIC";+}++TEST_F(SubgraphBehaviorInferTest, DynAttnBehaviorNotAttachedWithoutAttnIsolation) {+ auto model = ov::test::npuw::build_dynamic_attention_llm_model();++ auto plugin = std::make_shared<TestPlugin>();+ auto core = make_core(plugin);+ plugin->set_core(core);++ // Remove NPUW_ONLINE_ISOLATE so no "attn" functions are created by the online partitioner.+ ov::AnyMap props = {{"NPU_USE_NPUW", "YES"},+ {"NPUW_DEVICES", "CPU"},+ {"NPUW_UNFOLD_IREQS", "NO"},+ {"NPUW_ATTN", std::string("DYNAMIC")},+ {"NPUW_FOLD", "YES"},+ {"NPUW_ONLINE_PIPELINE", "REP"},+ {"NPUW_ONLINE_KEEP_BLOCKS", "2"},+ {"NPUW_ONLINE_KEEP_BLOCK_SIZE", "1"}};+ auto compiled = std::make_shared<ov::npuw::CompiledModel>(model, plugin, props);+ EXPECT_EQ(count_dyn_attn_behaviors(compiled), 0u)+ << "DynAttnBehavior must NOT be attached when NPUW_ONLINE_ISOLATE=ATTN is not set";+}+} // namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/subgraph_pipeline.cpp b/src/plugins/intel_npu/tests/unit/npuw/subgraph_pipeline.cppindex b1fadd0dc3e..58d9a10b674 100644--- a/src/plugins/intel_npu/tests/unit/npuw/subgraph_pipeline.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/subgraph_pipeline.cpp@@ -2,15 +2,17 @@// SPDX-License-Identifier: Apache-2.0//+#include "v1/subgraph_pipeline.hpp"+#include <gtest/gtest.h>#include <string>+#include "attn/attn_subgraph.hpp"#include "moe/moe_executor.hpp"#include "partitioning/partitioning.hpp"#include "partitioning/patterns/moe.hpp"#include "partitioning/patterns/sdpa.hpp"-#include "v1/subgraph_pipeline.hpp"namespace {@@ -73,17 +75,17 @@ TEST(SubgraphPipelineBehaviorTest, RealPatternRegistrationBuildsRuntimeBehaviorFsubgraph.settag(ov::npuw::patterns::attn::SDPA::isolation_tag());ov::npuw::v1::subgraphs::PatternRegistry registry;- auto scoped_registration = registry.on<ov::npuw::patterns::attn::SDPA>()- .at_compile([](ov::npuw::v1::subgraphs::CompiledPipeline&,- ov::npuw::v1::subgraphs::Context& ctx) {- ctx.put<std::string>("marker");- })- .at_runtime([](const ov::npuw::v1::subgraphs::Context& ctx)- -> ov::npuw::v1::subgraphs::ISubgraphBehavior::Ptr {- EXPECT_EQ(ctx.get<std::string>(), "marker");- return ov::npuw::v1::subgraphs::make_direct_behavior();- })- .scoped();+ auto scoped_registration =+ registry.on<ov::npuw::patterns::attn::SDPA>()+ .at_compile([](ov::npuw::v1::subgraphs::CompiledPipeline&, ov::npuw::v1::subgraphs::Context& ctx) {+ ctx.put<std::string>("marker");+ })+ .at_runtime(+ [](const ov::npuw::v1::subgraphs::Context& ctx) -> ov::npuw::v1::subgraphs::ISubgraphBehavior::Ptr {+ EXPECT_EQ(ctx.get<std::string>(), "marker");+ return ov::npuw::v1::subgraphs::make_direct_behavior();+ })+ .scoped();registry.apply(subgraph);@@ -95,8 +97,7 @@ TEST(SubgraphPipelineBehaviorTest, RealPatternRegistrationBuildsRuntimeBehaviorFASSERT_TRUE(compiled_pipeline.runtime_behavior.has_value());EXPECT_EQ(compiled_pipeline.registration.name, ov::npuw::patterns::attn::SDPA::pattern_name());- EXPECT_EQ(compiled_pipeline.runtime_behavior->registration.name,- ov::npuw::patterns::attn::SDPA::pattern_name());+ EXPECT_EQ(compiled_pipeline.runtime_behavior->registration.name, ov::npuw::patterns::attn::SDPA::pattern_name());auto behavior = compiled_pipeline.runtime_behavior->factory(compiled_pipeline.runtime_behavior->context);EXPECT_NE(behavior, nullptr);}@@ -106,8 +107,7 @@ TEST(SubgraphPipelineBehaviorTest, MoERegistrationBuildsDeferredPartitionPipelinfunction.settag(ov::npuw::patterns::moe::GPTOSSExpert::isolation_tag());ov::npuw::v1::subgraphs::PatternRegistry registry;- auto registrations =- ov::npuw::moe::register_patterns(registry, 0u);+ auto registrations = ov::npuw::moe::register_patterns(registry, 0u);registry.apply(function);ASSERT_TRUE(static_cast<bool>(function._pipeline.partition_stage));@@ -119,3 +119,92 @@ TEST(SubgraphPipelineBehaviorTest, MoERegistrationBuildsDeferredPartitionPipelinov::npuw::patterns::moe::GPTOSSExpert::pattern_name()),function._pipeline.registration.patterns.end());}++// Verify that attn::register_patterns() chains partition_stage and compile_stage on any+// Function whose isolation tag matches SDPA::isolation_tag() ("attn").+TEST(SubgraphPipelineBehaviorTest, AttnRegistrationSetsPartitionAndCompileStagesForAttnTaggedFunction) {+ ov::npuw::Function function;+ function.settag(ov::npuw::patterns::attn::SDPA::isolation_tag());++ ov::npuw::v1::subgraphs::PatternRegistry registry;+ auto registrations = ov::npuw::attn::register_patterns(registry);+ registry.apply(function);++ ASSERT_TRUE(static_cast<bool>(function._pipeline.partition_stage));+ ASSERT_TRUE(static_cast<bool>(function._pipeline.compile_stage));+ // The registration must carry the SDPA pattern name so the compile loop can identify it.+ EXPECT_NE(std::find(function._pipeline.registration.patterns.begin(),+ function._pipeline.registration.patterns.end(),+ ov::npuw::patterns::attn::SDPA::isolation_tag()),+ function._pipeline.registration.patterns.end());+}++// Verify that the compile_stage does NOT attach a runtime behavior when the partition_stage+// was never given a compiled::Attention context entry — i.e. when f._attention is not set+// (NPUW_ATTN=STATIC, or the model has no dynamic dims in the attention function).+TEST(SubgraphPipelineBehaviorTest, AttnCompileStageSkipsRuntimeBehaviorWhenAttentionNotDynamic) {+ ov::npuw::Function function;+ function.settag(ov::npuw::patterns::attn::SDPA::isolation_tag());++ ov::npuw::v1::subgraphs::PatternRegistry registry;+ auto registrations = ov::npuw::attn::register_patterns(registry);+ registry.apply(function);++ ASSERT_TRUE(static_cast<bool>(function._pipeline.partition_stage));+ ASSERT_TRUE(static_cast<bool>(function._pipeline.compile_stage));++ // Run partition_stage WITHOUT setting f._attention — simulates NPUW_ATTN=STATIC or a+ // model where function::Attention::from() found no dynamic dims.+ function._pipeline.partition_stage(function, function._pipeline.context);+ EXPECT_FALSE(function._pipeline.context.contains<ov::npuw::compiled::Attention>())+ << "partition_stage must not put compiled::Attention in context when f._attention is unset";++ // Run compile_stage: with no compiled::Attention in context, no runtime behavior should appear.+ ov::npuw::v1::subgraphs::CompiledPipeline compiled;+ compiled.registration = function._pipeline.registration;+ compiled.context = function._pipeline.context;+ function._pipeline.compile_stage(compiled, compiled.context);++ EXPECT_FALSE(compiled.runtime_behavior.has_value())+ << "compile_stage must not attach DynAttnBehavior when compiled::Attention is absent";+}++TEST(SubgraphPipelineBehaviorTest, AttnCompileStageAttachesPyramidBehaviorWhenHintIsPresent) {+ ov::npuw::Function function;+ function.settag(ov::npuw::patterns::attn::SDPA::isolation_tag());++ ov::npuw::v1::subgraphs::PatternRegistry registry;+ auto registrations = ov::npuw::attn::register_patterns(registry);+ registry.apply(function);++ function._pipeline.context.put<ov::npuw::attn::BehaviorKind>(ov::npuw::attn::BehaviorKind::Pyramid);++ ov::npuw::v1::subgraphs::CompiledPipeline compiled;+ compiled.registration = function._pipeline.registration;+ compiled.context = function._pipeline.context;+ function._pipeline.compile_stage(compiled, compiled.context);++ ASSERT_TRUE(compiled.runtime_behavior.has_value());+ auto behavior = compiled.runtime_behavior->factory(compiled.runtime_behavior->context);+ EXPECT_NE(behavior, nullptr);+}++TEST(SubgraphPipelineBehaviorTest, AttnCompileStageAttachesHFABehaviorWhenHintIsPresent) {+ ov::npuw::Function function;+ function.settag(ov::npuw::patterns::attn::SDPA::isolation_tag());++ ov::npuw::v1::subgraphs::PatternRegistry registry;+ auto registrations = ov::npuw::attn::register_patterns(registry);+ registry.apply(function);++ function._pipeline.context.put<ov::npuw::attn::BehaviorKind>(ov::npuw::attn::BehaviorKind::HFA);++ ov::npuw::v1::subgraphs::CompiledPipeline compiled;+ compiled.registration = function._pipeline.registration;+ compiled.context = function._pipeline.context;+ function._pipeline.compile_stage(compiled, compiled.context);++ ASSERT_TRUE(compiled.runtime_behavior.has_value());+ auto behavior = compiled.runtime_behavior->factory(compiled.runtime_behavior->context);+ EXPECT_NE(behavior, nullptr);+}