Skip to content

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

NPUW: Pyramid attention (#31917)

intelgaoxiong289064360042
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.hpp
index 4d184aa060e..9c32c98f7ce 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,7 @@ 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, bool, true, npuw::partitioning::attn, 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);
@@ -163,7 +164,7 @@ namespace npuw {
namespace llm {
enum class PrefillHint { DYNAMIC, STATIC };
enum class GenerateHint { FAST_COMPILE, BEST_PERF };
-enum class AttentionHint { DYNAMIC, STATIC };
+enum class AttentionHint { DYNAMIC, STATIC, PYRAMID };
} // namespace llm
} // namespace npuw
@@ -225,6 +226,8 @@ struct ATTN_HINT_BASE : OptionBase<ATTN_HINT_BASE, ::intel_npu::npuw::llm::Atten
return ::intel_npu::npuw::llm::AttentionHint::DYNAMIC;
} else if (val == "STATIC") {
return ::intel_npu::npuw::llm::AttentionHint::STATIC;
+ } else if (val == "PYRAMID") {
+ return ::intel_npu::npuw::llm::AttentionHint::PYRAMID;
}
OPENVINO_THROW("Unsupported attention hint provided: ", val);
return {};
@@ -236,6 +239,8 @@ struct ATTN_HINT_BASE : OptionBase<ATTN_HINT_BASE, ::intel_npu::npuw::llm::Atten
return "DYNAMIC";
case ::intel_npu::npuw::llm::AttentionHint::STATIC:
return "STATIC";
+ case ::intel_npu::npuw::llm::AttentionHint::PYRAMID:
+ return "PYRAMID";
default:
OPENVINO_THROW("Can't convert provided attention hint : ", int(val), " to string.");
}
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.hpp
index 68ac3f2160f..041171903f5 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,14 @@ 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.
+ * Apply attention optimizations (e.g. DYNAMIC, PYRAMID, and others) when attention block detected.
+ * Default value: true
+ */
+static constexpr ov::Property<bool> attn{"NPUW_ATTN"};
+
/**
* @brief
* Type: boolean.
diff --git a/src/plugins/intel_npu/src/al/src/config/npuw.cpp b/src/plugins/intel_npu/src/al/src/config/npuw.cpp
index ad2cc62b308..bc8e178384f 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,7 @@ void intel_npu::registerNPUWOptions(OptionsDesc& desc) {
desc.add<NPUW_SPATIAL>();
desc.add<NPUW_SPATIAL_NWAY>();
desc.add<NPUW_SPATIAL_DYN>();
+ desc.add<NPUW_ATTN>();
desc.add<NPUW_ATTN_DYN>();
desc.add<NPUW_ATTN_NO_COPY>();
desc.add<NPUW_HOST_GATHER>();
diff --git a/src/plugins/intel_npu/src/plugin/include/properties.hpp b/src/plugins/intel_npu/src/plugin/include/properties.hpp
index e7b18603470..22f6f5ebb95 100644
--- a/src/plugins/intel_npu/src/plugin/include/properties.hpp
+++ b/src/plugins/intel_npu/src/plugin/include/properties.hpp
@@ -91,6 +91,7 @@ private:
ov::intel_npu::npuw::partitioning::online::min_size.name(),
ov::intel_npu::npuw::partitioning::online::keep_blocks.name(),
ov::intel_npu::npuw::partitioning::online::keep_block_size.name(),
+ ov::intel_npu::npuw::partitioning::attn.name(),
ov::intel_npu::npuw::partitioning::fold.name(),
ov::intel_npu::npuw::partitioning::cwai.name(),
ov::intel_npu::npuw::partitioning::dyn_quant.name(),
diff --git a/src/plugins/intel_npu/src/plugin/npuw/attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/attention.cpp
index ba0dc81f16b..0b493f354c4 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/attention.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/attention.cpp
@@ -6,6 +6,7 @@
#include "openvino/op/broadcast.hpp"
#include "openvino/op/scaled_dot_product_attention.hpp"
#include "openvino/op/util/op_types.hpp" // is_parameter
+#include "pyramid_attention.hpp"
#include "util.hpp"
namespace {
@@ -103,30 +104,7 @@ std::optional<ov::npuw::function::Attention> ov::npuw::function::Attention::from
// 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);
- }
+ ov::npuw::function::patch_broadcast_constants(model, dyn.context_len());
model->validate_nodes_and_infer_types();
return {std::move(dyn)};
diff --git a/src/plugins/intel_npu/src/plugin/npuw/attention.hpp b/src/plugins/intel_npu/src/plugin/npuw/attention.hpp
index f271d1668a2..e03174f4eb6 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/attention.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/attention.hpp
@@ -50,6 +50,13 @@ struct Attention {
static std::optional<Attention> from(const std::shared_ptr<ov::Model>& model);
};
+// Helper function to patch broadcast constants (set to 1 for dynamic handling)
+void patch_broadcast_constants(const std::shared_ptr<ov::Model>& model, size_t target_length);
+
+// Helper function to patch reshape constants (-1 substitution)
+void patch_reshape_constants(const std::shared_ptr<ov::Model>& model,
+ const std::map<std::string, size_t>& past_value_sequence_dims);
+
} // namespace function
namespace compiled {
diff --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.cpp
index 5a012f9a197..c626ac3cdda 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
@@ -5,6 +5,7 @@
#include "base_sync_infer_request.hpp"
#include "compiled_model.hpp"
+#include "infer_request_utils.hpp" // to utilize copy_tensor_by_dim
#include "intel_npu/config/npuw.hpp"
#include "intel_npu/utils/zero/zero_host_tensor.hpp"
#include "intel_npu/utils/zero/zero_remote_tensor.hpp"
@@ -494,6 +495,7 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ
const 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();
+ const bool is_pyramid_attention = proto_comp_model_desc.pyramid_attention.has_value();
// a list of ports to copy tensors, if needed: FROM -> TO
std::vector<std::pair<ov::SoPtr<ov::ITensor>, ov::Output<const ov::Node>>> copy_list;
@@ -520,6 +522,18 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ
});
};
+ auto is_pyramid_attn_param = [&](std::size_t sub_in_idx) -> bool {
+ if (!is_pyramid_attention) {
+ return false; // Early return
+ }
+
+ auto pyramid_id = m_pyramid_selector->pyramid_id();
+ auto& pyramid_attn = proto_comp_model_desc.pyramid_attention.value()._attention_infos[pyramid_id];
+ return std::any_of(pyramid_attn.params.begin(), pyramid_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;
@@ -540,7 +554,7 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ
// 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)) {
+ } else if (is_attn_param(sub_in_idx) || is_pyramid_attn_param(sub_in_idx)) {
// Register for future use
m_attention_io[idx].inputs.at(sub_in_idx) = g_tnsr;
} else {
@@ -583,6 +597,11 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ
bind_attention_inputs(idx, request);
});
+ // Handle pyramid attention inputs, if required
+ m_profile["attn(io)"].record([&]() {
+ bind_pyramid_attention_inputs(idx, request);
+ });
+
LOG_DEBUG("Done");
}
@@ -736,6 +755,118 @@ void ov::npuw::IBaseInferRequest::bind_attention_inputs(std::size_t idx, RqPtr r
LOG_DEBUG("Done");
}
+void ov::npuw::IBaseInferRequest::bind_pyramid_attention_inputs(std::size_t idx, RqPtr request) {
+ auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real(idx)];
+ if (!comp_model_desc.pyramid_attention) {
+ return;
+ }
+
+ LOG_DEBUG("Binding Pyramid Attention inputs...");
+ LOG_BLOCK();
+
+ const auto pyramid_id = m_pyramid_selector->pyramid_id();
+ const auto& pyramid_attention = comp_model_desc.pyramid_attention.value();
+ const auto& attention_info = pyramid_attention._attention_infos[pyramid_id];
+ const auto& pyramid_model = pyramid_attention._compiled_models[pyramid_id];
+
+ const auto pos_id = m_pyramid_selector->length();
+ if (pos_id == -1) {
+ // Pyramid dynamic range couldn't be identified - fallback to the default
+ // (worst case) behavior
+ for (auto&& param : attention_info.params) {
+ const auto& iport = pyramid_model->inputs()[param.idx];
+ const auto& input = m_attention_io[idx].inputs.at(param.idx);
+ request->set_tensor(iport, input);
+ }
+
+ return;
+ }
+
+ // Pyramid dynamic range identified
+ const auto past_len = m_pyramid_selector->past_length();
+ const auto infer_case = m_pyramid_selector->this_case();
+
+ using namespace ov::npuw::runtime;
+
+ // Process each KV parameter based on inference case
+ if (infer_case == pyramid_attention::Selector::Case::PREFILL) {
+ // PREFILL: Set or copy past KV to destination tensors
+ for (auto&& param : attention_info.params) {
+ const auto& iport = pyramid_model->inputs()[param.idx];
+ const auto& input = m_attention_io[idx].inputs.at(param.idx);
+ const auto& input_shape = input->get_shape();
+
+ LOG_DEBUG(iport);
+ LOG_BLOCK();
+
+ // Optimization for the last chunk: Direct tensor reuse when shapes match
+ if (static_cast<int64_t>(input_shape[param.dim]) == past_len) {
+ request->set_tensor(iport, input);
+ continue;
+ }
+
+ // Create view of past KV data
+ const auto& view = ov::npuw::util::view(input, param.dim, 0, past_len);
+ const auto& shape = view->get_shape();
+
+ // Handle empty shape case (first chunk)
+ if (ov::shape_size(shape) == 0) {
+ request->get_tensor(iport)->set_shape(shape);
+ continue;
+ }
+
+ // Copy past KV to full destination tensor
+ LOG_DEBUG("Do copy: " << shape << "...");
+ const auto& dst = request->get_tensor(iport);
+ ov::npuw::util::copy_tensor_by_dim(view,
+ dst,
+ static_cast<uint32_t>(param.dim),
+ static_cast<uint32_t>(param.dim));
+ }
+ } else if (infer_case == pyramid_attention::Selector::Case::GENERATE) {
+ // GENERATE: Set or copy past KV, preserving existing data
+ for (auto&& param : attention_info.params) {
+ const auto& iport = pyramid_model->inputs()[param.idx];
+ const auto& input = m_attention_io[idx].inputs.at(param.idx);
+ const auto& input_shape = input->get_shape();
+
+ LOG_DEBUG(iport);
+ LOG_BLOCK();
+
+ // Validation: ensure space for new tokens
+ if (static_cast<int64_t>(input_shape[param.dim]) == past_len) {
+ NPUW_ASSERT(false && "Past KV is full, no space for generation");
+ }
+
+ const auto& dst = request->get_tensor(iport);
+ const auto& dst_shape = dst->get_shape();
+
+ // Optimization: Direct tensor reuse when destination matches input
+ if (dst_shape == input_shape) {
+ request->set_tensor(iport, input);
+ continue;
+ }
+
+ // FIXME: No need to copy whole past KV, just the new part
+
+ // Create view of past KV data
+ const auto& view = ov::npuw::util::view(input, param.dim, 0, past_len);
+
+ // Copy past KV to sliced destination (preserve space for new tokens)
+ LOG_DEBUG("Do copy: " << view->get_shape() << "...");
+ const auto& dst_slice = ov::npuw::util::view(dst, param.dim, 0, past_len);
+ ov::npuw::util::copy_tensor_by_dim(view,
+ dst_slice,
+ static_cast<uint32_t>(param.dim),
+ static_cast<uint32_t>(param.dim));
+ }
+ } else {
+ NPUW_ASSERT(false && "Unsupported pyramid attention case");
+ }
+
+ 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.hpp
index 7a988a6b555..e866197e98e 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
@@ -16,6 +16,7 @@
#include "openvino/runtime/isync_infer_request.hpp"
#include "openvino/runtime/so_ptr.hpp"
#include "perf.hpp"
+#include "pyramid_attention.hpp"
#include "spatial.hpp"
#include "util.hpp"
@@ -146,6 +147,9 @@ protected:
// Same thing about this one
runtime::attention::Selector::Ptr m_attention_selector;
+ // Separate selector for pyramid attention
+ runtime::pyramid_attention::Selector::Ptr m_pyramid_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
@@ -178,6 +182,7 @@ protected:
void handle_quant_host_gather(std::size_t idx, RqPtr request);
void bind_attention_inputs(std::size_t idx, RqPtr request);
+ void bind_pyramid_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.cpp
index 8c4f9641892..27a21d64704 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
@@ -377,6 +377,13 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
m_compiled_submodels[id].attention =
compiled::Attention(fcn_template._attention.value(), fcn_template._model);
}
+
+ if (fcn_template._pyramid_attention) {
+ LOG_INFO("Creating compiled::PyramidAttention for Subgraph[" << id << "] (function "
+ << subgraph._funcall << ")");
+ m_compiled_submodels[id].pyramid_attention =
+ compiled::PyramidAttention(fcn_template._pyramid_attention.value());
+ }
LOG_INFO("Subgraph[" << id << "] is a function body for " << subgraph._funcall);
} else {
// ...and refer to it in other calls
@@ -405,8 +412,20 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
// FIXME: a hotfix for a crash where we have too many names in submodel's output
// Do it just once if that's a function
if (real_id == id) {
- remove_long_output_names(m_compiled_submodels[real_id].model);
- fill_empty_tensor_names(m_compiled_submodels[real_id].model);
+ auto fix_tensor_names = [&](const std::shared_ptr<ov::Model>& model) {
+ remove_long_output_names(model);
+ fill_empty_tensor_names(model);
+ };
+
+ fix_tensor_names(m_compiled_submodels[real_id].model);
+
+ // Ensure all submodels (including pyramid attention) have consistent and valid tensor names
+ // to avoid issues in downstream inference and model serialization.
+ if (const auto& pyramid_attn = m_compiled_submodels[real_id].pyramid_attention) {
+ for (const auto& model : pyramid_attn.value()._models_to_compile) {
+ fix_tensor_names(model);
+ }
+ }
}
if (ov::npuw::util::is_set(id, dump_sub_opt, real_id, end_sub_idx)) {
@@ -421,9 +440,23 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
(subgraph._funcall.empty() ? "" : "_" + subgraph._funcall) + ".xml";
ov::save_model(model_to_dump, model_dump_path);
LOG_INFO("Wrote " << model_dump_path);
- // Note: keep here naming as it would be the subgraph
+
+ // Dump pyramid attention models if present
+ if (m_compiled_submodels[id].pyramid_attention) {
+ LOG_INFO("NOTE: Subgraph[" << id << "] has a pyramid attention mechanism.");
+ const auto& pyramid_attention_models =
+ m_compiled_submodels[id].pyramid_attention.value()._models_to_compile;
+ for (std::size_t idx = 0; idx < pyramid_attention_models.size(); ++idx) {
+ std::string pyramid_attention_model_dump_path =
+ m_name + "_" + ov::npuw::util::fmt(id, m_compiled_submodels.size()) +
+ (subgraph._funcall.empty() ? "" : "_" + subgraph._funcall) + "_pyramid_" +
+ ov::npuw::util::fmt(idx, pyramid_attention_models.size()) + ".xml";
+ ov::save_model(pyramid_attention_models[idx], pyramid_attention_model_dump_path);
+ LOG_INFO("Wrote " << pyramid_attention_model_dump_path);
+ }
+ }
} // if(dump)
- } // for(orderedSubgraphs)
+ } // for(orderedSubGraphs)
std::map<std::size_t, std::string> forced_sub_devices{};
std::string fsd_opt = m_cfg.get<::intel_npu::NPUW_SUBMODEL_DEVICE>();
@@ -652,6 +685,20 @@ void ov::npuw::CompiledModel::CompiledModelDesc::serialize(std::ostream& stream,
write(stream, spatial);
write(stream, attention);
+ // Serialize compiled submodels for pyramid attention, except the last one
+ write(stream, pyramid_attention);
+ if (pyramid_attention.has_value()) {
+ size_t num_models = pyramid_attention.value()._compiled_models.size();
+ write(stream, num_models);
+
+ for (size_t i = 0; i < num_models - 1; ++i) {
+ std::stringstream ss;
+ auto compiled_model = pyramid_attention.value()._compiled_models[i];
+ compiled_model->export_model(ss);
+ write(stream, ss.str());
+ }
+ }
+
auto& closure_desc = closure.get();
write(stream, closure_desc.is_remote);
@@ -705,7 +752,8 @@ void ov::npuw::CompiledModel::CompiledModelDesc::serialize(std::ostream& stream,
}
void ov::npuw::CompiledModel::CompiledModelDesc::deserialize(std::istream& stream,
- const ov::npuw::s11n::WeightsContext& ctx) {
+ const ov::npuw::s11n::WeightsContext& ctx,
+ const ov::npuw::s11n::PyramidCtx& pyramid_ctx) {
using namespace ov::npuw::s11n;
LOG_DEBUG("Deserializing CompiledModelDesc...");
@@ -729,6 +777,30 @@ void ov::npuw::CompiledModel::CompiledModelDesc::deserialize(std::istream& strea
read(stream, spatial);
read(stream, attention);
+ read(stream, pyramid_attention);
+ if (pyramid_attention.has_value()) {
+ size_t num_models = 0;
+ read(stream, num_models);
+ pyramid_attention.value()._compiled_models.resize(num_models);
+
+ if (num_models > 0) {
+ // Import all pyramid models except the last one
+ for (size_t i = 0; i < num_models - 1; ++i) {
+ std::string model_str;
+ read(stream, model_str);
+ std::stringstream ss(model_str);
+ pyramid_attention->_compiled_models[i] =
+ pyramid_ctx.plugin->get_core()->import_model(ss, pyramid_ctx.device);
+ }
+
+ // Reuse the already compiled model for the last pyramid attention model
+ if (pyramid_ctx.compiled_model) {
+ pyramid_attention->_compiled_models[num_models - 1] = pyramid_ctx.compiled_model;
+ LOG_DEBUG("Reused compiled_model for the last pyramid attention model");
+ }
+ }
+ }
+
auto& closure_desc = closure.get();
read(stream, closure_desc.is_remote);
@@ -1213,7 +1285,11 @@ std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::deserialize(
plugin->get_core()->import_model(buffer, compiled->m_dev_list[device_idx]);
}
compiled->m_compiled_submodels[i].device_it = compiled->m_dev_list.begin() + device_idx;
- compiled->m_compiled_submodels[i].deserialize(stream, compiled->m_import_weights_ctx);
+
+ ov::npuw::s11n::PyramidCtx pyramid_ctx(plugin,
+ compiled->m_dev_list[device_idx],
+ compiled->m_compiled_submodels[i].compiled_model);
+ compiled->m_compiled_submodels[i].deserialize(stream, compiled->m_import_weights_ctx, pyramid_ctx);
}
compiled->implement_properties();
@@ -1371,6 +1447,10 @@ void ov::npuw::CompiledModel::detach_memory() {
LOG_INFO("No fallback expected - clear the OV model for Subgraph[" << idx << "]");
proto_comp_model_desc.model.reset();
}
+
+ // No need to clear pyramid attention data - it's self-contained!
+ // The _models_to_compile is already cleared in set_compiled_models()
+ // and compiled::PyramidAttention only stores _compiled_models (not original models)
}
LOG_INFO("Done");
}
@@ -1539,6 +1619,9 @@ bool ov::npuw::CompiledModel::compile_for_device(std::size_t id, const std::stri
m_profile["compile/" + device_to_try].record([&]() {
m_compiled_submodels[id].compiled_model = compile_submodel(m_compiled_submodels[id].model, device_to_try);
});
+
+ // Compile pyramid attention models if present
+ compile_pyramid_attention_models(id, device_to_try);
} catch (const std::exception& ex) {
LOG_ERROR("Subgraph [" << id << "] Failed to compile: " << std::endl << ex.what());
dump_on_fail(id, device_to_try, ex.what());
@@ -1553,6 +1636,74 @@ bool ov::npuw::CompiledModel::compile_for_device(std::size_t id, const std::stri
return true;
}
+void ov::npuw::CompiledModel::compile_pyramid_attention_models(std::size_t id, const std::string& device) {
+ // Check if we have pyramid attention to compile
+ if (!m_compiled_submodels[id].pyramid_attention.has_value()) {
+ return;
+ }
+
+ LOG_INFO("Compiling pyramid attention submodels for Subgraph[" << id << "]...");
+ LOG_BLOCK();
+
+ auto& pyramid_attn = m_compiled_submodels[id].pyramid_attention.value();
+ const auto& pyramid_attn_models = pyramid_attn._models_to_compile;
+ const size_t total_models = pyramid_attn_models.size();
+
+ LOG_INFO("Total pyramid models to compile: " << total_models);
+
+ // Pre-allocate the compiled models vector
+ std::vector<ov::SoPtr<ov::ICompiledModel>> compiled_models(total_models);
+
+ // Compile all pyramid models except the last one in parallel
+ // The last model will reuse the already compiled original model
+ const size_t models_to_compile = total_models > 0 ? total_models - 1 : 0;
+
+ if (models_to_compile > 0) {
+ LOG_INFO("Compiling " << models_to_compile << " pyramid models in parallel...");
+
+ auto compile_one_model = [&](size_t model_id) {
+ try {
+ const auto& model = pyramid_attn_models[model_id];
+ LOG_DEBUG("Compiling pyramid attention submodel[" << model_id << "]: " << model->get_friendly_name());
+
+ auto compiled = compile_submodel(model, device);
+ OPENVINO_ASSERT(compiled, "Failed to compile pyramid attention submodel");
+
+ compiled_models[model_id] = compiled;
+
+ LOG_INFO("Compiled pyramid attention submodel[" << model_id << "]");
+ } catch (const std::exception& ex) {
+ OPENVINO_THROW("Pyramid attention submodel[", model_id, "] compilation failed: ", ex.what());
+ } catch (...) {
+ OPENVINO_THROW("Pyramid attention submodel[", model_id, "] compilation failed with unknown error");
+ }
+ };
+
+ const bool par_opt = m_cfg.get<::intel_npu::NPUW_PARALLEL_COMPILE>();
+ if (par_opt) {
+ ov::parallel_for(models_to_compile, compile_one_model);
+ } else {
+ for (std::size_t model_id = 0u; model_id < models_to_compile; model_id++) {
+ compile_one_model(model_id);
+ }
+ }
+ }
+
+ // Handle the last model: reuse the already compiled original model
+ if (total_models > 0) {
+ LOG_INFO("Reusing already compiled original model for pyramid attention submodel[" << (total_models - 1)
+ << "] (optimization)");
+ OPENVINO_ASSERT(m_compiled_submodels[id].compiled_model, "Original compiled model should exist");
+ compiled_models[total_models - 1] = m_compiled_submodels[id].compiled_model;
+ }
+
+ // Set compiled models - this also clears _models_to_compile internally
+ LOG_INFO("Setting compiled models into compiled::PyramidAttention...");
+ pyramid_attn.set_compiled_models(std::move(compiled_models));
+
+ LOG_INFO("Pyramid attention compilation complete for Subgraph[" << id << "]");
+}
+
ov::SoPtr<ov::ICompiledModel> ov::npuw::CompiledModel::compile_submodel(const std::shared_ptr<ov::Model>& submodel,
const std::string& device) {
auto plugin = get_npuw_plugin();
diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
index de81713b2f0..19c32d5bbb4 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
@@ -18,6 +18,7 @@
#include "openvino/util/mmap_object.hpp"
#include "partitioning/partitioning.hpp"
#include "perf.hpp"
+#include "pyramid_attention.hpp"
#include "serialization.hpp"
#include "spatial.hpp"
#include "weights_bank.hpp"
@@ -78,6 +79,7 @@ private:
bool compile_for_device(std::size_t id, const std::string& device_to_try);
ov::SoPtr<ov::ICompiledModel> compile_submodel(const std::shared_ptr<ov::Model>& submodel,
const std::string& device);
+ void compile_pyramid_attention_models(std::size_t id, const std::string& device);
void dump_on_fail(std::size_t id, const std::string& device_to_stry, const char* extra);
@@ -177,6 +179,14 @@ private:
Subgraph::QuantUnpackGather quant_unpack_gather;
std::optional<ov::npuw::compiled::Spatial> spatial;
std::optional<ov::npuw::compiled::Attention> attention;
+ std::optional<ov::npuw::compiled::PyramidAttention> pyramid_attention;
+
+ // Infer requests for pyramid attention models (if pyramid_attention is present)
+ std::vector<ov::SoPtr<ov::IAsyncInferRequest>> pyramid_infer_requests;
+
+ // Pipeline infer requests for pyramid attention models (if pyramid_attention is present and pipelining is
+ // enabled)
+ std::vector<ov::SoPtr<ov::IAsyncInferRequest>> pyramid_pipeline_requests;
// FIXME: This is a 1:1 copy of the ov::npuw::Subgraph structure
// w.r.t. function calls
@@ -212,7 +222,9 @@ private:
execution_stats stat;
void serialize(std::ostream& stream, const ov::npuw::s11n::WeightsContext& ctx) const;
- void deserialize(std::istream& stream, const ov::npuw::s11n::WeightsContext& ctx);
+ void deserialize(std::istream& stream,
+ const ov::npuw::s11n::WeightsContext& ctx,
+ const ov::npuw::s11n::PyramidCtx& pyramid_ctx);
};
std::vector<CompiledModelDesc> m_compiled_submodels;
diff --git a/src/plugins/intel_npu/src/plugin/npuw/infer_request_utils.cpp b/src/plugins/intel_npu/src/plugin/npuw/infer_request_utils.cpp
index 82fe5cae911..d4e4ff66371 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/infer_request_utils.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/infer_request_utils.cpp
@@ -128,7 +128,8 @@ void ov::npuw::util::copy_tensor_by_dim(ov::SoPtr<ov::ITensor> src_tensor,
// for multiple heads, while dst_tensor will still have [1, heads, d_v, seq_len!=1],
// shape, awaiting updates at column dimension, as value vectors are columns now.
if (src_shape[kv_dim_src] == 1 && src_tensor->is_continuous()) {
- ov::npuw::util::XARCH::copy_row_as_column(src_tensor, dst_tensor);
+ // FIXME: ov::npuw::util::XARCH::copy_row_as_column(src_tensor, dst_tensor) throws when used here
+ copy_columns_by_row_chunks(src_tensor, dst_tensor);
} else {
copy_columns_by_row_chunks(src_tensor, dst_tensor);
}
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.cpp
index 36a4de68367..e05261ef8b0 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
@@ -12,11 +12,13 @@
#include <utility>
#include "compiled_model.hpp"
+#include "infer_request_utils.hpp" // to utilize copy_tensor_by_dim
#include "logging.hpp"
#include "openvino/core/except.hpp"
#include "openvino/core/parallel.hpp"
#include "openvino/runtime/iasync_infer_request.hpp"
#include "plugin.hpp"
+#include "pyramid_attention.hpp"
#include "util.hpp"
#include "weights_bank.hpp"
@@ -203,7 +205,9 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
bool failover_happened = false;
bool has_spatial = false;
bool has_dynamic = false;
+ bool has_pyramid = false;
std::size_t dynamic_sub_idx = -1;
+ std::size_t pyramid_sub_idx = -1;
for (size_t i = 0; i < m_num_submodels; i++) {
LOG_INFO("Creating infer request for Subgraph[" << i << "]...");
LOG_BLOCK();
@@ -261,6 +265,16 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
m_attention_io[i].inputs.resize(proto_comp_model_desc.param_base);
} // if(dynamic)
+ if (proto_comp_model_desc.pyramid_attention) {
+ // Sanity check first
+ if (has_pyramid && pyramid_sub_idx != real_idx) {
+ OPENVINO_THROW("Only single pyramid attention type is permitted for model");
+ }
+ has_pyramid = true;
+ pyramid_sub_idx = real_idx;
+ m_attention_io[i].inputs.resize(proto_comp_model_desc.param_base);
+ } // if(pyramid)
+
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);
@@ -284,6 +298,17 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
m_funcall_pipeline[i].subrequest = rqs.at(1);
}
+ // Create pyramid attention infer requests if this function has pyramid attention
+ // IMPORTANT: Must be created AFTER main infer requests to enable direct reuse:
+ // The last pyramid infer request directly reuses the main infer request object
+ if (comp_model_desc.replaced_by) {
+ const auto real_idx = comp_model_desc.replaced_by.value();
+ auto& proto_comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];
+ if (proto_comp_model_desc.pyramid_attention) {
+ setup_pyramid_infer_requests(real_idx, is_piped, false);
+ }
+ }
+
LOG_INFO("DONE");
} // for(submodels)
@@ -383,6 +408,24 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
}
LOG_VERB("Done");
}
+
+ // Handle pyramid attention
+ if (has_pyramid) {
+ const auto& pyramid_dyn = m_npuw_model->m_compiled_submodels.at(pyramid_sub_idx).pyramid_attention.value();
+ const auto pyramid_count = pyramid_dyn._compiled_models.size();
+ if (!m_npuw_model->m_cfg.get<::intel_npu::NPUW_ATTN_DYN>()) {
+ // Even if the attention is detected and ready to go pyramid,
+ // force it on the full range
+ m_pyramid_selector.reset(new runtime::pyramid_attention::All(pyramid_count));
+ } else {
+ m_pyramid_selector = runtime::pyramid_attention::PositionIDs::find(pyramid_dyn, *this);
+ if (!m_pyramid_selector) {
+ LOG_WARN("Pyramid dynamic capability is enabled, but no run-time features were found.");
+ // Create All selector with the number of pyramid models
+ m_pyramid_selector.reset(new runtime::pyramid_attention::All(pyramid_count));
+ }
+ }
+ }
}
void ov::npuw::JustInferRequest::set_tensor(const ov::Output<const ov::Node>& port,
@@ -492,6 +535,23 @@ void ov::npuw::JustInferRequest::prepare_for_infer() {
LOG_DEBUG("Preparing to infer...");
LOG_BLOCK();
+ if (m_pyramid_selector) {
+ m_pyramid_selector->prepare(get_history_size());
+
+ // Get the pyramid model ID based on current sequence length (updated in prepare())
+ auto pyramid_id = m_pyramid_selector->pyramid_id();
+
+ for (auto&& id : m_funcall_heads) {
+ auto& comp_model_desc = m_npuw_model->m_compiled_submodels[id];
+ if (comp_model_desc.pyramid_attention.has_value()) {
+ m_subrequests[id] = comp_model_desc.pyramid_infer_requests[pyramid_id];
+ if (is_pipelined(id)) {
+ m_funcall_pipeline[id].subrequest = comp_model_desc.pyramid_pipeline_requests[pyramid_id];
+ }
+ }
+ }
+ }
+
// Submit global parameters (if needed) for the first subgraph
bind_global_parameters(next(0));
@@ -578,12 +638,14 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t 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 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) {
+ // 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 != d.mask_idx;
+ const bool not_mask = in_idx != info.mask_idx;
return not_param && not_mask;
};
@@ -619,7 +681,16 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {
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)) {
+ 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;
@@ -638,6 +709,12 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t 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.
@@ -746,6 +823,93 @@ void ov::npuw::JustInferRequest::function_prologue_attn(std::size_t real_idx, st
}
}
+void ov::npuw::JustInferRequest::function_prologue_pyramid_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.pyramid_attention.has_value());
+
+ auto& r = m_subrequests[real_idx];
+ auto pyramid_id = m_pyramid_selector->pyramid_id();
+
+ const auto& dynamic = comp_model_desc.pyramid_attention.value()._attention_infos[pyramid_id];
+ auto mask_iport =
+ comp_model_desc.pyramid_attention.value()._compiled_models[pyramid_id]->inputs()[dynamic.mask_idx];
+
+ const auto& graph_mask = m_attention_io[idx].inputs.at(dynamic.mask_idx);
+ const auto this_case = m_pyramid_selector->this_case();
+ const auto present_len = dynamic.query_size;
+
+ // FIXME: get the right dim
+ const uint32_t kv_dim = 3;
+
+ // Get destination tensor once for all code paths
+ const auto& dst = r->get_tensor(mask_iport);
+
+ // Lambda: copy attention mask segment from source to destination
+ auto copy_mask_segment = [&](std::size_t dst_offset, std::size_t src_offset, std::size_t length) {
+ if (length == 0) {
+ return;
+ }
+ const auto& dst_view = ov::npuw::util::view(dst, kv_dim, dst_offset, length);
+ const auto& src_view = ov::npuw::util::view(graph_mask, kv_dim, src_offset, length);
+ ov::npuw::util::copy_tensor_by_dim(src_view, dst_view, kv_dim, kv_dim);
+ };
+
+ auto pos_id = m_pyramid_selector->length();
+ if (pos_id == -1) {
+ // Pyramid dynamic range couldn't be identified - fallback to default behavior
+ r->set_tensor(mask_iport, graph_mask);
+ return;
+ }
+
+ // Pyramid dynamic range identified
+ const auto past_len = m_pyramid_selector->past_length();
+
+ // Early return: reuse cached attention mask if available
+ 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;
+ }
+
+ // Now set the mask. Here comes very strong chunking & SDPA knowledge again
+ using namespace ov::npuw::runtime;
+ const auto full_mask_shape = graph_mask->get_shape();
+
+ if (this_case == pyramid_attention::Selector::Case::GENERATE) {
+ const auto dst_shape = dst->get_shape();
+
+ // Optimization: if shapes match, use the full mask directly
+ if (dst_shape == full_mask_shape) {
+ r->set_tensor(mask_iport, graph_mask);
+ m_cached_attention_mask = graph_mask;
+ return;
+ }
+
+ // FIXME: No need to copy whole attention mask, just mark the new tokens to valid
+
+ std::size_t dst_present_offset = dst_shape[kv_dim] - present_len;
+
+ // Copy present mask: tail of source -> tail of destination
+ copy_mask_segment(dst_present_offset, full_mask_shape[kv_dim] - present_len, present_len);
+
+ // Copy past mask: head of source [0, dst_present_offset) -> head of destination
+ copy_mask_segment(0, 0, dst_present_offset);
+
+ m_cached_attention_mask = dst;
+ } else if (this_case == pyramid_attention::Selector::Case::PREFILL) {
+ // Copy present mask: tail of source -> [past_len, past_len + present_len)
+ copy_mask_segment(past_len, full_mask_shape[kv_dim] - present_len, present_len);
+
+ // Copy past mask: head of source -> [0, past_len)
+ copy_mask_segment(0, 0, past_len);
+
+ m_cached_attention_mask = dst;
+ } else {
+ NPUW_ASSERT(false && "Unsupported pyramid attention case");
+ }
+}
+
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);
@@ -762,6 +926,15 @@ void ov::npuw::JustInferRequest::recreate_subrequests(std::size_t idx) {
if (is_piped) {
m_funcall_pipeline[real_idx].subrequest = new_rqs.at(1);
}
+
+ // Recreate pyramid infer requests if this function has pyramid attention
+ if (comp_model_desc.replaced_by) {
+ auto& proto_comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];
+ if (proto_comp_model_desc.pyramid_attention) {
+ setup_pyramid_infer_requests(real_idx, is_piped, true);
+ }
+ }
+
// After an infer request is recreated, the internal cross-request
// connections should be re-established (in/out tensors reset properly)
// Note: these two proceduers do the full I/O reset procedure what's
@@ -771,6 +944,91 @@ void ov::npuw::JustInferRequest::recreate_subrequests(std::size_t idx) {
m_subrequest_devices[idx] = *comp_model_desc.device_it;
}
+void ov::npuw::JustInferRequest::setup_pyramid_infer_requests(std::size_t real_idx, bool is_piped, bool is_recreate) {
+ auto& submodel_desc = m_npuw_model->m_compiled_submodels[real_idx];
+ if (!submodel_desc.pyramid_attention.has_value()) {
+ return;
+ }
+
+ LOG_INFO((is_recreate ? "Recreating" : "Creating") << " pyramid infer requests...");
+ LOG_BLOCK();
+
+ const auto& pyramid_models = submodel_desc.pyramid_attention.value()._compiled_models;
+ const size_t num_pyramid_models = pyramid_models.size();
+
+ // Clear existing requests if recreating
+ if (is_recreate) {
+ submodel_desc.pyramid_infer_requests.clear();
+ submodel_desc.pyramid_pipeline_requests.clear();
+ }
+
+ // Allocate storage for infer requests
+ submodel_desc.pyramid_infer_requests.resize(num_pyramid_models);
+ if (is_piped) {
+ submodel_desc.pyramid_pipeline_requests.resize(num_pyramid_models);
+ }
+
+ // Create infer requests for all but the last pyramid model
+ for (size_t model_idx = 0; model_idx + 1 < num_pyramid_models; ++model_idx) {
+ try {
+ // Create main infer request
+ submodel_desc.pyramid_infer_requests[model_idx] = pyramid_models[model_idx]->create_infer_request();
+ // Create pipeline infer request if pipelined
+ if (is_piped) {
+ submodel_desc.pyramid_pipeline_requests[model_idx] = pyramid_models[model_idx]->create_infer_request();
+ }
+ } catch (const std::exception& ex) {
+ LOG_ERROR("Failed to " << (is_recreate ? "recreate" : "create") << " infer request for pyramid model["
+ << model_idx << "]: " << ex.what());
+ NPUW_ASSERT(false && "Pyramid model infer request creation/recreation failed");
+ } catch (...) {
+ LOG_ERROR("Failed to " << (is_recreate ? "recreate" : "create") << " infer request for pyramid model["
+ << model_idx << "]: Unknown error");
+ NPUW_ASSERT(false && "Pyramid model infer request creation/recreation failed with unknown error");
+ }
+
+ // Share input tensors between pyramid and main infer requests
+ const size_t num_inputs = pyramid_models[model_idx]->inputs().size();
+ NPUW_ASSERT(num_inputs == submodel_desc.compiled_model->inputs().size());
+ for (size_t input_idx = 0; input_idx < num_inputs; ++input_idx) {
+ auto pyramid_input = pyramid_models[model_idx]->inputs()[input_idx];
+ auto main_input = submodel_desc.compiled_model->inputs()[input_idx];
+
+ // Get tensor from main infer request and share its memory with the pyramid infer request
+ auto main_tensor_ptr = m_subrequests[real_idx]->get_tensor(main_input)->data();
+ auto pyramid_tensor = submodel_desc.pyramid_infer_requests[model_idx]->get_tensor(pyramid_input);
+ auto shared_tensor = ov::get_tensor_impl(
+ ov::Tensor(pyramid_tensor->get_element_type(), pyramid_tensor->get_shape(), main_tensor_ptr));
+ submodel_desc.pyramid_infer_requests[model_idx]->set_tensor(pyramid_input, shared_tensor);
+
+ // Repeat for pipeline infer request if pipelined
+ if (is_piped) {
+ auto pipeline_tensor = submodel_desc.pyramid_pipeline_requests[model_idx]->get_tensor(pyramid_input);
+ auto pipeline_tensor_ptr = m_funcall_pipeline[real_idx].subrequest->get_tensor(main_input)->data();
+ auto shared_pipeline_tensor = ov::get_tensor_impl(
+ ov::Tensor(pipeline_tensor->get_element_type(), pipeline_tensor->get_shape(), pipeline_tensor_ptr));
+ submodel_desc.pyramid_pipeline_requests[model_idx]->set_tensor(pyramid_input, shared_pipeline_tensor);
+ }
+ }
+ }
+
+ // For the last pyramid model, reuse the original model's infer requests
+ if (num_pyramid_models > 0) {
+ const size_t last_model_idx = num_pyramid_models - 1;
+ LOG_INFO("Reusing " << (is_recreate ? "recreated " : "") << "original infer requests for last pyramid model["
+ << last_model_idx << "]");
+ submodel_desc.pyramid_infer_requests[last_model_idx] = m_subrequests[real_idx];
+ if (is_piped) {
+ submodel_desc.pyramid_pipeline_requests[last_model_idx] = m_funcall_pipeline[real_idx].subrequest;
+ }
+ }
+
+ if (!is_recreate && num_pyramid_models > 0) {
+ LOG_INFO("Successfully created " << (num_pyramid_models - 1)
+ << " new pyramid infer requests and reused 1 original request");
+ }
+}
+
void ov::npuw::JustInferRequest::run_subrequest_for_success(std::size_t idx, bool& failover) {
failover = false;
auto& comp_model_desc = m_npuw_model->m_compiled_submodels[idx];
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.hpp
index 482793a634a..1e6799e947e 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
@@ -99,6 +99,7 @@ protected:
void function_prologue(std::size_t idx);
void function_prologue_attn(std::size_t real_idx, std::size_t idx);
+ void function_prologue_pyramid_attn(std::size_t real_idx, std::size_t 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);
@@ -108,6 +109,9 @@ protected:
void connect_subrequests();
void recreate_subrequests(std::size_t idx);
+ // Helper function to setup pyramid attention infer requests
+ void setup_pyramid_infer_requests(std::size_t real_idx, bool is_piped, bool is_recreate);
+
FuncMemMgr m_func_mem_mgr; // Owns memory
std::map<LinkFrom, TensorPtr> m_funcall_result; // Provides a convenient link
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
index 10fa1a492cb..f12dacc83de 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
@@ -1515,6 +1515,9 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
const bool prefill_attn_dyn = prefill_attn_hint == ::intel_npu::npuw::llm::AttentionHint::DYNAMIC;
const bool generate_attn_dyn = generate_attn_hint == ::intel_npu::npuw::llm::AttentionHint::DYNAMIC;
+ const bool prefill_attn_pyramid = prefill_attn_hint == ::intel_npu::npuw::llm::AttentionHint::PYRAMID;
+ const bool generate_attn_pyramid = generate_attn_hint == ::intel_npu::npuw::llm::AttentionHint::PYRAMID;
+
const bool optimize_v_tensors = m_cfg.get<::intel_npu::NPUW_LLM_OPTIMIZE_V_TENSORS>();
if (optimize_v_tensors) {
LOG_DEBUG("Check and apply opt layout");
@@ -1582,10 +1585,10 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
{"NPUW_ONLINE_KEEP_BLOCK_SIZE", "4"},
{"NPUW_UNFOLD_IREQS", "NO"},
};
- if (prefill_attn_dyn) {
+ if (prefill_attn_dyn || prefill_attn_pyramid) {
merge_config_with(prefill_config, dyn_attn_opts);
}
- if (generate_attn_dyn) {
+ if (generate_attn_dyn || generate_attn_pyramid) {
merge_config_with(generate_config, dyn_attn_opts);
}
@@ -1628,10 +1631,10 @@ 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>();
- if (generate_attn_dyn) {
+ if (generate_attn_dyn || generate_attn_pyramid) {
rewr.run_on_model(kvcache_model);
}
- if (prefill_attn_dyn) {
+ if (prefill_attn_dyn || prefill_attn_pyramid) {
rewr.run_on_model(prefill_model);
}
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.cpp
index 7c84d0e6e81..ff21829ff55 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
@@ -531,7 +531,8 @@ void Snapshot::earlyRegroup() {
HNDL_FAKE(FakeConvert);
HNDL_FAKE(FakeQuantize);
HNDL_ATTN(SDPA);
-#undef HNDL_SPDA
+ HNDL_ATTN(SDPADecomposed);
+#undef HNDL_ATTN
#undef HNDL_FAKE
#undef HNDL
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp
index d9c8c2688fc..c4ab1321d99 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/online/utils/utils.hpp
@@ -96,7 +96,7 @@ static const std::map<std::string, std::string> ISOL_PRESETS = {{"COMPUTE",
"P:RMSNorm3/compute,P:RMSNorm4/compute,"
"P:VariadicSplit/compute"},
{"FAKE", "P:FakeConvert/fake,P:FakeQuantize/fake"},
- {"ATTN", "P:SDPA/attn"}};
+ {"ATTN", "P:SDPA/attn,P:SDPADecomposed/attn"}};
} // namespace util
} // namespace online
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp
index a144dc8e509..491f1bd477e 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp
@@ -1892,15 +1892,29 @@ void Partitioner::attention(const std::string& func_name) {
return;
}
+ if (!cfg.get<::intel_npu::NPUW_ATTN>()) {
+ LOG_VERB("Dynamic handling is possible for " << func_name << " in model " << model->get_friendly_name()
+ << " but is disabled explicitly");
+ 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");
+ if (f._attention) {
+ LOG_VERB("Done");
return;
}
- LOG_VERB("Done");
+
+ LOG_WARN("No dynamic ranges found in the ATTN block");
+ f._pyramid_attention = ov::npuw::function::PyramidAttention::from(f._model);
+ if (f._pyramid_attention) {
+ LOG_VERB("Done");
+ return;
+ }
+
+ LOG_WARN("No pyramid attention found in the ATTN block");
}
void Partitioner::optimize(const std::string& func_name) {
diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp
index fd782bffe52..33879450a80 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp
@@ -11,6 +11,7 @@
#include "../attention.hpp"
#include "../lazy_tensor.hpp"
+#include "../pyramid_attention.hpp"
#include "../spatial.hpp"
#include "intel_npu/config/config.hpp"
#include "openvino/openvino.hpp"
@@ -86,7 +87,10 @@ struct Function {
std::map<std::pair<std::string, std::size_t>, std::size_t> _param_mapping;
std::optional<ov::npuw::function::Spatial> _spatial;
+ // Single attention graph with dynamic shapes
std::optional<ov::npuw::function::Attention> _attention;
+ // Multiple attention graphs with different shapes
+ std::optional<ov::npuw::function::PyramidAttention> _pyramid_attention;
// FIXME: They should exclude each other (introduce a hierarchy, finally?)
// FIXME: shouldn't be here. Needed to not unpack some lazy closures in DCOFF
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.cpp
index e1ab6c96c74..4cd84bbd2c3 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
@@ -78,6 +78,94 @@ SDPA::SDPA(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const st
register_matcher(std::make_shared<opp::Matcher>(reshape, "TagSDPA"), std::move(callback));
}
+/*
+ Decomposed SDPA Pattern:
+ Convert
+ \ /
+ Concat
+ |
+ Unsqueeze
+ |
+ Broadcast Convert
+ | \ /
+ Reshape Concat
+ \ / |
+ MatMul Unsqueeze
+ \ / |
+ Add Broadcast
+ | |
+ Softmax Reshape
+ \ /
+ MatMul
+ |
+ Transpose
+ |
+ Reshape
+ |
+*/
+
+SDPADecomposed::SDPADecomposed(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot,
+ const std::string& isol_tag) {
+ auto convert1 = opp::wrap_type<ov::op::v0::Convert>({opp::any_input()});
+ auto concat1 = opp::wrap_type<ov::op::v0::Concat>({convert1, opp::any_input()});
+ auto unsqueeze1 = opp::wrap_type<ov::op::v0::Unsqueeze>({concat1, opp::any_input()});
+ auto broadcast1 = opp::wrap_type<ov::op::v3::Broadcast>({unsqueeze1, opp::any_input()});
+ auto reshape1 = opp::wrap_type<ov::op::v1::Reshape>({broadcast1, opp::any_input()});
+
+ auto convert2 = opp::wrap_type<ov::op::v0::Convert>({opp::any_input()});
+ auto concat2 = opp::wrap_type<ov::op::v0::Concat>({convert2, opp::any_input()});
+ auto unsqueeze2 = opp::wrap_type<ov::op::v0::Unsqueeze>({concat2, opp::any_input()});
+ auto broadcast2 = opp::wrap_type<ov::op::v3::Broadcast>({unsqueeze2, opp::any_input()});
+ auto reshape2 = opp::wrap_type<ov::op::v1::Reshape>({broadcast2, opp::any_input()});
+
+ auto matmul1 = opp::wrap_type<ov::op::v0::MatMul>({opp::any_input(), reshape1});
+ auto add = opp::wrap_type<ov::op::v1::Add>({matmul1, opp::any_input()});
+ auto softmax = opp::wrap_type<ov::op::v8::Softmax>({add});
+
+ auto matmul2 = opp::wrap_type<ov::op::v0::MatMul>({softmax, reshape2});
+ auto transpose = opp::wrap_type<ov::op::v1::Transpose>({matmul2, opp::any_input()});
+ auto reshape3 = opp::wrap_type<ov::op::v1::Reshape>({transpose, opp::any_input()});
+
+ auto node_to_gptr = snapshot->getNodeToGroupMap();
+
+ // Note: Use [=] to make sure the above objects stay alive in the callback
+ auto callback = [=](ov::pass::pattern::Matcher& m) {
+ LOG_DEBUG("Decomposed SDPA pattern matched!");
+
+ auto& node_to_output = m.get_pattern_value_map();
+
+ // Helper lambda to extract and isolate matched nodes
+ auto isolate_matched = [&](const auto& pattern) {
+ auto matched_node = node_to_output.at(pattern).get_node_shared_ptr();
+ node_to_gptr->at(matched_node)->isolate(isol_tag);
+ };
+
+ // Isolate all matched nodes in the pattern
+ isolate_matched(convert1);
+ isolate_matched(concat1);
+ isolate_matched(unsqueeze1);
+ isolate_matched(broadcast1);
+ isolate_matched(reshape1);
+
+ isolate_matched(convert2);
+ isolate_matched(concat2);
+ isolate_matched(unsqueeze2);
+ isolate_matched(broadcast2);
+ isolate_matched(reshape2);
+
+ isolate_matched(matmul1);
+ isolate_matched(add);
+ isolate_matched(softmax);
+ isolate_matched(matmul2);
+ isolate_matched(transpose);
+ isolate_matched(reshape3);
+
+ return false; // root hasn't changed
+ };
+
+ register_matcher(std::make_shared<opp::Matcher>(reshape3, "TagSDPADecomposed"), std::move(callback));
+}
+
} // namespace attn
namespace regularize {
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.hpp
index 129abbe9275..23befa4b8d6 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
@@ -28,6 +28,12 @@ public:
SDPA(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);
};
+class SDPADecomposed : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::attn::SDPADecomposed");
+ SDPADecomposed(const std::shared_ptr<ov::npuw::online::Snapshot>& snapshot, const std::string& isol_tag);
+};
+
} // namespace attn
namespace regularize {
diff --git a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp
new file mode 100644
index 00000000000..c238aee7a13
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp
@@ -0,0 +1,706 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#include "pyramid_attention.hpp"
+
+#include <algorithm>
+#include <iostream>
+#include <map>
+#include <memory>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "openvino/op/add.hpp"
+#include "openvino/op/broadcast.hpp"
+#include "openvino/op/matmul.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/softmax.hpp"
+#include "openvino/opsets/opset13.hpp"
+#include "openvino/pass/graph_rewrite.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "openvino/pass/validate.hpp"
+#include "util.hpp"
+
+namespace opp = ov::pass::pattern;
+
+namespace ov {
+namespace npuw {
+namespace function {
+
+// Helper function to find mask parameter by traversing from Add node
+std::shared_ptr<ov::op::v0::Parameter> find_mask_parameter(const std::shared_ptr<ov::Node>& add_node) {
+ if (!add_node || add_node->get_input_size() < 2) {
+ return nullptr;
+ }
+
+ // Traverse the Add node's mask input (input 1) upwards to find the proper Parameter
+ // Only unary ops are allowed along the way
+ auto mask_in_node = add_node->input(1).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 Add to input mask");
+ return nullptr;
+ }
+ mask_in_node = mask_in_node->inputs()[0].get_source_output().get_node_shared_ptr();
+ }
+
+ if (mask_in_node && ov::op::util::is_parameter(mask_in_node)) {
+ return std::static_pointer_cast<ov::op::v0::Parameter>(mask_in_node);
+ }
+
+ return nullptr;
+}
+
+// Helper function to patch broadcast constants (set to 1 for dynamic handling)
+void patch_broadcast_constants(const std::shared_ptr<ov::Model>& model, size_t target_length) {
+ 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) == target_length) {
+ 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);
+ }
+}
+
+// Helper function to patch reshape constants for pre-reshape (-1 substitution)
+void patch_reshape_constants(const std::shared_ptr<ov::Model>& model,
+ const std::map<std::string, size_t>& past_value_sequence_dims) {
+ for (auto&& op : model->get_ordered_ops()) {
+ if (!ov::is_type<ov::op::v1::Reshape>(op)) {
+ continue;
+ }
+
+ // Check if Reshape's single consumer is MatMul
+ auto target_inputs = op->output(0).get_target_inputs();
+ if (target_inputs.size() != 1) {
+ continue; // Reshape should have exactly one consumer
+ }
+
+ auto matmul_node = target_inputs.begin()->get_node()->shared_from_this();
+ if (!ov::is_type<ov::op::v0::MatMul>(matmul_node)) {
+ continue;
+ }
+
+ // Check if MatMul's input 0 is from Softmax
+ auto matmul_input0 = matmul_node->input(0).get_source_output().get_node_shared_ptr();
+ if (!ov::is_type<ov::op::v8::Softmax>(matmul_input0)) {
+ continue;
+ }
+
+ LOG_INFO("Found Reshape -> MatMul pattern where MatMul input 0 is from Softmax, "
+ "patching Reshape constant");
+
+ // Inspect the reshape constant (shape input)
+ 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("Reshape's shape 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>();
+
+ // Find the first past value sequence dimension from the map
+ // All past value parameters should have the same sequence dimension
+ if (past_value_sequence_dims.empty()) {
+ LOG_WARN("No past value sequence dimensions provided for reshape patching");
+ continue;
+ }
+
+ size_t value_seq_dim = past_value_sequence_dims.begin()->second;
+ NPUW_ASSERT(value_seq_dim < shape_values.size());
+ shape_values[value_seq_dim] = -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);
+
+ LOG_INFO("Done");
+ return;
+ }
+}
+
+// Helper function to create Attention instance from a model
+std::optional<ov::npuw::function::Attention> create_attention_from_model(
+ const std::shared_ptr<ov::Model>& model,
+ const std::map<std::string, size_t>& past_key_sequence_dims,
+ const std::map<std::string, size_t>& past_value_sequence_dims) {
+ // Find SDPA pattern nodes in the model
+ auto pattern_nodes = find_sdpa_pattern_nodes(model);
+ if (!pattern_nodes.is_valid()) {
+ LOG_WARN("Could not find SDPA pattern in model");
+ return std::nullopt;
+ }
+
+ // Find mask parameter in the model
+ auto mask_param = find_mask_parameter(pattern_nodes.add_node);
+ if (!mask_param) {
+ LOG_WARN("Could not find mask parameter in model");
+ return std::nullopt;
+ }
+
+ // Create Attention instance
+ ov::npuw::function::Attention attention;
+ attention._mask = mask_param;
+ attention._mask_shape = mask_param->get_shape();
+
+ // Add past key/value inputs to attention
+ const auto& params = model->get_parameters();
+ for (const auto& param : params) {
+ const std::string param_name = param->get_friendly_name();
+ if (ov::npuw::util::isPastKeyValuesKey(param_name)) {
+ auto dim_iter = past_key_sequence_dims.find(param_name);
+ if (dim_iter != past_key_sequence_dims.end()) {
+ attention._inputs.push_back(ov::npuw::function::Attention::Param{param, dim_iter->second});
+ }
+ } else if (ov::npuw::util::isPastKeyValuesValue(param_name)) {
+ auto dim_iter = past_value_sequence_dims.find(param_name);
+ if (dim_iter != past_value_sequence_dims.end()) {
+ attention._inputs.push_back(ov::npuw::function::Attention::Param{param, dim_iter->second});
+ }
+ }
+ }
+
+ return attention;
+}
+
+// Helper function to process a single pyramid model (clone, reshape, patch, optimize)
+std::optional<PyramidModelResult> process_pyramid_model(const std::shared_ptr<ov::Model>& original_model,
+ size_t model_idx,
+ size_t pyramid_step,
+ size_t query_length,
+ size_t full_past_kv_length,
+ size_t full_context_length,
+ const std::map<std::string, size_t>& past_key_sequence_dims,
+ const std::map<std::string, size_t>& past_value_sequence_dims) {
+ // Clone the original model for modification
+ auto cloned_model = original_model->clone();
+
+ // Calculate dimensions for this model
+ size_t current_context_length = 0u;
+ size_t current_past_length = 0u;
+
+ // FIXME: SPECULATIVE CASE!!!
+ if (query_length == 1u) {
+ // GENERATE
+ auto output_len = full_context_length - query_length - full_past_kv_length;
+ current_context_length = (model_idx + 1) * pyramid_step + output_len;
+ current_past_length = current_context_length - query_length;
+ } else {
+ // PREFILL
+ current_context_length = (model_idx + 1) * pyramid_step;
+ current_past_length = current_context_length - query_length;
+ }
+ // FIXME: Probably the generic formula for all cases is:
+ // current_context_length = (model_idx + 1) * pyramid_step;
+ // current_past = current_context_length - query_length
+ // - should work for the speculative case as well
+ LOG_DEBUG("Model " << model_idx << ":");
+ LOG_DEBUG(" Context length: " << current_context_length);
+ LOG_DEBUG(" Past length: " << current_past_length);
+
+ // Create initial Attention instance to get mask parameter for reshaping
+ auto initial_attention =
+ create_attention_from_model(cloned_model, past_key_sequence_dims, past_value_sequence_dims);
+ if (!initial_attention) {
+ LOG_WARN("Could not create attention from cloned model " << model_idx);
+ return std::nullopt;
+ }
+
+ auto cloned_mask_param = initial_attention->_mask;
+
+ // Create reshape map for this model
+ std::map<ov::Output<ov::Node>, ov::PartialShape> new_shapes;
+
+ // Update parameters shapes
+ const auto& params = cloned_model->get_parameters();
+ for (auto&& param : params) {
+ const std::string param_name = param->get_friendly_name();
+ auto original_shape = param->get_shape();
+ ov::PartialShape new_shape = original_shape;
+
+ if (param == cloned_mask_param) {
+ // Handle attention mask parameter - use the mask parameter found in cloned model
+ // Update the last dimension to current context length
+ if (new_shape.size() >= 1) {
+ new_shape[new_shape.size() - 1] = current_context_length;
+ new_shapes[param->output(0)] = new_shape;
+ LOG_DEBUG(" Mask param '" << param_name << "' shape: " << original_shape << " -> " << new_shape);
+ }
+ } else if (ov::npuw::util::isPastKeyValuesKey(param_name)) {
+ // Handle past key parameters
+ // Use pre-analyzed sequence dimension information
+ auto dim_iter = past_key_sequence_dims.find(param_name);
+ if (dim_iter != past_key_sequence_dims.end()) {
+ size_t sequence_dim_idx = dim_iter->second;
+ new_shape[sequence_dim_idx] = current_past_length;
+ new_shapes[param->output(0)] = new_shape;
+ LOG_DEBUG(" Past key param '" << param_name << "' shape: " << original_shape << " -> " << new_shape);
+
+ // Record past key input (will be handled later)
+ } else {
+ LOG_WARN("No pre-analyzed sequence dimension for past key param: " << param_name);
+ return std::nullopt;
+ }
+ } else if (ov::npuw::util::isPastKeyValuesValue(param_name)) {
+ // Handle past value parameters
+ // Use pre-analyzed sequence dimension information
+ auto dim_iter = past_value_sequence_dims.find(param_name);
+ if (dim_iter != past_value_sequence_dims.end()) {
+ size_t sequence_dim_idx = dim_iter->second;
+ new_shape[sequence_dim_idx] = current_past_length;
+ new_shapes[param->output(0)] = new_shape;
+ LOG_DEBUG(" Past value param '" << param_name << "' shape: " << original_shape << " -> " << new_shape);
+
+ // Record past value input (will be handled later)
+ } else {
+ LOG_WARN("No pre-analyzed sequence dimension for past value param: " << param_name);
+ return std::nullopt;
+ }
+ }
+ }
+
+ // Apply the reshaping to the cloned model
+ if (new_shapes.empty()) {
+ LOG_WARN("No parameters found for reshaping in model " << model_idx << ", skipping this model");
+ return std::nullopt;
+ }
+
+ // Apply pre-reshape patching using helper functions
+ patch_broadcast_constants(cloned_model, full_context_length);
+ patch_reshape_constants(cloned_model, past_value_sequence_dims);
+
+ cloned_model->reshape(new_shapes);
+ cloned_model->validate_nodes_and_infer_types();
+
+ LOG_DEBUG("Model " << model_idx << " reshaped successfully");
+
+ // Create final Attention instance after reshape
+ auto final_attention = create_attention_from_model(cloned_model, past_key_sequence_dims, past_value_sequence_dims);
+ if (!final_attention) {
+ LOG_WARN("Could not create final attention after reshape for model " << model_idx);
+ return std::nullopt;
+ }
+
+ LOG_DEBUG(" Updated attention after reshape");
+
+ // Log attention information for this model
+ LOG_DEBUG(" Attention info - mask: " << (final_attention->_mask ? "present" : "absent"));
+ LOG_DEBUG(" Attention info - inputs count: " << final_attention->_inputs.size());
+ if (final_attention->_mask) {
+ LOG_DEBUG(" Mask shape: " << final_attention->_mask_shape);
+ }
+
+ return PyramidModelResult{cloned_model, std::move(*final_attention)};
+}
+
+// Helper function to validate model and extract necessary information for pyramid attention
+std::optional<PyramidValidationResult> validate_and_setup_pyramid_attention(const std::shared_ptr<ov::Model>& model) {
+ // Find SDPA pattern nodes using the extracted function
+ auto pattern_nodes = find_sdpa_pattern_nodes(model);
+ if (!pattern_nodes.is_valid()) {
+ LOG_WARN("Could not find valid SDPA pattern in model");
+ return std::nullopt;
+ }
+
+ LOG_INFO("Found SDPA pattern: MatMul -> Add -> Softmax -> MatMul");
+
+ // Extract query_length and full_context_length from Softmax output shape
+ auto softmax_output_shape = pattern_nodes.softmax_node->get_output_shape(0);
+ size_t query_length = 0;
+ size_t past_kv_length = 0;
+ size_t full_context_length = 0;
+
+ if (softmax_output_shape.size() >= 2) {
+ full_context_length = softmax_output_shape.back(); // Last dimension
+ query_length = softmax_output_shape[softmax_output_shape.size() - 2]; // Second-to-last dimension
+
+ LOG_DEBUG("Extracted from Softmax output shape:");
+ LOG_DEBUG(" Query length: " << query_length);
+ LOG_DEBUG(" Full context length: " << full_context_length);
+ } else {
+ LOG_WARN("Softmax output shape has insufficient dimensions: " << softmax_output_shape.size());
+ return std::nullopt;
+ }
+
+ // Early return for invalid parameters
+ if (query_length == 0 || full_context_length == 0 || full_context_length < query_length) {
+ LOG_WARN("Invalid query_length (" << query_length << ") or full_context_length (" << full_context_length
+ << ") for pyramid attention");
+ return std::nullopt;
+ }
+
+ // Pre-analyze original model to find sequence dimensions for past key/value parameters
+ // This avoids repeated analysis in each cloned model
+ std::map<std::string, size_t> past_key_sequence_dims;
+ std::map<std::string, size_t> past_value_sequence_dims;
+
+ // Helper function to find sequence dimension in parameter shape
+ auto find_context_dim = [](const std::shared_ptr<ov::op::v0::Parameter>& param,
+ size_t target_length) -> std::optional<size_t> {
+ const auto& param_shape = param->get_shape();
+ auto dim_iter = std::find(param_shape.begin(), param_shape.end(), target_length);
+ if (dim_iter == param_shape.end()) {
+ return std::nullopt; // No such dim found
+ }
+ if (std::find(dim_iter + 1, param_shape.end(), target_length) != param_shape.end()) {
+ return std::nullopt; // There must be no other such dim
+ }
+ return std::distance(param_shape.begin(), dim_iter);
+ };
+
+ // Analyze original model parameters to find sequence dimensions
+ const auto& original_params = model->get_parameters();
+ for (const auto& param : original_params) {
+ const std::string param_name = param->get_friendly_name();
+
+ if (ov::npuw::util::isPastKeyValuesKey(param_name)) {
+ auto sequence_dim_opt = find_context_dim(param, full_context_length - query_length);
+ if (sequence_dim_opt) {
+ past_key_sequence_dims[param_name] = *sequence_dim_opt;
+ LOG_DEBUG("Found past key sequence dimension for '" << param_name << "': " << *sequence_dim_opt);
+
+ auto curr_past_kv_length = param->get_shape()[*sequence_dim_opt];
+ if (past_kv_length && past_kv_length != curr_past_kv_length) {
+ LOG_WARN("Inconsistent past KV lengths found among parameters");
+ return std::nullopt;
+ } else {
+ past_kv_length = curr_past_kv_length;
+ }
+ } else {
+ LOG_WARN("Could not find sequence dimension for past key param: " << param_name);
+ return std::nullopt;
+ }
+ } else if (ov::npuw::util::isPastKeyValuesValue(param_name)) {
+ auto sequence_dim_opt = find_context_dim(param, full_context_length - query_length);
+ if (sequence_dim_opt) {
+ past_value_sequence_dims[param_name] = *sequence_dim_opt;
+ LOG_DEBUG("Found past value sequence dimension for '" << param_name << "': " << *sequence_dim_opt);
+
+ auto curr_past_kv_length = param->get_shape()[*sequence_dim_opt];
+ if (past_kv_length && past_kv_length != curr_past_kv_length) {
+ LOG_WARN("Inconsistent past KV lengths found among parameters");
+ return std::nullopt;
+ } else {
+ past_kv_length = curr_past_kv_length;
+ }
+ } else {
+ LOG_WARN("Could not find sequence dimension for past value param: " << param_name);
+ return std::nullopt;
+ }
+ }
+ }
+
+ return PyramidValidationResult{query_length,
+ past_kv_length,
+ full_context_length,
+ past_key_sequence_dims,
+ past_value_sequence_dims};
+}
+
+SDPAPatternNodes find_sdpa_pattern_nodes(const std::shared_ptr<ov::Model>& model) {
+ // Find decomposed SDPA pattern components
+ SDPAPatternNodes pattern_nodes;
+
+ // Find past key and value parameter nodes
+ for (auto input : model->inputs()) {
+ auto input_node = input.get_node();
+ auto input_name = input_node->get_friendly_name();
+ if (ov::npuw::util::isPastKeyValuesKey(input_name)) {
+ pattern_nodes.past_key_param_node = input_node->shared_from_this();
+ } else if (ov::npuw::util::isPastKeyValuesValue(input_name)) {
+ pattern_nodes.past_value_param_node = input_node->shared_from_this();
+ }
+ }
+
+ // Search for the pattern: MatMul -> Add -> Softmax -> MatMul
+ auto ops = model->get_ordered_ops();
+ for (auto&& node : ops) {
+ if (ov::is_type<ov::op::v8::Softmax>(node)) {
+ pattern_nodes.softmax_node = node;
+
+ // Check if softmax is fed by Add
+ auto softmax_input = node->input(0).get_source_output().get_node_shared_ptr();
+ if (ov::is_type<ov::op::v1::Add>(softmax_input)) {
+ pattern_nodes.add_node = softmax_input;
+
+ // Check if add is fed by MatMul (first MatMul)
+ auto add_input0 = pattern_nodes.add_node->input(0).get_source_output().get_node_shared_ptr();
+ if (ov::is_type<ov::op::v0::MatMul>(add_input0)) {
+ pattern_nodes.matmul1_node = add_input0;
+ }
+ }
+
+ // Check if softmax feeds into MatMul (second MatMul)
+ for (auto&& output : node->outputs()) {
+ for (auto&& target_input : output.get_target_inputs()) {
+ auto target_node = target_input.get_node()->shared_from_this();
+ if (ov::is_type<ov::op::v0::MatMul>(target_node)) {
+ pattern_nodes.matmul2_node = target_node;
+ break;
+ }
+ }
+ if (pattern_nodes.matmul2_node)
+ break;
+ }
+
+ if (pattern_nodes.is_valid()) {
+ pattern_nodes.log_pattern();
+ break; // Found complete pattern
+ }
+ }
+ }
+
+ return pattern_nodes;
+}
+
+std::optional<PyramidAttention> PyramidAttention::from(const std::shared_ptr<ov::Model>& model) {
+ // Validate and setup pyramid attention
+ auto validation_result = validate_and_setup_pyramid_attention(model);
+ if (!validation_result) {
+ return std::nullopt;
+ }
+
+ size_t query_length = validation_result->query_length;
+ size_t full_past_kv_length = validation_result->past_kv_length;
+ size_t full_context_length = validation_result->full_context_length;
+ const auto& past_key_sequence_dims = validation_result->past_key_sequence_dims;
+ const auto& past_value_sequence_dims = validation_result->past_value_sequence_dims;
+
+ std::vector<std::shared_ptr<ov::Model>> pyramid_models;
+
+ // Use step 1024 to generate attention pyramid if it is the GENERATE case.
+ // FIXME: Make it configurable
+ // FIXME: Handle the speculative case here (query_length > 1; << 1024)
+ bool is_generate = query_length == 1;
+ size_t pyramid_step = is_generate ? 1024u : query_length;
+ // FIXME: Check all the right alignments
+ size_t num_models = full_context_length / pyramid_step;
+ LOG_INFO("Creating " << num_models << " pyramid attention models");
+
+ // Store Attention instances for each model
+ std::vector<Attention> pyramid_attentions;
+
+ for (size_t model_idx = 0; model_idx < num_models; ++model_idx) {
+ // Optimization: The last model (num_models - 1) is the same as the original model
+ // Skip reshape and directly use the original model pointer
+ if (model_idx == num_models - 1) {
+ LOG_INFO("Using original model for pyramid model[" << model_idx << "] (optimization)");
+ pyramid_models.push_back(model); // Direct use of original model pointer
+
+ // Create Attention instance using the helper function
+ auto last_attention = create_attention_from_model(model, past_key_sequence_dims, past_value_sequence_dims);
+ if (!last_attention) {
+ LOG_WARN("Could not create attention for original model");
+ return std::nullopt;
+ }
+
+ pyramid_attentions.push_back(std::move(*last_attention));
+ LOG_INFO("Successfully setup attention for original model[" << model_idx << "]");
+ } else {
+ // Process pyramid models 0 to num_models-2 using the helper function
+ auto result = process_pyramid_model(model,
+ model_idx,
+ pyramid_step,
+ query_length,
+ full_past_kv_length,
+ full_context_length,
+ past_key_sequence_dims,
+ past_value_sequence_dims);
+ if (!result) {
+ return std::nullopt;
+ }
+
+ pyramid_models.push_back(result->model);
+ pyramid_attentions.push_back(std::move(result->attention));
+ }
+ }
+
+ LOG_INFO("Successfully created " << pyramid_models.size() << " pyramid attention models");
+
+ // Create PyramidAttention instance and set the extracted values
+ PyramidAttention pyramid_attention;
+ pyramid_attention._query_length = query_length;
+ pyramid_attention._full_context_length = full_context_length;
+ pyramid_attention._models = pyramid_models;
+ pyramid_attention._attentions = pyramid_attentions;
+
+ // Early return with pyramid attention result
+ LOG_INFO("Returning pyramid attention with " << pyramid_models.size() << " models");
+ LOG_INFO(" Query length: " << pyramid_attention._query_length);
+ LOG_INFO(" Full context length: " << pyramid_attention._full_context_length);
+ LOG_INFO(" Attention instances: " << pyramid_attention._attentions.size());
+ return pyramid_attention;
+}
+
+} // namespace function
+
+namespace compiled {
+
+// Constructor implementation - extracts metadata and stores models for compilation
+PyramidAttention::PyramidAttention(const function::PyramidAttention& func_pyramid)
+ : query_size(func_pyramid._query_length),
+ full_context_size(func_pyramid._full_context_length),
+ _models_to_compile(func_pyramid._models) { // Store models for later compilation
+ NPUW_ASSERT(func_pyramid._models.size() == func_pyramid._attentions.size());
+
+ const size_t num_models = func_pyramid._models.size();
+ _attention_infos.reserve(num_models);
+ _context_lengths.reserve(num_models);
+
+ LOG_INFO("Constructing compiled::PyramidAttention with " << num_models << " models");
+
+ // Extract metadata from each model
+ for (size_t i = 0; i < num_models; ++i) {
+ const auto& func_attn = func_pyramid._attentions[i];
+ const auto& model = func_pyramid._models[i];
+
+ // Build attention info
+ PyramidAttentionInfo attention_info;
+ attention_info.params.reserve(func_attn._inputs.size());
+
+ for (const auto& input : func_attn._inputs) {
+ std::size_t p_idx = model->get_parameter_index(input.param);
+ attention_info.params.push_back({p_idx, input.dim});
+ }
+
+ attention_info.mask_idx = model->get_parameter_index(func_attn._mask);
+ attention_info.query_size = func_attn.query_len();
+ attention_info.context_length = func_attn.context_len();
+
+ _attention_infos.push_back(std::move(attention_info));
+ _context_lengths.push_back(attention_info.context_length);
+ }
+
+ LOG_INFO("compiled::PyramidAttention metadata extracted, models stored for compilation");
+}
+
+// Set compiled models after parallel compilation and clear temporary storage
+void PyramidAttention::set_compiled_models(std::vector<ov::SoPtr<ov::ICompiledModel>>&& compiled_models) {
+ NPUW_ASSERT(compiled_models.size() == _attention_infos.size() && "Compiled models count must match metadata count");
+ _compiled_models = std::move(compiled_models);
+
+ // Clear temporary models storage
+ _models_to_compile.clear();
+ _models_to_compile.shrink_to_fit();
+
+ LOG_INFO("compiled::PyramidAttention compiled models set successfully (" << _compiled_models.size() << " models)");
+}
+
+} // namespace compiled
+
+namespace runtime {
+namespace pyramid_attention {
+
+// Pyramid Attention PositionIDs implementation
+PositionIDs::PositionIDs(std::size_t param_idx, const compiled::PyramidAttention& d, const ov::ISyncInferRequest& rq)
+ : m_position_ids_idx(param_idx),
+ m_query_size(d.query_size),
+ m_pyramid_attention(&d),
+ m_rq(rq) {
+ // FIXME: speculative decode is indistinguishable at this point!
+ m_case = m_query_size == 1 ? Case::GENERATE : Case::PREFILL;
+}
+
+Selector::Ptr PositionIDs::find(const compiled::PyramidAttention& 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 PositionIDs::prepare(int64_t past_len) {
+ 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();
+
+ // Same logic as regular attention PositionIDs
+ 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 = ((past_len + m_query_size - 1) / m_query_size) * m_query_size;
+ break;
+ default:
+ NPUW_ASSERT(false && "Reached the unreachable code");
+ }
+
+ // Select the optimal pyramid model based on current sequence length
+ NPUW_ASSERT(m_pyramid_attention && "PyramidAttention reference must not be null");
+
+ const auto& context_lengths = m_pyramid_attention->_context_lengths;
+ const int64_t current_seq_length = m_query_size + m_past_length;
+
+ // Find the smallest pyramid model that can handle the current sequence length
+ for (std::size_t i = 0; i < context_lengths.size(); ++i) {
+ if (current_seq_length <= static_cast<int64_t>(context_lengths[i])) {
+ m_pyramid_id = i;
+ return;
+ }
+ }
+
+ // If sequence length exceeds all models' capacity, use the largest model
+ m_pyramid_id = context_lengths.size() - 1;
+ return;
+ }
+ }
+ LOG_WARN("Dynamic selector - no data found in the feature?");
+ m_current_length = -1;
+
+ NPUW_ASSERT(m_pyramid_attention && "PyramidAttention reference must not be null");
+ // Default to largest model if no data found (safest choice for unknown sequence length)
+ m_pyramid_id = m_pyramid_attention->_context_lengths.size() - 1;
+}
+
+int64_t PositionIDs::length() const {
+ return m_current_length;
+}
+
+int64_t PositionIDs::past_length() const {
+ return m_past_length;
+}
+
+} // namespace pyramid_attention
+} // namespace runtime
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.hpp b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.hpp
new file mode 100644
index 00000000000..bf6866ee30b
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.hpp
@@ -0,0 +1,237 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#pragma once
+
+#include <iostream>
+#include <map>
+#include <memory>
+#include <optional>
+#include <string>
+#include <vector>
+
+#include "attention.hpp"
+
+namespace ov {
+namespace npuw {
+
+namespace function {
+
+// Helper struct to hold validation and setup results
+struct PyramidValidationResult {
+ size_t query_length = 0;
+ size_t past_kv_length = 0;
+ size_t full_context_length = 0;
+ std::map<std::string, size_t> past_key_sequence_dims;
+ std::map<std::string, size_t> past_value_sequence_dims;
+
+ // Validation helper
+ bool is_valid() const {
+ return query_length > 0 && full_context_length > 0 && full_context_length >= query_length &&
+ !past_key_sequence_dims.empty() && !past_value_sequence_dims.empty();
+ }
+};
+
+// Helper struct to hold model processing result
+struct PyramidModelResult {
+ std::shared_ptr<ov::Model> model;
+ ov::npuw::function::Attention attention;
+
+ bool is_valid() const {
+ return model != nullptr;
+ }
+};
+
+// Helper function to create Attention instance from a model
+std::optional<ov::npuw::function::Attention> create_attention_from_model(
+ const std::shared_ptr<ov::Model>& model,
+ const std::map<std::string, size_t>& past_key_sequence_dims,
+ const std::map<std::string, size_t>& past_value_sequence_dims);
+
+// Helper function to process a single pyramid model (clone, reshape, patch, optimize)
+std::optional<PyramidModelResult> process_pyramid_model(const std::shared_ptr<ov::Model>& original_model,
+ size_t model_idx,
+ size_t pyramid_step,
+ size_t query_length,
+ size_t full_past_kv_length,
+ size_t full_context_length,
+ const std::map<std::string, size_t>& past_key_sequence_dims,
+ const std::map<std::string, size_t>& past_value_sequence_dims);
+
+// Helper function to validate model and extract necessary information for pyramid attention
+std::optional<PyramidValidationResult> validate_and_setup_pyramid_attention(const std::shared_ptr<ov::Model>& model);
+
+// Structure to hold SDPA pattern nodes
+struct SDPAPatternNodes {
+ std::shared_ptr<ov::Node> matmul1_node = nullptr;
+ std::shared_ptr<ov::Node> matmul2_node = nullptr;
+ std::shared_ptr<ov::Node> softmax_node = nullptr;
+ std::shared_ptr<ov::Node> add_node = nullptr;
+ std::shared_ptr<ov::Node> past_key_param_node = nullptr;
+ std::shared_ptr<ov::Node> past_value_param_node = nullptr;
+
+ bool is_valid() const {
+ return matmul1_node && matmul2_node && softmax_node && add_node && past_key_param_node && past_value_param_node;
+ }
+
+ // Log pattern information for debugging
+ void log_pattern() const {
+ LOG_DEBUG("SDPA Pattern nodes:");
+ LOG_DEBUG(" MatMul1: " << (matmul1_node ? matmul1_node->get_friendly_name() : "null"));
+ LOG_DEBUG(" Add: " << (add_node ? add_node->get_friendly_name() : "null"));
+ LOG_DEBUG(" Softmax: " << (softmax_node ? softmax_node->get_friendly_name() : "null"));
+ LOG_DEBUG(" MatMul2: " << (matmul2_node ? matmul2_node->get_friendly_name() : "null"));
+ }
+};
+
+// Function to find SDPA pattern nodes in the model
+SDPAPatternNodes find_sdpa_pattern_nodes(const std::shared_ptr<ov::Model>& model);
+
+// Function to find mask parameter by traversing from Add node
+std::shared_ptr<ov::op::v0::Parameter> find_mask_parameter(const std::shared_ptr<ov::Node>& add_node);
+
+// PyramidAttention structure definition
+struct PyramidAttention {
+ std::vector<Attention> _attentions;
+ std::vector<std::shared_ptr<ov::Model>> _models;
+ size_t _query_length = 0;
+ size_t _full_context_length = 0;
+
+ // Validation helpers
+ bool is_valid() const {
+ return !_models.empty() && _models.size() == _attentions.size() && _query_length > 0 &&
+ _full_context_length > 0;
+ }
+
+ size_t num_models() const {
+ return _models.size();
+ }
+
+ // Factory method
+ static std::optional<PyramidAttention> from(const std::shared_ptr<ov::Model>& model);
+};
+
+} // namespace function
+
+namespace compiled {
+
+// Simplified pyramid attention parameter info
+struct PyramidAttentionInfo {
+ 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;
+ std::size_t query_size = 0u; // Added for PositionIDs selector compatibility
+ std::size_t context_length = 0u; // Context length this pyramid model supports
+};
+
+// Compile-time pyramid attention information
+struct PyramidAttention {
+ std::vector<PyramidAttentionInfo> _attention_infos;
+ std::vector<ov::SoPtr<ov::ICompiledModel>> _compiled_models;
+ std::vector<std::size_t> _context_lengths;
+
+ std::size_t query_size = 0u;
+ std::size_t full_context_size = 0u;
+
+ // Store models temporarily for compilation - cleared after compilation completes in set_compiled_models()
+ std::vector<std::shared_ptr<ov::Model>> _models_to_compile;
+
+ PyramidAttention() = default;
+
+ // Constructor that extracts metadata and stores models for compilation
+ // Compiled models are set later via set_compiled_models()
+ explicit PyramidAttention(const function::PyramidAttention& func_pyramid);
+
+ // Set compiled models after parallel compilation completes
+ // Also clears _models_to_compile to free memory
+ void set_compiled_models(std::vector<ov::SoPtr<ov::ICompiledModel>>&& compiled_models);
+
+ // Return number of pyramid models
+ size_t num_models() const {
+ return _attention_infos.size();
+ }
+
+ // Get context length for a specific model
+ std::size_t get_context_length(size_t model_idx) const {
+ return model_idx < _context_lengths.size() ? _context_lengths[model_idx] : 0;
+ }
+};
+
+} // namespace compiled
+
+namespace runtime {
+namespace pyramid_attention {
+
+// A base class to decide pyramid model selection
+class Selector {
+public:
+ enum class Case { PREFILL, GENERATE, UNKNOWN };
+
+ using Ptr = std::shared_ptr<Selector>;
+ virtual ~Selector() = default;
+ virtual void prepare(int64_t past_len) = 0;
+ virtual int64_t length() const = 0;
+ virtual int64_t past_length() const = 0;
+
+ // Getter for the selected pyramid model ID (updated by prepare())
+ std::size_t pyramid_id() const {
+ return m_pyramid_id;
+ }
+
+ Case this_case() const {
+ return m_case;
+ }
+
+protected:
+ Case m_case = Case::UNKNOWN;
+ std::size_t m_pyramid_id = 0; // Selected pyramid model ID, updated by prepare()
+};
+
+// No dynamic dispatch - just use the largest pyramid model
+class All final : public Selector {
+ std::size_t m_pyramid_count = 0;
+
+public:
+ explicit All(std::size_t pyramid_count) : m_pyramid_count(pyramid_count) {}
+
+ void prepare(int64_t past_len) override {
+ // Always use the largest pyramid model (last one)
+ m_pyramid_id = m_pyramid_count > 0 ? m_pyramid_count - 1 : 0;
+ }
+ int64_t length() const override {
+ return -1;
+ }
+ int64_t past_length() const override {
+ OPENVINO_NOT_IMPLEMENTED;
+ }
+};
+
+// Define pyramid model selection 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;
+ std::size_t m_query_size = 0u;
+
+ // Store pyramid attention reference for pyramid model selection
+ const compiled::PyramidAttention* m_pyramid_attention = nullptr;
+
+ const ov::ISyncInferRequest& m_rq;
+
+ PositionIDs(std::size_t param_idx, const compiled::PyramidAttention& d, const ov::ISyncInferRequest& rq);
+ void prepare(int64_t past_len) override;
+ int64_t length() const override;
+ int64_t past_length() const override;
+
+public:
+ static Selector::Ptr find(const compiled::PyramidAttention& d, const ov::ISyncInferRequest& rq);
+};
+
+} // namespace pyramid_attention
+} // namespace runtime
+
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
index 7322ed67b3c..df81b75d608 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
@@ -15,6 +15,7 @@
#include "openvino/reference/convert.hpp"
#include "openvino/runtime/shared_buffer.hpp"
#include "openvino/util/mmap_object.hpp"
+#include "pyramid_attention.hpp"
#include "spatial.hpp"
#include "util.hpp"
@@ -105,6 +106,27 @@ void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::Atten
write(stream, var.attend_all);
}
+void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::PyramidAttention& var) {
+ using ov::npuw::s11n::write;
+
+ write(stream, var.query_size);
+ write(stream, var.full_context_size);
+ write(stream, var._context_lengths);
+
+ // Serialize attention infos
+ write(stream, var._attention_infos.size());
+ for (const auto& info : var._attention_infos) {
+ write(stream, info.params.size());
+ for (const auto& p : info.params) {
+ write(stream, p.idx);
+ write(stream, p.dim);
+ }
+ write(stream, info.mask_idx);
+ write(stream, info.query_size);
+ write(stream, info.context_length);
+ }
+}
+
void ov::npuw::s11n::write(std::ostream& stream, const ov::Tensor& var) {
using ov::npuw::s11n::write;
@@ -227,6 +249,32 @@ void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::Attention& v
read(stream, var.attend_all);
}
+void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::PyramidAttention& var) {
+ using ov::npuw::s11n::read;
+
+ read(stream, var.query_size);
+ read(stream, var.full_context_size);
+ read(stream, var._context_lengths);
+
+ // Deserialize attention infos
+ std::size_t attention_infos_size = 0;
+ read(stream, attention_infos_size);
+ var._attention_infos.resize(attention_infos_size);
+
+ for (auto& info : var._attention_infos) {
+ std::size_t params_size = 0;
+ read(stream, params_size);
+ info.params.resize(params_size);
+ for (auto& p : info.params) {
+ read(stream, p.idx);
+ read(stream, p.dim);
+ }
+ read(stream, info.mask_idx);
+ read(stream, info.query_size);
+ read(stream, info.context_length);
+ }
+}
+
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.hpp
index 64f08aa7c17..81cba881004 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
@@ -34,7 +34,7 @@ const constexpr ov::npuw::s11n::IndicatorType NPUW_COMPILED_MODEL_INDICATOR =
const constexpr ov::npuw::s11n::IndicatorType NPUW_LLM_COMPILED_MODEL_INDICATOR =
{char{0x4c}, char{0x4c}, char{0x4d}, char{0x43}, char{0x4d}, char{0x4f}};
-const constexpr char* NPUW_SERIALIZATION_VERSION = "0.13";
+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.14";
// Forward declaration
namespace intel_npu {
@@ -47,10 +47,14 @@ namespace ov {
class Any;
class Node;
class Tensor;
+class IPlugin;
+class ICompiledModel;
template <class>
class Output;
template <class>
class SharedBuffer;
+template <class>
+struct SoPtr;
class MappedMemory;
class Model;
enum class CacheMode;
@@ -74,6 +78,7 @@ namespace npuw {
namespace compiled {
struct Spatial;
struct Attention;
+struct PyramidAttention;
} // namespace compiled
namespace weights {
class LazyTensor;
@@ -143,6 +148,19 @@ struct WeightsContext {
BF16Cache bf16_consts;
};
+struct PyramidCtx {
+ PyramidCtx(const std::shared_ptr<const ov::IPlugin>& _plugin,
+ const std::string& _device,
+ const ov::SoPtr<ov::ICompiledModel>& _compiled_model)
+ : plugin(_plugin),
+ device(_device),
+ compiled_model(_compiled_model) {}
+
+ std::shared_ptr<const ov::IPlugin> plugin;
+ std::string device;
+ const ov::SoPtr<ov::ICompiledModel>& compiled_model;
+};
+
BF16Cache get_bf16_consts(const std::shared_ptr<ov::Model>& model);
// Specific type overloads
@@ -152,6 +170,7 @@ 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::npuw::compiled::PyramidAttention& 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);
@@ -168,6 +187,7 @@ 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::npuw::compiled::PyramidAttention& 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/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cpp
index 917c829c9f1..80eb0aeeb59 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp
@@ -951,5 +951,16 @@ bool ov::npuw::util::matchLoRAMatMulAlphaString(const std::string& input) {
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);
+ const size_t byte_size = tensor->get_byte_size();
+ std::memset(tensor_data, fill_val, byte_size);
+}
+
+bool ov::npuw::util::isPastKeyValuesKey(const std::string& str) {
+ std::regex pattern(R"(past_key_values\.\d+\.key)");
+ return std::regex_match(str, pattern);
+}
+
+bool ov::npuw::util::isPastKeyValuesValue(const std::string& str) {
+ std::regex pattern(R"(past_key_values\.\d+\.value)");
+ return std::regex_match(str, pattern);
}
diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.hpp b/src/plugins/intel_npu/src/plugin/npuw/util.hpp
index dac90f0aa20..d1f771cab4b 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/util.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/util.hpp
@@ -243,6 +243,10 @@ private:
mutable bool done = false;
};
+bool isPastKeyValuesKey(const std::string& str);
+
+bool isPastKeyValuesValue(const std::string& str);
+
} // namespace util
} // namespace npuw
} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
index b983a7b32ae..8ddc8901dea 100644
--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp
@@ -352,6 +352,7 @@ void Plugin::init_options() {
REGISTER_OPTION(NPUW_ONLINE_MIN_SIZE);
REGISTER_OPTION(NPUW_ONLINE_KEEP_BLOCKS);
REGISTER_OPTION(NPUW_ONLINE_KEEP_BLOCK_SIZE);
+ REGISTER_OPTION(NPUW_ATTN);
REGISTER_OPTION(NPUW_FOLD);
REGISTER_OPTION(NPUW_CWAI);
REGISTER_OPTION(NPUW_DQ);
diff --git a/src/plugins/intel_npu/src/plugin/src/properties.cpp b/src/plugins/intel_npu/src/plugin/src/properties.cpp
index fe0cbc43608..e17efcf920d 100644
--- a/src/plugins/intel_npu/src/plugin/src/properties.cpp
+++ b/src/plugins/intel_npu/src/plugin/src/properties.cpp
@@ -437,6 +437,7 @@ void Properties::registerPluginProperties() {
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::partitioning::online::keep_blocks, NPUW_ONLINE_KEEP_BLOCKS);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::partitioning::online::keep_block_size,
NPUW_ONLINE_KEEP_BLOCK_SIZE);
+ TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::partitioning::attn, NPUW_ATTN);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::partitioning::fold, NPUW_FOLD);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::partitioning::cwai, NPUW_CWAI);
TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::partitioning::dyn_quant, NPUW_DQ);
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index 03b3a7d8c41..983904d5ef6 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -42,6 +42,7 @@ ov_add_test_target(
${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.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp
LINK_LIBRARIES
${MANDATORY_UNIT_TESTS_LIBS}
LABELS