Skip to content

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

NPU Flash Attention. (#33036)

intelgaoxiongb91e08552b95
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 b13ecb83fa4..3d1e54c9be7 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,7 +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, std::string, "STATIC", 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);
@@ -166,7 +166,7 @@ namespace npuw {
namespace llm {
enum class PrefillHint { DYNAMIC, STATIC };
enum class GenerateHint { FAST_COMPILE, BEST_PERF };
-enum class AttentionHint { DYNAMIC, STATIC, PYRAMID };
+enum class AttentionHint { DYNAMIC, STATIC, PYRAMID, HFA };
} // namespace llm
} // namespace npuw
@@ -230,6 +230,8 @@ struct ATTN_HINT_BASE : OptionBase<ATTN_HINT_BASE, ::intel_npu::npuw::llm::Atten
return ::intel_npu::npuw::llm::AttentionHint::STATIC;
} else if (val == "PYRAMID") {
return ::intel_npu::npuw::llm::AttentionHint::PYRAMID;
+ } else if (val == "HFA") {
+ return ::intel_npu::npuw::llm::AttentionHint::HFA;
}
OPENVINO_THROW("Unsupported attention hint provided: ", val);
return {};
@@ -243,6 +245,8 @@ struct ATTN_HINT_BASE : OptionBase<ATTN_HINT_BASE, ::intel_npu::npuw::llm::Atten
return "STATIC";
case ::intel_npu::npuw::llm::AttentionHint::PYRAMID:
return "PYRAMID";
+ case ::intel_npu::npuw::llm::AttentionHint::HFA:
+ return "HFA";
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 a95cec66a9d..5d750de825f 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
@@ -249,11 +249,12 @@ 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
+ * Type: std::string.
+ * Select attention optimization mode when attention block detected.
+ * Possible values: "DYNAMIC", "STATIC", "PYRAMID", "HFA"
+ * Default value: "STATIC"
*/
-static constexpr ov::Property<bool> attn{"NPUW_ATTN"};
+static constexpr ov::Property<std::string> attn{"NPUW_ATTN"};
/**
* @brief
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 96f2ee3f8ba..2d89201b887 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
@@ -509,6 +509,7 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ
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();
+ const bool is_hfa_attention = proto_comp_model_desc.host_flash_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;
@@ -547,6 +548,18 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ
});
};
+ auto is_hfa_attn_param = [&](std::size_t sub_in_idx) -> bool {
+ if (!is_hfa_attention) {
+ return false; // Early return
+ }
+ // Check if sub_in_idx matches any SDPA parameter index
+ auto& hfa_attn = proto_comp_model_desc.host_flash_attention.value()._sdpa_attention_info;
+ const auto& sdpa_in = hfa_attn._sdpa_indices;
+ return sub_in_idx == sdpa_in.query || sub_in_idx == sdpa_in.past_key || sub_in_idx == sdpa_in.past_value ||
+ sub_in_idx == sdpa_in.present_key || sub_in_idx == sdpa_in.present_value ||
+ sub_in_idx == sdpa_in.attention_mask;
+ };
+
for (auto&& it : iodesc.global_params) {
std::size_t param_idx{}, sub_in_idx{};
std::tie(param_idx, sub_in_idx) = it;
@@ -557,6 +570,7 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ
const auto& s_port = request->get_inputs()[sub_in_idx];
LOG_DEBUG("Processing " << g_port << " -> " << s_port << "...");
LOG_BLOCK();
+
if (is_spatial_param(sub_in_idx)) {
// Register for future use
// FIXME: Not sure why this code is here. There should be no
@@ -570,6 +584,9 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ
} 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 if (is_hfa_attn_param(sub_in_idx)) {
+ // Register for future use
+ m_hfa_io[idx].inputs.at(sub_in_idx) = g_tnsr;
} else {
// Lock mutex just in case. m_input_allocated might be altered in parallel in get_tensor()
std::unique_lock lock(m_io_storages_mutex);
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 644c2abc653..f00d1827106 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
@@ -12,6 +12,7 @@
#include <vector>
#include "attention.hpp"
+#include "host_flash_attention.hpp"
#include "openvino/runtime/iasync_infer_request.hpp"
#include "openvino/runtime/isync_infer_request.hpp"
#include "openvino/runtime/so_ptr.hpp"
@@ -146,6 +147,14 @@ protected:
};
std::vector<AttentionIO> m_attention_io;
+ // Host Flash Attention I/O structure
+ // Stores input and output tensors for HFA tiled inference
+ struct HostFlashAttentionIO {
+ std::vector<ov::SoPtr<ov::ITensor>> inputs; // # of elements - # of original SDPA model inputs
+ std::vector<ov::SoPtr<ov::ITensor>> outputs; // # of elements - # of original SDPA model outputs
+ };
+ std::vector<HostFlashAttentionIO> m_hfa_io;
+
// FIXME: Currently is initialized/managed by subclass as well.
// Moved here dumping purposes only
// Represents spatial run-time info
@@ -157,6 +166,9 @@ protected:
// Separate selector for pyramid attention
runtime::pyramid_attention::Selector::Ptr m_pyramid_selector;
+ // Host flash attention selector for dynamic execution
+ runtime::host_flash_attention::Selector::Ptr m_hfa_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
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 2f4ee84b774..088153a8ba7 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp
@@ -363,7 +363,15 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
if (compiled_fcn_iter == compiledFunctions.end()) {
// A function call: store the model for function call only once...
compiledFunctions.insert({subgraph._funcall, id});
- m_compiled_submodels[id].model = fcn_template._model;
+
+ // For HFA, use the final tile model instead of the original SDPA model
+ // because the original SDPA model won't be compiled
+ if (fcn_template._host_flash_attention) {
+ m_compiled_submodels[id].model = fcn_template._host_flash_attention.value()._final_tile_model;
+ } else {
+ m_compiled_submodels[id].model = fcn_template._model;
+ }
+
m_compiled_submodels[id].replaced_by = id; // FIXME: UGLY
// Fill in the spatial information, if it is present
@@ -384,6 +392,14 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
m_compiled_submodels[id].pyramid_attention =
compiled::PyramidAttention(fcn_template._pyramid_attention.value());
}
+
+ if (fcn_template._host_flash_attention) {
+ LOG_INFO("Creating compiled::HostFlashAttention for Subgraph[" << id << "] (function "
+ << subgraph._funcall << ")");
+ m_compiled_submodels[id].host_flash_attention =
+ compiled::HostFlashAttention(fcn_template._host_flash_attention.value());
+ }
+
LOG_INFO("Subgraph[" << id << "] is a function body for " << subgraph._funcall);
} else {
// ...and refer to it in other calls
@@ -428,34 +444,7 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
}
}
- if (ov::npuw::util::is_set(id, dump_sub_opt, real_id, end_sub_idx)) {
- LOG_INFO("Dumping Subgraph[" << id << "]");
- LOG_BLOCK();
- if (real_id != id) {
- LOG_INFO("NOTE: Dumping Subgraph[" << real_id << "]" << " as it is a function body for Subgraph[" << id
- << "]");
- }
- const auto model_to_dump = m_compiled_submodels[real_id].model;
- std::string model_dump_path = m_name + "_" + ov::npuw::util::fmt(id, m_compiled_submodels.size()) +
- (subgraph._funcall.empty() ? "" : "_" + subgraph._funcall) + ".xml";
- ov::save_model(model_to_dump, model_dump_path);
- LOG_INFO("Wrote " << model_dump_path);
-
- // 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)
+ dump_subgraph_model(id, subgraph._funcall, dump_sub_opt);
} // for(orderedSubGraphs)
std::map<std::size_t, std::string> forced_sub_devices{};
@@ -699,6 +688,20 @@ void ov::npuw::CompiledModel::CompiledModelDesc::serialize(std::ostream& stream,
}
}
+ // Serialize host flash attention
+ write(stream, host_flash_attention);
+ if (host_flash_attention.has_value()) {
+ // Serialize compiled tile model
+ if (host_flash_attention.value()._compiled_tile_model) {
+ write(stream, true);
+ std::stringstream ss;
+ host_flash_attention.value()._compiled_tile_model->export_model(ss);
+ write(stream, ss.str());
+ } else {
+ write(stream, false);
+ }
+ }
+
auto& closure_desc = closure.get();
write(stream, closure_desc.is_remote);
@@ -751,9 +754,10 @@ void ov::npuw::CompiledModel::CompiledModelDesc::serialize(std::ostream& stream,
LOG_DEBUG("DONE.");
}
-void ov::npuw::CompiledModel::CompiledModelDesc::deserialize(std::istream& stream,
- const ov::npuw::s11n::WeightsContext& ctx,
- const ov::npuw::s11n::PyramidCtx& pyramid_ctx) {
+void ov::npuw::CompiledModel::CompiledModelDesc::deserialize(
+ std::istream& stream,
+ const ov::npuw::s11n::WeightsContext& ctx,
+ const ov::npuw::s11n::SubmodelDeserializeCtx& submodel_ctx) {
using namespace ov::npuw::s11n;
LOG_DEBUG("Deserializing CompiledModelDesc...");
@@ -790,17 +794,36 @@ void ov::npuw::CompiledModel::CompiledModelDesc::deserialize(std::istream& strea
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);
+ submodel_ctx.plugin->get_core()->import_model(ss, submodel_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;
+ if (submodel_ctx.compiled_model) {
+ pyramid_attention->_compiled_models[num_models - 1] = submodel_ctx.compiled_model;
LOG_DEBUG("Reused compiled_model for the last pyramid attention model");
}
}
}
+ // Deserialize host flash attention
+ read(stream, host_flash_attention);
+ if (host_flash_attention.has_value()) {
+ bool has_compiled_model = false;
+ read(stream, has_compiled_model);
+ if (has_compiled_model) {
+ std::string model_str;
+ read(stream, model_str);
+ std::stringstream ss(model_str);
+ host_flash_attention->_compiled_tile_model =
+ submodel_ctx.plugin->get_core()->import_model(ss, submodel_ctx.device);
+ LOG_DEBUG("Imported compiled tile model for host flash attention");
+ }
+
+ // Set reference to the final tile model (which is the main compiled_model for HFA)
+ host_flash_attention->_compiled_final_tile_model = submodel_ctx.compiled_model;
+ LOG_DEBUG("Set compiled final tile model reference for host flash attention");
+ }
+
auto& closure_desc = closure.get();
read(stream, closure_desc.is_remote);
@@ -1301,10 +1324,12 @@ std::shared_ptr<ov::npuw::CompiledModel> ov::npuw::CompiledModel::deserialize(
}
compiled->m_compiled_submodels[i].device_it = compiled->m_dev_list.begin() + device_idx;
- 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);
+ // Create unified deserialization context for submodels with dynamic mechanisms
+ // (Pyramid Attention, Host Flash Attention, etc.)
+ ov::npuw::s11n::SubmodelDeserializeCtx submodel_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, submodel_ctx);
}
compiled->implement_properties();
@@ -1637,6 +1662,9 @@ bool ov::npuw::CompiledModel::compile_for_device(std::size_t id, const std::stri
// Compile pyramid attention models if present
compile_pyramid_attention_models(id, device_to_try);
+
+ // Compile host flash attention model if present
+ compile_host_flash_attention_model(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());
@@ -1719,6 +1747,58 @@ void ov::npuw::CompiledModel::compile_pyramid_attention_models(std::size_t id, c
LOG_INFO("Pyramid attention compilation complete for Subgraph[" << id << "]");
}
+void ov::npuw::CompiledModel::compile_host_flash_attention_model(std::size_t id, const std::string& device) {
+ // Check if we have host flash attention to compile
+ if (!m_compiled_submodels[id].host_flash_attention.has_value()) {
+ return;
+ }
+
+ LOG_INFO("Compiling host flash attention tile models for Subgraph[" << id << "]...");
+ LOG_BLOCK();
+
+ auto& hfa = m_compiled_submodels[id].host_flash_attention.value();
+
+ // Check if we have tile model to compile
+ if (!hfa._tile_model_to_compile) {
+ LOG_WARN("Host flash attention tile model is null, skipping compilation");
+ return;
+ }
+
+ // Note: The final tile model has already been compiled via compile_submodel(m_compiled_submodels[id].model, ...)
+ // because m_compiled_submodels[id].model points to _final_tile_model for HFA
+ // So we only need to compile the regular tile model here
+
+ // Compile regular tile model
+ LOG_INFO("Compiling flash attention regular tile model on " << device);
+ try {
+ auto compiled_tile_model = compile_submodel(hfa._tile_model_to_compile, device);
+ OPENVINO_ASSERT(compiled_tile_model, "Failed to compile host flash attention tile model");
+
+ hfa.set_compiled_tile_model(std::move(compiled_tile_model));
+
+ LOG_INFO("Successfully compiled host flash attention regular tile model");
+ std::cout << "HostFlashAttention tile model compiled on " << device << " (tile_size=" << hfa._tile_size << ")"
+ << std::endl;
+ } catch (const std::exception& ex) {
+ LOG_ERROR("Failed to compile host flash attention tile model: " << ex.what());
+ OPENVINO_THROW("Host flash attention tile model compilation failed: ", ex.what());
+ } catch (...) {
+ LOG_ERROR("Failed to compile host flash attention tile model: Unknown error");
+ OPENVINO_THROW("Host flash attention tile model compilation failed with unknown error");
+ }
+
+ // Store the already-compiled final tile model reference
+ // The final tile model was compiled at line ~1676 and stored in compiled_model
+ hfa.set_compiled_final_tile_model(m_compiled_submodels[id].compiled_model);
+
+ LOG_INFO("Host flash attention compilation complete for Subgraph[" << id << "]");
+
+ // Memory cleanup notes:
+ // 1. _tile_model_to_compile is released by set_compiled_tile_model()
+ // 2. _final_tile_model_to_compile is released by set_compiled_final_tile_model()
+ // 3. m_compiled_submodels[id].model points to _final_tile_model and will be managed by detach_memory()
+}
+
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();
@@ -1760,6 +1840,59 @@ void ov::npuw::CompiledModel::dump_on_fail(std::size_t id, const std::string& de
}
}
+void ov::npuw::CompiledModel::dump_subgraph_model(std::size_t id,
+ const std::string& funcall,
+ const std::string& dump_sub_opt) {
+ const std::size_t end_sub_idx = m_compiled_submodels.size();
+ const std::size_t real_id = m_compiled_submodels[id].replaced_by.value_or(id);
+
+ if (!ov::npuw::util::is_set(id, dump_sub_opt, real_id, end_sub_idx)) {
+ return;
+ }
+
+ LOG_INFO("Dumping Subgraph[" << id << "]");
+ LOG_BLOCK();
+ if (real_id != id) {
+ LOG_INFO("NOTE: Dumping Subgraph[" << real_id << "]" << " as it is a function body for Subgraph[" << id << "]");
+ }
+ const auto model_to_dump = m_compiled_submodels[real_id].model;
+ std::string model_dump_path = m_name + "_" + ov::npuw::util::fmt(id, m_compiled_submodels.size()) +
+ (funcall.empty() ? "" : "_" + funcall) + ".xml";
+ ov::save_model(model_to_dump, model_dump_path);
+ LOG_INFO("Wrote " << model_dump_path);
+
+ // 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()) +
+ (funcall.empty() ? "" : "_" + 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);
+ }
+ }
+
+ // Dump host flash attention models if present
+ if (m_compiled_submodels[id].host_flash_attention) {
+ LOG_INFO("NOTE: Subgraph[" << id << "] has a host flash attention mechanism.");
+ const auto& hfa_tile_model = m_compiled_submodels[id].host_flash_attention.value()._tile_model_to_compile;
+ std::string hfa_tile_model_dump_path = m_name + "_" + ov::npuw::util::fmt(id, m_compiled_submodels.size()) +
+ (funcall.empty() ? "" : "_" + funcall) + "_hfa_tile.xml";
+ ov::save_model(hfa_tile_model, hfa_tile_model_dump_path);
+ LOG_INFO("Wrote " << hfa_tile_model_dump_path);
+
+ const auto& hfa_final_tile_model =
+ m_compiled_submodels[id].host_flash_attention.value()._final_tile_model_to_compile;
+ std::string hfa_final_tile_model_dump_path = m_name + "_" +
+ ov::npuw::util::fmt(id, m_compiled_submodels.size()) +
+ (funcall.empty() ? "" : "_" + funcall) + "_hfa_final_tile.xml";
+ ov::save_model(hfa_final_tile_model, hfa_final_tile_model_dump_path);
+ }
+}
+
std::shared_ptr<ov::npuw::IBaseInferRequest> ov::npuw::CompiledModel::create_base_infer_request() const {
// Synchronous infer request implementation may vary based on the
// selected strategy
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 19c32d5bbb4..b43aac7d8f0 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp
@@ -9,6 +9,7 @@
#include "attention.hpp"
#include "base_sync_infer_request.hpp"
#include "common.hpp"
+#include "host_flash_attention.hpp"
#include "intel_npu/config/config.hpp"
#include "intel_npu/config/npuw.hpp"
#include "openvino/openvino.hpp"
@@ -80,8 +81,10 @@ private:
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 compile_host_flash_attention_model(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);
+ void dump_subgraph_model(std::size_t id, const std::string& funcall, const std::string& dump_sub_opt);
void report_io() const;
@@ -180,6 +183,7 @@ private:
std::optional<ov::npuw::compiled::Spatial> spatial;
std::optional<ov::npuw::compiled::Attention> attention;
std::optional<ov::npuw::compiled::PyramidAttention> pyramid_attention;
+ std::optional<ov::npuw::compiled::HostFlashAttention> host_flash_attention;
// Infer requests for pyramid attention models (if pyramid_attention is present)
std::vector<ov::SoPtr<ov::IAsyncInferRequest>> pyramid_infer_requests;
@@ -188,6 +192,21 @@ private:
// enabled)
std::vector<ov::SoPtr<ov::IAsyncInferRequest>> pyramid_pipeline_requests;
+ // HFA tile model indices for infer request vectors
+ enum HFATileIdx : size_t {
+ REGULAR_TILE = 0, // Regular tile model (intermediate tiles)
+ FINAL_TILE = 1, // Final tile model (last tile with division and transpose)
+ COUNT = 2 // Total number of HFA tile models
+ };
+
+ // Infer requests for host flash attention tile models (if host_flash_attention is present)
+ // [REGULAR_TILE]: regular tile model, [FINAL_TILE]: final tile model
+ std::vector<ov::SoPtr<ov::IAsyncInferRequest>> hfa_infer_requests;
+
+ // Pipeline infer requests for host flash attention tile models (if host_flash_attention is present and
+ // pipelining is enabled)
+ std::vector<ov::SoPtr<ov::IAsyncInferRequest>> hfa_pipeline_requests;
+
// FIXME: This is a 1:1 copy of the ov::npuw::Subgraph structure
// w.r.t. function calls
std::size_t param_base = 0;
@@ -224,7 +243,7 @@ private:
void serialize(std::ostream& stream, const ov::npuw::s11n::WeightsContext& ctx) const;
void deserialize(std::istream& stream,
const ov::npuw::s11n::WeightsContext& ctx,
- const ov::npuw::s11n::PyramidCtx& pyramid_ctx);
+ const ov::npuw::s11n::SubmodelDeserializeCtx& submodel_ctx);
};
std::vector<CompiledModelDesc> m_compiled_submodels;
diff --git a/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp
new file mode 100644
index 00000000000..cc23b9cfed4
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp
@@ -0,0 +1,1165 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+// Configuration: Enable loop-based Q@K computation to avoid materialized K/V broadcast
+// Set to 1 to enable grouped computation, 0 to use traditional broadcast
+// Disabled by default because NPU compiler optimizations are suboptimal
+#define ENABLE_HFA_LOOP_BASED_COMPUTATION 0
+
+#include "host_flash_attention.hpp"
+
+#include "logging.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/op/ops.hpp"
+#include "openvino/openvino.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "pyramid_attention.hpp"
+#include "util.hpp"
+
+namespace ov {
+namespace npuw {
+namespace function {
+
+namespace opp = ov::pass::pattern;
+
+// Helper struct: Holds all input parameter nodes for HFA tile model creation
+// Contains 7 parameters: past_acc, past_max, past_d, k_tile, v_tile, q, mask_tile
+struct HFATileInputs {
+ std::shared_ptr<ov::op::v0::Parameter> past_acc;
+ std::shared_ptr<ov::op::v0::Parameter> past_max;
+ std::shared_ptr<ov::op::v0::Parameter> past_d;
+ std::shared_ptr<ov::op::v0::Parameter> k_tile;
+ std::shared_ptr<ov::op::v0::Parameter> v_tile;
+ std::shared_ptr<ov::op::v0::Parameter> q;
+ std::shared_ptr<ov::op::v0::Parameter> mask_tile;
+};
+
+// Helper struct: Holds f32-converted nodes from input parameters for computation
+// All computations are performed in f32 for numerical stability
+struct HFATileF32Nodes {
+ std::shared_ptr<ov::Node> past_acc_f32;
+ std::shared_ptr<ov::Node> past_max_f32;
+ std::shared_ptr<ov::Node> past_d_f32;
+ std::shared_ptr<ov::Node> k_tile_f32;
+ std::shared_ptr<ov::Node> v_tile_f32;
+ std::shared_ptr<ov::Node> q_f32;
+ std::shared_ptr<ov::Node> mask_tile_f32;
+};
+
+// Helper struct: Flash attention computation results (all in f32 precision)
+// Contains: acc (accumulator), maxx (maximum values), d (normalization denominator)
+struct FlashAttentionResults {
+ std::shared_ptr<ov::Node> acc;
+ std::shared_ptr<ov::Node> maxx;
+ std::shared_ptr<ov::Node> d;
+};
+
+// ============================================================================
+// Helper function: Create input parameters for HFA tile model
+// ============================================================================
+static HFATileInputs create_hfa_tile_inputs(const ov::Shape& q_shape,
+ const ov::element::Type& input_dtype,
+ const ov::element::Type& mask_dtype,
+ int64_t tile_size,
+ size_t kv_num_heads) {
+ auto batch = q_shape[0];
+ auto num_heads = q_shape[1];
+ auto seq_len = q_shape[2];
+ auto head_dim = q_shape[3];
+
+ HFATileInputs inputs;
+
+ // past_acc: [batch, num_heads, seq_len, head_dim]
+ inputs.past_acc =
+ std::make_shared<ov::op::v0::Parameter>(input_dtype, ov::Shape{batch, num_heads, seq_len, head_dim});
+ inputs.past_acc->set_friendly_name("past_acc");
+ inputs.past_acc->output(0).get_tensor().set_names({"past_acc"});
+
+ // past_max: [batch, num_heads, seq_len, 1]
+ inputs.past_max = std::make_shared<ov::op::v0::Parameter>(input_dtype, ov::Shape{batch, num_heads, seq_len, 1});
+ inputs.past_max->set_friendly_name("past_max");
+ inputs.past_max->output(0).get_tensor().set_names({"past_max"});
+
+ // past_d: [batch, num_heads, seq_len, 1]
+ inputs.past_d = std::make_shared<ov::op::v0::Parameter>(input_dtype, ov::Shape{batch, num_heads, seq_len, 1});
+ inputs.past_d->set_friendly_name("past_d");
+ inputs.past_d->output(0).get_tensor().set_names({"past_d"});
+
+ // k_tile: [batch, kv_num_heads, tile_size, head_dim]
+ inputs.k_tile = std::make_shared<ov::op::v0::Parameter>(
+ input_dtype,
+ ov::Shape{batch, kv_num_heads, static_cast<size_t>(tile_size), head_dim});
+ inputs.k_tile->set_friendly_name("k_tile");
+ inputs.k_tile->output(0).get_tensor().set_names({"k_tile"});
+
+ // v_tile: [batch, kv_num_heads, head_dim, tile_size]
+ inputs.v_tile = std::make_shared<ov::op::v0::Parameter>(
+ input_dtype,
+ ov::Shape{batch, kv_num_heads, head_dim, static_cast<size_t>(tile_size)});
+ inputs.v_tile->set_friendly_name("v_tile");
+ inputs.v_tile->output(0).get_tensor().set_names({"v_tile"});
+
+ // q: [batch, num_heads, seq_len, head_dim]
+ inputs.q = std::make_shared<ov::op::v0::Parameter>(input_dtype, ov::Shape{batch, num_heads, seq_len, head_dim});
+ inputs.q->set_friendly_name("q");
+ inputs.q->output(0).get_tensor().set_names({"q"});
+
+ // mask_tile: [batch, 1, seq_len, tile_size] - use mask's original dtype
+ inputs.mask_tile =
+ std::make_shared<ov::op::v0::Parameter>(mask_dtype,
+ ov::Shape{batch, 1, seq_len, static_cast<size_t>(tile_size)});
+ inputs.mask_tile->set_friendly_name("mask_tile");
+ inputs.mask_tile->output(0).get_tensor().set_names({"mask_tile"});
+
+ return inputs;
+}
+
+// ============================================================================
+// Helper function: Convert input parameters to f32
+// ============================================================================
+static HFATileF32Nodes convert_inputs_to_f32(const HFATileInputs& inputs,
+ const ov::element::Type& mask_dtype,
+ const ov::element::Type& compute_dtype) {
+ HFATileF32Nodes f32_nodes;
+
+ f32_nodes.past_acc_f32 = std::make_shared<ov::op::v0::Convert>(inputs.past_acc, compute_dtype);
+ f32_nodes.past_acc_f32->set_friendly_name("past_acc_f32");
+
+ f32_nodes.past_max_f32 = std::make_shared<ov::op::v0::Convert>(inputs.past_max, compute_dtype);
+ f32_nodes.past_max_f32->set_friendly_name("past_max_f32");
+
+ f32_nodes.past_d_f32 = std::make_shared<ov::op::v0::Convert>(inputs.past_d, compute_dtype);
+ f32_nodes.past_d_f32->set_friendly_name("past_d_f32");
+
+ f32_nodes.k_tile_f32 = std::make_shared<ov::op::v0::Convert>(inputs.k_tile, compute_dtype);
+ f32_nodes.k_tile_f32->set_friendly_name("k_tile_f32");
+
+ f32_nodes.v_tile_f32 = std::make_shared<ov::op::v0::Convert>(inputs.v_tile, compute_dtype);
+ f32_nodes.v_tile_f32->set_friendly_name("v_tile_f32");
+
+ f32_nodes.q_f32 = std::make_shared<ov::op::v0::Convert>(inputs.q, compute_dtype);
+ f32_nodes.q_f32->set_friendly_name("q_f32");
+
+ // Convert mask to f32 if needed
+ if (mask_dtype == compute_dtype) {
+ f32_nodes.mask_tile_f32 = inputs.mask_tile;
+ } else {
+ f32_nodes.mask_tile_f32 = std::make_shared<ov::op::v0::Convert>(inputs.mask_tile, compute_dtype);
+ f32_nodes.mask_tile_f32->set_friendly_name("mask_tile_f32");
+ }
+
+ return f32_nodes;
+}
+
+// ============================================================================
+// Helper function: Execute flash attention algorithm (unified implementation)
+// Supports both traditional broadcast and loop-based grouped computation
+// ============================================================================
+// Parameters:
+// use_grouped: If true, uses loop-based grouped computation (Q/P reshape)
+// If false, uses traditional broadcast K/V approach
+static FlashAttentionResults execute_flash_attention(const HFATileF32Nodes& f32_nodes,
+ const std::shared_ptr<ov::Node>& q_input,
+ const std::shared_ptr<ov::Node>& k_input,
+ const std::shared_ptr<ov::Node>& v_input,
+ size_t batch,
+ size_t num_heads,
+ size_t kv_num_heads,
+ size_t seq_len,
+ size_t tile_size,
+ size_t head_dim,
+ bool use_grouped = false) {
+ FlashAttentionResults results;
+
+ // ========================================================================
+ // Step 1: Compute QK (method differs based on use_grouped flag)
+ // ========================================================================
+ std::shared_ptr<ov::Node> qk;
+
+ if (use_grouped) {
+ // Loop-based grouped computation: Q and K are grouped format
+ // Q_input: [batch, kv_num_heads, factor * seq_len, head_dim]
+ // K_input: [batch, kv_num_heads, tile_size, head_dim]
+ // QK_grouped: [batch, kv_num_heads, factor * seq_len, tile_size]
+ auto qk_grouped = std::make_shared<ov::op::v0::MatMul>(q_input, k_input, false, true);
+ qk_grouped->set_friendly_name("qk_grouped");
+
+ // Reshape QK back: [batch, kv_num_heads, factor * seq_len, tile_size] -> [batch, num_heads, seq_len, tile_size]
+ auto qk_reshape_pattern =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64,
+ ov::Shape{4},
+ std::vector<int64_t>{static_cast<int64_t>(batch),
+ static_cast<int64_t>(num_heads),
+ static_cast<int64_t>(seq_len),
+ static_cast<int64_t>(tile_size)});
+ qk = std::make_shared<ov::op::v1::Reshape>(qk_grouped, qk_reshape_pattern, false);
+ qk->set_friendly_name("qk");
+ } else {
+ // Traditional broadcast computation: use broadcast K directly
+ // Q_input: [batch, num_heads, seq_len, head_dim]
+ // K_input: [batch, num_heads, tile_size, head_dim] (already broadcast)
+ // QK: [batch, num_heads, seq_len, tile_size]
+ qk = std::make_shared<ov::op::v0::MatMul>(q_input, k_input, false, true);
+ qk->set_friendly_name("qk");
+ }
+
+ // ========================================================================
+ // Step 2: Flash Attention core algorithm (same for both methods)
+ // ========================================================================
+
+ // qkm = qk + mask
+ auto qkm = std::make_shared<ov::op::v1::Add>(qk, f32_nodes.mask_tile_f32);
+ qkm->set_friendly_name("qkm");
+
+ // maxx = max(past_max, reduce_max(qkm, axis=-1, keepdims=True))
+ auto axes_const = std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1});
+ auto qkm_max = std::make_shared<ov::op::v1::ReduceMax>(qkm, axes_const, true);
+ qkm_max->set_friendly_name("qkm_max");
+
+ results.maxx = std::make_shared<ov::op::v1::Maximum>(qkm_max, f32_nodes.past_max_f32);
+ results.maxx->set_friendly_name("maxx");
+
+ // p = exp(qkm - maxx)
+ auto qkm_sub_maxx = std::make_shared<ov::op::v1::Subtract>(qkm, results.maxx);
+ auto p = std::make_shared<ov::op::v0::Exp>(qkm_sub_maxx);
+ p->set_friendly_name("p");
+
+ // l = reduce_sum(p, axis=-1, keepdims=True)
+ auto l = std::make_shared<ov::op::v1::ReduceSum>(p, axes_const, true);
+ l->set_friendly_name("l");
+
+ // alpha = exp(past_max - maxx)
+ auto past_max_sub_maxx = std::make_shared<ov::op::v1::Subtract>(f32_nodes.past_max_f32, results.maxx);
+ auto alpha = std::make_shared<ov::op::v0::Exp>(past_max_sub_maxx);
+ alpha->set_friendly_name("alpha");
+
+ // d = past_d * alpha + l
+ auto past_d_alpha = std::make_shared<ov::op::v1::Multiply>(f32_nodes.past_d_f32, alpha);
+ results.d = std::make_shared<ov::op::v1::Add>(past_d_alpha, l);
+ results.d->set_friendly_name("d");
+
+ // ========================================================================
+ // Step 3: Compute PV and final accumulator (method differs based on use_grouped flag)
+ // ========================================================================
+
+ auto past_acc_alpha = std::make_shared<ov::op::v1::Multiply>(f32_nodes.past_acc_f32, alpha);
+ std::shared_ptr<ov::Node> pv;
+
+ if (use_grouped) {
+ // Loop-based grouped computation: reshape P, multiply with V, reshape back
+ size_t factor = num_heads / kv_num_heads;
+
+ // Reshape P for grouped V multiplication: [batch, num_heads, seq_len, tile_size]
+ // -> [batch, kv_num_heads, factor * seq_len, tile_size]
+ auto p_reshape_pattern =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64,
+ ov::Shape{4},
+ std::vector<int64_t>{static_cast<int64_t>(batch),
+ static_cast<int64_t>(kv_num_heads),
+ static_cast<int64_t>(factor * seq_len),
+ static_cast<int64_t>(tile_size)});
+ auto p_grouped = std::make_shared<ov::op::v1::Reshape>(p, p_reshape_pattern, false);
+ p_grouped->set_friendly_name("p_grouped");
+
+ // pv_grouped = matmul(p_grouped, v^T)
+ // P_grouped: [batch, kv_num_heads, factor * seq_len, tile_size]
+ // V_input: [batch, kv_num_heads, head_dim, tile_size]
+ // PV_grouped: [batch, kv_num_heads, factor * seq_len, head_dim]
+ auto pv_grouped = std::make_shared<ov::op::v0::MatMul>(p_grouped, v_input, false, true);
+ pv_grouped->set_friendly_name("pv_grouped");
+
+ // Reshape PV back: [batch, kv_num_heads, factor * seq_len, head_dim] -> [batch, num_heads, seq_len, head_dim]
+ auto pv_reshape_pattern =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64,
+ ov::Shape{4},
+ std::vector<int64_t>{static_cast<int64_t>(batch),
+ static_cast<int64_t>(num_heads),
+ static_cast<int64_t>(seq_len),
+ static_cast<int64_t>(head_dim)});
+ pv = std::make_shared<ov::op::v1::Reshape>(pv_grouped, pv_reshape_pattern, false);
+ pv->set_friendly_name("pv");
+ } else {
+ // Traditional broadcast computation: use broadcast V directly
+ // P: [batch, num_heads, seq_len, tile_size]
+ // V_input: [batch, num_heads, head_dim, tile_size] (already broadcast)
+ // PV: [batch, num_heads, seq_len, head_dim]
+ pv = std::make_shared<ov::op::v0::MatMul>(p, v_input, false, true);
+ pv->set_friendly_name("pv");
+ }
+
+ // acc = past_acc * alpha + pv
+ results.acc = std::make_shared<ov::op::v1::Add>(past_acc_alpha, pv);
+ results.acc->set_friendly_name("acc");
+
+ return results;
+}
+
+// ============================================================================
+// Helper function: Broadcast KV from kv_num_heads to num_heads
+// ============================================================================
+static std::pair<std::shared_ptr<ov::Node>, std::shared_ptr<ov::Node>> broadcast_kv_tiles(
+ const std::shared_ptr<ov::Node>& k_tile_f32,
+ const std::shared_ptr<ov::Node>& v_tile_f32,
+ size_t batch,
+ size_t num_heads,
+ size_t kv_num_heads,
+ size_t tile_size,
+ size_t head_dim) {
+ size_t head_expansion = num_heads / kv_num_heads;
+
+ // Broadcast K: [batch, kv_num_heads, tile_size, head_dim] -> [batch, num_heads, tile_size, head_dim]
+ auto unsqueeze_axes_k =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{2});
+ auto k_unsqueezed = std::make_shared<ov::op::v0::Unsqueeze>(k_tile_f32, unsqueeze_axes_k);
+
+ auto repeats_k =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64,
+ ov::Shape{5},
+ std::vector<int64_t>{1, 1, static_cast<int64_t>(head_expansion), 1, 1});
+ auto k_tiled = std::make_shared<ov::op::v0::Tile>(k_unsqueezed, repeats_k);
+
+ auto k_reshape_pattern =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64,
+ ov::Shape{4},
+ std::vector<int64_t>{static_cast<int64_t>(batch),
+ static_cast<int64_t>(num_heads),
+ static_cast<int64_t>(tile_size),
+ static_cast<int64_t>(head_dim)});
+ auto k_tile_broadcast = std::make_shared<ov::op::v1::Reshape>(k_tiled, k_reshape_pattern, false);
+ k_tile_broadcast->set_friendly_name("k_tile_broadcast");
+
+ // Broadcast V: [batch, kv_num_heads, head_dim, tile_size] -> [batch, num_heads, head_dim, tile_size]
+ auto unsqueeze_axes_v =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{2});
+ auto v_unsqueezed = std::make_shared<ov::op::v0::Unsqueeze>(v_tile_f32, unsqueeze_axes_v);
+
+ auto repeats_v =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64,
+ ov::Shape{5},
+ std::vector<int64_t>{1, 1, static_cast<int64_t>(head_expansion), 1, 1});
+ auto v_tiled = std::make_shared<ov::op::v0::Tile>(v_unsqueezed, repeats_v);
+
+ auto v_reshape_pattern =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64,
+ ov::Shape{4},
+ std::vector<int64_t>{static_cast<int64_t>(batch),
+ static_cast<int64_t>(num_heads),
+ static_cast<int64_t>(head_dim),
+ static_cast<int64_t>(tile_size)});
+ auto v_tile_broadcast = std::make_shared<ov::op::v1::Reshape>(v_tiled, v_reshape_pattern, false);
+ v_tile_broadcast->set_friendly_name("v_tile_broadcast");
+
+ return {k_tile_broadcast, v_tile_broadcast};
+}
+
+#if ENABLE_HFA_LOOP_BASED_COMPUTATION
+// ============================================================================
+// Helper function: Reshape Q for grouped computation (loop-based approach)
+// Avoids materializing broadcasted K/V tensors by reshaping Q to match KV heads
+// ============================================================================
+// Q: [batch, num_heads, seq_len, head_dim] -> [batch, kv_num_heads, factor * seq_len, head_dim]
+// where factor = num_heads / kv_num_heads
+static std::shared_ptr<ov::Node> reshape_q_for_groups(const std::shared_ptr<ov::Node>& q_f32,
+ size_t batch,
+ size_t num_heads,
+ size_t kv_num_heads,
+ size_t seq_len,
+ size_t head_dim) {
+ size_t factor = num_heads / kv_num_heads;
+
+ // Reshape Q: [batch, num_heads, seq_len, head_dim] -> [batch, kv_num_heads, factor * seq_len, head_dim]
+ auto q_reshape_pattern =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64,
+ ov::Shape{4},
+ std::vector<int64_t>{static_cast<int64_t>(batch),
+ static_cast<int64_t>(kv_num_heads),
+ static_cast<int64_t>(factor * seq_len),
+ static_cast<int64_t>(head_dim)});
+ auto q_grouped = std::make_shared<ov::op::v1::Reshape>(q_f32, q_reshape_pattern, false);
+ q_grouped->set_friendly_name("q_grouped");
+
+ return q_grouped;
+}
+#endif // ENABLE_HFA_LOOP_BASED_COMPUTATION
+
+// ============================================================================
+// Helper function: Create final tile model outputs (division, transpose, reshape)
+// ============================================================================
+static ov::ResultVector create_final_tile_outputs(const FlashAttentionResults& results,
+ const ov::element::Type& output_dtype,
+ size_t batch,
+ size_t seq_len,
+ size_t num_heads,
+ size_t head_dim) {
+ // Division: result = acc / d
+ auto final_result = std::make_shared<ov::op::v1::Divide>(results.acc, results.d);
+ final_result->set_friendly_name("final_result");
+
+ // Transpose (0,2,1,3): [batch, num_heads, seq_len, head_dim] -> [batch, seq_len, num_heads, head_dim]
+ auto transpose_order =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 2, 1, 3});
+ auto transposed_result = std::make_shared<ov::op::v1::Transpose>(final_result, transpose_order);
+ transposed_result->set_friendly_name("transposed_result");
+
+ // Reshape: [batch, seq_len, num_heads, head_dim] -> [batch, seq_len, num_heads*head_dim]
+ auto reshape_pattern =
+ std::make_shared<ov::op::v0::Constant>(ov::element::i64,
+ ov::Shape{3},
+ std::vector<int64_t>{static_cast<int64_t>(batch),
+ static_cast<int64_t>(seq_len),
+ static_cast<int64_t>(num_heads * head_dim)});
+ auto reshaped_result = std::make_shared<ov::op::v1::Reshape>(transposed_result, reshape_pattern, false);
+ reshaped_result->set_friendly_name("reshaped_result");
+
+ // Convert final output to original SDPA output dtype
+ auto final_output = std::make_shared<ov::op::v0::Convert>(reshaped_result, output_dtype);
+ final_output->set_friendly_name("final_output");
+ final_output->output(0).get_tensor().set_names({"output"});
+
+ // Create result - only ONE output
+ auto out_result = std::make_shared<ov::op::v0::Result>(final_output);
+ out_result->set_friendly_name("out_result");
+
+ return {out_result};
+}
+
+// ============================================================================
+// Helper function: Create regular tile model outputs (intermediate states: acc, max, d)
+// ============================================================================
+static ov::ResultVector create_regular_tile_outputs(const FlashAttentionResults& results,
+ const ov::element::Type& input_dtype) {
+ // Convert outputs back to input_dtype (f16)
+ auto acc_output = std::make_shared<ov::op::v0::Convert>(results.acc, input_dtype);
+ acc_output->set_friendly_name("acc_output");
+ acc_output->output(0).get_tensor().set_names({"acc"});
+
+ auto maxx_output = std::make_shared<ov::op::v0::Convert>(results.maxx, input_dtype);
+ maxx_output->set_friendly_name("maxx_output");
+ maxx_output->output(0).get_tensor().set_names({"maxx"});
+
+ auto d_output = std::make_shared<ov::op::v0::Convert>(results.d, input_dtype);
+ d_output->set_friendly_name("d_output");
+ d_output->output(0).get_tensor().set_names({"d"});
+
+ // Create results
+ auto out_acc = std::make_shared<ov::op::v0::Result>(acc_output);
+ out_acc->set_friendly_name("out_acc");
+
+ auto out_maxx = std::make_shared<ov::op::v0::Result>(maxx_output);
+ out_maxx->set_friendly_name("out_maxx");
+
+ auto out_d = std::make_shared<ov::op::v0::Result>(d_output);
+ out_d->set_friendly_name("out_d");
+
+ return {out_acc, out_maxx, out_d};
+}
+
+// ============================================================================
+// Helper function: Create individual tile model (regular or final)
+// ============================================================================
+// Parameters:
+// is_final_tile: If true, creates final tile with division/transpose/reshape
+// output_dtype: Output data type (only used when is_final_tile=true)
+static std::shared_ptr<ov::Model> create_hfa_tile_model(const ov::Shape& q_shape,
+ const ov::element::Type& input_dtype,
+ const ov::element::Type& mask_dtype,
+ int64_t tile_size,
+ size_t kv_num_heads,
+ bool is_final_tile = false,
+ const ov::element::Type& output_dtype = ov::element::f16) {
+ LOG_DEBUG("Creating HFA " << (is_final_tile ? "FINAL " : "") << "tile model with tile_size=" << tile_size
+ << ", kv_num_heads=" << kv_num_heads << ", mask_dtype=" << mask_dtype
+ << (is_final_tile ? ", output_dtype=" + output_dtype.get_type_name() : ""));
+
+ // Extract dimensions
+ NPUW_ASSERT(q_shape.size() == 4);
+ auto batch = q_shape[0];
+ auto num_heads = q_shape[1];
+ auto seq_len = q_shape[2];
+ auto head_dim = q_shape[3];
+
+ NPUW_ASSERT(num_heads % kv_num_heads == 0 && "Q heads must be divisible by KV heads");
+
+ auto compute_dtype = ov::element::f32;
+ LOG_DEBUG("Using compute_dtype=f32 for all operations to match mask type");
+
+ // Create input parameters
+ auto inputs = create_hfa_tile_inputs(q_shape, input_dtype, mask_dtype, tile_size, kv_num_heads);
+
+ // Convert all inputs to f32
+ auto f32_nodes = convert_inputs_to_f32(inputs, mask_dtype, compute_dtype);
+
+ FlashAttentionResults results;
+
+#if ENABLE_HFA_LOOP_BASED_COMPUTATION
+ // ========================================================================
+ // Loop-based computation: Reshape Q to avoid K/V broadcast materialization
+ // ========================================================================
+ LOG_DEBUG("Using loop-based grouped computation (ENABLED) - avoids K/V broadcast");
+
+ // Reshape Q for grouped computation
+ auto q_grouped = reshape_q_for_groups(f32_nodes.q_f32, batch, num_heads, kv_num_heads, seq_len, head_dim);
+
+ // Execute flash attention with grouped computation (K and V remain 4D, no broadcast)
+ results = execute_flash_attention(f32_nodes,
+ q_grouped, // Q: grouped format
+ f32_nodes.k_tile_f32, // K: original 4D
+ f32_nodes.v_tile_f32, // V: original 4D
+ batch,
+ num_heads,
+ kv_num_heads,
+ seq_len,
+ tile_size,
+ head_dim,
+ true); // use_grouped = true
+#else
+ // ========================================================================
+ // Traditional broadcast-based computation: Materialize K/V broadcast
+ // ========================================================================
+ LOG_DEBUG("Using traditional broadcast computation (DISABLED loop-based) - materializes K/V broadcast");
+
+ // Broadcast K and V tiles from kv_num_heads to num_heads
+ auto [k_broadcast, v_broadcast] = broadcast_kv_tiles(f32_nodes.k_tile_f32,
+ f32_nodes.v_tile_f32,
+ batch,
+ num_heads,
+ kv_num_heads,
+ tile_size,
+ head_dim);
+
+ // Execute flash attention algorithm with broadcasted K/V
+ results = execute_flash_attention(f32_nodes,
+ f32_nodes.q_f32, // Q: original 4D
+ k_broadcast, // K: broadcast to num_heads
+ v_broadcast, // V: broadcast to num_heads
+ batch,
+ num_heads,
+ kv_num_heads,
+ seq_len,
+ tile_size,
+ head_dim,
+ false); // use_grouped = false
+#endif // ENABLE_HFA_LOOP_BASED_COMPUTATION
+
+ // Create model outputs and name based on tile type
+ ov::ResultVector model_results;
+ std::string model_name;
+
+ if (is_final_tile) {
+ // === FINAL TILE: Add division, transpose and reshape for final output ===
+ model_results = create_final_tile_outputs(results, output_dtype, batch, seq_len, num_heads, head_dim);
+ model_name = "HFA_Final_Tile";
+ LOG_DEBUG("HFA FINAL tile model created: inputs=" << input_dtype << ", compute=" << compute_dtype
+ << ", output=" << output_dtype);
+ } else {
+ // === REGULAR TILE: Output intermediate states (acc, max, d) ===
+ model_results = create_regular_tile_outputs(results, input_dtype);
+ model_name = "HFA_Tile";
+ LOG_DEBUG("HFA tile model created: inputs=" << input_dtype << ", compute=" << compute_dtype
+ << ", outputs=" << input_dtype);
+ }
+
+ // Create model parameters
+ ov::ParameterVector model_params =
+ {inputs.past_acc, inputs.past_max, inputs.past_d, inputs.k_tile, inputs.v_tile, inputs.q, inputs.mask_tile};
+
+ // Create and return model
+ return std::make_shared<ov::Model>(model_results, model_params, model_name);
+}
+
+// ============================================================================
+// Helper function: Extract actual Parameter by skipping Convert nodes
+// ============================================================================
+static std::shared_ptr<ov::Node> skip_convert_nodes(const std::shared_ptr<ov::Node>& node) {
+ auto current = node;
+ while (current && ov::is_type<ov::op::v0::Convert>(current.get())) {
+ if (current->get_input_size() > 0) {
+ current = current->get_input_node_shared_ptr(0);
+ } else {
+ break;
+ }
+ }
+ return current;
+}
+
+// ============================================================================
+// Helper function: Build SDPA parameter index mapping
+// ============================================================================
+static void build_sdpa_param_mapping(HostFlashAttention& hfa,
+ const std::shared_ptr<ov::Model>& model,
+ const SDPAPatternNodes& pattern_nodes) {
+ LOG_INFO("Building SDPA input parameter index mapping...");
+
+ // Helper lambda to safely extract parameter from node (skipping Convert ops)
+ auto extract_param = [&](const std::shared_ptr<ov::Node>& node) -> std::shared_ptr<ov::op::v0::Parameter> {
+ return ov::as_type_ptr<ov::op::v0::Parameter>(skip_convert_nodes(node));
+ };
+
+ // Extract Q (query) parameter - input 0 of MatMul1
+ if (auto q_param = extract_param(pattern_nodes.matmul1_node->get_input_node_shared_ptr(0))) {
+ std::size_t q_idx = model->get_parameter_index(q_param);
+ hfa._sdpa_param_index_map[SDPAInputId::QUERY] = q_idx;
+ LOG_DEBUG("Mapped QUERY to parameter index " << q_idx);
+ }
+
+ // Extract past_key parameter - input 0 of past_key_concat
+ if (pattern_nodes.past_key_concat_node) {
+ if (auto past_k_param = extract_param(pattern_nodes.past_key_concat_node->get_input_node_shared_ptr(0))) {
+ std::size_t past_k_idx = model->get_parameter_index(past_k_param);
+ hfa._sdpa_param_index_map[SDPAInputId::PAST_KEY] = past_k_idx;
+ LOG_DEBUG("Mapped PAST_KEY to parameter index " << past_k_idx);
+ }
+
+ // Extract present_key parameter - input 1 of past_key_concat
+ if (auto present_k_param = extract_param(pattern_nodes.past_key_concat_node->get_input_node_shared_ptr(1))) {
+ std::size_t present_k_idx = model->get_parameter_index(present_k_param);
+ hfa._sdpa_param_index_map[SDPAInputId::PRESENT_KEY] = present_k_idx;
+ LOG_DEBUG("Mapped PRESENT_KEY to parameter index " << present_k_idx);
+ }
+ }
+
+ // Extract past_value parameter - input 0 of past_value_concat
+ if (pattern_nodes.past_value_concat_node) {
+ if (auto past_v_param = extract_param(pattern_nodes.past_value_concat_node->get_input_node_shared_ptr(0))) {
+ std::size_t past_v_idx = model->get_parameter_index(past_v_param);
+ hfa._sdpa_param_index_map[SDPAInputId::PAST_VALUE] = past_v_idx;
+ LOG_DEBUG("Mapped PAST_VALUE to parameter index " << past_v_idx);
+ }
+
+ // Extract present_value parameter - input 1 of past_value_concat
+ if (auto present_v_param = extract_param(pattern_nodes.past_value_concat_node->get_input_node_shared_ptr(1))) {
+ std::size_t present_v_idx = model->get_parameter_index(present_v_param);
+ hfa._sdpa_param_index_map[SDPAInputId::PRESENT_VALUE] = present_v_idx;
+ LOG_DEBUG("Mapped PRESENT_VALUE to parameter index " << present_v_idx);
+ }
+ }
+
+ // Extract mask parameter - input 1 of add_node
+ if (auto add_param = extract_param(pattern_nodes.add_node->get_input_node_shared_ptr(1))) {
+ std::size_t mask_idx = model->get_parameter_index(add_param);
+ hfa._sdpa_param_index_map[SDPAInputId::ATTENTION_MASK] = mask_idx;
+ LOG_DEBUG("Mapped ATTENTION_MASK to parameter index " << mask_idx);
+ }
+
+ LOG_INFO("Built SDPA input mapping with " << hfa._sdpa_param_index_map.size() << " entries");
+
+ // Print the complete mapping table
+ std::cout << "\n========== SDPA Input Index Mapping ==========\n";
+ std::cout << "Total entries: " << hfa._sdpa_param_index_map.size() << "\n";
+
+ for (const auto& [input_id, param_idx] : hfa._sdpa_param_index_map) {
+ std::cout << " " << sdpa_input_id_to_string(input_id) << " -> parameter[" << param_idx << "]" << std::endl;
+ }
+ std::cout << "=============================================\n" << std::endl;
+}
+
+// ============================================================================
+// Helper function: Build tile model parameter index mapping
+// ============================================================================
+static void build_tile_param_mapping(HostFlashAttention& hfa, const std::shared_ptr<ov::Model>& tile_model) {
+ LOG_INFO("Building HFA Tile Model input index mapping...");
+
+ // Parse tile model inputs by their tensor names
+ // Expected input order: [past_acc, past_max, past_d, k_tile, v_tile, q, mask_tile]
+ const auto& tile_inputs = tile_model->inputs();
+ for (std::size_t i = 0; i < tile_inputs.size(); ++i) {
+ const auto& tensor_names = tile_inputs[i].get_names();
+ if (tensor_names.empty()) {
+ LOG_WARN("Tile model input[" << i << "] has no tensor name");
+ continue;
+ }
+
+ const std::string& name = *tensor_names.begin();
+
+ // Map tensor name to enum ID
+ if (name == "past_acc") {
+ hfa._tile_param_index_map[HFATileInputId::PAST_ACC] = i;
+ LOG_DEBUG("Mapped PAST_ACC to tile input[" << i << "]");
+ } else if (name == "past_max") {
+ hfa._tile_param_index_map[HFATileInputId::PAST_MAX] = i;
+ LOG_DEBUG("Mapped PAST_MAX to tile input[" << i << "]");
+ } else if (name == "past_d") {
+ hfa._tile_param_index_map[HFATileInputId::PAST_D] = i;
+ LOG_DEBUG("Mapped PAST_D to tile input[" << i << "]");
+ } else if (name == "k_tile") {
+ hfa._tile_param_index_map[HFATileInputId::K_TILE] = i;
+ LOG_DEBUG("Mapped K_TILE to tile input[" << i << "]");
+ } else if (name == "v_tile") {
+ hfa._tile_param_index_map[HFATileInputId::V_TILE] = i;
+ LOG_DEBUG("Mapped V_TILE to tile input[" << i << "]");
+ } else if (name == "q") {
+ hfa._tile_param_index_map[HFATileInputId::Q] = i;
+ LOG_DEBUG("Mapped Q to tile input[" << i << "]");
+ } else if (name == "mask_tile") {
+ hfa._tile_param_index_map[HFATileInputId::MASK_TILE] = i;
+ LOG_DEBUG("Mapped MASK_TILE to tile input[" << i << "]");
+ } else {
+ LOG_WARN("Unknown tile model input name: " << name);
+ }
+ }
+
+ // Print the tile input mapping
+ std::cout << "\n========== HFA Tile Model Input Mapping ==========\n";
+ std::cout << "Total entries: " << hfa._tile_param_index_map.size() << "\n";
+
+ for (const auto& [input_id, input_idx] : hfa._tile_param_index_map) {
+ std::cout << " " << hfa_tile_input_id_to_string(input_id) << " -> input[" << input_idx << "]" << std::endl;
+ }
+ std::cout << "==================================================\n" << std::endl;
+}
+
+// ============================================================================
+// Helper function: Build tile model output index mapping
+// ============================================================================
+static void build_tile_output_mapping(HostFlashAttention& hfa, const std::shared_ptr<ov::Model>& tile_model) {
+ LOG_INFO("Building HFA Tile Model output index mapping...");
+
+ // Parse tile model outputs by their tensor names
+ // Expected output order: [acc, maxx, d]
+ const auto& tile_outputs = tile_model->outputs();
+ for (std::size_t i = 0; i < tile_outputs.size(); ++i) {
+ const auto& tensor_names = tile_outputs[i].get_names();
+ if (tensor_names.empty()) {
+ LOG_WARN("Tile model output[" << i << "] has no tensor name");
+ continue;
+ }
+
+ const std::string& name = *tensor_names.begin();
+
+ // Map tensor name to enum ID
+ if (name == "acc") {
+ hfa._tile_output_index_map[HFATileOutputId::ACC] = i;
+ LOG_DEBUG("Mapped ACC to tile output[" << i << "]");
+ } else if (name == "maxx") {
+ hfa._tile_output_index_map[HFATileOutputId::MAXX] = i;
+ LOG_DEBUG("Mapped MAXX to tile output[" << i << "]");
+ } else if (name == "d") {
+ hfa._tile_output_index_map[HFATileOutputId::D] = i;
+ LOG_DEBUG("Mapped D to tile output[" << i << "]");
+ } else {
+ LOG_WARN("Unknown tile model output name: " << name);
+ }
+ }
+
+ // Print the tile output mapping
+ std::cout << "\n========== HFA Tile Model Output Mapping ==========\n";
+ std::cout << "Total entries: " << hfa._tile_output_index_map.size() << "\n";
+
+ for (const auto& [output_id, output_idx] : hfa._tile_output_index_map) {
+ std::cout << " " << hfa_tile_output_id_to_string(output_id) << " -> output[" << output_idx << "]" << std::endl;
+ }
+ std::cout << "==================================================\n" << std::endl;
+}
+
+// ============================================================================
+// Helper function: Extract sequence dimension from Concat node
+// ============================================================================
+static std::optional<std::size_t> extract_sequence_dim_from_concat(const std::shared_ptr<ov::Node>& concat_node,
+ const std::string& tensor_name) {
+ if (!concat_node) {
+ LOG_WARN("Failed to extract " << tensor_name << " concat node");
+ return std::nullopt;
+ }
+
+ auto concat_op = std::dynamic_pointer_cast<ov::op::v0::Concat>(concat_node);
+ if (!concat_op) {
+ LOG_WARN("Failed to cast " << tensor_name << "_concat to Concat op");
+ return std::nullopt;
+ }
+
+ const auto& concat_out_shape = concat_op->get_output_partial_shape(0);
+ return ov::util::try_normalize_axis(concat_op->get_axis(), concat_out_shape.rank(), *concat_op);
+}
+
+std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr<ov::Model>& model) {
+ LOG_INFO("Attempting to create HostFlashAttention from model");
+ LOG_BLOCK();
+
+ // ========================================================================
+ // Step 1: Validate SDPA pattern and extract key nodes
+ // ========================================================================
+ auto pattern_nodes = find_sdpa_pattern_nodes(model);
+ if (!pattern_nodes.is_valid()) {
+ LOG_WARN("Failed to re-find SDPA pattern nodes");
+ return std::nullopt;
+ }
+
+ auto q_input = pattern_nodes.matmul1_node->get_input_node_shared_ptr(0);
+ auto k_concat = pattern_nodes.past_key_concat_node;
+
+ // Skip Convert nodes to get to the actual Parameter/input
+ q_input = skip_convert_nodes(q_input);
+
+ if (!q_input || !k_concat) {
+ LOG_WARN("Failed to extract Q input or K concat from pattern");
+ return std::nullopt;
+ }
+
+ // ========================================================================
+ // Step 2: Extract shape and data type information
+ // ========================================================================
+ auto q_shape = q_input->get_output_partial_shape(0);
+ if (q_shape.is_dynamic()) {
+ LOG_WARN("Dynamic shapes not yet supported for HFA");
+ return std::nullopt;
+ }
+
+ auto q_shape_static = q_shape.to_shape();
+ auto dtype = q_input->get_output_element_type(0);
+
+ // Validate Q shape and extract query_size (seq_len dimension)
+ if (q_shape_static.size() != 4) {
+ LOG_WARN("Q shape must be 4D, got " << q_shape_static.size() << "D shape");
+ return std::nullopt;
+ }
+ std::size_t query_size = q_shape_static[2]; // seq_len at index 2
+ LOG_DEBUG("Extracted query_size (seq_len) from Q shape: " << query_size);
+
+ 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;
+ }
+ auto mask_dtype = mask_param->get_output_element_type(0);
+
+ auto output_dtype = ov::element::f16; // Default fallback
+ if (model->outputs().size() > 0) {
+ output_dtype = model->output(0).get_element_type();
+ LOG_DEBUG("Original SDPA output data type: " << output_dtype);
+ } else {
+ LOG_WARN("No outputs found in model, using default output dtype: " << output_dtype);
+ }
+
+ // ========================================================================
+ // Step 3: Extract K/V sequence dimensions from Concat nodes
+ // ========================================================================
+ auto k_seq_dim_opt = extract_sequence_dim_from_concat(pattern_nodes.past_key_concat_node, "K");
+ if (!k_seq_dim_opt) {
+ return std::nullopt;
+ }
+ std::size_t k_seq_dim = k_seq_dim_opt.value();
+
+ auto v_seq_dim_opt = extract_sequence_dim_from_concat(pattern_nodes.past_value_concat_node, "V");
+ if (!v_seq_dim_opt) {
+ return std::nullopt;
+ }
+ std::size_t v_seq_dim = v_seq_dim_opt.value();
+
+ // ========================================================================
+ // Step 4: Extract KV heads configuration and context size
+ // ========================================================================
+ size_t kv_num_heads = 0;
+ size_t context_size = 0;
+ if (!k_concat->get_output_partial_shape(0).is_static()) {
+ return std::nullopt;
+ }
+
+ auto k_full_shape = k_concat->get_output_partial_shape(0).to_shape();
+ // K shape after concat: [batch, kv_num_heads, kv_cache_size, head_dim]
+ if (k_full_shape.size() != 4) {
+ return std::nullopt;
+ }
+
+ kv_num_heads = k_full_shape[1]; // Extract kv_num_heads from K shape
+ context_size = k_full_shape[k_seq_dim]; // Extract context size from sequence dimension
+
+ if (kv_num_heads == 0) {
+ LOG_WARN("Failed to determine KV num_heads");
+ return std::nullopt;
+ }
+
+ if (context_size == 0) {
+ LOG_WARN("Failed to determine context_size");
+ return std::nullopt;
+ }
+
+ // ========================================================================
+ // Step 5: Create tile models using query_size as tile_size
+ // ========================================================================
+ LOG_INFO("Creating HFA tile models with tile_size=" << query_size);
+ auto tile_model = create_hfa_tile_model(q_shape_static, dtype, mask_dtype, query_size, kv_num_heads, false);
+ if (!tile_model) {
+ LOG_WARN("Failed to create HFA tile model");
+ return std::nullopt;
+ }
+
+ auto final_tile_model =
+ create_hfa_tile_model(q_shape_static, dtype, mask_dtype, query_size, kv_num_heads, true, output_dtype);
+ if (!final_tile_model) {
+ LOG_WARN("Failed to create HFA final tile model");
+ return std::nullopt;
+ }
+
+ // ========================================================================
+ // Step 6: Create HostFlashAttention structure and set configuration
+ // ========================================================================
+ HostFlashAttention hfa;
+ hfa._tile_model = tile_model;
+ hfa._final_tile_model = final_tile_model;
+ hfa._query_size = query_size;
+ hfa._context_size = context_size;
+ hfa._tile_size = query_size;
+ hfa._k_seq_dim = k_seq_dim;
+ hfa._v_seq_dim = v_seq_dim;
+
+ // ========================================================================
+ // Step 7: Build SDPA parameter index mapping
+ // ========================================================================
+ build_sdpa_param_mapping(hfa, model, pattern_nodes);
+
+ // ========================================================================
+ // Step 8: Build tile model parameter index mapping
+ // ========================================================================
+ build_tile_param_mapping(hfa, tile_model);
+
+ // ========================================================================
+ // Step 9: Build tile model output index mapping
+ // ========================================================================
+ build_tile_output_mapping(hfa, tile_model);
+
+ LOG_INFO("Successfully created HostFlashAttention with query_size="
+ << query_size << ", context_size=" << context_size << ", tile_size=" << query_size);
+
+ return hfa;
+}
+
+} // namespace function
+
+namespace compiled {
+
+// Constructor implementation - extracts metadata
+HostFlashAttention::HostFlashAttention(const function::HostFlashAttention& func_hfa) {
+ LOG_INFO("Constructing compiled::HostFlashAttention");
+ LOG_BLOCK();
+
+ // Extract tile configuration from function HFA
+ _tile_size = func_hfa._tile_size;
+
+ // Store the tile models for later compilation
+ _tile_model_to_compile = func_hfa._tile_model;
+ _final_tile_model_to_compile = func_hfa._final_tile_model;
+
+ // Copy query size, context size, and K/V sequence dimensions from function HFA
+ _sdpa_attention_info._query_size = func_hfa._query_size;
+ _sdpa_attention_info._context_size = func_hfa._context_size;
+ _sdpa_attention_info._k_seq_dim = func_hfa._k_seq_dim;
+ _sdpa_attention_info._v_seq_dim = func_hfa._v_seq_dim;
+
+ // Pre-cache all indices from function HFA maps
+ LOG_INFO("Pre-caching SDPA and tile indices...");
+
+ // Pre-cache SDPA parameter indices
+ auto get_sdpa_param_idx = [&](SDPAInputId input_id) -> std::size_t {
+ auto it = func_hfa._sdpa_param_index_map.find(input_id);
+ if (it == func_hfa._sdpa_param_index_map.end()) {
+ OPENVINO_THROW("HFA: SDPA parameter mapping not found for input ID: ", static_cast<uint8_t>(input_id));
+ }
+ return it->second;
+ };
+
+ _sdpa_attention_info._sdpa_indices.query = get_sdpa_param_idx(SDPAInputId::QUERY);
+ _sdpa_attention_info._sdpa_indices.past_key = get_sdpa_param_idx(SDPAInputId::PAST_KEY);
+ _sdpa_attention_info._sdpa_indices.past_value = get_sdpa_param_idx(SDPAInputId::PAST_VALUE);
+ _sdpa_attention_info._sdpa_indices.present_key = get_sdpa_param_idx(SDPAInputId::PRESENT_KEY);
+ _sdpa_attention_info._sdpa_indices.present_value = get_sdpa_param_idx(SDPAInputId::PRESENT_VALUE);
+ _sdpa_attention_info._sdpa_indices.attention_mask = get_sdpa_param_idx(SDPAInputId::ATTENTION_MASK);
+
+ // Pre-cache tile input indices
+ auto get_tile_input_idx = [&](HFATileInputId input_id) -> std::size_t {
+ auto it = func_hfa._tile_param_index_map.find(input_id);
+ if (it == func_hfa._tile_param_index_map.end()) {
+ OPENVINO_THROW("HFA: Tile input mapping not found for input ID: ", static_cast<uint8_t>(input_id));
+ }
+ return it->second;
+ };
+
+ auto get_tile_output_idx = [&](HFATileOutputId output_id) -> std::size_t {
+ auto it = func_hfa._tile_output_index_map.find(output_id);
+ if (it == func_hfa._tile_output_index_map.end()) {
+ OPENVINO_THROW("HFA: Tile output mapping not found for output ID: ", static_cast<uint8_t>(output_id));
+ }
+ return it->second;
+ };
+
+ // Cache all tile input indices
+ _sdpa_attention_info._tile_input_indices.q = get_tile_input_idx(HFATileInputId::Q);
+ _sdpa_attention_info._tile_input_indices.k = get_tile_input_idx(HFATileInputId::K_TILE);
+ _sdpa_attention_info._tile_input_indices.v = get_tile_input_idx(HFATileInputId::V_TILE);
+ _sdpa_attention_info._tile_input_indices.mask = get_tile_input_idx(HFATileInputId::MASK_TILE);
+ _sdpa_attention_info._tile_input_indices.acc = get_tile_input_idx(HFATileInputId::PAST_ACC);
+ _sdpa_attention_info._tile_input_indices.max = get_tile_input_idx(HFATileInputId::PAST_MAX);
+ _sdpa_attention_info._tile_input_indices.d = get_tile_input_idx(HFATileInputId::PAST_D);
+
+ // Cache all tile output indices
+ _sdpa_attention_info._tile_output_indices.acc = get_tile_output_idx(HFATileOutputId::ACC);
+ _sdpa_attention_info._tile_output_indices.max = get_tile_output_idx(HFATileOutputId::MAXX);
+ _sdpa_attention_info._tile_output_indices.d = get_tile_output_idx(HFATileOutputId::D);
+
+ LOG_INFO("Pre-cached SDPA indices: [query="
+ << _sdpa_attention_info._sdpa_indices.query << ", past_key=" << _sdpa_attention_info._sdpa_indices.past_key
+ << ", past_value=" << _sdpa_attention_info._sdpa_indices.past_value
+ << ", present_key=" << _sdpa_attention_info._sdpa_indices.present_key
+ << ", present_value=" << _sdpa_attention_info._sdpa_indices.present_value
+ << ", attention_mask=" << _sdpa_attention_info._sdpa_indices.attention_mask << "]");
+ LOG_INFO("Attention configuration: query_size="
+ << _sdpa_attention_info._query_size << ", context_size=" << _sdpa_attention_info._context_size
+ << ", k_seq_dim=" << _sdpa_attention_info._k_seq_dim << ", v_seq_dim=" << _sdpa_attention_info._v_seq_dim);
+ LOG_INFO("Pre-cached tile indices: inputs[q=" << _sdpa_attention_info._tile_input_indices.q
+ << ", k=" << _sdpa_attention_info._tile_input_indices.k
+ << ", v=" << _sdpa_attention_info._tile_input_indices.v
+ << ", mask=" << _sdpa_attention_info._tile_input_indices.mask
+ << ", acc=" << _sdpa_attention_info._tile_input_indices.acc
+ << ", max=" << _sdpa_attention_info._tile_input_indices.max
+ << ", d=" << _sdpa_attention_info._tile_input_indices.d
+ << "], outputs[acc=" << _sdpa_attention_info._tile_output_indices.acc
+ << ", max=" << _sdpa_attention_info._tile_output_indices.max
+ << ", d=" << _sdpa_attention_info._tile_output_indices.d << "]");
+
+ // Note: _compiled_tile_model and _compiled_final_tile_model will be set later by
+ // compile_host_flash_attention_model()
+}
+} // namespace compiled
+
+namespace runtime {
+namespace host_flash_attention {
+
+// PositionIDs constructor
+PositionIDs::PositionIDs(std::size_t param_idx, std::size_t query_size, const ov::ISyncInferRequest& rq)
+ : _position_ids_idx(param_idx),
+ _query_size(query_size),
+ _rq(rq) {
+ // FIXME: speculative decode is indistinguishable at this point!
+ _case = _query_size == 1 ? Case::GENERATE : Case::PREFILL;
+}
+
+Selector::Ptr PositionIDs::find(std::size_t query_size, 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, query_size, rq)};
+ }
+ return Selector::Ptr{};
+}
+
+void PositionIDs::prepare(int64_t past_len) {
+ const auto& iport = _rq.get().get_compiled_model()->inputs()[_position_ids_idx];
+ const auto in_tensor = _rq.get().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
+ _current_length = pos_data_ptr[idx];
+ switch (_case) {
+ case Case::GENERATE:
+ // decode case, we have pos_id-1 past elements to take from kvcache
+ _past_length = _current_length;
+ break;
+ case Case::PREFILL:
+ // chunked prefill case. calculate the past_length in full chunks
+ // FIXME: We know too much about chunking here
+ _past_length = ((past_len + _query_size - 1) / _query_size) * _query_size;
+ break;
+ default:
+ NPUW_ASSERT(false && "Reached the unreachable code");
+ }
+ return;
+ }
+ }
+ LOG_WARN("Dynamic selector - no data found in the feature?");
+ _current_length = -1;
+}
+
+int64_t PositionIDs::context_length() const {
+ return _query_size + _past_length;
+}
+
+// ============================================================================
+// HFARuntimeContext Implementation
+// ============================================================================
+
+void HFARuntimeContext::reset() {
+ m_mask_tile_cache.clear();
+ m_mask_tile_buffers.clear();
+ m_state_buffers.reset();
+ m_current_buffer_idx = 0;
+}
+
+ov::SoPtr<ov::ITensor> HFARuntimeContext::find_cached_mask_tile(const ov::SoPtr<ov::ITensor>& mask_tensor,
+ int64_t mask_offset,
+ int64_t tile_length) const {
+ HFATileMaskKey cache_key{mask_tensor, mask_offset, tile_length};
+ auto it = m_mask_tile_cache.find(cache_key);
+ if (it != m_mask_tile_cache.end()) {
+ return it->second;
+ }
+ return {};
+}
+
+ov::SoPtr<ov::ITensor> HFARuntimeContext::get_mask_tile_buffer(size_t index) const {
+ if (index >= m_mask_tile_buffers.size()) {
+ throw std::out_of_range("HFA: mask tile buffer index " + std::to_string(index) + " out of range [0, " +
+ std::to_string(m_mask_tile_buffers.size()) + ")");
+ }
+ return m_mask_tile_buffers[index];
+}
+
+void HFARuntimeContext::cache_mask_tile(const ov::SoPtr<ov::ITensor>& mask_tensor,
+ int64_t mask_offset,
+ int64_t tile_length,
+ const ov::SoPtr<ov::ITensor>& cached_tile) {
+ HFATileMaskKey cache_key{mask_tensor, mask_offset, tile_length};
+ m_mask_tile_cache[cache_key] = cached_tile;
+}
+
+void HFARuntimeContext::clear_mask_cache() {
+ m_mask_tile_cache.clear();
+}
+
+void HFARuntimeContext::initialize_state_tensors(ov::SoPtr<ov::ITensor>& acc,
+ ov::SoPtr<ov::ITensor>& max,
+ ov::SoPtr<ov::ITensor>& sum) {
+ const auto type = acc->get_element_type();
+ if (type == ov::element::f16) {
+ std::memset(acc->data<ov::float16>(), 0, acc->get_byte_size());
+ std::fill_n(max->data<ov::float16>(), max->get_size(), std::numeric_limits<ov::float16>::lowest());
+ std::memset(sum->data<ov::float16>(), 0, sum->get_byte_size());
+ } else if (type == ov::element::f32) {
+ std::memset(acc->data<float>(), 0, acc->get_byte_size());
+ std::fill_n(max->data<float>(), max->get_size(), std::numeric_limits<float>::lowest());
+ std::memset(sum->data<float>(), 0, sum->get_byte_size());
+ } else {
+ throw std::runtime_error("HFA: Unsupported state tensor type");
+ }
+}
+
+void HFARuntimeContext::prepare_next_state_buffers() {
+ if (!m_state_buffers.has_value()) {
+ return;
+ }
+ size_t next_idx = 1 - m_current_buffer_idx;
+ auto& next_buffer = (*m_state_buffers)[next_idx];
+ initialize_state_tensors(next_buffer.acc, next_buffer.max, next_buffer.sum);
+}
+
+void HFARuntimeContext::switch_buffers() {
+ if (m_state_buffers.has_value()) {
+ m_current_buffer_idx = 1 - m_current_buffer_idx;
+ }
+}
+
+} // namespace host_flash_attention
+} // namespace runtime
+
+} // namespace npuw
+} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.hpp b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.hpp
new file mode 100644
index 00000000000..48febe31a44
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.hpp
@@ -0,0 +1,500 @@
+// Copyright (C) 2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#pragma once
+
+#include <map>
+#include <memory>
+#include <optional>
+
+#include "openvino/core/except.hpp"
+#include "openvino/openvino.hpp"
+#include "openvino/runtime/isync_infer_request.hpp"
+#include "openvino/runtime/itensor.hpp"
+#include "openvino/runtime/so_ptr.hpp"
+
+namespace ov {
+namespace npuw {
+
+// SDPA (Scaled Dot-Product Attention) input tensor identifiers
+// Represents the standardized input layout for SDPA operations
+// Defined at namespace level for use in both function and compiled namespaces
+enum class SDPAInputId : uint8_t {
+ PAST_KEY = 0, // Historical key cache tensor
+ PAST_VALUE = 1, // Historical value cache tensor
+ QUERY = 2, // Query tensor for current iteration
+ PRESENT_KEY = 3, // Current key tensor (new tokens)
+ ATTENTION_MASK = 4, // Attention mask tensor
+ PRESENT_VALUE = 5, // Current value tensor (new tokens)
+
+ // Sentinel value for enum range
+ COUNT
+};
+
+// HFA Tile Model input tensor identifiers
+// Represents the input layout for Host Flash Attention tile models
+// Input names: [past_acc, past_max, past_d, k_tile, v_tile, q, mask_tile]
+enum class HFATileInputId : uint8_t {
+ PAST_ACC = 0, // Accumulated attention output from previous tiles
+ PAST_MAX = 1, // Maximum values from previous tiles (for numerical stability)
+ PAST_D = 2, // Normalization denominator from previous tiles
+ K_TILE = 3, // Current K (key) tile slice
+ V_TILE = 4, // Current V (value) tile slice
+ Q = 5, // Query tensor (full, not tiled)
+ MASK_TILE = 6, // Current attention mask tile slice
+
+ // Sentinel value for enum range
+ COUNT
+};
+
+// HFA Regular Tile Model output tensor identifiers
+// Represents the output layout for regular (non-final) tile models
+// Output names: [acc, maxx, d]
+enum class HFATileOutputId : uint8_t {
+ ACC = 0, // Accumulated attention output
+ MAXX = 1, // Maximum values for numerical stability
+ D = 2, // Normalization denominator
+
+ // Sentinel value for enum range
+ COUNT
+};
+
+// Helper functions to convert enum values to string representations for logging/debugging
+inline const char* sdpa_input_id_to_string(SDPAInputId id) {
+ switch (id) {
+ case SDPAInputId::PAST_KEY:
+ return "PAST_KEY";
+ case SDPAInputId::PAST_VALUE:
+ return "PAST_VALUE";
+ case SDPAInputId::QUERY:
+ return "QUERY";
+ case SDPAInputId::PRESENT_KEY:
+ return "PRESENT_KEY";
+ case SDPAInputId::ATTENTION_MASK:
+ return "ATTENTION_MASK";
+ case SDPAInputId::PRESENT_VALUE:
+ return "PRESENT_VALUE";
+ default:
+ return "UNKNOWN";
+ }
+}
+
+inline const char* hfa_tile_input_id_to_string(HFATileInputId id) {
+ switch (id) {
+ case HFATileInputId::PAST_ACC:
+ return "PAST_ACC";
+ case HFATileInputId::PAST_MAX:
+ return "PAST_MAX";
+ case HFATileInputId::PAST_D:
+ return "PAST_D";
+ case HFATileInputId::K_TILE:
+ return "K_TILE";
+ case HFATileInputId::V_TILE:
+ return "V_TILE";
+ case HFATileInputId::Q:
+ return "Q";
+ case HFATileInputId::MASK_TILE:
+ return "MASK_TILE";
+ default:
+ return "UNKNOWN";
+ }
+}
+
+inline const char* hfa_tile_output_id_to_string(HFATileOutputId id) {
+ switch (id) {
+ case HFATileOutputId::ACC:
+ return "ACC";
+ case HFATileOutputId::MAXX:
+ return "MAXX";
+ case HFATileOutputId::D:
+ return "D";
+ default:
+ return "UNKNOWN";
+ }
+}
+
+namespace function {
+
+// HostFlashAttention structure definition
+struct HostFlashAttention {
+ // Tiled model for flash attention execution (regular tiles)
+ std::shared_ptr<ov::Model> _tile_model;
+
+ // Final tiled model for flash attention execution (with division and transpose)
+ std::shared_ptr<ov::Model> _final_tile_model;
+
+ // Tile configuration
+ int64_t _tile_size = 0; // K/V tile size for flash attention chunking
+
+ // Query sequence length (extracted from Q shape[2])
+ // Used for selector compatibility and runtime decision-making
+ std::size_t _query_size = 0;
+
+ // Context size (extracted from K concat output shape - kv_cache_size dimension)
+ // Represents the total KV cache length available for attention computation
+ std::size_t _context_size = 0;
+
+ // Sequence dimension indices for K and V tensors
+ // These indicate which dimension is the sequence/cache dimension in past_key and past_value tensors
+ // Extracted from Concat operations in the SDPA pattern
+ std::size_t _k_seq_dim = 0;
+ std::size_t _v_seq_dim = 0;
+
+ // SDPA model parameter index mapping
+ // Maps semantic SDPA parameter IDs (QUERY, PAST_KEY, etc.) to actual parameter indices
+ // This is created during pattern analysis in from() method
+ std::map<SDPAInputId, std::size_t> _sdpa_param_index_map;
+
+ // Tile model parameter index mapping
+ // Maps tile parameter IDs (PAST_ACC, K_TILE, Q, etc.) to actual input indices
+ // Tile model I/O: Inputs[past_acc, past_max, past_d, k_tile, v_tile, q, mask_tile]
+ // Outputs[acc, max, d] for regular tiles or [output] for final tile
+ // This is created after tile model generation in from() method
+ std::map<HFATileInputId, std::size_t> _tile_param_index_map;
+
+ // Tile model output index mapping
+ // Maps tile output IDs (UPDATED_ACC, UPDATED_MAX, UPDATED_D) to actual output indices
+ // Only applicable to regular tile model (final tile has single output at index 0)
+ // This is created after tile model generation in from() method
+ std::map<HFATileOutputId, std::size_t> _tile_output_index_map;
+
+ // Validation helpers
+ bool is_valid() const {
+ return _tile_model != nullptr && _final_tile_model != nullptr && _tile_size > 0;
+ }
+
+ // Factory method
+ static std::optional<HostFlashAttention> from(const std::shared_ptr<ov::Model>& model);
+};
+
+} // namespace function
+
+namespace compiled {
+
+// Simplified host flash attention parameter info
+// Contains parameter indices from the original SDPA model
+struct HostFlashAttentionInfo {
+ std::size_t _query_size = 0u; // query size for selector compatibility
+ std::size_t _context_size = 0u;
+
+ // Sequence dimension indices for K and V tensors in the original SDPA model
+ // These indicate which dimension is the sequence/cache dimension in past_key and past_value tensors
+ // Copied from function::HostFlashAttention::_k_seq_dim and _v_seq_dim
+ std::size_t _k_seq_dim = 0u;
+ std::size_t _v_seq_dim = 0u;
+
+ // NOTE: SDPA parameter map is not stored to save memory.
+ // Indices are pre-cached below during compilation.
+
+ // Pre-cached SDPA parameter indices
+ struct {
+ std::size_t query = 0u;
+ std::size_t past_key = 0u;
+ std::size_t past_value = 0u;
+ std::size_t present_key = 0u;
+ std::size_t present_value = 0u;
+ std::size_t attention_mask = 0u;
+ } _sdpa_indices;
+
+ // Pre-cached tile input indices
+ struct {
+ std::size_t q = 0u;
+ std::size_t k = 0u;
+ std::size_t v = 0u;
+ std::size_t mask = 0u;
+ std::size_t acc = 0u;
+ std::size_t max = 0u;
+ std::size_t d = 0u;
+ } _tile_input_indices;
+
+ // Pre-cached tile output indices
+ struct {
+ std::size_t acc = 0u;
+ std::size_t max = 0u;
+ std::size_t d = 0u;
+ } _tile_output_indices;
+};
+
+// Compile-time host flash attention information
+struct HostFlashAttention {
+ // Models to compile (will be cleared after compilation)
+ std::shared_ptr<ov::Model> _tile_model_to_compile;
+ std::shared_ptr<ov::Model> _final_tile_model_to_compile;
+
+ // Compiled tile model for NPU execution (regular tiles)
+ ov::SoPtr<ov::ICompiledModel> _compiled_tile_model;
+
+ // Compiled FINAL tile model for NPU execution (with division and transpose)
+ ov::SoPtr<ov::ICompiledModel> _compiled_final_tile_model;
+
+ // Attention parameter info from original SDPA model (not from tile models)
+ HostFlashAttentionInfo _sdpa_attention_info;
+
+ // Tile configuration
+ int64_t _tile_size = 0;
+
+ HostFlashAttention() = default;
+
+ // Constructor that extracts metadata
+ explicit HostFlashAttention(const function::HostFlashAttention& func_hfa);
+
+ // Set the compiled tile model and clear the model to compile
+ void set_compiled_tile_model(ov::SoPtr<ov::ICompiledModel> compiled_model) {
+ _compiled_tile_model = std::move(compiled_model);
+ _tile_model_to_compile.reset(); // Free memory after compilation
+ }
+
+ // Set the compiled FINAL tile model and clear the model to compile
+ void set_compiled_final_tile_model(ov::SoPtr<ov::ICompiledModel> compiled_model) {
+ _compiled_final_tile_model = std::move(compiled_model);
+ _final_tile_model_to_compile.reset(); // Free memory after compilation
+ }
+
+ bool is_valid() const {
+ return _compiled_tile_model != nullptr && _compiled_final_tile_model != nullptr && _tile_size > 0;
+ }
+};
+
+} // namespace compiled
+
+namespace runtime {
+namespace host_flash_attention {
+
+// Key for HFA tiled attention mask cache
+struct HFATileMaskKey {
+ ov::SoPtr<ov::ITensor> mask_tensor; // Original mask tensor
+ int64_t mask_offset; // Offset in the mask sequence dimension
+ int64_t tile_length; // Length of the tile
+
+ bool operator<(const HFATileMaskKey& other) const {
+ if (mask_tensor._ptr != other.mask_tensor._ptr)
+ return mask_tensor._ptr < other.mask_tensor._ptr;
+ if (mask_offset != other.mask_offset)
+ return mask_offset < other.mask_offset;
+ return tile_length < other.tile_length;
+ }
+};
+
+/// HFA runtime context - manages cache and buffers for tiled attention.
+/// @warning NOT thread-safe. Each inference request must have its own instance.
+struct HFARuntimeContext {
+ // ============================================================================
+ // Type Aliases
+ // ============================================================================
+
+ /// Memory allocator: (type, shape, device) -> tensor
+ using AllocatorFn =
+ std::function<ov::SoPtr<ov::ITensor>(const ov::element::Type&, const ov::Shape&, const std::string&)>;
+
+ /// State tensors for accumulation: acc, max, sum
+ struct StateBuffers {
+ ov::SoPtr<ov::ITensor> acc; // Accumulated output
+ ov::SoPtr<ov::ITensor> max; // Max values for stability
+ ov::SoPtr<ov::ITensor> sum; // Normalization denominator
+ };
+
+ // ============================================================================
+ // Mask Cache Optimization
+ // ============================================================================
+
+ /// Cached mask tiles: (tensor, offset, length) -> tile
+ std::map<HFATileMaskKey, ov::SoPtr<ov::ITensor>> m_mask_tile_cache;
+
+ /// Pre-allocated buffers for mask extraction on cache miss
+ std::vector<ov::SoPtr<ov::ITensor>> m_mask_tile_buffers;
+
+ // ============================================================================
+ // State Double-Buffering Optimization
+ // ============================================================================
+
+ /// Two state buffers: [current, next] (swap after each inference)
+ std::optional<std::array<StateBuffers, 2>> m_state_buffers;
+
+ /// Current active buffer index (0 or 1)
+ size_t m_current_buffer_idx = 0;
+
+ // ============================================================================
+ // Initialization
+ // ============================================================================
+
+ /// Initialize mask cache: allocate `context_size / query_size` temporary buffers.
+ /// Call once during setup before inference.
+ /// @throws std::runtime_error if context_size not divisible by query_size
+ template <typename HFADesc>
+ void initialize_mask_cache(const HFADesc& hfa_desc, const std::string& device_name, AllocatorFn allocator) {
+ // Get mask tensor shape from the tile model
+ const size_t mask_input_idx = hfa_desc._sdpa_attention_info._tile_input_indices.mask;
+ const auto& mask_port = hfa_desc._compiled_tile_model->inputs()[mask_input_idx];
+ const auto mask_shape = mask_port.get_shape();
+ const auto mask_dtype = mask_port.get_element_type();
+
+ // Calculate maximum number of tiles based on context size
+ const size_t context_size = hfa_desc._sdpa_attention_info._context_size;
+ const size_t query_size = hfa_desc._sdpa_attention_info._query_size;
+
+ // Validate configuration
+ if (context_size % query_size != 0) {
+ throw std::runtime_error("HFA: context_size (" + std::to_string(context_size) +
+ ") must be divisible by query_size (" + std::to_string(query_size) + ")");
+ }
+
+ const size_t max_num_tiles = context_size / query_size;
+
+ // Allocate temporary buffers for mask tile extraction
+ m_mask_tile_buffers.clear();
+ m_mask_tile_buffers.reserve(max_num_tiles);
+
+ for (size_t i = 0; i < max_num_tiles; ++i) {
+ auto mask_tile = allocator(mask_dtype, mask_shape, device_name);
+ m_mask_tile_buffers.push_back(mask_tile);
+ }
+ }
+
+ /// Reset all resources (mask cache + state buffers)
+ void reset();
+
+ // ============================================================================
+ // Mask Cache Queries
+ // ============================================================================
+
+ /// Find cached mask tile, returns nullptr if not found
+ ov::SoPtr<ov::ITensor> find_cached_mask_tile(const ov::SoPtr<ov::ITensor>& mask_tensor,
+ int64_t mask_offset,
+ int64_t tile_length) const;
+
+ /// Get temporary buffer for mask extraction (throws if out of bounds)
+ ov::SoPtr<ov::ITensor> get_mask_tile_buffer(size_t index) const;
+
+ /// Number of temporary mask tile buffers
+ size_t num_mask_tile_buffers() const {
+ return m_mask_tile_buffers.size();
+ }
+
+ // ============================================================================
+ // Mask Cache Modifications
+ // ============================================================================
+
+ /// Cache a mask tile (overwrites if key exists)
+ void cache_mask_tile(const ov::SoPtr<ov::ITensor>& mask_tensor,
+ int64_t mask_offset,
+ int64_t tile_length,
+ const ov::SoPtr<ov::ITensor>& cached_tile);
+
+ /// Clear mask cache (keeps buffers allocated)
+ void clear_mask_cache();
+
+ // ============================================================================
+ // State Buffer Initialization
+ // ============================================================================
+
+ /// Initialize double-buffering: buffer[0] = provided, buffer[1] = allocated
+ template <typename HFADesc>
+ void initialize_state_buffers(const StateBuffers& initial_buffers,
+ const HFADesc& hfa_desc,
+ const std::string& device_name,
+ AllocatorFn allocator) {
+ m_state_buffers.emplace();
+ auto& buffers = *m_state_buffers;
+ m_current_buffer_idx = 0;
+
+ // Buffer 0: reuse provided tensors
+ buffers[0] = initial_buffers;
+
+ // Buffer 1: allocate independent tensors
+ const auto dtype = initial_buffers.acc->get_element_type();
+ buffers[1].acc = allocator(dtype, initial_buffers.acc->get_shape(), device_name);
+ buffers[1].max = allocator(dtype, initial_buffers.max->get_shape(), device_name);
+ buffers[1].sum = allocator(dtype, initial_buffers.sum->get_shape(), device_name);
+ }
+
+ // ============================================================================
+ // State Buffer Queries
+ // ============================================================================
+
+ /// Get current state buffers (throws if not initialized)
+ const StateBuffers& get_current_state_buffers() const {
+ if (!m_state_buffers.has_value()) {
+ throw std::runtime_error("HFA: State buffers not initialized");
+ }
+ return (*m_state_buffers)[m_current_buffer_idx];
+ }
+
+ /// Get mutable current state buffers
+ StateBuffers& get_current_state_buffers() {
+ if (!m_state_buffers.has_value()) {
+ throw std::runtime_error("HFA: State buffers not initialized");
+ }
+ return (*m_state_buffers)[m_current_buffer_idx];
+ }
+
+ // ============================================================================
+ // State Buffer Modifications
+ // ============================================================================
+
+ /// Initialize state tensors: acc=0, max=-inf, sum=0 (static utility)
+ static void initialize_state_tensors(ov::SoPtr<ov::ITensor>& acc,
+ ov::SoPtr<ov::ITensor>& max,
+ ov::SoPtr<ov::ITensor>& sum);
+
+ /// Prepare next buffer asynchronously (call during NPU execution)
+ void prepare_next_state_buffers();
+
+ /// Switch to next buffer after inference
+ void switch_buffers();
+
+ /// Check if state buffers initialized
+ bool has_state_buffers() const {
+ return m_state_buffers.has_value();
+ }
+};
+
+// A base class to decide host flash attention execution
+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 context_length() const = 0;
+
+ Case this_case() const {
+ return _case;
+ }
+
+protected:
+ Case _case = Case::UNKNOWN;
+};
+
+// Selector that processes all tiles unconditionally (no dynamic range optimization)
+class All final : public Selector {
+public:
+ void prepare(int64_t past_len) override {}
+
+ int64_t context_length() const override {
+ OPENVINO_NOT_IMPLEMENTED;
+ }
+};
+
+// Define execution selection based on position ids
+class PositionIDs final : public Selector {
+ std::size_t _position_ids_idx = 0u;
+ int64_t _current_length = 0;
+ int64_t _past_length = 0;
+ std::size_t _query_size = 0u;
+
+ std::reference_wrapper<const ov::ISyncInferRequest> _rq;
+
+ PositionIDs(std::size_t param_idx, std::size_t query_size, const ov::ISyncInferRequest& rq);
+ void prepare(int64_t past_len) override;
+ int64_t context_length() const override;
+
+public:
+ static Selector::Ptr find(std::size_t query_size, const ov::ISyncInferRequest& rq);
+};
+
+} // namespace host_flash_attention
+} // namespace runtime
+
+} // namespace npuw
+} // namespace ov
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 d16c62f7a94..9d709b73546 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
@@ -5,13 +5,11 @@
#include "just_sync_infer_request.hpp"
#include <algorithm>
-#include <future>
-#include <map>
#include <memory>
#include <string>
-#include <utility>
#include "compiled_model.hpp"
+#include "host_flash_attention.hpp"
#include "infer_request_utils.hpp" // to utilize copy_tensor_by_dim
#include "logging.hpp"
#include "openvino/core/except.hpp"
@@ -19,7 +17,6 @@
#include "openvino/runtime/iasync_infer_request.hpp"
#include "plugin.hpp"
#include "pyramid_attention.hpp"
-#include "util.hpp"
#include "weights_bank.hpp"
ov::npuw::MemAccessSim::MemAccessSim(const std::shared_ptr<ov::npuw::CompiledModel>& compiled_model) {
@@ -201,6 +198,7 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
m_spatial_io.resize(m_num_submodels);
m_attention_io.resize(m_num_submodels);
+ m_hfa_io.resize(m_num_submodels);
// Create infer requests
// Preallocate funcall tensors & substitute function call requests
@@ -208,8 +206,10 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
bool has_spatial = false;
bool has_dynamic = false;
bool has_pyramid = false;
+ bool has_hfa = false;
std::size_t dynamic_sub_idx = -1;
std::size_t pyramid_sub_idx = -1;
+ std::size_t hfa_sub_idx = -1;
for (size_t i = 0; i < m_num_submodels; i++) {
LOG_INFO("Creating infer request for Subgraph[" << i << "]...");
LOG_BLOCK();
@@ -277,6 +277,19 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
m_attention_io[i].inputs.resize(proto_comp_model_desc.param_base);
} // if(pyramid)
+ if (proto_comp_model_desc.host_flash_attention) {
+ // Sanity check first
+ if (has_hfa && hfa_sub_idx != real_idx) {
+ OPENVINO_THROW("Only single flash attention type is permitted for model");
+ }
+ has_hfa = true;
+ hfa_sub_idx = real_idx;
+ m_hfa_io[i].inputs.resize(proto_comp_model_desc.param_base);
+ const auto num_outputs =
+ proto_comp_model_desc.host_flash_attention.value()._compiled_final_tile_model->outputs().size();
+ m_hfa_io[i].outputs.resize(num_outputs);
+ } // if(hfa)
+
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);
@@ -309,6 +322,13 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
if (proto_comp_model_desc.pyramid_attention) {
setup_pyramid_infer_requests(real_idx, is_piped, false);
}
+ // Create HFA tile infer requests if this function has host flash attention
+ if (proto_comp_model_desc.host_flash_attention) {
+ setup_hfa_infer_requests(real_idx,
+ is_piped,
+ /* is_recreate */ false,
+ /* enable_hfa_optimizations */ true);
+ }
}
LOG_INFO("DONE");
@@ -428,6 +448,18 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com
}
}
}
+
+ if (has_hfa) {
+ const auto& hfa_desc = m_npuw_model->m_compiled_submodels.at(hfa_sub_idx).host_flash_attention.value();
+ const size_t query_size = hfa_desc._sdpa_attention_info._query_size;
+ m_hfa_selector = runtime::host_flash_attention::PositionIDs::find(query_size, *this);
+ if (!m_hfa_selector) {
+ // HFA requires PositionIDs selector - cannot fallback to 'All' like Dynamic/Pyramid
+ // because HFA uses tile-based execution without a full-range infer request
+ OPENVINO_THROW("HFA dynamic capability is enabled, but no run-time features were found.");
+ }
+ LOG_VERB("Done");
+ }
}
void ov::npuw::JustInferRequest::set_tensor(const ov::Output<const ov::Node>& port,
@@ -570,6 +602,14 @@ void ov::npuw::JustInferRequest::prepare_for_infer() {
m_attention_selector->prepare(get_history_size());
}
+ // HFA selector
+ if (m_hfa_selector) {
+ m_hfa_selector->prepare(get_history_size());
+ if (m_hfa_runtime_ctx) {
+ m_hfa_runtime_ctx->clear_mask_cache();
+ }
+ }
+
// FIXME: attention-specific, needs to be moved out after refactoring
m_cached_attention_mask = {};
@@ -637,6 +677,7 @@ 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 bool is_hfa = func_desc.host_flash_attention.has_value();
// Generalized: check if input is neither param nor mask
auto is_non_param_mask = [](const auto& info, std::size_t in_idx) {
@@ -693,6 +734,9 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {
} else {
m_attention_io[idx].inputs.at(i) = i_tensor;
}
+ } else if (is_hfa) {
+ // Host Flash Attention case - defer, use dedicated HFA I/O structure
+ m_hfa_io[idx].inputs.at(i) = i_tensor;
} else {
// Default case
m_subrequests[real_idx]->set_tensor(iport, i_tensor);
@@ -731,7 +775,10 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {
LOG_DEBUG("Binding result[" << i << "]...");
auto& oport = func_desc.compiled_model->outputs()[i];
auto o_tensor = m_funcall_result.at({idx, i});
- if (!is_spatial) {
+ if (is_hfa) {
+ // HFA case - defer, store in dedicated HFA I/O structure
+ m_hfa_io[idx].outputs.at(i) = o_tensor;
+ } else if (!is_spatial) {
// Non-spatial case - set immediately
m_subrequests[real_idx]->set_tensor(oport, o_tensor);
} else {
@@ -931,6 +978,10 @@ void ov::npuw::JustInferRequest::recreate_subrequests(std::size_t idx) {
if (proto_comp_model_desc.pyramid_attention) {
setup_pyramid_infer_requests(real_idx, is_piped, true);
}
+ // Recreate HFA tile infer requests if this function has host flash attention
+ if (proto_comp_model_desc.host_flash_attention) {
+ setup_hfa_infer_requests(real_idx, is_piped, /* is_recreate */ true, /* enable_hfa_optimizations */ true);
+ }
}
// After an infer request is recreated, the internal cross-request
@@ -1027,6 +1078,153 @@ void ov::npuw::JustInferRequest::setup_pyramid_infer_requests(std::size_t real_i
}
}
+void ov::npuw::JustInferRequest::setup_hfa_infer_requests(std::size_t real_idx,
+ bool is_piped,
+ bool is_recreate,
+ bool enable_hfa_optimizations) {
+ auto& submodel_desc = m_npuw_model->m_compiled_submodels[real_idx];
+ if (!submodel_desc.host_flash_attention.has_value()) {
+ return;
+ }
+
+ LOG_INFO((is_recreate ? "Recreating" : "Creating") << " HFA tile infer requests...");
+ LOG_BLOCK();
+
+ const auto& hfa = submodel_desc.host_flash_attention.value();
+
+ // Clear existing requests if recreating
+ if (is_recreate) {
+ submodel_desc.hfa_infer_requests.clear();
+ submodel_desc.hfa_pipeline_requests.clear();
+ }
+
+ // Allocate storage for infer requests: [REGULAR_TILE] and [FINAL_TILE]
+ submodel_desc.hfa_infer_requests.resize(CompiledModel::CompiledModelDesc::HFATileIdx::COUNT);
+ if (is_piped) {
+ submodel_desc.hfa_pipeline_requests.resize(CompiledModel::CompiledModelDesc::HFATileIdx::COUNT);
+ }
+
+ // Create infer request for regular tile model
+ try {
+ LOG_INFO("Creating infer request for HFA regular tile model...");
+ submodel_desc.hfa_infer_requests[CompiledModel::CompiledModelDesc::HFATileIdx::REGULAR_TILE] =
+ hfa._compiled_tile_model->create_infer_request();
+ if (is_piped) {
+ submodel_desc.hfa_pipeline_requests[CompiledModel::CompiledModelDesc::HFATileIdx::REGULAR_TILE] =
+ hfa._compiled_tile_model->create_infer_request();
+ }
+ } catch (const std::exception& ex) {
+ LOG_ERROR("Failed to " << (is_recreate ? "recreate" : "create")
+ << " infer request for HFA regular tile model: " << ex.what());
+ OPENVINO_THROW("HFA regular tile model infer request creation failed: ", ex.what());
+ } catch (...) {
+ LOG_ERROR("Failed to " << (is_recreate ? "recreate" : "create")
+ << " infer request for HFA regular tile model: Unknown error");
+ OPENVINO_THROW("HFA regular tile model infer request creation failed with unknown error");
+ }
+
+ // For final tile model, reuse the main compiled_model's infer request
+ // because compiled_model points to _compiled_final_tile_model for HFA
+ LOG_INFO("Reusing " << (is_recreate ? "recreated " : "") << "main infer request for HFA final tile model");
+ submodel_desc.hfa_infer_requests[CompiledModel::CompiledModelDesc::HFATileIdx::FINAL_TILE] =
+ m_subrequests[real_idx];
+ if (is_piped) {
+ submodel_desc.hfa_pipeline_requests[CompiledModel::CompiledModelDesc::HFATileIdx::FINAL_TILE] =
+ m_funcall_pipeline[real_idx].subrequest;
+ }
+
+ // Share input tensors between HFA tile models and main infer request
+ // Note: Both tile models have the same input structure
+ const size_t num_inputs = hfa._compiled_tile_model->inputs().size();
+ for (size_t input_idx = 0; input_idx < num_inputs; ++input_idx) {
+ auto tile_input = hfa._compiled_tile_model->inputs()[input_idx];
+ auto final_tile_input = hfa._compiled_final_tile_model->inputs()[input_idx];
+
+ // Directly share tensor from main infer request to regular tile request
+ auto main_tensor = m_subrequests[real_idx]->get_tensor(final_tile_input);
+ submodel_desc.hfa_infer_requests[CompiledModel::CompiledModelDesc::HFATileIdx::REGULAR_TILE]->set_tensor(
+ tile_input,
+ main_tensor);
+
+ // Repeat for pipeline infer request if pipelined
+ if (is_piped) {
+ auto pipeline_tensor = m_funcall_pipeline[real_idx].subrequest->get_tensor(final_tile_input);
+ submodel_desc.hfa_pipeline_requests[CompiledModel::CompiledModelDesc::HFATileIdx::REGULAR_TILE]->set_tensor(
+ tile_input,
+ pipeline_tensor);
+ }
+ }
+
+ LOG_INFO("Successfully " << (is_recreate ? "recreated" : "created")
+ << " HFA tile infer requests with shared input tensors");
+
+ // Initialize HFA optimizations (mask cache + state double-buffering) if enabled
+ if (enable_hfa_optimizations) {
+ LOG_INFO("HFA optimizations are ENABLED (mask cache + state double-buffering)");
+
+ // Initialize runtime context if needed
+ if (!m_hfa_runtime_ctx) {
+ m_hfa_runtime_ctx.emplace();
+ }
+
+ if (is_recreate) {
+ m_hfa_runtime_ctx->reset();
+ }
+
+ LOG_INFO("Pre-allocating HFA mask tile buffers...");
+
+ // Initialize pre-allocated buffers
+ m_hfa_runtime_ctx->initialize_mask_cache(
+ hfa,
+ *submodel_desc.device_it,
+ [this](const ov::element::Type& dtype, const ov::Shape& shape, const std::string& device) {
+ return allocMem(dtype, shape, device);
+ });
+
+ LOG_INFO("Pre-allocated " << m_hfa_runtime_ctx->num_mask_tile_buffers() << " mask tile buffer(s)");
+
+ // Initialize state buffers and double-buffering for first inference
+ LOG_INFO("Initializing HFA state tensors and double-buffering...");
+
+ // Get pre-cached indices
+ const auto& tile_in = hfa._sdpa_attention_info._tile_input_indices;
+
+ // Get state tensors from regular tile request
+ auto state_acc =
+ submodel_desc.hfa_infer_requests[CompiledModel::CompiledModelDesc::HFATileIdx::REGULAR_TILE]->get_tensor(
+ hfa._compiled_tile_model->inputs()[tile_in.acc]);
+ auto state_max =
+ submodel_desc.hfa_infer_requests[CompiledModel::CompiledModelDesc::HFATileIdx::REGULAR_TILE]->get_tensor(
+ hfa._compiled_tile_model->inputs()[tile_in.max]);
+ auto state_sum =
+ submodel_desc.hfa_infer_requests[CompiledModel::CompiledModelDesc::HFATileIdx::REGULAR_TILE]->get_tensor(
+ hfa._compiled_tile_model->inputs()[tile_in.d]);
+
+ // Initialize state tensors with zeros/minus infinity
+ runtime::host_flash_attention::HFARuntimeContext::initialize_state_tensors(state_acc, state_max, state_sum);
+
+ // Setup double-buffering with initialized state
+ runtime::host_flash_attention::HFARuntimeContext::StateBuffers initial_buffers{state_acc, state_max, state_sum};
+
+ m_hfa_runtime_ctx->initialize_state_buffers(
+ initial_buffers,
+ hfa,
+ *submodel_desc.device_it,
+ [this](const ov::element::Type& dtype, const ov::Shape& shape, const std::string& device) {
+ return allocMem(dtype, shape, device);
+ });
+
+ LOG_INFO("HFA state tensors and double-buffering initialized successfully");
+ } else {
+ LOG_INFO("HFA optimizations are DISABLED - will extract mask tiles on-the-fly without state caching");
+
+ // Clear runtime context if it exists
+ if (m_hfa_runtime_ctx) {
+ m_hfa_runtime_ctx.reset();
+ }
+ }
+}
+
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];
@@ -1108,7 +1306,8 @@ void ov::npuw::JustInferRequest::run_subrequest_for_success(std::size_t idx, boo
void ov::npuw::JustInferRequest::unsafe_during(std::size_t real_idx, std::size_t idx, const std::function<void()>& f) {
auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];
- if (!comp_model_desc.spatial) {
+
+ if (!comp_model_desc.spatial && !comp_model_desc.host_flash_attention.has_value()) {
// Normal: trigger request asynchronously, run `f` in this context
// FIXME: dynamic could hit here too, but it has special logic
// around execution which makes it harder to run than a plain start_async()
@@ -1117,14 +1316,359 @@ void ov::npuw::JustInferRequest::unsafe_during(std::size_t real_idx, std::size_t
f(); // expect noexcept
r->wait();
} else {
- // Spatial... Do the opposite - run f
- // asynchronously, and meanwhile run the spatial inference
+ // Spatial or HFA: Run f asynchronously while executing spatial/HFA inference
auto future = std::async(std::launch::async, f);
unsafe_infer(real_idx, idx);
future.wait();
}
}
+// ====================================================================================================
+// Host Flash Attention (HFA) Helper Functions
+// ====================================================================================================
+
+// Extract tile slice with optional type conversion
+void ov::npuw::JustInferRequest::hfa_extract_and_copy_tile(const ov::SoPtr<ov::ITensor>& source_tensor,
+ const ov::SoPtr<ov::ITensor>& dest_tensor,
+ uint32_t sequence_dim,
+ int64_t sequence_offset,
+ int64_t sequence_length,
+ const std::string& tensor_name) {
+ if (!dest_tensor->is_continuous()) {
+ OPENVINO_THROW("HFA tile extraction error: destination tensor for '",
+ tensor_name,
+ "' is not continuous - cannot perform direct copy");
+ }
+
+ auto source_view = ov::npuw::util::view(source_tensor, sequence_dim, sequence_offset, sequence_length);
+ const auto dest_type = dest_tensor->get_element_type();
+ const auto source_type = source_tensor->get_element_type();
+
+ if (dest_type == source_type) {
+ ov::npuw::util::copy_tensor_by_dim(source_view, dest_tensor, sequence_dim, sequence_dim);
+ } else {
+ LOG_WARN("Performing type conversion for " << tensor_name << " tile: " << source_type << " -> " << dest_type);
+
+ // Copy to intermediate buffer first
+ auto intermediate_tensor = ov::Tensor(source_type, source_view->get_shape());
+ ov::npuw::util::copy_tensor_by_dim(source_view,
+ ov::get_tensor_impl(intermediate_tensor),
+ sequence_dim,
+ sequence_dim);
+
+ // Convert element-by-element
+ const size_t total_elements = intermediate_tensor.get_size();
+ if (dest_type == ov::element::f32 && source_type == ov::element::f16) {
+ // FP16 -> FP32 conversion
+ auto src_data = intermediate_tensor.data<ov::float16>();
+ auto dst_data = dest_tensor->data<float>();
+ for (size_t i = 0; i < total_elements; ++i) {
+ dst_data[i] = static_cast<float>(src_data[i]);
+ }
+ } else if (dest_type == ov::element::f16 && source_type == ov::element::f32) {
+ // FP32 -> FP16 conversion
+ auto src_data = intermediate_tensor.data<float>();
+ auto dst_data = dest_tensor->data<ov::float16>();
+ for (size_t i = 0; i < total_elements; ++i) {
+ dst_data[i] = static_cast<ov::float16>(src_data[i]);
+ }
+ } else {
+ OPENVINO_THROW("Unsupported type conversion for ", tensor_name, " tile: ", source_type, " -> ", dest_type);
+ }
+ }
+}
+
+// Check if tensor can be reused directly (zero-copy optimization)
+bool ov::npuw::JustInferRequest::hfa_can_reuse_tensor_zero_copy(const ov::SoPtr<ov::ITensor>& source_tensor,
+ const ov::SoPtr<ov::ITensor>& dest_tensor,
+ uint32_t sequence_dim,
+ int64_t sequence_offset,
+ int64_t tile_length) {
+ const auto source_shape = source_tensor->get_shape();
+ const int64_t source_full_length = static_cast<int64_t>(source_shape[sequence_dim]);
+
+ // Zero-copy conditions:
+ // 1. Offset must be 0 (no slicing from middle)
+ // 2. Tile length must match full source length (using entire tensor)
+ // 3. Element types must match (no conversion needed)
+ return (sequence_offset == 0 && tile_length == source_full_length &&
+ dest_tensor->get_element_type() == source_tensor->get_element_type());
+}
+
+// ====================================================================================================
+// Host Flash Attention (HFA) Tiled Inference
+// ====================================================================================================
+//
+// Implements Flash Attention using tile-based processing to reduce memory footprint.
+//
+// Algorithm:
+// - Split KV cache into tiles of size tile_size
+// - For tiles [0..N-2]: Use regular_tile_model, output intermediate states (acc, max, d)
+// - For tile [N-1]: Use final_tile_model, output final result with division + transpose
+// - Maintain numerically stable online softmax across tiles
+//
+// Optimizations:
+// - Zero-copy when tile size equals full tensor size
+// - Pre-cached input/output indices to avoid repeated map lookups
+// - Automatic FP16/FP32 conversion when needed
+//
+// ====================================================================================================
+
+void ov::npuw::JustInferRequest::run_hfa_tiled_inference(std::size_t real_idx, std::size_t idx) {
+ // ================================================================================================
+ // SECTION 1: Configuration and Validation
+ // ================================================================================================
+
+ auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];
+ auto& hfa_desc = comp_model_desc.host_flash_attention.value();
+
+ NPUW_ASSERT(hfa_desc.is_valid() && "HFA configuration must be valid");
+ NPUW_ASSERT(comp_model_desc.hfa_infer_requests.size() == CompiledModel::CompiledModelDesc::HFATileIdx::COUNT &&
+ "HFA infer requests must be created");
+
+ // Calculate tile configuration
+ const int64_t tile_size = hfa_desc._tile_size;
+ const int64_t total_kv_length = m_hfa_selector->context_length();
+ const int64_t num_tiles = total_kv_length / tile_size;
+
+ NPUW_ASSERT(total_kv_length % tile_size == 0 && "HFA total KV length must be multiple of tile size for now");
+
+ // ================================================================================================
+ // SECTION 2: Input/Output Tensor Extraction
+ // ================================================================================================
+
+ const auto& hfa_inputs = m_hfa_io[idx].inputs;
+ const auto& hfa_outputs = m_hfa_io[idx].outputs;
+ const auto& sdpa_info = hfa_desc._sdpa_attention_info;
+
+ // Use pre-cached SDPA indices
+ const auto& sdpa_in = sdpa_info._sdpa_indices;
+
+ auto past_key_tensor = hfa_inputs.at(sdpa_in.past_key);
+ auto past_value_tensor = hfa_inputs.at(sdpa_in.past_value);
+ auto query_tensor = hfa_inputs.at(sdpa_in.query);
+ auto present_key_tensor = hfa_inputs.at(sdpa_in.present_key);
+ auto attention_mask_tensor = hfa_inputs.at(sdpa_in.attention_mask);
+ auto present_value_tensor = hfa_inputs.at(sdpa_in.present_value);
+
+ auto attention_output_tensor = hfa_outputs.at(0);
+
+ // ================================================================================================
+ // SECTION 3: State Initialization
+ // ================================================================================================
+
+ // Get tile infer requests
+ auto& regular_tile_request =
+ comp_model_desc.hfa_infer_requests[CompiledModel::CompiledModelDesc::HFATileIdx::REGULAR_TILE];
+ auto& final_tile_request =
+ comp_model_desc.hfa_infer_requests[CompiledModel::CompiledModelDesc::HFATileIdx::FINAL_TILE];
+
+ // Use pre-cached indices (populated during compilation)
+ const auto& tile_in = sdpa_info._tile_input_indices;
+ const auto& tile_out = sdpa_info._tile_output_indices;
+
+ // Get pre-initialized state buffers from runtime context (initialized during setup phase)
+ // If optimizations are disabled, get tensors directly from request (no double-buffering)
+ ov::SoPtr<ov::ITensor> state_acc, state_max, state_sum;
+
+ if (m_hfa_runtime_ctx && m_hfa_runtime_ctx->has_state_buffers()) {
+ // Use pre-initialized state from current buffer (double-buffering enabled)
+ const auto& current_buffer = m_hfa_runtime_ctx->get_current_state_buffers();
+
+ state_acc = current_buffer.acc;
+ state_max = current_buffer.max;
+ state_sum = current_buffer.sum;
+
+ regular_tile_request->set_tensor(hfa_desc._compiled_tile_model->inputs()[tile_in.acc], state_acc);
+ regular_tile_request->set_tensor(hfa_desc._compiled_tile_model->inputs()[tile_in.max], state_max);
+ regular_tile_request->set_tensor(hfa_desc._compiled_tile_model->inputs()[tile_in.d], state_sum);
+ } else {
+ // Optimizations disabled: use tensors directly without double-buffering
+ state_acc = regular_tile_request->get_tensor(hfa_desc._compiled_tile_model->inputs()[tile_in.acc]);
+ state_max = regular_tile_request->get_tensor(hfa_desc._compiled_tile_model->inputs()[tile_in.max]);
+ state_sum = regular_tile_request->get_tensor(hfa_desc._compiled_tile_model->inputs()[tile_in.d]);
+
+ // Initialize state tensors for each inference run (no caching)
+ runtime::host_flash_attention::HFARuntimeContext::initialize_state_tensors(state_acc, state_max, state_sum);
+ }
+
+ // Set query tensor once (constant across all tiles)
+ regular_tile_request->set_tensor(hfa_desc._compiled_tile_model->inputs()[tile_in.q], query_tensor);
+ final_tile_request->set_tensor(hfa_desc._compiled_final_tile_model->inputs()[tile_in.q], query_tensor);
+
+ // Set output state tensors for regular tile model (will be updated in-place after each tile execution)
+ regular_tile_request->set_tensor(hfa_desc._compiled_tile_model->outputs()[tile_out.acc], state_acc);
+ regular_tile_request->set_tensor(hfa_desc._compiled_tile_model->outputs()[tile_out.max], state_max);
+ regular_tile_request->set_tensor(hfa_desc._compiled_tile_model->outputs()[tile_out.d], state_sum);
+
+ // Set accumulated state tensors as inputs for final tile (will read from regular tiles' outputs)
+ final_tile_request->set_tensor(hfa_desc._compiled_final_tile_model->inputs()[tile_in.acc], state_acc);
+ final_tile_request->set_tensor(hfa_desc._compiled_final_tile_model->inputs()[tile_in.max], state_max);
+ final_tile_request->set_tensor(hfa_desc._compiled_final_tile_model->inputs()[tile_in.d], state_sum);
+
+ // Final attention output
+ final_tile_request->set_tensor(hfa_desc._compiled_final_tile_model->outputs()[0], attention_output_tensor);
+
+ // ================================================================================================
+ // SECTION 4: Tile Processing Loop
+ // ================================================================================================
+
+ // Dimension configuration for tensor slicing
+ const uint32_t K_SEQ_DIM = static_cast<uint32_t>(sdpa_info._k_seq_dim);
+ const uint32_t V_SEQ_DIM = static_cast<uint32_t>(sdpa_info._v_seq_dim);
+ constexpr uint32_t MASK_KV_SEQ_DIM = 3;
+
+ size_t next_available_mask_buffer_idx = 0; // Track next available pre-allocated mask buffer for cache misses
+
+ // Helper lambda: Process a single tile
+ auto process_tile = [&](auto& request,
+ auto& model,
+ const ov::SoPtr<ov::ITensor>& k_source,
+ const ov::SoPtr<ov::ITensor>& v_source,
+ int64_t kv_offset,
+ int64_t mask_offset,
+ int64_t tile_length,
+ bool async = false) {
+ // Get tile input buffers
+ auto k_tile_buffer = request->get_tensor(model->inputs()[tile_in.k]);
+ auto v_tile_buffer = request->get_tensor(model->inputs()[tile_in.v]);
+ auto mask_tile_buffer = request->get_tensor(model->inputs()[tile_in.mask]);
+
+ // Extract K tile
+ if (hfa_can_reuse_tensor_zero_copy(k_source, k_tile_buffer, K_SEQ_DIM, kv_offset, tile_length)) {
+ request->set_tensor(model->inputs()[tile_in.k], k_source);
+ } else {
+ hfa_extract_and_copy_tile(k_source, k_tile_buffer, K_SEQ_DIM, kv_offset, tile_length, "K");
+ }
+
+ // Extract V tile
+ if (hfa_can_reuse_tensor_zero_copy(v_source, v_tile_buffer, V_SEQ_DIM, kv_offset, tile_length)) {
+ request->set_tensor(model->inputs()[tile_in.v], v_source);
+ } else {
+ hfa_extract_and_copy_tile(v_source, v_tile_buffer, V_SEQ_DIM, kv_offset, tile_length, "V");
+ }
+
+ // Extract mask tile with caching (if enabled) to avoid redundant extraction
+ if (attention_mask_tensor) {
+ // Check if zero-copy is possible (rare case where full mask matches tile)
+ if (hfa_can_reuse_tensor_zero_copy(attention_mask_tensor,
+ mask_tile_buffer,
+ MASK_KV_SEQ_DIM,
+ mask_offset,
+ tile_length)) {
+ request->set_tensor(model->inputs()[tile_in.mask], attention_mask_tensor);
+ } else if (m_hfa_runtime_ctx.has_value()) {
+ // Cache is enabled - try to find cached tile
+ auto cached_tile =
+ m_hfa_runtime_ctx->find_cached_mask_tile(attention_mask_tensor, mask_offset, tile_length);
+ if (cached_tile) {
+ // Cache hit - reuse previously extracted tile
+ request->set_tensor(model->inputs()[tile_in.mask], cached_tile);
+ LOG_DEBUG("HFA: Cache hit for mask tile [offset=" << mask_offset << ", length=" << tile_length
+ << "]");
+ } else {
+ // Cache miss - extract and cache this tile
+ LOG_DEBUG("HFA: Cache miss for mask tile [offset=" << mask_offset << ", length=" << tile_length
+ << "], extracting...");
+
+ // Use pre-allocated mask buffer for this tile
+ ov::SoPtr<ov::ITensor> cached_mask_tile =
+ m_hfa_runtime_ctx->get_mask_tile_buffer(next_available_mask_buffer_idx);
+
+ // Extract mask data into the pre-allocated buffer
+ hfa_extract_and_copy_tile(attention_mask_tensor,
+ cached_mask_tile,
+ MASK_KV_SEQ_DIM,
+ mask_offset,
+ tile_length,
+ "Mask");
+
+ // Cache the extracted tile for future reuse
+ m_hfa_runtime_ctx->cache_mask_tile(attention_mask_tensor,
+ mask_offset,
+ tile_length,
+ cached_mask_tile);
+
+ // Use the cached tensor for this inference
+ request->set_tensor(model->inputs()[tile_in.mask], cached_mask_tile);
+
+ // Move to next pre-allocated buffer for next cache miss
+ next_available_mask_buffer_idx++;
+ }
+ } else {
+ // Cache is disabled - extract mask tile on-the-fly directly into tile buffer
+ LOG_DEBUG("HFA: Extracting mask tile on-the-fly [offset=" << mask_offset << ", length=" << tile_length
+ << "] (cache disabled)");
+ hfa_extract_and_copy_tile(attention_mask_tensor,
+ mask_tile_buffer,
+ MASK_KV_SEQ_DIM,
+ mask_offset,
+ tile_length,
+ "Mask");
+ }
+ }
+
+ // Execute tile (async mode pre-initializes next state buffer in parallel if optimizations enabled)
+ if (async) {
+ request->start_async();
+ if (m_hfa_runtime_ctx && m_hfa_runtime_ctx->has_state_buffers()) {
+ m_hfa_runtime_ctx->prepare_next_state_buffers();
+ }
+ request->wait();
+ } else {
+ request->infer();
+ }
+ };
+
+ int64_t mask_tile_offset = 0;
+ int64_t kv_tile_offset = 0;
+
+ // Process regular tiles (all but the last one)
+ // Each regular tile processes past KV cache and outputs intermediate states (acc, max, d)
+ for (int64_t tile_idx = 0; tile_idx < num_tiles - 1; ++tile_idx) {
+ process_tile(regular_tile_request,
+ hfa_desc._compiled_tile_model,
+ past_key_tensor,
+ past_value_tensor,
+ kv_tile_offset,
+ mask_tile_offset,
+ tile_size);
+
+ kv_tile_offset += tile_size;
+ mask_tile_offset += tile_size;
+ }
+
+ // Process final tile separately
+ // Final tile processes present KV tokens and produces final attention output
+ if (num_tiles > 0) {
+ const size_t present_seq_length = present_key_tensor->get_shape()[K_SEQ_DIM];
+ const int64_t final_tile_length = static_cast<int64_t>(present_seq_length);
+
+ // Verify that final tile can process entire present KV in one inference
+ NPUW_ASSERT(final_tile_length == tile_size &&
+ "Final tile must process entire present KV sequence in a single inference. "
+ "This is guaranteed during compilation (tile_size = query_size = present_seq_length).");
+
+ // Calculate mask offset for final tile (points to tail of mask corresponding to present tokens)
+ const int64_t mask_total_length = attention_mask_tensor->get_shape()[MASK_KV_SEQ_DIM];
+ const int64_t final_mask_offset = mask_total_length - final_tile_length;
+
+ process_tile(final_tile_request,
+ hfa_desc._compiled_final_tile_model,
+ present_key_tensor,
+ present_value_tensor,
+ 0,
+ final_mask_offset,
+ final_tile_length,
+ true); // async: pre-init next state buffer
+ }
+
+ // Switch to other buffer for next inference (only if optimizations enabled)
+ if (m_hfa_runtime_ctx && m_hfa_runtime_ctx->has_state_buffers()) {
+ m_hfa_runtime_ctx->switch_buffers();
+ }
+}
+
void ov::npuw::JustInferRequest::unsafe_infer_spatial(std::size_t real_idx, std::size_t) {
auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];
NPUW_ASSERT(comp_model_desc.spatial.has_value());
@@ -1233,6 +1777,8 @@ void ov::npuw::JustInferRequest::unsafe_infer(std::size_t real_idx, std::size_t
auto& r = m_subrequests[real_idx];
if (comp_model_desc.spatial) {
unsafe_infer_spatial(real_idx, idx);
+ } else if (comp_model_desc.host_flash_attention) {
+ run_hfa_tiled_inference(real_idx, idx);
} else {
r->infer(); // Run normally
}
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 2de1bb66e01..544300e0782 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
@@ -11,6 +11,7 @@
#include <vector>
#include "base_sync_infer_request.hpp"
+#include "host_flash_attention.hpp"
#include "openvino/runtime/iplugin.hpp"
#include "openvino/runtime/iremote_context.hpp"
#include "openvino/runtime/make_tensor.hpp"
@@ -106,12 +107,34 @@ protected:
void unsafe_infer_spatial(std::size_t real_idx, std::size_t idx);
void unsafe_run_this_prep_next(std::size_t idx, bool& next_prepared_p);
+ void run_hfa_tiled_inference(std::size_t real_idx, std::size_t idx);
+
+ // HFA helper functions
+ static void hfa_extract_and_copy_tile(const ov::SoPtr<ov::ITensor>& source_tensor,
+ const ov::SoPtr<ov::ITensor>& dest_tensor,
+ uint32_t sequence_dim,
+ int64_t sequence_offset,
+ int64_t sequence_length,
+ const std::string& tensor_name);
+
+ static bool hfa_can_reuse_tensor_zero_copy(const ov::SoPtr<ov::ITensor>& source_tensor,
+ const ov::SoPtr<ov::ITensor>& dest_tensor,
+ uint32_t sequence_dim,
+ int64_t sequence_offset,
+ int64_t tile_length);
+
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);
+ // Helper function to setup host flash attention tile infer requests
+ void setup_hfa_infer_requests(std::size_t real_idx,
+ bool is_piped,
+ bool is_recreate,
+ bool enable_hfa_optimizations = true);
+
FuncMemMgr m_func_mem_mgr; // Owns memory
std::map<LinkFrom, TensorPtr> m_funcall_result; // Provides a convenient link
@@ -138,6 +161,9 @@ protected:
// Cached attention mask for SDPA operations to avoid recomputing
ov::SoPtr<ov::ITensor> m_cached_attention_mask;
+
+ // HFA runtime context (holds cached masks, pre-allocated buffers, and state buffers)
+ std::optional<runtime::host_flash_attention::HFARuntimeContext> m_hfa_runtime_ctx;
};
} // namespace npuw
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp
index 8d56febd6f6..c180057a6ac 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
@@ -1642,6 +1642,9 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
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 prefill_attn_hfa = prefill_attn_hint == ::intel_npu::npuw::llm::AttentionHint::HFA;
+ const bool generate_attn_hfa = generate_attn_hint == ::intel_npu::npuw::llm::AttentionHint::HFA;
+
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");
@@ -1721,6 +1724,14 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m
merge_config_with(prefill_config, prefill_config_addition_value);
merge_config_with(generate_config, generate_config_addition_value);
+ // Convert LLM-specific attention hints to NPUW_ATTN
+ if (npuw_llm_props.count("NPUW_LLM_PREFILL_ATTENTION_HINT")) {
+ prefill_config["NPUW_ATTN"] = npuw_llm_props["NPUW_LLM_PREFILL_ATTENTION_HINT"];
+ }
+ if (npuw_llm_props.count("NPUW_LLM_GENERATE_ATTENTION_HINT")) {
+ generate_config["NPUW_ATTN"] = npuw_llm_props["NPUW_LLM_GENERATE_ATTENTION_HINT"];
+ }
+
// Generate a random weights bank name unique to this LLMCompiledModel object
auto weights_bank_name = ov::npuw::util::generate_random_string();
LOG_VERB("Generated a unique weights bank name: " << weights_bank_name);
@@ -1735,10 +1746,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 || prefill_attn_pyramid) {
+ if (prefill_attn_dyn || prefill_attn_pyramid || prefill_attn_hfa) {
merge_config_with(prefill_config, dyn_attn_opts);
}
- if (generate_attn_dyn || generate_attn_pyramid) {
+ if (generate_attn_dyn || generate_attn_pyramid || generate_attn_hfa) {
merge_config_with(generate_config, dyn_attn_opts);
}
@@ -1786,12 +1797,12 @@ 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 || generate_attn_pyramid) {
+ if (generate_attn_dyn || generate_attn_pyramid || generate_attn_hfa) {
for (auto& model_variant : generate_model_variants) {
rewr.run_on_model(model_variant);
}
}
- if (prefill_attn_dyn || prefill_attn_pyramid) {
+ if (prefill_attn_dyn || prefill_attn_pyramid || prefill_attn_hfa) {
rewr.run_on_model(prefill_model);
}
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 cd316234312..a3c2f894fe5 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.cpp
@@ -1892,29 +1892,51 @@ 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");
+ // Get attention mode from NPUW_ATTN config (string type)
+ const auto attn_mode = cfg.get<::intel_npu::NPUW_ATTN>();
+
+ // Check if attention optimization is disabled
+ if (attn_mode == "STATIC") {
+ LOG_VERB("Attention optimization disabled (STATIC mode) for " << func_name << " in model "
+ << model->get_friendly_name());
return;
}
- LOG_VERB("Turn " << func_name << " into dynamic Attention block in model " << model->get_friendly_name() << "...");
+ LOG_VERB("Turn " << func_name << " into Attention block (mode: " << attn_mode << ") in model "
+ << model->get_friendly_name() << "...");
LOG_BLOCK();
- f._attention = ov::npuw::function::Attention::from(f._model);
- if (f._attention) {
- LOG_VERB("Done");
- return;
+ // Try DYNAMIC attention
+ if (attn_mode == "DYNAMIC") {
+ f._attention = ov::npuw::function::Attention::from(f._model);
+ if (f._attention) {
+ LOG_VERB("Done - DYNAMIC attention");
+ return;
+ }
+ LOG_WARN("No dynamic ranges found in the ATTN block");
}
- 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;
+ // Try PYRAMID attention
+ if (attn_mode == "PYRAMID") {
+ LOG_DEBUG("Attempting PyramidAttention based on config");
+ f._pyramid_attention = ov::npuw::function::PyramidAttention::from(f._model);
+ if (f._pyramid_attention) {
+ LOG_VERB("Done - PYRAMID attention");
+ return;
+ }
+ LOG_WARN("No pyramid attention found in the ATTN block");
}
- LOG_WARN("No pyramid attention found in the ATTN block");
+ // Try HFA (Host Flash Attention)
+ if (attn_mode == "HFA") {
+ LOG_DEBUG("Attempting HostFlashAttention based on config");
+ f._host_flash_attention = ov::npuw::function::HostFlashAttention::from(f._model);
+ if (f._host_flash_attention) {
+ LOG_VERB("Done - HFA (Host Flash Attention)");
+ return;
+ }
+ LOG_WARN("No host flash 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 0729ad429b3..d57d98f8cec 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/partitioning.hpp
@@ -10,10 +10,12 @@
#include <vector>
#include "../attention.hpp"
+#include "../host_flash_attention.hpp"
#include "../lazy_tensor.hpp"
#include "../pyramid_attention.hpp"
#include "../spatial.hpp"
#include "intel_npu/config/config.hpp"
+#include "intel_npu/config/npuw.hpp"
#include "openvino/openvino.hpp"
namespace ov {
@@ -99,6 +101,8 @@ struct Function {
std::optional<ov::npuw::function::Attention> _attention;
// Multiple attention graphs with different shapes
std::optional<ov::npuw::function::PyramidAttention> _pyramid_attention;
+ // Host Flash Attention
+ std::optional<ov::npuw::function::HostFlashAttention> _host_flash_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
std::set<std::size_t> _idx_lazy_unpack;
diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
index 10a6b58d065..f434ee6100f 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.cpp
@@ -5,6 +5,7 @@
#include "serialization.hpp"
#include "attention.hpp"
+#include "host_flash_attention.hpp"
#include "intel_npu/config/config.hpp"
#include "intel_npu/config/npuw.hpp"
#include "lazy_tensor.hpp"
@@ -129,6 +130,43 @@ void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::Pyram
}
}
+void ov::npuw::s11n::write(std::ostream& stream, const ov::npuw::compiled::HostFlashAttention& var) {
+ using ov::npuw::s11n::write;
+
+ // Serialize basic info from _sdpa_attention_info
+ write(stream, var._sdpa_attention_info._query_size);
+ write(stream, var._sdpa_attention_info._context_size);
+ write(stream, var._sdpa_attention_info._k_seq_dim);
+ write(stream, var._sdpa_attention_info._v_seq_dim);
+
+ // Serialize SDPA indices from _sdpa_attention_info
+ write(stream, var._sdpa_attention_info._sdpa_indices.query);
+ write(stream, var._sdpa_attention_info._sdpa_indices.past_key);
+ write(stream, var._sdpa_attention_info._sdpa_indices.past_value);
+ write(stream, var._sdpa_attention_info._sdpa_indices.present_key);
+ write(stream, var._sdpa_attention_info._sdpa_indices.present_value);
+ write(stream, var._sdpa_attention_info._sdpa_indices.attention_mask);
+
+ // Serialize tile input indices from _sdpa_attention_info
+ write(stream, var._sdpa_attention_info._tile_input_indices.q);
+ write(stream, var._sdpa_attention_info._tile_input_indices.k);
+ write(stream, var._sdpa_attention_info._tile_input_indices.v);
+ write(stream, var._sdpa_attention_info._tile_input_indices.mask);
+ write(stream, var._sdpa_attention_info._tile_input_indices.acc);
+ write(stream, var._sdpa_attention_info._tile_input_indices.max);
+ write(stream, var._sdpa_attention_info._tile_input_indices.d);
+
+ // Serialize tile output indices from _sdpa_attention_info
+ write(stream, var._sdpa_attention_info._tile_output_indices.acc);
+ write(stream, var._sdpa_attention_info._tile_output_indices.max);
+ write(stream, var._sdpa_attention_info._tile_output_indices.d);
+
+ // Serialize tile_size
+ write(stream, var._tile_size);
+ // Note: _tile_model_to_compile and _compiled_tile_model are not serialized here
+ // They are handled separately in CompiledModelDesc::serialize()
+}
+
void ov::npuw::s11n::write(std::ostream& stream, const ov::Tensor& var) {
using ov::npuw::s11n::write;
@@ -277,6 +315,43 @@ void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::PyramidAtten
}
}
+void ov::npuw::s11n::read(std::istream& stream, ov::npuw::compiled::HostFlashAttention& var) {
+ using ov::npuw::s11n::read;
+
+ // Deserialize basic info into _sdpa_attention_info
+ read(stream, var._sdpa_attention_info._query_size);
+ read(stream, var._sdpa_attention_info._context_size);
+ read(stream, var._sdpa_attention_info._k_seq_dim);
+ read(stream, var._sdpa_attention_info._v_seq_dim);
+
+ // Deserialize SDPA indices into _sdpa_attention_info
+ read(stream, var._sdpa_attention_info._sdpa_indices.query);
+ read(stream, var._sdpa_attention_info._sdpa_indices.past_key);
+ read(stream, var._sdpa_attention_info._sdpa_indices.past_value);
+ read(stream, var._sdpa_attention_info._sdpa_indices.present_key);
+ read(stream, var._sdpa_attention_info._sdpa_indices.present_value);
+ read(stream, var._sdpa_attention_info._sdpa_indices.attention_mask);
+
+ // Deserialize tile input indices into _sdpa_attention_info
+ read(stream, var._sdpa_attention_info._tile_input_indices.q);
+ read(stream, var._sdpa_attention_info._tile_input_indices.k);
+ read(stream, var._sdpa_attention_info._tile_input_indices.v);
+ read(stream, var._sdpa_attention_info._tile_input_indices.mask);
+ read(stream, var._sdpa_attention_info._tile_input_indices.acc);
+ read(stream, var._sdpa_attention_info._tile_input_indices.max);
+ read(stream, var._sdpa_attention_info._tile_input_indices.d);
+
+ // Deserialize tile output indices into _sdpa_attention_info
+ read(stream, var._sdpa_attention_info._tile_output_indices.acc);
+ read(stream, var._sdpa_attention_info._tile_output_indices.max);
+ read(stream, var._sdpa_attention_info._tile_output_indices.d);
+
+ // Deserialize tile_size
+ read(stream, var._tile_size);
+ // Note: _tile_model_to_compile and _compiled_tile_model are not deserialized here
+ // They are handled separately in CompiledModelDesc::deserialize()
+}
+
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 aaa1ac357cf..c97580327c1 100644
--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp
@@ -81,6 +81,7 @@ namespace compiled {
struct Spatial;
struct Attention;
struct PyramidAttention;
+struct HostFlashAttention;
} // namespace compiled
namespace weights {
class LazyTensor;
@@ -152,10 +153,13 @@ struct WeightsContext {
ov::FileHandleProvider handle_provider = nullptr;
};
-struct PyramidCtx {
- PyramidCtx(const std::shared_ptr<const ov::IPlugin>& _plugin,
- const std::string& _device,
- const ov::SoPtr<ov::ICompiledModel>& _compiled_model)
+// Context for deserializing submodels with dynamic attention mechanisms
+// (Pyramid Attention, Host Flash Attention, etc.)
+// Provides plugin, device, and compiled model reference for proper deserialization
+struct SubmodelDeserializeCtx {
+ SubmodelDeserializeCtx(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) {}
@@ -175,6 +179,7 @@ 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::npuw::compiled::HostFlashAttention& 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);
@@ -192,6 +197,7 @@ 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::npuw::compiled::HostFlashAttention& 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/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index f55f7c991d6..705ccba3a2a 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/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
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp
LINK_LIBRARIES
${MANDATORY_UNIT_TESTS_LIBS}
LABELS