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: Dynamic attention (#32000)
Dmitry Matveev223048ff356b
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hppindex 2163b84f7e6..4c393209b99 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp@@ -117,6 +117,8 @@ DEFINE_OPT(NPUW_SPATIAL, bool, false, npuw::partitioning::spatial, RunTime);DEFINE_OPT(NPUW_F16IC, bool, true, npuw::partitioning::f16_interconnect, RunTime);DEFINE_OPT(NPUW_SPATIAL_NWAY, std::size_t, 128, npuw::partitioning::spatial_nway, RunTime);DEFINE_OPT(NPUW_SPATIAL_DYN, bool, true, npuw::partitioning::spatial_dyn, RunTime);+DEFINE_OPT(NPUW_ATTN_DYN, bool, true, npuw::partitioning::attn_dyn, RunTime);+DEFINE_OPT(NPUW_ATTN_NO_COPY, bool, false, npuw::partitioning::attn_no_copy, RunTime);DEFINE_OPT(NPUW_DCOFF_TYPE, std::string, "", npuw::partitioning::dcoff_type, RunTime);DEFINE_OPT(NPUW_DCOFF_SCALE, bool, false, npuw::partitioning::dcoff_with_scale, RunTime);DEFINE_OPT(NPUW_FUNCALL_FOR_ALL, bool, false, npuw::partitioning::funcall_for_all, RunTime);@@ -126,6 +128,7 @@ DEFINE_OPT(NPUW_WEIGHTS_BANK_ALLOC, std::string, "", npuw::weights_bank_alloc, RDEFINE_OPT(NPUW_CACHE_DIR, std::string, "", npuw::cache_dir, RunTime);DEFINE_OPT(NPUW_FUNCALL_ASYNC, bool, false, npuw::funcall_async, RunTime);DEFINE_OPT(NPUW_UNFOLD_IREQS, bool, false, npuw::unfold_ireqs, RunTime);+DEFINE_OPT(NPUW_FALLBACK_EXEC, bool, true, npuw::fallback_exec, RunTime);DEFINE_OPT(NPUW_ACC_CHECK, bool, false, npuw::accuracy::check, RunTime);DEFINE_OPT(NPUW_ACC_THRESH, double, 0.01, npuw::accuracy::threshold, RunTime);DEFINE_OPT(NPUW_ACC_DEVICE, std::string, "", npuw::accuracy::reference_device, RunTime);diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hppindex df2b38547f1..b4ae012f4a5 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp@@ -234,6 +234,22 @@ static constexpr ov::Property<std::size_t> spatial_nway{"NPUW_SPATIAL_NWAY"};*/static constexpr ov::Property<bool> spatial_dyn{"NPUW_SPATIAL_DYN"};+/**+ * @brief+ * Type: boolean.+ * Enable dynamic dispatch for the attention block, if detected+ * Default value: true+ */+static constexpr ov::Property<bool> attn_dyn{"NPUW_ATTN_DYN"};++/**+ * @brief+ * Type: boolean.+ * Force no-copy mode for the attention block, if detected+ * Default value: false+ */+static constexpr ov::Property<bool> attn_no_copy{"NPUW_ATTN_NO_COPY"};+/*** @brief* Type: boolean@@ -303,6 +319,14 @@ static constexpr ov::Property<bool> funcall_async{"NPUW_FUNCALL_ASYNC"};*/static constexpr ov::Property<bool> unfold_ireqs{"NPUW_UNFOLD_IREQS"};+/**+ * @brief+ * Type: boolean+ * Fallback in case of runtime failure+ * Default value: true.+ */+static constexpr ov::Property<bool> fallback_exec{"NPUW_FALLBACK_EXEC"};+namespace accuracy {/*** @briefdiff --git a/src/plugins/intel_npu/src/al/src/config/npuw.cpp b/src/plugins/intel_npu/src/al/src/config/npuw.cppindex 426fe804156..238f7687141 100644--- a/src/plugins/intel_npu/src/al/src/config/npuw.cpp+++ b/src/plugins/intel_npu/src/al/src/config/npuw.cpp@@ -33,6 +33,8 @@ void intel_npu::registerNPUWOptions(OptionsDesc& desc) {desc.add<NPUW_SPATIAL>();desc.add<NPUW_SPATIAL_NWAY>();desc.add<NPUW_SPATIAL_DYN>();+ desc.add<NPUW_ATTN_DYN>();+ desc.add<NPUW_ATTN_NO_COPY>();desc.add<NPUW_HOST_GATHER>();desc.add<NPUW_F16IC>();desc.add<NPUW_DCOFF_TYPE>();@@ -41,6 +43,7 @@ void intel_npu::registerNPUWOptions(OptionsDesc& desc) {desc.add<NPUW_PARALLEL_COMPILE>();desc.add<NPUW_FUNCALL_ASYNC>();desc.add<NPUW_UNFOLD_IREQS>();+ desc.add<NPUW_FALLBACK_EXEC>();desc.add<NPUW_WEIGHTS_BANK>();desc.add<NPUW_WEIGHTS_BANK_ALLOC>();desc.add<NPUW_CACHE_DIR>();diff --git a/src/plugins/intel_npu/src/plugin/include/properties.hpp b/src/plugins/intel_npu/src/plugin/include/properties.hppindex 1f86ce6c9ec..20fccd4e9d3 100644--- a/src/plugins/intel_npu/src/plugin/include/properties.hpp+++ b/src/plugins/intel_npu/src/plugin/include/properties.hpp@@ -107,6 +107,7 @@ private:ov::intel_npu::npuw::partitioning::funcall_for_all.name(),ov::intel_npu::npuw::funcall_async.name(),ov::intel_npu::npuw::unfold_ireqs.name(),+ ov::intel_npu::npuw::fallback_exec.name(),ov::intel_npu::npuw::llm::enabled.name(),ov::intel_npu::npuw::llm::batch_dim.name(),ov::intel_npu::npuw::llm::seq_len_dim.name(),diff --git a/src/plugins/intel_npu/src/plugin/npuw/attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/attention.cppnew file mode 100644index 00000000000..e5602400dd8--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/attention.cpp@@ -0,0 +1,208 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0++#include "attention.hpp"++#include "openvino/op/broadcast.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/op/util/op_types.hpp" // is_parameter+#include "util.hpp"++namespace {+enum class SDPA_Inputs : std::size_t { Q = 0, K, V, M, NUM_REQUIRED };+}++std::optional<ov::npuw::function::Attention> ov::npuw::function::Attention::from(+ const std::shared_ptr<ov::Model>& model) {+ ov::npuw::function::Attention dyn;++ // Find the mask input (also sizeable). FIXME: We know too much at this point+ auto ops = model->get_ordered_ops();+ auto sdpa_iter = std::find_if(ops.begin(), ops.end(), [](auto&& node_ptr) {+ return ov::is_type<ov::op::v13::ScaledDotProductAttention>(node_ptr);+ });+ if (sdpa_iter == ops.end()) {+ LOG_WARN("SDPA is not found in the attn subgraph!");+ return std::nullopt;+ }++ // Traverse the SDPA's mask input upwards to find the proper Parameter.+ // Only unary ops are allowed along the way+ auto sdpa_node = *sdpa_iter;+ NPUW_ASSERT(sdpa_node->inputs().size() >= util::_v(SDPA_Inputs::NUM_REQUIRED));++ auto mask_in_node = sdpa_node->inputs()[util::_v(SDPA_Inputs::M)].get_source_output().get_node_shared_ptr();+ while (mask_in_node && !ov::op::util::is_parameter(mask_in_node)) {+ if (mask_in_node->inputs().size() != 1) {+ LOG_WARN("Non-unary or disconnected op on the way from SDPA to input mask");+ return std::nullopt;+ }+ mask_in_node = mask_in_node->inputs()[0].get_source_output().get_node_shared_ptr();+ }+ NPUW_ASSERT(ov::op::util::is_parameter(mask_in_node));+ dyn._mask = std::static_pointer_cast<ov::op::v0::Parameter>(mask_in_node);+ dyn._mask_shape = dyn._mask->get_shape();++ // Find the attention inputs with dynamic range+ const auto& f_params = model->get_parameters();+ NPUW_ASSERT(f_params.size() > 0);++ auto find_context_dim = [&](const auto& param, auto&& f) {+ const auto& param_shape = param->get_shape();+ // Look for the dynamic parameter size - past size in this case+ // With our approach it is context_size - query_size+ auto past_len = dyn.context_len() - dyn.query_len();+ auto dim_iter = std::find(param_shape.begin(), param_shape.end(), past_len);+ if (dim_iter == param_shape.end()) {+ // No such dim found+ return false;+ }+ if (std::find(dim_iter + 1, param_shape.end(), past_len) != param_shape.end()) {+ // There must be no other such dim+ return false;+ }+ f(std::distance(param_shape.begin(), dim_iter));+ return true;+ };++ for (auto&& param : f_params) {+ // A bad test but it is what it is+ if (ov::npuw::util::starts_with(param->get_friendly_name(), "past")) {+ if (!find_context_dim(param, [&](std::size_t dim_idx) {+ dyn._inputs.push_back(ov::npuw::function::Attention::Param{param, dim_idx});+ })) {+ LOG_WARN("Couldn't identify SDPA parameter's dynamic dimension");+ return std::nullopt;+ }+ }+ } // for(f_params)++ // There must be exactly two inputs found, for past_k and past_v.+ if (dyn._inputs.size() != 2u || !dyn._mask) {+ return std::nullopt;+ }++ // Apply transformation to the model. Note: only function body is modified+ // Accumulate the reshape map+ std::map<ov::Output<ov::Node>, ov::PartialShape> new_shapes;+ for (auto&& p : dyn._inputs) {+ ov::PartialShape dyn_shape = p.param->get_shape(); // Here it is yet static+ dyn_shape[p.dim] = ov::Dimension(); // ..and now is dynamic+ new_shapes[p.param->output(0)] = std::move(dyn_shape);+ }+ // Mask+ {+ ov::PartialShape dyn_shape = dyn._mask_shape;+ // Put the mask's innermost dimension dynamic+ *dyn_shape.rbegin() = ov::Dimension();+ new_shapes[dyn._mask->output(0)] = std::move(dyn_shape);+ }+ model->reshape(new_shapes);++ // Patch Broadcast constants if there's any. If there's broadcast in the attention+ // block, its shape argument is normally a precomputed Const (which would be+ // an expression/a subgraph in the original dynamic IR). Since we retrofit+ // dynamism into a static shape environment here, we need to patch it back.+ for (auto&& op : model->get_ordered_ops()) {+ if (!ov::is_type<ov::op::v3::Broadcast>(op)) {+ continue;+ }+ // Inspect the constant+ auto shape_source = op->input(1).get_source_output().get_node_shared_ptr();+ if (!ov::is_type<ov::op::v0::Constant>(shape_source)) {+ LOG_WARN("SDPA Broadcast's 2nd input is not Const: " << shape_source << ", skipping");+ continue;+ }++ auto shape_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(shape_source);+ auto shape_values = shape_const->cast_vector<int32_t>();+ for (auto&& d : shape_values) {+ // Assume the context length is the mask's innermost dimension+ if (static_cast<std::size_t>(d) == dyn.context_len()) {+ d = 1;+ }+ }+ auto new_const = std::make_shared<ov::op::v0::Constant>(shape_const->get_element_type(),+ shape_const->get_shape(),+ shape_values);+ op->input(1).replace_source_output(new_const);+ }+ model->validate_nodes_and_infer_types();++ return {std::move(dyn)};+}++ov::npuw::runtime::attention::PositionIDs::PositionIDs(std::size_t param_idx,+ const ov::npuw::compiled::Attention& d,+ const ov::ISyncInferRequest& rq)+ : m_position_ids_idx(param_idx),+ m_d(d),+ m_rq(rq) {+ // FIXME: speculative decode is indistinguishable at this point!+ m_case = m_d.query_size == 1 ? Case::GENERATE : Case::PREFILL;+}++ov::npuw::runtime::attention::Selector::Ptr ov::npuw::runtime::attention::PositionIDs::find(+ const ov::npuw::compiled::Attention& d,+ const ov::ISyncInferRequest& rq) {+ auto is_position_ids = [](const ov::Output<const ov::Node>& p) {+ const auto& shape = p.get_shape();+ // FIXME: 2D/3D position IDs are not supported here YET+ return p.get_node()->get_friendly_name() == "position_ids" &&+ (shape.size() == 1 || (shape.size() == 2 && shape[0] == 1));+ };++ const auto& inputs = rq.get_inputs();+ auto pos_ids_iter = std::find_if(inputs.begin(), inputs.end(), is_position_ids);+ if (pos_ids_iter != inputs.end()) {+ const auto param_idx = std::distance(inputs.begin(), pos_ids_iter);+ return Selector::Ptr{new PositionIDs(param_idx, d, rq)};+ }+ return Selector::Ptr{};+}++void ov::npuw::runtime::attention::PositionIDs::prepare() {+ const auto& iport = m_rq.get_compiled_model()->inputs()[m_position_ids_idx];+ const auto in_tensor = m_rq.get_tensor(iport);+ const auto in_dims = in_tensor->get_shape();++ // There's several cases possible:+ // a. Prefill input_ids, including chunk+ // b. Generate input_ids, 1+ // c. Generate input_ids, N (speculative)+ // Prefill (even chunked) is left-padded, so for (a) it's enough to take the last element.+ // Same works for b (there's no choice).+ // c may require traversing the tensor backwards as Generate with N>1 is right_padded (?)++ auto* pos_data_ptr = in_tensor->data<int64_t>();+ for (auto idx = in_dims.back() - 1; idx >= 0; idx--) {+ if (pos_data_ptr[idx] > 0) {+ // Initialize fields+ m_current_length = pos_data_ptr[idx];+ switch (m_case) {+ case Case::GENERATE:+ // decode case, we have pos_id-1 past elements to take from kvcache+ m_past_length = m_current_length;+ break;+ case Case::PREFILL:+ // chunked prefill case. calculate the past_length in full chunks+ // FIXME: We know too much about chunking here+ m_past_length = (m_current_length / m_d.query_size) * m_d.query_size;+ break;+ default:+ NPUW_ASSERT(false && "Reached the unreachable code");+ }+ return;+ }+ }+ LOG_WARN("Dynamic selector - no data found in the feature?");+ m_current_length = -1;+}++int64_t ov::npuw::runtime::attention::PositionIDs::length() const {+ return m_current_length;+}++int64_t ov::npuw::runtime::attention::PositionIDs::past_length() const {+ return m_past_length;+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/attention.hpp b/src/plugins/intel_npu/src/plugin/npuw/attention.hppnew file mode 100644index 00000000000..7da6762f5ea--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/attention.hpp@@ -0,0 +1,187 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <optional>+#include <vector>++#include "logging.hpp" // NPUW_ASSERT+#include "openvino/openvino.hpp"+#include "openvino/runtime/icompiled_model.hpp"+#include "openvino/runtime/isync_infer_request.hpp"+#include "openvino/runtime/make_tensor.hpp" // get_tensor_impl+#include "util.hpp" // fill_tensor++namespace ov {+namespace npuw {++namespace function {++// Partition-time attention information. So far assume dynamic execution in 1 dimension only+// Defined at this level to be aligned with other partitioning entities (but needs to be moved?)+struct Attention {+ using PPtr = std::shared_ptr<ov::op::v0::Parameter>;+ struct Param {+ PPtr param;+ std::size_t dim;+ };+ std::vector<Param> _inputs;++ // FIXME: This may be way too specific for a generic dynamic block,+ // as it reflects the attention input here.+ PPtr _mask;+ ov::Shape _mask_shape;++ std::size_t query_len() const {+ // Put the mask's innermost dimension dynamic+ NPUW_ASSERT(_mask_shape.size() == 4);+ return _mask_shape.at(2);+ }++ std::size_t context_len() const {+ // Put the mask's innermost dimension dynamic+ NPUW_ASSERT(_mask_shape.size() == 4);+ return _mask_shape.at(3);+ }++ static std::optional<Attention> from(const std::shared_ptr<ov::Model>& model);+};++} // namespace function++namespace compiled {++namespace {+template <typename T>+void prepare_mask(ov::SoPtr<ov::ITensor> tensor) {+ // Initialize the top-right triangle with -inf+ // e.g., for a matrix like below where i = -inf (of type T)+ // <-past -> < q >+ // 000000000 0iiii+ // 000000000 00iii+ // 000000000 000ii+ // 000000000 0000i+ // 000000000 00000+ NPUW_ASSERT(tensor->is_continuous());+ ov::npuw::util::fill_tensor<T>(tensor, 0);++ const auto shape = tensor->get_shape();+ NPUW_ASSERT(shape.size() == 4);+ NPUW_ASSERT(shape[0] == 1);+ NPUW_ASSERT(shape[1] == 1);++ const auto q_size = shape[2];+ const auto ctx_size = shape[3];+ for (std::size_t i = 0; i < q_size - 1; i++) {+ T* pRow = tensor->data<T>() + i * ctx_size;+ for (std::size_t j = ctx_size - q_size + i; j < ctx_size; j++) {+ pRow[j] = std::numeric_limits<T>::lowest();+ }+ }+}+} // anonymous namespace++// Compile-time attention information. Not much different from the above+struct Attention {+ std::size_t query_size = 0u;+ std::size_t context_size = 0u;++ struct Param {+ std::size_t idx; // function input index for this spatial parameter+ std::size_t dim;+ };+ std::vector<Param> params;+ std::size_t mask_idx = 0u;++ ov::Tensor attend_all;++ Attention() = default;+ Attention(const function::Attention& d, const std::shared_ptr<ov::Model>& m)+ : query_size(d.query_len()),+ context_size(d.context_len()) {+ for (auto&& input : d._inputs) {+ std::size_t p_idx = m->get_parameter_index(input.param);+ params.push_back(Param{p_idx, input.dim});+ }+ mask_idx = m->get_parameter_index(d._mask);++ // Create a mask data tensor here. Technically it is a runtime parameter,+ // but in fact it doesn't change in runtime (we ignore what user passes us!)+ // FIXME: Probably it is wrong+ const auto mask_type = d._mask->get_element_type();+ attend_all = ov::Tensor(mask_type, d._mask_shape);++ switch (mask_type) {+ case ov::element::f16:+ prepare_mask<ov::float16>(ov::get_tensor_impl(attend_all));+ break;+ case ov::element::f32:+ prepare_mask<float>(ov::get_tensor_impl(attend_all));+ break;+ default:+ OPENVINO_THROW("Dynamic attenion mask type ", mask_type, " is not supported yet");+ }+ }+};++} // namespace compiled++namespace runtime {+namespace attention {++// A base class to decide the work-scope from some feature+class Selector {+public:+ enum class Case { PREFILL, GENERATE, UNKNOWN };++ using Ptr = std::shared_ptr<Selector>;+ virtual ~Selector() = default;+ virtual void prepare() = 0;+ virtual int64_t length() const = 0;+ virtual int64_t past_length() const = 0;++ Case this_case() const {+ return m_case;+ }++protected:+ Case m_case = Case::UNKNOWN;+};++// No dynamic dispatch - just run over the whole range+class All final : public Selector {+ void prepare() override {}+ int64_t length() const override {+ return -1;+ }+ int64_t past_length() const override {+ OPENVINO_NOT_IMPLEMENTED; // And shouldn't be here+ }+};++// Define work scope based on position ids+class PositionIDs final : public Selector {+ std::size_t m_position_ids_idx = 0u;+ int64_t m_current_length = 0;+ int64_t m_past_length = 0;++ const compiled::Attention& m_d;+ const ov::ISyncInferRequest& m_rq;++ PositionIDs(std::size_t param_idx, const compiled::Attention& d, const ov::ISyncInferRequest& rq);+ void prepare() override;+ int64_t length() const override;+ int64_t past_length() const override;++public:+ static Selector::Ptr find(const compiled::Attention& d, const ov::ISyncInferRequest& rq);+};++} // namespace attention+} // namespace runtime++} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cppindex 24be22f5a2e..e97b2ac5439 100644--- a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.cpp@@ -491,6 +491,7 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requconst auto& proto_comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];const bool is_spatial = proto_comp_model_desc.spatial.has_value();+ const bool is_attention = proto_comp_model_desc.attention.has_value();// a list of ports to copy tensors, if needed: FROM -> TOstd::vector<std::pair<ov::SoPtr<ov::ITensor>, ov::Output<const ov::Node>>> copy_list;@@ -506,6 +507,17 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ});};+ // Check if the given subgraph's input is dynamic+ auto is_attn_param = [&](std::size_t sub_in_idx) -> bool {+ if (!is_attention) {+ return false; // Early return+ }+ auto& attn = proto_comp_model_desc.attention.value();+ return std::any_of(attn.params.begin(), attn.params.end(), [&](const auto& p) -> bool {+ return p.idx == sub_in_idx;+ });+ };+for (auto&& it : iodesc.global_params) {std::size_t param_idx{}, sub_in_idx{};std::tie(param_idx, sub_in_idx) = it;@@ -516,7 +528,20 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requconst auto& s_port = request->get_inputs()[sub_in_idx];LOG_DEBUG("Processing " << g_port << " -> " << s_port << "...");LOG_BLOCK();- if (!is_spatial_param(sub_in_idx)) {+ if (is_spatial_param(sub_in_idx)) {+ // Register for future use+ // FIXME: Not sure why this code is here. There should be no+ // spatial global parameters, as this execution mode iterates over+ // the iterations only.+ // Also, it pretty much looks like _io[] should be taken at+ // idx but not real_idx, as referring to real_idx breaks the+ // function pipelining+ NPUW_ASSERT(false && "Global parameter can't be spatial");+ m_spatial_io[real_idx].inputs.at(sub_in_idx) = g_tnsr;+ } else if (is_attn_param(sub_in_idx)) {+ // Register for future use+ m_attention_io[idx].inputs.at(sub_in_idx) = g_tnsr;+ } else {// Input parameter is non-spatial, do normal handlingif (m_input_allocated.count(g_tnsr->data()) == 0 && do_copy) {LOG_DEBUG("Will be copied");@@ -525,11 +550,8 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requLOG_DEBUG("Will be set");request->set_tensor(s_port, g_tnsr);}- } else {- // Register for future use- m_spatial_io[real_idx].inputs.at(sub_in_idx) = g_tnsr;}- }+ } // for(global_params)LOG_DEBUG("Running copy...");ov::parallel_for(copy_list.size(), [&](std::size_t idx) {@@ -553,6 +575,11 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ// Run host-side quantized gather, if requiredhandle_quant_host_gather(idx, request);+ // Handle attention inputs, if required+ m_profile["attn(io)"].record([&]() {+ bind_attention_inputs(idx, request);+ });+LOG_DEBUG("Done");}@@ -647,6 +674,65 @@ void ov::npuw::IBaseInferRequest::handle_quant_host_gather(std::size_t idx, RqPt}}+void ov::npuw::IBaseInferRequest::bind_attention_inputs(std::size_t idx, RqPtr request) {+ auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real(idx)];+ if (!comp_model_desc.attention) {+ return;+ }++ LOG_DEBUG("Binding Attention inputs...");+ LOG_BLOCK();++ const auto& dynamic = comp_model_desc.attention.value();+ auto& r = request;++ const auto pos_id = m_attention_selector->length();+ if (pos_id == -1) {+ // Dynamic range couldn't be identified - fallback to the default+ // (worst case) behavior+ for (auto&& param : dynamic.params) {+ const auto& iport = comp_model_desc.compiled_model->inputs()[param.idx];+ const auto& input = m_attention_io[idx].inputs.at(param.idx);+ r->set_tensor(iport, input);+ }+ } else {+ const auto past_len = m_attention_selector->past_length();+ const auto do_copy = needs_copy(idx) && !m_npuw_model->m_cfg.get<::intel_npu::NPUW_ATTN_NO_COPY>();++ // Set the past k/v values first+ for (auto&& param : dynamic.params) {+ const auto& iport = comp_model_desc.compiled_model->inputs()[param.idx];+ const auto& input = m_attention_io[idx].inputs.at(param.idx);+ const auto& view = ov::npuw::util::view(input, param.dim, 0, past_len);+ const auto shape = view->get_shape();++ LOG_DEBUG(iport);+ LOG_BLOCK();+ if (do_copy && ov::shape_size(shape) > 0) {+ // FIXME: Same devices that don't tolerate set_, also don't tolerate strided inputs+ const auto& dst = r->get_tensor(iport);+ const auto old_ptr = dst->data();+ dst->set_shape(shape);+ const auto new_ptr = dst->data();+ if (old_ptr != new_ptr) {+ m_footprint[*comp_model_desc.device_it] += dst->get_byte_size();+ }+ LOG_DEBUG("Do copy: " << shape << "...");+ view->copy_to(dst._ptr);+ } else if (do_copy && ov::shape_size(shape) == 0) {+ // Special case for 0ths chunk.+ // Zero the tensor shape but not set to view+ // (a view tensor can't be extended)+ r->get_tensor(iport)->set_shape(shape);+ } else {+ r->set_tensor(iport, view);+ }+ } // for(params)+ }++ LOG_DEBUG("Done");+}+void ov::npuw::IBaseInferRequest::bind_global_results(std::size_t idx, RqPtr request) {LOG_DEBUG("Binding results for Subgraph[" << idx << "]");LOG_BLOCK();diff --git a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hppindex 858556d68d6..c17765261ca 100644--- a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp@@ -11,6 +11,7 @@#include <string>#include <vector>+#include "attention.hpp"#include "openvino/runtime/iasync_infer_request.hpp"#include "openvino/runtime/isync_infer_request.hpp"#include "openvino/runtime/so_ptr.hpp"@@ -121,11 +122,20 @@ protected:};std::vector<SpatialIO> m_spatial_io;+ // FIXME: All comments for SpatialIO above apply here as well.+ struct AttentionIO {+ std::vector<ov::SoPtr<ov::ITensor>> inputs; // # of elements - # of graph-side inputs+ };+ std::vector<AttentionIO> m_attention_io;+// FIXME: Currently is initialized/managed by subclass as well.// Moved here dumping purposes only// Represents spatial run-time inforuntime::spatial::Selector::Ptr m_spatial_selector;+ // Same thing about this one+ runtime::attention::Selector::Ptr m_attention_selector;+// This structure tracks how every individual subrequest// access the model's top-level (global, public, etc) parameters// and results. Again, is managed by subclasses@@ -157,6 +167,8 @@ protected:void alloc_quant_gather_tensors(std::size_t idx, RqPtr request);void handle_quant_host_gather(std::size_t idx, RqPtr request);+ void bind_attention_inputs(std::size_t idx, RqPtr request);+void dump_input_tensors(std::size_t idx);void dump_output_tensors(std::size_t idx);diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cppindex 9e9633523e7..86d52a1cb6e 100644--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp@@ -172,6 +172,8 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,m_cfg(m_options_desc),m_name(model->get_friendly_name()),m_loaded_from_cache(false) {+ init_profiling();+// Note: we need to identify original bf16 constants for potential weightless deserialization later// And only then do bf16 to f16 transformationm_bf16_consts = ov::npuw::s11n::get_bf16_consts(model);@@ -368,6 +370,12 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,m_compiled_submodels[id].spatial =compiled::Spatial(fcn_template._spatial.value(), fcn_template._model);}+ // Does the same for dynamic. FIXME: This selection should be hidden here+ // in the object semantics+ if (fcn_template._attention) {+ m_compiled_submodels[id].attention =+ compiled::Attention(fcn_template._attention.value(), fcn_template._model);+ }LOG_INFO("Subgraph[" << id << "] is a function body for " << subgraph._funcall);} else {// ...and refer to it in other calls@@ -530,6 +538,8 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,m_name(model->get_friendly_name()),m_loaded_from_cache(serialized) {NPUW_ASSERT(serialized && "This constructor should only be utilized during deserialization!");+ init_profiling();+::intel_npu::registerNPUWOptions(*m_options_desc);LOG_DEBUG("CompiledModel is being deserialized, skipping the full constructor flow...");}@@ -637,6 +647,7 @@ void ov::npuw::CompiledModel::CompiledModelDesc::serialize(std::ostream& stream,write(stream, quant_unpack_gather.idx_idx);write(stream, spatial);+ write(stream, attention);write(stream, is_remote);write(stream, closure_uid);@@ -711,6 +722,7 @@ void ov::npuw::CompiledModel::CompiledModelDesc::deserialize(std::istream& strearead(stream, quant_unpack_gather.idx_idx);read(stream, spatial);+ read(stream, attention);read(stream, is_remote);read(stream, closure_uid);@@ -1306,13 +1318,16 @@ void ov::npuw::CompiledModel::store_const_offsets(const std::shared_ptr<ov::Modevoid ov::npuw::CompiledModel::detach_memory() {LOG_INFO("Detaching model & weight memory...");LOG_BLOCK();++ const bool no_runtime_fallback = !m_cfg.get<::intel_npu::NPUW_FALLBACK_EXEC>();+for (size_t idx = 0; idx < m_compiled_submodels.size(); ++idx) {auto& comp_model_desc = m_compiled_submodels[idx];auto& proto_comp_model_desc = m_compiled_submodels[comp_model_desc.replaced_by.value_or(idx)];if (!proto_comp_model_desc.model || !proto_comp_model_desc.compiled_model) {continue; // optimized-out OR already cleared - skip}- if (proto_comp_model_desc.device_it + 1 == m_dev_list.end()) {+ if ((proto_comp_model_desc.device_it + 1 == m_dev_list.end()) || no_runtime_fallback) {LOG_INFO("No fallback expected - clear the OV model for Subgraph[" << idx << "]");proto_comp_model_desc.model.reset();}diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hppindex 425281be488..a783b5b0a99 100644--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp@@ -6,6 +6,7 @@#include <optional>+#include "attention.hpp"#include "common.hpp"#include "intel_npu/config/config.hpp"#include "intel_npu/config/npuw.hpp"@@ -166,6 +167,7 @@ private:Subgraph::Gather host_gather;Subgraph::QuantUnpackGather quant_unpack_gather;std::optional<ov::npuw::compiled::Spatial> spatial;+ std::optional<ov::npuw::compiled::Attention> attention;// FIXME: This is a 1:1 copy of the ov::npuw::Subgraph structure// w.r.t. function callsdiff --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 2f755dfdb13..0844624680b 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@@ -196,11 +196,14 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com}m_spatial_io.resize(m_num_submodels);+ m_attention_io.resize(m_num_submodels);// Create infer requests// Preallocate funcall tensors & substitute function call requestsbool failover_happened = false;bool has_spatial = false;+ bool has_dynamic = false;+ std::size_t dynamic_sub_idx = -1;for (size_t i = 0; i < m_num_submodels; i++) {LOG_INFO("Creating infer request for Subgraph[" << i << "]...");LOG_BLOCK();@@ -247,6 +250,17 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com}} // if(spatial)+ // Initialize the dynamic IO placeholders, if required+ if (proto_comp_model_desc.attention) {+ // Sanity check first+ if (has_dynamic && dynamic_sub_idx != real_idx) {+ OPENVINO_THROW("Only single attention type is permitted for model");+ }+ has_dynamic = true;+ dynamic_sub_idx = real_idx;+ m_attention_io[i].inputs.resize(proto_comp_model_desc.param_base);+ } // if(dynamic)+for (size_t out_idx = 0; out_idx < num_outputs; out_idx++) {const auto from = LinkFrom{i, out_idx};m_funcall_result[from] = m_func_mem_mgr.get_tensor(from);@@ -351,6 +365,24 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com}LOG_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");+ }}void ov::npuw::JustInferRequest::set_tensor(const ov::Output<const ov::Node>& port,@@ -474,6 +506,15 @@ void ov::npuw::JustInferRequest::prepare_for_infer() {if (m_spatial_selector) {m_spatial_selector->prepare();}++ // So do the dynamic range+ if (m_attention_selector) {+ m_attention_selector->prepare();+ }++ // FIXME: attention-specific, needs to be moved out after refactoring+ m_cached_attention_mask = {};+LOG_DEBUG("Done");}@@ -536,6 +577,15 @@ 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 auto non_dynamic_act_in = [](const ov::npuw::compiled::Attention& d, std::size_t in_idx) {+ const bool not_param = std::none_of(d.params.begin(), d.params.end(), [&](auto&& p) {+ return p.idx == in_idx;+ });+ const bool not_mask = in_idx != d.mask_idx;+ return not_param && not_mask;+ };// Function call prologue:// 1. Walk through function dependencies and set the respective tensors@@ -551,32 +601,43 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {std::size_t prod_port;std::tie(prod_idx, prod_port) = link_iter->second;- if (!m_npuw_model->m_compiled_submodels[prod_idx].replaced_by) {- // Producer is a normal model -> take its tensor directly- const auto& oport = m_npuw_model->m_compiled_submodels[prod_idx].compiled_model->outputs()[prod_port];- auto i_tensor = m_subrequests[prod_idx]->get_tensor(oport);- if (!is_spatial) {- // Non-spatial case - set immediately- m_subrequests[real_idx]->set_tensor(iport, i_tensor);+ const auto& i_tensor = [&]() {+ if (!m_npuw_model->m_compiled_submodels[prod_idx].replaced_by) {+ // Producer is a normal model -> take its tensor directly+ const auto& oport =+ m_npuw_model->m_compiled_submodels[prod_idx].compiled_model->outputs()[prod_port];+ return m_subrequests[prod_idx]->get_tensor(oport);} else {- // Spatial case - defer- m_spatial_io[real_idx].inputs.at(i) = i_tensor;+ // Producer is a function - maybe the same as we're calling now.+ // Take its tensor from the storage+ return m_funcall_result.at({prod_idx, prod_port});}- } else {- // Producer is a function - maybe the same as we're calling now.- // Take its tensor from the storage- const auto& i_tensor = m_funcall_result.at({prod_idx, prod_port});- if (!is_spatial) {- // Non-spatial case - again, set immediately+ }();++ if (is_spatial) {+ // Spatial case - defer+ m_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 (non_dynamic_act_in(*func_desc.attention, i)) {m_subrequests[real_idx]->set_tensor(iport, i_tensor);} else {- // Spatial case - defer- m_spatial_io[real_idx].inputs.at(i) = i_tensor;+ m_attention_io[idx].inputs.at(i) = i_tensor;}+ } else {+ // Default case+ m_subrequests[real_idx]->set_tensor(iport, i_tensor);}- }+ } // 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);+ });+ }+// 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.@@ -606,6 +667,85 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {LOG_DEBUG("Done");}+void ov::npuw::JustInferRequest::function_prologue_attn(std::size_t real_idx, std::size_t idx) {+ auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];+ NPUW_ASSERT(comp_model_desc.attention.has_value());++ auto& r = m_subrequests[real_idx];++ const auto& dynamic = comp_model_desc.attention.value();+ auto mask_iport = comp_model_desc.compiled_model->inputs()[dynamic.mask_idx];++ const auto& graph_mask = m_attention_io[idx].inputs.at(dynamic.mask_idx);+ const auto this_case = m_attention_selector->this_case();+ auto pos_id = m_attention_selector->length();++ if (pos_id == -1) {+ // Dynamic range couldn't be identified - fallback to the default+ // (worst case) behavior+ r->set_tensor(mask_iport, graph_mask);+ } else {+ const auto past_len = m_attention_selector->past_length();+ const auto present_len = dynamic.query_size;+ // FIXME: get the right dim+ const uint32_t kv_dim = 3;++ auto set_or_copy = [&](const auto& view) {+ if (!needs_copy(idx)) {+ r->set_tensor(mask_iport, view);+ } else {+ const auto& dst = r->get_tensor(mask_iport);+ dst->set_shape(view->get_shape());+ view->copy_to(dst._ptr);+ }+ };++ // Now set the mask. Here comes very strong chunking & SDPA knowledge again+ using namespace ov::npuw::runtime;+ if (this_case == attention::Selector::Case::GENERATE) {+ // Take a view from our "attend_all" mask+ const auto& view = ov::npuw::util::view(ov::get_tensor_impl(dynamic.attend_all), kv_dim, 0, past_len + 1);+ set_or_copy(view);+ } else if (this_case == attention::Selector::Case::PREFILL) {+ // Use our in-graph synthesized mask+ if (m_cached_attention_mask) {+ // All sub models are sharing the same attention mask, we can use the cached attention+ // mask directly to avoid redundant tensor copy+ m_subrequests[real_idx]->set_tensor(mask_iport, m_cached_attention_mask);+ return;+ }++ // Handle attention mask concatenation for SDPA:+ // The attention mask is composed with 2 parts:+ // The 1st part is for the "present", which is at the tail: starting from past_len to context_len+ // The 2nd part is for the "past", which is at the beginning: starting from 0 to past_len+ auto full_mask_shape = graph_mask->get_shape();+ auto actual_mask_shape = full_mask_shape;+ actual_mask_shape[kv_dim] = present_len + past_len;++ // Reshape the input to the proper shape+ const auto& dst = r->get_tensor(mask_iport);+ dst->set_shape(actual_mask_shape);++ // Copy "present" attention mask+ const auto& present_dst_view = ov::npuw::util::view(dst, kv_dim, past_len, present_len);+ const auto& present_src_view =+ ov::npuw::util::view(graph_mask, kv_dim, full_mask_shape[kv_dim] - present_len, present_len);+ present_src_view->copy_to(present_dst_view._ptr);++ // Copy "past" attention mask+ if (past_len > 0) {+ const auto& past_dst_view = ov::npuw::util::view(dst, kv_dim, 0, past_len);+ const auto& past_src_view = ov::npuw::util::view(graph_mask, kv_dim, 0, past_len);+ past_src_view->copy_to(past_dst_view._ptr);+ }+ m_cached_attention_mask = dst;+ } else {+ NPUW_ASSERT(false && "Reached the unreachable code");+ }+ }+}+void ov::npuw::JustInferRequest::recreate_subrequests(std::size_t idx) {auto& comp_model_desc = m_npuw_model->m_compiled_submodels[idx];auto real_idx = comp_model_desc.replaced_by.value_or(idx);@@ -665,6 +805,7 @@ void ov::npuw::JustInferRequest::run_subrequest_for_success(std::size_t idx, boodump_input_tensors(idx);}+ std::string error_text;try {LOG_DEBUG("Trying to run subrequest[" << idx << "]...");LOG_BLOCK();@@ -672,20 +813,28 @@ void ov::npuw::JustInferRequest::run_subrequest_for_success(std::size_t idx, boojob_done = true;LOG_DEBUG("Done: " << idx << "(exec subrequest)");} catch (const std::exception& ex) {- LOG_ERROR("Subgraph [" << idx << "] - FAILED to run infer request:" << std::endl << ex.what());+ error_text = ex.what();+ LOG_ERROR("Subgraph [" << idx << "] - FAILED to run infer request:" << std::endl+ << error_text << std::endl);should_recreate = true;} catch (...) {LOG_ERROR("Subgraph [" << idx << "] - FAILED to run infer request: REASON UNKNOWN");should_recreate = true;}if (should_recreate) {- failover = true;- LOG_INFO("- Trying next device...");-// Altering iterators here!! Contracts should be changed!comp_model_desc.device_it++;++ // Check if failover is actually possible+ if ((m_npuw_model->m_dev_list.cend() == comp_model_desc.device_it) ||+ !m_npuw_model->m_cfg.get<::intel_npu::NPUW_FALLBACK_EXEC>()) {+ OPENVINO_THROW("Execution error: \"", error_text, "\" - no fallback possible");+ }++ failover = true;+ LOG_INFO("- Trying next device...");if (!m_npuw_model->compile_for_success(real_idx)) {- OPENVINO_THROW("Failed to compile. No more devices are left!");+ OPENVINO_THROW("Execution error: \"", error_text, "\" - failed to recompile the model in runtime");}recreate_subrequests(idx);}@@ -701,129 +850,135 @@ void ov::npuw::JustInferRequest::run_subrequest_for_success(std::size_t idx, boo}}-void ov::npuw::JustInferRequest::unsafe_during(std::size_t real_idx, const std::function<void()>& f) {+void ov::npuw::JustInferRequest::unsafe_during(std::size_t real_idx, std::size_t idx, const std::function<void()>& f) {auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];if (!comp_model_desc.spatial) {- // Non-spatial execution: trigger request asynchronously, run `f` in this context+ // Normal: trigger request asynchronously, run `f` in this context+ // FIXME: dynamic could hit here too, but it has special logic+ // around execution which makes it harder to run than a plain start_async()auto& r = m_subrequests[real_idx];r->start_async();f(); // expect noexceptr->wait();} else {- // Spatial execution... Do the opposite - run f asynchronously, and meanwhile run the- // spatial inference+ // Spatial... Do the opposite - run f+ // asynchronously, and meanwhile run the spatial inferenceauto future = std::async(std::launch::async, f);- unsafe_infer(real_idx);+ unsafe_infer(real_idx, idx);future.wait();}}-void ov::npuw::JustInferRequest::unsafe_infer(std::size_t real_idx) {+void ov::npuw::JustInferRequest::unsafe_infer_spatial(std::size_t real_idx, std::size_t) {auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];+ NPUW_ASSERT(comp_model_desc.spatial.has_value());+auto& r = m_subrequests[real_idx];- if (!comp_model_desc.spatial) {- // Run normally++ // Run over the specified range... Note: the full inputs/outputs+ // must be prepared in the m_spatial_io at this point+ const auto& spatial = comp_model_desc.spatial.value();+ const auto num_outputs = comp_model_desc.compiled_model->outputs().size();+ NPUW_ASSERT(m_spatial_selector);++ // Create a sparse vector with full input sizes.+ // For the access simplicity, its size is aligned with function's+ // number of input parameters (activations) so some slots may be+ // not used here.+ // FIXME: All these preparations could be done statically (just once)+ std::vector<ov::Shape> full_in_shapes(comp_model_desc.param_base);+ for (auto&& param : spatial.params) {+ full_in_shapes[param.idx] = m_spatial_io[real_idx].inputs.at(param.idx)->get_shape();+ }++ // Now handle the range, even if it is not a multiply of nway (slice):+ //+ // |<- - - - full range - - - ->|+ // +------+------+------+------+-++ // | nway | nway | nway | nway | |+ // +------+------+------+------+-++ // ^tail+ // The block is always compiled to produce nway. If we need a smaller tensor+ // on the last iteration, the sub-nway will be copied from the input range to+ // a temporary tensor, and then the sub-nwway range will be copied from the+ // request's output range.++ std::size_t offset = 0u;+ for (std::size_t i = 0u; i < spatial.nway_iters; i++, offset += spatial.nway) {+ if (!m_spatial_selector->need_submit(offset, spatial.nway)) {+ continue;+ }++ // Collect spatial inputs for this offset+ for (auto&& param : spatial.params) {+ const auto& iport = comp_model_desc.compiled_model->inputs()[param.idx];+ const auto& iview =+ ov::npuw::util::view(m_spatial_io[real_idx].inputs.at(param.idx), param.dim, offset, spatial.nway);+ r->set_tensor(iport, iview);+ } // for(params)++ // Now set the spatial outputs+ for (std::size_t out_idx = 0u; out_idx < num_outputs; out_idx++) {+ const auto& oport = comp_model_desc.compiled_model->outputs()[out_idx];+ r->set_tensor(oport,+ ov::npuw::util::view(m_spatial_io[real_idx].outputs.at(out_idx),+ spatial.out_dim,+ offset,+ spatial.nway));+ } // for(outputs)++ // Now run the partr->infer();- } else {- // Run over the specified range... Note: the full inputs/outputs- // must be prepared in the m_spatial_io at this point- const auto& spatial = comp_model_desc.spatial.value();- const auto num_outputs = comp_model_desc.compiled_model->outputs().size();- NPUW_ASSERT(m_spatial_selector);-- // Create a sparse vector with full input sizes.- // For the access simplicity, its size is aligned with function's- // number of input parameters (activations) so some slots may be- // not used here.- // FIXME: All these preparations could be done statically (just once)- std::vector<ov::Shape> full_in_shapes(comp_model_desc.param_base);+ } // for(full_nway_times)++ // Now process the tail, if required+ if (spatial.tail_size && m_spatial_selector->need_submit(offset, spatial.tail_size)) {+ // Copy the sub-ranges to spatial inputs+ // NOTE: tails buffers are read from/written to at 0th offset!for (auto&& param : spatial.params) {- full_in_shapes[param.idx] = m_spatial_io[real_idx].inputs.at(param.idx)->get_shape();- }+ auto in_view =+ ov::npuw::util::view(m_spatial_io[real_idx].inputs.at(param.idx), param.dim, offset, spatial.tail_size);- // Now handle the range, even if it is not a multiply of nway (slice):- //- // |<- - - - full range - - - ->|- // +------+------+------+------+-+- // | nway | nway | nway | nway | |- // +------+------+------+------+-+- // ^tail- // The block is always compiled to produce nway. If we need a smaller tensor- // on the last iteration, the sub-nway will be copied from the input range to- // a temporary tensor, and then the sub-nwway range will be copied from the- // request's output range.-- std::size_t offset = 0u;- for (std::size_t i = 0u; i < spatial.nway_iters; i++, offset += spatial.nway) {- if (!m_spatial_selector->need_submit(offset, spatial.nway)) {- continue;- }+ const auto& iport = comp_model_desc.compiled_model->inputs()[param.idx];+ auto out_view =+ ov::npuw::util::view(m_spatial_io[real_idx].input_tails.at(param.idx), param.dim, 0, spatial.tail_size);- // Collect spatial inputs for this offset- for (auto&& param : spatial.params) {- const auto& iport = comp_model_desc.compiled_model->inputs()[param.idx];- const auto& iview =- ov::npuw::util::view(m_spatial_io[real_idx].inputs.at(param.idx), param.dim, offset, spatial.nway);- r->set_tensor(iport, iview);- } // for(params)-- // Now set the spatial outputs- for (std::size_t out_idx = 0u; out_idx < num_outputs; out_idx++) {- const auto& oport = comp_model_desc.compiled_model->outputs()[out_idx];- r->set_tensor(oport,- ov::npuw::util::view(m_spatial_io[real_idx].outputs.at(out_idx),- spatial.out_dim,- offset,- spatial.nway));- } // for(outputs)-- // Now run the part- r->infer();- } // for(full_nway_times)-- // Now process the tail, if required- if (spatial.tail_size && m_spatial_selector->need_submit(offset, spatial.tail_size)) {- // Copy the sub-ranges to spatial inputs- // NOTE: tails buffers are read from/written to at 0th offset!- for (auto&& param : spatial.params) {- auto in_view = ov::npuw::util::view(m_spatial_io[real_idx].inputs.at(param.idx),- param.dim,- offset,- spatial.tail_size);-- const auto& iport = comp_model_desc.compiled_model->inputs()[param.idx];- auto out_view = ov::npuw::util::view(m_spatial_io[real_idx].input_tails.at(param.idx),- param.dim,- 0,- spatial.tail_size);-- in_view->copy_to(out_view._ptr);- r->set_tensor(iport, m_spatial_io[real_idx].input_tails.at(param.idx));- } // for(params)-- // Now set the tail tensors- for (std::size_t out_idx = 0u; out_idx < num_outputs; out_idx++) {- const auto& oport = comp_model_desc.compiled_model->outputs()[out_idx];- r->set_tensor(oport, m_spatial_io[real_idx].output_tails.at(out_idx));- } // for(outputs)-- // Now run the tail infer- r->infer();-- // Now copy the views from the output full-nway tensor to the output tensors- for (std::size_t out_idx = 0u; out_idx < num_outputs; out_idx++) {- auto in_view = ov::npuw::util::view(m_spatial_io[real_idx].output_tails.at(out_idx),- spatial.out_dim,- 0,- spatial.tail_size);-- auto out_view = ov::npuw::util::view(m_spatial_io[real_idx].outputs.at(out_idx),- spatial.out_dim,- offset,- spatial.tail_size);- in_view->copy_to(out_view._ptr);- } // for(outputs)- }+ in_view->copy_to(out_view._ptr);+ r->set_tensor(iport, m_spatial_io[real_idx].input_tails.at(param.idx));+ } // for(params)++ // Now set the tail tensors+ for (std::size_t out_idx = 0u; out_idx < num_outputs; out_idx++) {+ const auto& oport = comp_model_desc.compiled_model->outputs()[out_idx];+ r->set_tensor(oport, m_spatial_io[real_idx].output_tails.at(out_idx));+ } // for(outputs)++ // Now run the tail infer+ r->infer();++ // Now copy the views from the output full-nway tensor to the output tensors+ for (std::size_t out_idx = 0u; out_idx < num_outputs; out_idx++) {+ auto in_view = ov::npuw::util::view(m_spatial_io[real_idx].output_tails.at(out_idx),+ spatial.out_dim,+ 0,+ spatial.tail_size);++ auto out_view = ov::npuw::util::view(m_spatial_io[real_idx].outputs.at(out_idx),+ spatial.out_dim,+ offset,+ spatial.tail_size);+ in_view->copy_to(out_view._ptr);+ } // for(outputs)+ }+}++void ov::npuw::JustInferRequest::unsafe_infer(std::size_t real_idx, std::size_t idx) {+ auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];+ auto& r = m_subrequests[real_idx];+ if (comp_model_desc.spatial) {+ unsafe_infer_spatial(real_idx, idx);+ } else {+ r->infer(); // Run normally}}@@ -841,7 +996,7 @@ void ov::npuw::JustInferRequest::unsafe_run_this_prep_next(std::size_t idx, boolif (is_pipelined(real_idx)) {// function pipelining is here! and the next rq is ours.NPUW_ASSERT(m_funcall_pipeline[idx].next.value() == next_idx);- unsafe_during(real_idx, [&]() {+ unsafe_during(real_idx, idx, [&]() {LOG_DEBUG("Unpacking closures for the NEXT subrequest[" << next_idx << "]...");LOG_BLOCK();// Note: do it here unconditionally - if this request fails,@@ -852,7 +1007,7 @@ void ov::npuw::JustInferRequest::unsafe_run_this_prep_next(std::size_t idx, bool} else {// Function pipelining is not used. THIS infer request// is also the NEXT one. Nothing much to do here- unsafe_infer(real_idx);+ unsafe_infer(real_idx, idx);bind_global_parameters(next_idx);}} else {@@ -862,9 +1017,9 @@ void ov::npuw::JustInferRequest::unsafe_run_this_prep_next(std::size_t idx, boolif (next_idx == 0) {// Note: even if m_function_pipelining is ON,// SWAP won't happen here - see the below check for .next- unsafe_infer(real_idx);+ unsafe_infer(real_idx, idx);} else {- unsafe_during(real_idx, [&]() {+ unsafe_during(real_idx, idx, [&]() {if (!next_prepared) {bind_global_parameters(next_idx);next_prepared = true;@@ -882,9 +1037,9 @@ void ov::npuw::JustInferRequest::unsafe_run_this_prep_next(std::size_t idx, bool// This is a regular subgraph. Start it async to prepare the next// parametersif (next_idx == 0) {- unsafe_infer(real_idx);+ unsafe_infer(real_idx, idx);} else {- unsafe_during(real_idx, [&]() {+ unsafe_during(real_idx, idx, [&]() {if (!next_prepared) {bind_global_parameters(next_idx);next_prepared = true;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 e9c479e3104..482793a634a 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@@ -98,9 +98,11 @@ protected:using IBaseInferRequest::bind_global_results;void function_prologue(std::size_t idx);+ void function_prologue_attn(std::size_t real_idx, std::size_t idx);- void unsafe_during(std::size_t real_idx, const std::function<void()>& f);- void unsafe_infer(std::size_t real_idx);+ void unsafe_during(std::size_t real_idx, std::size_t idx, const std::function<void()>& f);+ void unsafe_infer(std::size_t real_idx, std::size_t idx);+ void unsafe_infer_spatial(std::size_t real_idx, std::size_t idx);void unsafe_run_this_prep_next(std::size_t idx, bool& next_prepared_p);void connect_subrequests();@@ -129,6 +131,9 @@ protected:// Cached check if we do FOLDing and need to update closures in the repeating blocksbool m_closure_update_required = false;++ // Cached attention mask for SDPA operations to avoid recomputing+ ov::SoPtr<ov::ITensor> m_cached_attention_mask;};} // namespace npuwdiff --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 25c0bb4574a..466e285af7f 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@@ -1123,7 +1123,6 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m// Generate a random weights bank name unique to this LLMCompiledModel objectauto weights_bank_name = ov::npuw::util::generate_random_string();LOG_VERB("Generated a unique weights bank name: " << weights_bank_name);-apply_weights_bank_name(prefill_config, weights_bank_name);apply_weights_bank_name(generate_config, weights_bank_name);@@ -1142,6 +1141,18 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mmerge_config_with(generate_config, dyn_attn_opts);}+ // Note: with dynamic attention in EITHER STAGE, we have to+ // explicitly disable the run-time fallback to so extra ov::Model+ // references won't be held by the npuw::CompiledModel, resulting+ // in a higher memory consumption. This behavior should be reworked!+ // The reason here is that NPUW_DEVICES may come as a global setting,+ // impacting all the stages.+ if (prefill_attn_dyn || generate_attn_dyn) {+ const ov::AnyMap no_runtime_fallback = {{"NPUW_FALLBACK_EXEC", "NO"}};+ merge_config_with(prefill_config, no_runtime_fallback);+ merge_config_with(generate_config, no_runtime_fallback);+ }+if (m_cfg.get<::intel_npu::NPUW_LLM_CACHE_ROPE>()) {LOG_DEBUG("Caching preROPE ");const uint32_t CACHE_ROPE_START = 2048;@@ -1164,6 +1175,7 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m{ov::pass::GraphRewrite rewr;rewr.add_matcher<ov::npuw::patterns::regularize::AttentionBroadcast>();+ rewr.add_matcher<ov::npuw::patterns::regularize::AttentionBroadcast2>();rewr.add_matcher<ov::npuw::patterns::regularize::ShapeOfParameter>();rewr.run_on_model(kvcache_model);rewr.run_on_model(prefill_model);diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cppindex 629e28b94ac..017f4c1736b 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp@@ -14,17 +14,7 @@namespace {-template <typename T>-void fill_tensor(ov::SoPtr<ov::ITensor> tensor, T fill_val, size_t offset = 0u) {- T* tensor_data = tensor->data<T>();- std::fill(tensor_data + offset, tensor_data + tensor->get_size(), fill_val);-}--void fill_tensor_bytes(ov::SoPtr<ov::ITensor> tensor, uint8_t fill_val) {- auto* tensor_data = reinterpret_cast<uint8_t*>(tensor->data());- std::fill_n(tensor_data, tensor->get_byte_size(), fill_val);-}-+// FIXME: Use ov::npuw::util::view insteadov::SoPtr<ov::ITensor> make_tensor_slice(ov::SoPtr<ov::ITensor> tensor,uint32_t dim,uint32_t start_pos,@@ -396,7 +386,7 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCocontinue;}auto kvcache_in_tensor = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(input_name));- fill_tensor<ov::float16>(kvcache_in_tensor, 0);+ ov::npuw::util::fill_tensor<ov::float16>(kvcache_in_tensor, 0);}}@@ -461,8 +451,8 @@ void ov::npuw::LLMInferRequest::apply_lora() {// Disable adapter by setting alpha to 0if (ov::npuw::util::matchLoRAMatMulAlphaString(state_name)) {- fill_tensor<float>(prefill_lora_in_tensor, 0.0f);- fill_tensor<float>(kvcach_lora_in_tensor, 0.0f);+ ov::npuw::util::fill_tensor<float>(prefill_lora_in_tensor, 0.0f);+ ov::npuw::util::fill_tensor<float>(kvcach_lora_in_tensor, 0.0f);}} else {// Generate with LoRA@@ -489,7 +479,7 @@ void ov::npuw::LLMInferRequest::apply_lora() {bool has_padding = state_tensor_rank != target_lora_rank;if (has_padding) {// Clear padding tensor in infer request- fill_tensor<float>(new_infer_tensor, 0.0f);+ ov::npuw::util::fill_tensor<float>(new_infer_tensor, 0.0f);}// Fill LoRA into infer request@@ -519,13 +509,14 @@ void ov::npuw::LLMInferRequest::apply_lora() {}void ov::npuw::LLMInferRequest::prepare_for_new_conversation() {- fill_tensor_bytes(m_prefill_request->get_tensor(m_prefill_in_ports.at(m_input_ids_name)), 0u);+ namespace uu = ov::npuw::util;+ uu::fill_tensor_bytes(m_prefill_request->get_tensor(m_prefill_in_ports.at(m_input_ids_name)), 0u);if (auto type_ids_port = m_prefill_in_ports.find(layer_names::token_type_ids);type_ids_port != m_prefill_in_ports.end()) {- fill_tensor_bytes(m_prefill_request->get_tensor(type_ids_port->second), 0u);+ uu::fill_tensor_bytes(m_prefill_request->get_tensor(type_ids_port->second), 0u);}- fill_tensor<int64_t>(m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask)), 0);- fill_tensor<int64_t>(m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::position_ids)), 0);+ uu::fill_tensor<int64_t>(m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask)), 0);+ uu::fill_tensor<int64_t>(m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::position_ids)), 0);m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens = 0u;apply_lora();@@ -679,7 +670,7 @@ void ov::npuw::LLMInferRequest::clear_chunk_prefill_kv_cache() {auto chunk_prefill_kvcache_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name));- fill_tensor<ov::float16>(chunk_prefill_kvcache_in_tensor, 0);+ ov::npuw::util::fill_tensor<ov::float16>(chunk_prefill_kvcache_in_tensor, 0);}}@@ -718,7 +709,7 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp// We will populate current_prompts_len on the right side of attention mask for the processing tokens// If the current prompt length is smaller than the chunk prompt length,// clear the last chunk of the attention mask to ensure non-relevant tokens are masked- fill_tensor<int64_t>(attn_mask_in_tensor, 0, last_chunk_offset);+ ov::npuw::util::fill_tensor<int64_t>(attn_mask_in_tensor, 0, last_chunk_offset);}std::copy_n(attention_mask->data<int64_t>() + kvcache_desc.num_stored_tokens,current_prompts_len,@@ -870,11 +861,13 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,copy_kvcache();LOG_DEBUG("Prepare inputs.");- fill_tensor_bytes(m_kvcache_request->get_tensor(m_kvcache_in_ports.at(m_input_ids_name)), 0u);- fill_tensor<int64_t>(m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::attention_mask)), 0);- fill_tensor<int64_t>(m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::position_ids)), 0);+ namespace uu = ov::npuw::util;+ uu::fill_tensor_bytes(m_kvcache_request->get_tensor(m_kvcache_in_ports.at(m_input_ids_name)), 0u);+ uu::fill_tensor<int64_t>(m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::attention_mask)), 0);+ uu::fill_tensor<int64_t>(m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::position_ids)), 0);if (token_type_ids) {- fill_tensor<int64_t>(m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::token_type_ids)), 0);+ uu::fill_tensor<int64_t>(m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::token_type_ids)),+ 0);}m_generate_initialized = true;}diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/group.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/group.cppindex b2d75a925b4..36206a60180 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/group.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/group.cpp@@ -251,18 +251,12 @@ void Group::fuseWith(const Group::GPtr& gptr_cons) {LOG_DEBUG("Fusing...");LOG_BLOCK();{- LOG_DEBUG("Merger:");- LOG_BLOCK();- for (auto&& layer : m_content) {- LOG_DEBUG(layer);- }+ LOG_DEBUG("Merger: " << this->specialTags());+ dump();}{- LOG_DEBUG("Mergee:");- LOG_BLOCK();- for (auto&& layer : gptr_cons->m_content) {- LOG_DEBUG(layer);- }+ LOG_DEBUG("Mergee: " << gptr_cons->specialTags());+ gptr_cons->dump();}}@@ -494,3 +488,10 @@ void Group::dontIsolate() {const std::string& Group::isolatedTag() const {return m_isol_tag;}++void Group::dump() const {+ LOG_BLOCK();+ for (auto&& layer : m_content) {+ LOG_DEBUG(layer);+ }+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/group.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/group.hppindex e49608545c8..5ea48108d9a 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/group.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/group.hpp@@ -84,6 +84,8 @@ public:void addWeightsPrecision(const std::vector<ov::element::Type>& prec);const std::vector<ov::element::Type>& getConstsPrecision() const;+ void dump() const;+private:void includeExtraLayers(detail::OVNodeSet& input_layers,detail::OVNodeSet& output_layers,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 e744e488269..168cfcd3b63 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@@ -886,6 +886,9 @@ std::shared_ptr<Repeated> Snapshot::tryGrowRepeatingGroups(const GPtrSet& repeatconst auto& this_avoided = first_rep_group->avoidedTargets();const auto& this_special = first_rep_group->specialTags();+ LOG_DEBUG("Trying to grow a repeating set tagged \"" << this_special << "\"");+ LOG_BLOCK();+std::unordered_map<PairMICVecIO, std::vector<std::pair<Group::GPtr, Group::GPtr>>> mics;std::vector<Group::GPtr> repeating_groups_sorted(repeating_groups.begin(), repeating_groups.end());@@ -906,9 +909,14 @@ std::shared_ptr<Repeated> Snapshot::tryGrowRepeatingGroups(const GPtrSet& repeat});for (const auto& group : repeating_groups_sorted) {+ LOG_DEBUG("cons_group:");+ group->dump();+ LOG_BLOCK();auto producers = group->srcNodes();for (const auto& prod_nh : producers) {Group::GPtr prod_group = m_graph->meta(prod_nh).get<Group::GPtr>();+ LOG_DEBUG("prod_group:");+ prod_group->dump();if (prod_group->repeated() && !prod_group->hasCycle(group) && prod_group->repeated() != this_rep_tag &&prod_group->avoidedTargets() == this_avoided && prod_group->specialTags() == this_special) {auto meta_interconnect = group->metaInterconnect(prod_group);@@ -918,6 +926,17 @@ std::shared_ptr<Repeated> Snapshot::tryGrowRepeatingGroups(const GPtrSet& repeatMICVec mic_sorted_key(meta_interconnect.first.begin(), meta_interconnect.first.end());std::sort(mic_sorted_key.begin(), mic_sorted_key.end());mics[{mic_sorted_key, meta_interconnect.second}].push_back({prod_group, group});+ LOG_DEBUG("Add the pair to the merge vector!");+ } else if (ov::npuw::debug_groups()) {+ LOG_DEBUG("Couldn't add the pair to the merge vector due to failed checks:");+ LOG_BLOCK();+#define INSPECT(x) LOG_DEBUG(#x " = " << (x))+ INSPECT(prod_group->specialTags());+ INSPECT(prod_group->repeated() != this_rep_tag);+ INSPECT(prod_group->hasCycle(group));+ INSPECT(prod_group->avoidedTargets() == this_avoided);+ INSPECT(prod_group->specialTags() == this_special);+#undef INSPECT}}}@@ -977,6 +996,7 @@ std::shared_ptr<Repeated> Snapshot::tryMergeRepeating(const std::vector<Group::G}if (conss.size() == 1) {+ LOG_DEBUG("Skip - consumer size is 1");return {};}@@ -995,6 +1015,7 @@ std::shared_ptr<Repeated> Snapshot::tryMergeRepeating(const std::vector<Group::G//// In this method we get [ A1, A1, A2, A2 ] as prods what is not very correct// but this check using std::set reverts it back to the proper [ A1, A2 ] form and the check fails+ LOG_DEBUG("Skip - triangle case");return {};}@@ -1015,6 +1036,7 @@ std::shared_ptr<Repeated> Snapshot::tryMergeRepeating(const std::vector<Group::G// Later in CleanUpUniques() pass those repeated blocks will be stripped off repeated tag due to the same check// in this "if". To prevent such cases where we would end up with small number of huge blocks this check was// introduced.+ LOG_DEBUG("Skip: " << prods.size() << " < " << m_ctx.keep_blocks);return {};}diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cppindex 7fc9e26c9b6..a144dc8e509 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp@@ -331,6 +331,7 @@ public:void createFunction(const std::string& func_name);void matchRepeatedSubgraphs(const std::string& func_name);void spatial(const std::string& func_name);+ void attention(const std::string& func_name);void optimize(const std::string& func_name);void decompressionCutOff(const std::string& func_name);@@ -1881,6 +1882,27 @@ void Partitioner::spatial(const std::string& func_name) {LOG_VERB("Done");}+void Partitioner::attention(const std::string& func_name) {+ ov::npuw::Function& f = P.functions.at(func_name);++ // Support only attention at the time+ if (f._tag != "attn") {+ LOG_VERB("No dynamic handling be done to " << func_name << " in model " << model->get_friendly_name()+ << "...");+ return;+ }++ LOG_VERB("Turn " << func_name << " into dynamic Attention block in model " << model->get_friendly_name() << "...");+ LOG_BLOCK();++ f._attention = ov::npuw::function::Attention::from(f._model);+ if (!f._attention) {+ LOG_WARN("Do dynamic ranges found in the ATTN block");+ return;+ }+ LOG_VERB("Done");+}+void Partitioner::optimize(const std::string& func_name) {using namespace ov::npuw::weights;@@ -2476,6 +2498,7 @@ ov::npuw::Partitioning ov::npuw::getPartitioning(const std::shared_ptr<ov::Modelp.matchResults(func_group);p.matchRepeatedSubgraphs(func_group);p.spatial(func_group);+ p.attention(func_group);p.optimize(func_group);p.decompressionCutOff(func_group);}diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hppindex ea091080c1d..fd782bffe52 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp@@ -9,6 +9,7 @@#include <variant>#include <vector>+#include "../attention.hpp"#include "../lazy_tensor.hpp"#include "../spatial.hpp"#include "intel_npu/config/config.hpp"@@ -85,6 +86,8 @@ struct Function {std::map<std::pair<std::string, std::size_t>, std::size_t> _param_mapping;std::optional<ov::npuw::function::Spatial> _spatial;+ std::optional<ov::npuw::function::Attention> _attention;+ // FIXME: They should exclude each other (introduce a hierarchy, finally?)// FIXME: shouldn't be here. Needed to not unpack some lazy closures in DCOFFstd::set<std::size_t> _idx_lazy_unpack;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 506bd1b6f2a..e1ab6c96c74 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@@ -95,6 +95,7 @@ AttentionBroadcast::AttentionBroadcast() {// NB: It only works in static shape graphsauto 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()});+ // NB: THREE inputs is also a case (see below)auto concat = opp::wrap_type<ov::op::v0::Concat>({gather, opp::any_input(), opp::any_input(), opp::any_input()});// Broadcast - the consumer@@ -121,6 +122,40 @@ AttentionBroadcast::AttentionBroadcast() {register_matcher(std::make_shared<opp::Matcher>(bcast_kv, "AttentionBroadcast"), std::move(callback));}+// FIXME: Same as above but Concat has three inputs instead of four+AttentionBroadcast2::AttentionBroadcast2() {+ 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()});++ 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()}); // THIS IS the difference++ // FIXME: using past_kv_cat as a 0th argument to this Unsqueeze breaks the pattern+ // for Phi-4+ auto unsq_kv = opp::wrap_type<ov::op::v0::Unsqueeze>({opp::any_input(), 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()) {+ 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, "AttentionBroadcast2"), 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});diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.hppindex 83fba08b9d2..129abbe9275 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/sdpa.hpp@@ -38,6 +38,12 @@ public:AttentionBroadcast();};+class AttentionBroadcast2 : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::attn::AttentionBroadcast2");+ AttentionBroadcast2();+};+class ShapeOfParameter : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::attn::ShapeOfParameter");diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.cppindex a2f51314b14..228abbfcb86 100644--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp@@ -4,6 +4,7 @@#include "serialization.hpp"+#include "attention.hpp"#include "intel_npu/config/config.hpp"#include "intel_npu/config/npuw.hpp"#include "lazy_tensor.hpp"@@ -87,6 +88,23 @@ void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::Spatiwrite(stream, var.tail_size);}+void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::Attention& var) {+ using ov::npuw::s11n::write;++ write(stream, var.query_size);+ write(stream, var.context_size);++ // NB: This should've been done through a generic vector<T> write!+ write(stream, var.params.size());+ for (const auto& p : var.params) {+ write(stream, p.idx);+ write(stream, p.dim);+ }++ write(stream, var.mask_idx);+ write(stream, var.attend_all);+}+void ov::npuw::s11n::write(std::ostream& stream, const ov::Tensor& var) {using ov::npuw::s11n::write;@@ -190,6 +208,25 @@ void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::Spatial& varread(stream, var.tail_size);}+void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::Attention& var) {+ using ov::npuw::s11n::read;++ read(stream, var.query_size);+ read(stream, var.context_size);++ std::size_t params_size = 0;+ read(stream, params_size);+ for (std::size_t i = 0; i < params_size; ++i) {+ ov::npuw::compiled::Attention::Param p;+ read(stream, p.idx);+ read(stream, p.dim);+ var.params.push_back(p);+ }++ read(stream, var.mask_idx);+ read(stream, var.attend_all);+}+void ov::npuw::s11n::read(std::istream& stream, ov::Tensor& var) {bool is_initialized = false;read(stream, is_initialized);diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hppindex 566a12fba5a..5378a81dda8 100644--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp@@ -73,6 +73,7 @@ namespace npuw {// Forward declarationnamespace compiled {struct Spatial;+struct Attention;} // namespace compilednamespace weights {class LazyTensor;@@ -150,6 +151,7 @@ void write(std::ostream& stream, const std::string& var);void write(std::ostream& stream, const bool& var);void write(std::ostream& stream, const float& var);void write(std::ostream& stream, const ov::npuw::compiled::Spatial& var);+void write(std::ostream& stream, const ov::npuw::compiled::Attention& var);void write(std::ostream& stream, const ov::Tensor& var);void write(std::ostream& stream, const ::intel_npu::Config& var);void write(std::ostream& stream, const ov::Output<const ov::Node>& var);@@ -165,6 +167,7 @@ void read(std::istream& stream, std::string& var);void read(std::istream& stream, bool& var);void read(std::istream& stream, float& var);void read(std::istream& stream, ov::npuw::compiled::Spatial& var);+void read(std::istream& stream, ov::npuw::compiled::Attention& var);void read(std::istream& stream, ov::Tensor& var);void read(std::istream& stream, ::intel_npu::Config& var);void read(std::istream& stream, std::shared_ptr<ov::op::v0::Parameter>& var);diff --git a/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cppindex 0e60f2886f1..e7036e16106 100644--- a/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cpp@@ -30,6 +30,9 @@ ov::npuw::UnfoldInferRequest::UnfoldInferRequest(const std::shared_ptr<ov::npuw:if (proto_comp_model_desc.spatial) {NPUW_ASSERT(false && "Spatial is not supported in unfold");}+ if (proto_comp_model_desc.attention) {+ NPUW_ASSERT(false && "Dynamic is not supported in unfold");+ }} // if(replaced_by)const auto real_idx = comp_model_desc.replaced_by.value_or(i);diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cppindex e99f5988409..917c829c9f1 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp@@ -948,3 +948,8 @@ bool ov::npuw::util::matchLoRAMatMulBString(const std::string& input) {bool ov::npuw::util::matchLoRAMatMulAlphaString(const std::string& input) {return ov::npuw::util::matchStringWithLoRAPattern(input, LoRANames::MatMul_alpha);}++void ov::npuw::util::fill_tensor_bytes(ov::SoPtr<ov::ITensor> tensor, uint8_t fill_val) {+ auto* tensor_data = reinterpret_cast<uint8_t*>(tensor->data());+ std::fill_n(tensor_data, tensor->get_byte_size(), fill_val);+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.hpp b/src/plugins/intel_npu/src/plugin/npuw/util.hppindex f1b5f914ab6..edbacfbdbc8 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.hpp@@ -188,6 +188,19 @@ bool matchLoRAMatMulBString(const std::string& input);bool matchLoRAMatMulAlphaString(const std::string& input);+template <typename T>+void fill_tensor(ov::SoPtr<ov::ITensor> tensor, T fill_val, size_t offset = 0u) {+ T* tensor_data = tensor->data<T>();+ std::fill(tensor_data + offset, tensor_data + tensor->get_size(), fill_val);+}++void fill_tensor_bytes(ov::SoPtr<ov::ITensor> tensor, uint8_t fill_val);++template <class T>+typename std::underlying_type<T>::type _v(T&& t) {+ return static_cast<typename std::underlying_type<T>::type>(t);+}+} // namespace util} // namespace npuw} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cppindex a40740e5e9c..2dbab6197e3 100644--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp@@ -344,6 +344,7 @@ void Plugin::init_options() {REGISTER_OPTION(NPUW_FUNCALL_FOR_ALL);REGISTER_OPTION(NPUW_FUNCALL_ASYNC);REGISTER_OPTION(NPUW_UNFOLD_IREQS);+ REGISTER_OPTION(NPUW_FALLBACK_EXEC);REGISTER_OPTION(NPUW_LLM);REGISTER_OPTION(NPUW_LLM_BATCH_DIM);REGISTER_OPTION(NPUW_LLM_SEQ_LEN_DIM);diff --git a/src/plugins/intel_npu/src/plugin/src/properties.cpp b/src/plugins/intel_npu/src/plugin/src/properties.cppindex 661adbb471d..f7180e96127 100644--- a/src/plugins/intel_npu/src/plugin/src/properties.cpp+++ b/src/plugins/intel_npu/src/plugin/src/properties.cpp@@ -450,6 +450,7 @@ void Properties::registerPluginProperties() {TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::partitioning::funcall_for_all, NPUW_FUNCALL_FOR_ALL);TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::funcall_async, NPUW_FUNCALL_ASYNC);TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::unfold_ireqs, NPUW_UNFOLD_IREQS);+ TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::fallback_exec, NPUW_FALLBACK_EXEC);TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::enabled, NPUW_LLM);TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::batch_dim, NPUW_LLM_BATCH_DIM);TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::seq_len_dim, NPUW_LLM_SEQ_LEN_DIM);diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex b42deb6c470..b85ca206b29 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -39,6 +39,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/util.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/util_xarch.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/lazy_tensor.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/attention.cppLINK_LIBRARIES${MANDATORY_UNIT_TESTS_LIBS}LABELS