OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
NPUW: Attention behaviors refactoring continued (#35682)
Dmitry Matveevb363c7daf6cb
diff --git a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cppindex 9a51a17dd8d..8a16a67ee6f 100644--- a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.cpp@@ -4,17 +4,63 @@#include "attn_subgraph.hpp"+#include <array>+#include <sstream>+#include <unordered_map>+#include "../attention.hpp"+#include "../compiled_model.hpp"+#include "../host_flash_attention.hpp"+#include "../infer_request_utils.hpp"#include "../just_sync_infer_request.hpp"#include "../logging.hpp"#include "../partitioning/partitioning.hpp"#include "../partitioning/patterns/sdpa.hpp"+#include "../pyramid_attention.hpp"+#include "../serialization.hpp"namespace ov {namespace npuw {namespace attn {namespace {+constexpr uint32_t ATTN_KV_DIM = 3;++struct BehaviorIO {+ std::vector<ov::SoPtr<ov::ITensor>> inputs;+ std::vector<ov::SoPtr<ov::ITensor>> outputs;+};++struct PyramidRequestSet {+ std::vector<ov::SoPtr<ov::IAsyncInferRequest>> infer_requests;+ std::vector<ov::SoPtr<ov::IAsyncInferRequest>> pipeline_requests;+ std::vector<ov::SoPtr<ov::ITensor>> anchors;+};++struct HFARequestSet {+ enum TileIdx : std::size_t {+ REGULAR_TILE = 0,+ FINAL_TILE = 1,+ COUNT = 2,+ };++ std::array<ov::SoPtr<ov::IAsyncInferRequest>, COUNT> infer_requests{};+ std::array<ov::SoPtr<ov::IAsyncInferRequest>, COUNT> pipeline_requests{};+};++struct RuntimeState {+ std::unordered_map<std::size_t, BehaviorIO> call_io;+ runtime::attention::Selector::Ptr attention_selector;+ runtime::pyramid_attention::Selector::Ptr pyramid_selector;+ runtime::host_flash_attention::Selector::Ptr hfa_selector;+ ov::SoPtr<ov::ITensor> cached_attention_mask;+ std::optional<runtime::host_flash_attention::HFARuntimeContext> hfa_runtime_ctx;+ PyramidRequestSet pyramid_requests;+ HFARequestSet hfa_requests;+ ov::SoPtr<ov::IAsyncInferRequest> base_request;+ ov::SoPtr<ov::IAsyncInferRequest> base_pipeline_request;+};+ov::npuw::JustInferRequest& get_request(ov::npuw::v1::subgraphs::InferContext& ctx) {auto* request = dynamic_cast<ov::npuw::JustInferRequest*>(&ctx.infer_request);OPENVINO_ASSERT(request != nullptr, "Expected JustInferRequest for attention runtime behavior");@@ -28,29 +74,435 @@ BehaviorKind get_behavior_kind(const ov::npuw::v1::subgraphs::Context& ctx) {OPENVINO_THROW("Attention behavior context is missing BehaviorKind");}+template <typename T>+T* get_compiled_state(ov::npuw::v1::subgraphs::Context& context) {+ auto* state = context.get_if<std::shared_ptr<T>>();+ return state == nullptr ? nullptr : state->get();+}++template <typename T>+const T* get_compiled_state(const ov::npuw::v1::subgraphs::Context& context) {+ auto* state = context.get_if<std::shared_ptr<T>>();+ return state == nullptr ? nullptr : state->get();+}++const ov::npuw::v1::subgraphs::CompiledPipeline& get_subgraph_pipeline(ov::npuw::v1::subgraphs::InferContext& ctx,+ std::size_t real_idx) {+ return get_request(ctx).subgraph_pipeline(real_idx);+}++const ov::SoPtr<ov::ICompiledModel>& get_compiled_submodel(ov::npuw::v1::subgraphs::InferContext& ctx,+ std::size_t real_idx) {+ return get_request(ctx).compiled_submodel(real_idx);+}++std::size_t get_param_base(ov::npuw::v1::subgraphs::InferContext& ctx, std::size_t real_idx) {+ return get_request(ctx).subgraph_param_base(real_idx);+}++RuntimeState& get_runtime_state(ov::npuw::v1::subgraphs::InferContext& ctx) {+ OPENVINO_ASSERT(ctx.runtime_state != nullptr, "Expected runtime state storage for attention behavior");+ auto* state = ctx.runtime_state->get_if<RuntimeState>();+ if (state == nullptr) {+ state = &ctx.runtime_state->emplace<RuntimeState>();+ }+ return *state;+}++BehaviorIO& get_behavior_io(RuntimeState& state,+ std::size_t subgraph_idx,+ std::size_t num_inputs,+ std::size_t num_outputs) {+ auto& io = state.call_io[subgraph_idx];+ if (io.inputs.size() != num_inputs) {+ io.inputs.resize(num_inputs);+ }+ if (io.outputs.size() != num_outputs) {+ io.outputs.resize(num_outputs);+ }+ return io;+}++void ensure_base_requests(ov::npuw::v1::subgraphs::InferContext& ctx, RuntimeState& state) {+ auto& request = get_request(ctx);+ if (!state.base_request) {+ state.base_request = request.get_subrequest(ctx.real_subgraph_idx);+ }+ if (request.is_subrequest_pipelined(ctx.real_subgraph_idx) && !state.base_pipeline_request) {+ state.base_pipeline_request = request.get_pipeline_subrequest(ctx.real_subgraph_idx);+ }+}++void ensure_dynamic_selector(ov::npuw::v1::subgraphs::InferContext& ctx, RuntimeState& state) {+ if (state.attention_selector) {+ return;+ }+ const auto& pipeline = get_subgraph_pipeline(ctx, ctx.real_subgraph_idx);+ const auto* dynamic = ov::npuw::attn::get_compiled_dynamic(pipeline.context);+ OPENVINO_ASSERT(dynamic != nullptr, "Missing compiled dynamic attention state");++ auto& request = get_request(ctx);+ if (!ctx.compiled_model.attention_dynamic_enabled()) {+ state.attention_selector = std::make_shared<runtime::attention::All>();+ return;+ }++ state.attention_selector = runtime::attention::PositionIDs::find(*dynamic, request);+ if (!state.attention_selector) {+ LOG_WARN("Dynamic capability is enabled, but no run-time features were found.");+ state.attention_selector = std::make_shared<runtime::attention::All>();+ }+}++void ensure_pyramid_selector(ov::npuw::v1::subgraphs::InferContext& ctx, RuntimeState& state) {+ if (state.pyramid_selector) {+ return;+ }+ const auto& pipeline = get_subgraph_pipeline(ctx, ctx.real_subgraph_idx);+ const auto* pyramid = ov::npuw::attn::get_compiled_pyramid(pipeline.context);+ OPENVINO_ASSERT(pyramid != nullptr, "Missing compiled pyramid attention state");++ auto& request = get_request(ctx);+ const auto pyramid_count = pyramid->_compiled_models.size();+ if (!ctx.compiled_model.attention_dynamic_enabled()) {+ state.pyramid_selector.reset(new runtime::pyramid_attention::All(pyramid_count));+ return;+ }++ state.pyramid_selector = runtime::pyramid_attention::PositionIDs::find(*pyramid, request);+ if (!state.pyramid_selector) {+ LOG_WARN("Pyramid dynamic capability is enabled, but no run-time features were found.");+ state.pyramid_selector.reset(new runtime::pyramid_attention::All(pyramid_count));+ }+}++void ensure_hfa_selector(ov::npuw::v1::subgraphs::InferContext& ctx, RuntimeState& state) {+ if (state.hfa_selector) {+ return;+ }+ const auto& pipeline = get_subgraph_pipeline(ctx, ctx.real_subgraph_idx);+ const auto* hfa = ov::npuw::attn::get_compiled_hfa(pipeline.context);+ OPENVINO_ASSERT(hfa != nullptr, "Missing compiled HFA state");++ auto& request = get_request(ctx);+ const size_t query_size = hfa->_sdpa_attention_info._query_size;+ state.hfa_selector = runtime::host_flash_attention::PositionIDs::find(query_size, request);+ if (!state.hfa_selector) {+ OPENVINO_THROW("HFA dynamic capability is enabled, but no run-time features were found.");+ }+}++void ensure_pyramid_requests(ov::npuw::v1::subgraphs::InferContext& ctx, RuntimeState& state) {+ if (!state.pyramid_requests.infer_requests.empty()) {+ return;+ }++ ensure_base_requests(ctx, state);++ const auto& compiled_model = get_compiled_submodel(ctx, ctx.real_subgraph_idx);+ const auto& pipeline = get_subgraph_pipeline(ctx, ctx.real_subgraph_idx);+ const auto* pyramid = ov::npuw::attn::get_compiled_pyramid(pipeline.context);+ OPENVINO_ASSERT(pyramid != nullptr, "Missing compiled pyramid attention state");++ auto& request = get_request(ctx);+ const auto& pyramid_models = pyramid->_compiled_models;+ const size_t num_pyramid_models = pyramid_models.size();+ const bool is_piped = request.is_subrequest_pipelined(ctx.real_subgraph_idx);++ state.pyramid_requests.infer_requests.resize(num_pyramid_models);+ if (is_piped) {+ state.pyramid_requests.pipeline_requests.resize(num_pyramid_models);+ }++ for (size_t model_idx = 0; model_idx + 1 < num_pyramid_models; ++model_idx) {+ state.pyramid_requests.infer_requests[model_idx] = pyramid_models[model_idx]->create_infer_request();+ if (is_piped) {+ state.pyramid_requests.pipeline_requests[model_idx] = pyramid_models[model_idx]->create_infer_request();+ }++ const size_t num_inputs = pyramid_models[model_idx]->inputs().size();+ OPENVINO_ASSERT(num_inputs == compiled_model->inputs().size(), "Unexpected pyramid input count mismatch");++ for (size_t input_idx = 0; input_idx < num_inputs; ++input_idx) {+ const auto pyramid_input = pyramid_models[model_idx]->inputs()[input_idx];+ const auto main_input = compiled_model->inputs()[input_idx];++ auto main_tensor_ptr = state.base_request->get_tensor(main_input)->data();+ auto pyramid_tensor = state.pyramid_requests.infer_requests[model_idx]->get_tensor(pyramid_input);+ auto shared_tensor = ov::get_tensor_impl(+ ov::Tensor(pyramid_tensor->get_element_type(), pyramid_tensor->get_shape(), main_tensor_ptr));+ state.pyramid_requests.infer_requests[model_idx]->set_tensor(pyramid_input, shared_tensor);++ if (is_piped) {+ auto pipeline_tensor = state.pyramid_requests.pipeline_requests[model_idx]->get_tensor(pyramid_input);+ auto pipeline_tensor_ptr = state.base_pipeline_request->get_tensor(main_input)->data();+ auto shared_pipeline_tensor = ov::get_tensor_impl(+ ov::Tensor(pipeline_tensor->get_element_type(), pipeline_tensor->get_shape(), pipeline_tensor_ptr));+ state.pyramid_requests.pipeline_requests[model_idx]->set_tensor(pyramid_input, shared_pipeline_tensor);+ }+ }+ }++ if (num_pyramid_models > 0) {+ const size_t last_model_idx = num_pyramid_models - 1;+ state.pyramid_requests.infer_requests[last_model_idx] = state.base_request;+ if (is_piped) {+ state.pyramid_requests.pipeline_requests[last_model_idx] = state.base_pipeline_request;+ }++ const size_t num_inputs = compiled_model->inputs().size();+ for (size_t input_idx = 0; input_idx < num_inputs; ++input_idx) {+ const auto main_input = compiled_model->inputs()[input_idx];+ state.pyramid_requests.anchors.push_back(state.base_request->get_tensor(main_input));+ if (is_piped) {+ state.pyramid_requests.anchors.push_back(state.base_pipeline_request->get_tensor(main_input));+ }+ }+ }+}++void ensure_hfa_requests(ov::npuw::v1::subgraphs::InferContext& ctx, RuntimeState& state) {+ if (state.hfa_requests.infer_requests[HFARequestSet::REGULAR_TILE]) {+ return;+ }++ ensure_base_requests(ctx, state);++ const auto& pipeline = get_subgraph_pipeline(ctx, ctx.real_subgraph_idx);+ const auto* hfa = ov::npuw::attn::get_compiled_hfa(pipeline.context);+ OPENVINO_ASSERT(hfa != nullptr, "Missing compiled HFA state");++ auto& request = get_request(ctx);+ const bool is_piped = request.is_subrequest_pipelined(ctx.real_subgraph_idx);++ state.hfa_requests.infer_requests[HFARequestSet::REGULAR_TILE] = hfa->_compiled_tile_model->create_infer_request();+ state.hfa_requests.infer_requests[HFARequestSet::FINAL_TILE] = state.base_request;+ if (is_piped) {+ state.hfa_requests.pipeline_requests[HFARequestSet::REGULAR_TILE] =+ hfa->_compiled_tile_model->create_infer_request();+ state.hfa_requests.pipeline_requests[HFARequestSet::FINAL_TILE] = state.base_pipeline_request;+ }++ const size_t num_inputs = hfa->_compiled_tile_model->inputs().size();+ for (size_t input_idx = 0; input_idx < num_inputs; ++input_idx) {+ const auto tile_input = hfa->_compiled_tile_model->inputs()[input_idx];+ const auto final_tile_input = hfa->_compiled_final_tile_model->inputs()[input_idx];++ auto main_tensor = state.base_request->get_tensor(final_tile_input);+ state.hfa_requests.infer_requests[HFARequestSet::REGULAR_TILE]->set_tensor(tile_input, main_tensor);++ if (is_piped) {+ auto pipeline_tensor = state.base_pipeline_request->get_tensor(final_tile_input);+ state.hfa_requests.pipeline_requests[HFARequestSet::REGULAR_TILE]->set_tensor(tile_input, pipeline_tensor);+ }+ }++ if (!state.hfa_runtime_ctx.has_value()) {+ state.hfa_runtime_ctx.emplace();+ }++ state.hfa_runtime_ctx->initialize_mask_cache(+ *hfa,+ request.subgraph_device(ctx.real_subgraph_idx),+ [&request](const ov::element::Type& dtype, const ov::Shape& shape, const std::string& device) {+ return request.allocate_mem(dtype, shape, device);+ });++ const auto& tile_in = hfa->_sdpa_attention_info._tile_input_indices;+ auto state_acc = state.hfa_requests.infer_requests[HFARequestSet::REGULAR_TILE]->get_tensor(+ hfa->_compiled_tile_model->inputs()[tile_in.acc]);+ auto state_max = state.hfa_requests.infer_requests[HFARequestSet::REGULAR_TILE]->get_tensor(+ hfa->_compiled_tile_model->inputs()[tile_in.max]);+ auto state_sum = state.hfa_requests.infer_requests[HFARequestSet::REGULAR_TILE]->get_tensor(+ hfa->_compiled_tile_model->inputs()[tile_in.d]);++ runtime::host_flash_attention::HFARuntimeContext::initialize_state_tensors(state_acc, state_max, state_sum);+ runtime::host_flash_attention::HFARuntimeContext::StateBuffers initial_buffers{state_acc, state_max, state_sum};+ state.hfa_runtime_ctx->initialize_state_buffers(+ initial_buffers,+ *hfa,+ request.subgraph_device(ctx.real_subgraph_idx),+ [&request](const ov::element::Type& dtype, const ov::Shape& shape, const std::string& device) {+ return request.allocate_mem(dtype, shape, device);+ });+}++void prepare_dynamic(ov::npuw::v1::subgraphs::InferContext& ctx) {+ auto& state = get_runtime_state(ctx);+ ensure_dynamic_selector(ctx, state);+ state.attention_selector->prepare(get_request(ctx).history_size());+ state.cached_attention_mask = {};+}++void prepare_pyramid(ov::npuw::v1::subgraphs::InferContext& ctx) {+ auto& request = get_request(ctx);+ auto& state = get_runtime_state(ctx);+ ensure_pyramid_selector(ctx, state);+ ensure_pyramid_requests(ctx, state);+ state.pyramid_selector->prepare(request.history_size());+ state.cached_attention_mask = {};++ const auto pyramid_id = state.pyramid_selector->pyramid_id();+ request.set_active_subrequest(ctx.real_subgraph_idx, state.pyramid_requests.infer_requests.at(pyramid_id));+ if (request.is_subrequest_pipelined(ctx.real_subgraph_idx)) {+ request.set_pipeline_subrequest(ctx.real_subgraph_idx, state.pyramid_requests.pipeline_requests.at(pyramid_id));+ }+}++void prepare_hfa(ov::npuw::v1::subgraphs::InferContext& ctx) {+ auto& request = get_request(ctx);+ auto& state = get_runtime_state(ctx);+ ensure_hfa_selector(ctx, state);+ ensure_hfa_requests(ctx, state);+ state.hfa_selector->prepare(request.history_size());+ state.cached_attention_mask = {};+ if (state.hfa_runtime_ctx) {+ state.hfa_runtime_ctx->clear_mask_cache();+ }+ request.set_active_subrequest(ctx.real_subgraph_idx, state.base_request);+ if (request.is_subrequest_pipelined(ctx.real_subgraph_idx)) {+ request.set_pipeline_subrequest(ctx.real_subgraph_idx, state.base_pipeline_request);+ }+}++void 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);+ return;+ }++ LOG_WARN("Performing type conversion for " << tensor_name << " tile: " << source_type << " -> " << dest_type);+ 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);++ const size_t total_elements = intermediate_tensor.get_size();+ if (dest_type == ov::element::f32 && source_type == ov::element::f16) {+ 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]);+ }+ return;+ }+ if (dest_type == ov::element::f16 && source_type == ov::element::f32) {+ 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]);+ }+ return;+ }+ OPENVINO_THROW("Unsupported type conversion for ", tensor_name, " tile: ", source_type, " -> ", dest_type);+}++bool 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]);+ return (sequence_offset == 0 && tile_length == source_full_length &&+ dest_tensor->get_element_type() == source_tensor->get_element_type());+}+ov::npuw::v1::subgraphs::RuntimeBehaviorFactory make_runtime_factory() {return [](const ov::npuw::v1::subgraphs::Context& ctx) -> ov::npuw::v1::subgraphs::ISubgraphBehavior::Ptr {class AttnBehavior final : public ov::npuw::v1::subgraphs::ISubgraphBehavior {public:explicit AttnBehavior(BehaviorKind kind) : m_kind(kind) {}+ void prepare(ov::npuw::v1::subgraphs::InferContext& ctx) override {+ switch (m_kind) {+ case BehaviorKind::Dynamic:+ prepare_dynamic(ctx);+ return;+ case BehaviorKind::Pyramid:+ prepare_pyramid(ctx);+ return;+ case BehaviorKind::HFA:+ prepare_hfa(ctx);+ return;+ }+ OPENVINO_THROW("Unsupported attention behavior kind");+ }+bool bind_function_input(ov::npuw::v1::subgraphs::InferContext& ctx,std::size_t input_idx,const ov::SoPtr<ov::ITensor>& tensor) override {- auto& request = get_request(ctx);+ auto& state = get_runtime_state(ctx);+ const auto& compiled_model = get_compiled_submodel(ctx, ctx.real_subgraph_idx);+ const auto& pipeline = get_subgraph_pipeline(ctx, ctx.real_subgraph_idx);switch (m_kind) {case BehaviorKind::Dynamic:- return request.behavior_bind_dynamic_input(ctx.real_subgraph_idx,- ctx.subgraph_idx,- input_idx,- tensor);+ if (const auto* dynamic = ov::npuw::attn::get_compiled_dynamic(pipeline.context)) {+ auto& io =+ get_behavior_io(state, ctx.subgraph_idx, get_param_base(ctx, ctx.real_subgraph_idx), 0u);+ const bool is_non_param_mask = std::none_of(dynamic->params.begin(),+ dynamic->params.end(),+ [&](auto&& param) {+ return param.idx == input_idx;+ }) &&+ input_idx != dynamic->mask_idx;+ const auto& iport = compiled_model->inputs()[input_idx];+ if (is_non_param_mask) {+ ctx.target_request->set_tensor(iport, tensor);+ } else {+ io.inputs.at(input_idx) = tensor;+ }+ return true;+ }+ return false;case BehaviorKind::Pyramid:- return request.behavior_bind_pyramid_input(ctx.real_subgraph_idx,- ctx.subgraph_idx,- input_idx,- tensor);+ if (const auto* pyramid = ov::npuw::attn::get_compiled_pyramid(pipeline.context)) {+ auto& io =+ get_behavior_io(state, ctx.subgraph_idx, get_param_base(ctx, ctx.real_subgraph_idx), 0u);+ ensure_pyramid_selector(ctx, state);+ const auto pyramid_id = state.pyramid_selector->pyramid_id();+ const auto& info = pyramid->_attention_infos[pyramid_id];+ const bool is_non_param_mask = std::none_of(info.params.begin(),+ info.params.end(),+ [&](auto&& param) {+ return param.idx == input_idx;+ }) &&+ input_idx != info.mask_idx;+ const auto& iport = compiled_model->inputs()[input_idx];+ if (is_non_param_mask) {+ ctx.target_request->set_tensor(iport, tensor);+ } else {+ io.inputs.at(input_idx) = tensor;+ }+ return true;+ }+ return false;case BehaviorKind::HFA:- return request.behavior_bind_hfa_input(ctx.subgraph_idx, input_idx, tensor);+ if (const auto* hfa = ov::npuw::attn::get_compiled_hfa(pipeline.context)) {+ auto& io = get_behavior_io(state,+ ctx.subgraph_idx,+ get_param_base(ctx, ctx.real_subgraph_idx),+ hfa->_compiled_final_tile_model->outputs().size());+ io.inputs.at(input_idx) = tensor;+ return true;+ }+ return false;}OPENVINO_THROW("Unsupported attention behavior kind");}@@ -58,24 +510,143 @@ ov::npuw::v1::subgraphs::RuntimeBehaviorFactory make_runtime_factory() {bool bind_function_output(ov::npuw::v1::subgraphs::InferContext& ctx,std::size_t output_idx,const ov::SoPtr<ov::ITensor>& tensor) override {- if (m_kind != BehaviorKind::HFA) {- return false;- }- auto& request = get_request(ctx);- return request.behavior_bind_hfa_output(ctx.subgraph_idx, output_idx, tensor);+ (void)ctx;+ (void)output_idx;+ (void)tensor;+ return false;}void prologue(ov::npuw::v1::subgraphs::InferContext& ctx) override {if (ctx.opaque_prologue) {ctx.opaque_prologue();}- auto& request = get_request(ctx);+ auto& state = get_runtime_state(ctx);+ const auto& compiled_model = get_compiled_submodel(ctx, ctx.real_subgraph_idx);+ const auto& pipeline = get_subgraph_pipeline(ctx, ctx.real_subgraph_idx);+ auto& io = get_behavior_io(state, ctx.subgraph_idx, get_param_base(ctx, ctx.real_subgraph_idx), 0u);switch (m_kind) {case BehaviorKind::Dynamic:- request.behavior_prologue_dynamic(ctx.real_subgraph_idx, ctx.subgraph_idx);+ if (const auto* dynamic = ov::npuw::attn::get_compiled_dynamic(pipeline.context)) {+ auto mask_iport = compiled_model->inputs()[dynamic->mask_idx];+ const auto& graph_mask = io.inputs.at(dynamic->mask_idx);+ const auto this_case = state.attention_selector->this_case();+ auto pos_id = state.attention_selector->length();++ if (pos_id == -1) {+ ctx.target_request->set_tensor(mask_iport, graph_mask);+ return;+ }++ const auto past_len = state.attention_selector->past_length();+ const auto present_len = dynamic->query_size;+ auto set_or_copy = [&](const ov::SoPtr<ov::ITensor>& view) {+ if (!get_request(ctx).subgraph_needs_copy(ctx.subgraph_idx)) {+ ctx.target_request->set_tensor(mask_iport, view);+ } else {+ const auto& dst = ctx.target_request->get_tensor(mask_iport);+ dst->set_shape(view->get_shape());+ view->copy_to(dst._ptr);+ }+ };++ using namespace ov::npuw::runtime;+ if (this_case == attention::Selector::Case::GENERATE) {+ set_or_copy(ov::npuw::util::view(ov::get_tensor_impl(dynamic->attend_all),+ ATTN_KV_DIM,+ 0,+ past_len + 1));+ return;+ }+ if (this_case == attention::Selector::Case::PREFILL) {+ if (state.cached_attention_mask) {+ ctx.target_request->set_tensor(mask_iport, state.cached_attention_mask);+ return;+ }++ auto full_mask_shape = graph_mask->get_shape();+ auto actual_mask_shape = full_mask_shape;+ actual_mask_shape[ATTN_KV_DIM] = present_len + past_len;++ const auto& dst = ctx.target_request->get_tensor(mask_iport);+ dst->set_shape(actual_mask_shape);++ const auto& present_dst_view =+ ov::npuw::util::view(dst, ATTN_KV_DIM, past_len, present_len);+ const auto& present_src_view =+ ov::npuw::util::view(graph_mask,+ ATTN_KV_DIM,+ full_mask_shape[ATTN_KV_DIM] - present_len,+ present_len);+ present_src_view->copy_to(present_dst_view._ptr);++ if (past_len > 0) {+ const auto& past_dst_view = ov::npuw::util::view(dst, ATTN_KV_DIM, 0, past_len);+ const auto& past_src_view = ov::npuw::util::view(graph_mask, ATTN_KV_DIM, 0, past_len);+ past_src_view->copy_to(past_dst_view._ptr);+ }+ state.cached_attention_mask = dst;+ return;+ }+ }return;case BehaviorKind::Pyramid:- request.behavior_prologue_pyramid(ctx.real_subgraph_idx, ctx.subgraph_idx);+ if (const auto* pyramid = ov::npuw::attn::get_compiled_pyramid(pipeline.context)) {+ const auto pyramid_id = state.pyramid_selector->pyramid_id();+ const auto& dynamic = pyramid->_attention_infos[pyramid_id];+ auto mask_iport = pyramid->_compiled_models[pyramid_id]->inputs()[dynamic.mask_idx];+ const auto& graph_mask = io.inputs.at(dynamic.mask_idx);+ const auto this_case = state.pyramid_selector->this_case();+ const auto present_len = dynamic.query_size;+ const auto& dst = ctx.target_request->get_tensor(mask_iport);++ auto copy_mask_segment = [&](std::size_t dst_offset,+ std::size_t src_offset,+ std::size_t length) {+ if (length == 0) {+ return;+ }+ const auto& dst_view = ov::npuw::util::view(dst, ATTN_KV_DIM, dst_offset, length);+ const auto& src_view = ov::npuw::util::view(graph_mask, ATTN_KV_DIM, src_offset, length);+ ov::npuw::util::copy_tensor_by_dim(src_view, dst_view, ATTN_KV_DIM, ATTN_KV_DIM);+ };++ if (state.pyramid_selector->length() == -1) {+ ctx.target_request->set_tensor(mask_iport, graph_mask);+ return;+ }++ const auto past_len = state.pyramid_selector->past_length();+ if (state.cached_attention_mask) {+ ctx.target_request->set_tensor(mask_iport, state.cached_attention_mask);+ return;+ }++ const auto full_mask_shape = graph_mask->get_shape();+ using namespace ov::npuw::runtime;+ if (this_case == pyramid_attention::Selector::Case::GENERATE) {+ const auto dst_shape = dst->get_shape();+ if (dst_shape == full_mask_shape) {+ ctx.target_request->set_tensor(mask_iport, graph_mask);+ state.cached_attention_mask = graph_mask;+ return;+ }++ const std::size_t dst_present_offset = dst_shape[ATTN_KV_DIM] - present_len;+ copy_mask_segment(dst_present_offset,+ full_mask_shape[ATTN_KV_DIM] - present_len,+ present_len);+ copy_mask_segment(0, 0, dst_present_offset);+ state.cached_attention_mask = dst;+ return;+ }+ if (this_case == pyramid_attention::Selector::Case::PREFILL) {+ copy_mask_segment(past_len, full_mask_shape[ATTN_KV_DIM] - present_len, present_len);+ copy_mask_segment(0, 0, past_len);+ state.cached_attention_mask = dst;+ return;+ }+ OPENVINO_ASSERT(false, "Unsupported pyramid attention case");+ }return;case BehaviorKind::HFA:return;@@ -84,14 +655,219 @@ ov::npuw::v1::subgraphs::RuntimeBehaviorFactory make_runtime_factory() {}void run(ov::npuw::v1::subgraphs::InferContext& ctx) override {- auto& request = get_request(ctx);switch (m_kind) {case BehaviorKind::Dynamic:case BehaviorKind::Pyramid:ctx.legacy_infer();return;case BehaviorKind::HFA:- request.behavior_run_hfa(ctx.real_subgraph_idx, ctx.subgraph_idx);+ if (const auto* hfa_desc = ov::npuw::attn::get_compiled_hfa(+ get_subgraph_pipeline(ctx, ctx.real_subgraph_idx).context)) {+ auto& state = get_runtime_state(ctx);+ auto& io = get_behavior_io(state,+ ctx.subgraph_idx,+ get_param_base(ctx, ctx.real_subgraph_idx),+ hfa_desc->_compiled_final_tile_model->outputs().size());++ OPENVINO_ASSERT(hfa_desc->is_valid(), "HFA configuration must be valid");+ const int64_t tile_size = hfa_desc->_tile_size;+ const int64_t total_kv_length = state.hfa_selector->context_length();+ const int64_t num_tiles = total_kv_length / tile_size;+ OPENVINO_ASSERT(total_kv_length % tile_size == 0,+ "HFA total KV length must be multiple of tile size for now");++ const auto& hfa_inputs = io.inputs;+ const auto& sdpa_info = hfa_desc->_sdpa_attention_info;+ 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& regular_tile_request = state.hfa_requests.infer_requests[HFARequestSet::REGULAR_TILE];+ auto& final_tile_request = state.hfa_requests.infer_requests[HFARequestSet::FINAL_TILE];+ auto attention_output_tensor =+ final_tile_request->get_tensor(hfa_desc->_compiled_final_tile_model->outputs()[0]);+ const auto& tile_in = sdpa_info._tile_input_indices;+ const auto& tile_out = sdpa_info._tile_output_indices;++ ov::SoPtr<ov::ITensor> state_acc, state_max, state_sum;+ if (state.hfa_runtime_ctx && state.hfa_runtime_ctx->has_state_buffers()) {+ const auto& current_buffer = state.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 {+ 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]);+ runtime::host_flash_attention::HFARuntimeContext::initialize_state_tensors(state_acc,+ state_max,+ state_sum);+ }++ 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);+ 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);+ 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_tile_request->set_tensor(hfa_desc->_compiled_final_tile_model->outputs()[0],+ attention_output_tensor);++ 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;++ 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) {+ 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]);++ if (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 if (hfa_desc->_can_use_tensor_view) {+ request->set_tensor(model->inputs()[tile_in.k],+ ov::npuw::util::view(k_source, K_SEQ_DIM, kv_offset, tile_length));+ } else {+ extract_and_copy_tile(k_source, k_tile_buffer, K_SEQ_DIM, kv_offset, tile_length, "K");+ }++ if (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 if (hfa_desc->_can_use_tensor_view) {+ request->set_tensor(model->inputs()[tile_in.v],+ ov::npuw::util::view(v_source, V_SEQ_DIM, kv_offset, tile_length));+ } else {+ extract_and_copy_tile(v_source, v_tile_buffer, V_SEQ_DIM, kv_offset, tile_length, "V");+ }++ if (attention_mask_tensor) {+ if (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 (state.hfa_runtime_ctx.has_value()) {+ auto cached_tile =+ state.hfa_runtime_ctx->find_cached_mask_tile(attention_mask_tensor,+ mask_offset,+ tile_length);+ if (cached_tile) {+ request->set_tensor(model->inputs()[tile_in.mask], cached_tile);+ } else {+ ov::SoPtr<ov::ITensor> cached_mask_tile =+ state.hfa_runtime_ctx->get_mask_tile_buffer(next_available_mask_buffer_idx);+ extract_and_copy_tile(attention_mask_tensor,+ cached_mask_tile,+ MASK_KV_SEQ_DIM,+ mask_offset,+ tile_length,+ "Mask");+ state.hfa_runtime_ctx->cache_mask_tile(attention_mask_tensor,+ mask_offset,+ tile_length,+ cached_mask_tile);+ request->set_tensor(model->inputs()[tile_in.mask], cached_mask_tile);+ next_available_mask_buffer_idx++;+ }+ } else {+ extract_and_copy_tile(attention_mask_tensor,+ mask_tile_buffer,+ MASK_KV_SEQ_DIM,+ mask_offset,+ tile_length,+ "Mask");+ }+ }++ if (async) {+ request->start_async();+ if (state.hfa_runtime_ctx && state.hfa_runtime_ctx->has_state_buffers()) {+ state.hfa_runtime_ctx->prepare_next_state_buffers();+ }+ request->wait();+ } else {+ request->infer();+ }+ };++ int64_t mask_tile_offset = 0;+ int64_t kv_tile_offset = 0;+ 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;+ }++ 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);+ OPENVINO_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).");+ 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);+ }++ if (state.hfa_runtime_ctx && state.hfa_runtime_ctx->has_state_buffers()) {+ state.hfa_runtime_ctx->switch_buffers();+ }+ return;+ }return;}OPENVINO_THROW("Unsupported attention behavior kind");@@ -107,6 +883,144 @@ ov::npuw::v1::subgraphs::RuntimeBehaviorFactory make_runtime_factory() {} // namespace+void put_compiled_dynamic(v1::subgraphs::Context& context, CompiledDynamicState state) {+ context.put<CompiledDynamicState>(std::move(state));+}++void put_compiled_pyramid(v1::subgraphs::Context& context, CompiledPyramidState state) {+ context.put<CompiledPyramidState>(std::move(state));+}++void put_compiled_hfa(v1::subgraphs::Context& context, CompiledHFAState state) {+ context.put<CompiledHFAState>(std::move(state));+}++ov::npuw::compiled::Attention* get_compiled_dynamic(v1::subgraphs::Context& context) {+ return get_compiled_state<ov::npuw::compiled::Attention>(context);+}++const ov::npuw::compiled::Attention* get_compiled_dynamic(const v1::subgraphs::Context& context) {+ return get_compiled_state<ov::npuw::compiled::Attention>(context);+}++ov::npuw::compiled::PyramidAttention* get_compiled_pyramid(v1::subgraphs::Context& context) {+ return get_compiled_state<ov::npuw::compiled::PyramidAttention>(context);+}++const ov::npuw::compiled::PyramidAttention* get_compiled_pyramid(const v1::subgraphs::Context& context) {+ return get_compiled_state<ov::npuw::compiled::PyramidAttention>(context);+}++ov::npuw::compiled::HostFlashAttention* get_compiled_hfa(v1::subgraphs::Context& context) {+ return get_compiled_state<ov::npuw::compiled::HostFlashAttention>(context);+}++const ov::npuw::compiled::HostFlashAttention* get_compiled_hfa(const v1::subgraphs::Context& context) {+ return get_compiled_state<ov::npuw::compiled::HostFlashAttention>(context);+}++bool has_compiled_state(const v1::subgraphs::CompiledPipeline& pipeline) {+ return get_compiled_dynamic(pipeline.context) != nullptr || get_compiled_pyramid(pipeline.context) != nullptr ||+ get_compiled_hfa(pipeline.context) != nullptr;+}++void serialize_compiled_state(v1::subgraphs::Context& context,+ ov::npuw::s11n::Stream& stream,+ const ov::npuw::s11n::SubmodelDeserializeCtx* submodel_ctx) {+ std::optional<ov::npuw::compiled::Attention> dynamic;+ if (const auto* state = get_compiled_dynamic(context)) {+ dynamic = *state;+ }+ stream & dynamic;+ if (stream.input() && dynamic.has_value()) {+ put_compiled_dynamic(context, std::make_shared<ov::npuw::compiled::Attention>(dynamic.value()));+ }++ std::optional<ov::npuw::compiled::PyramidAttention> pyramid;+ if (const auto* state = get_compiled_pyramid(context)) {+ pyramid = *state;+ }+ stream & pyramid;+ if (stream.input() && pyramid.has_value()) {+ put_compiled_pyramid(context, std::make_shared<ov::npuw::compiled::PyramidAttention>(pyramid.value()));+ }++ auto* mutable_pyramid = get_compiled_pyramid(context);+ if (mutable_pyramid != nullptr) {+ size_t num_models = 0;+ if (stream.output()) {+ num_models = mutable_pyramid->_compiled_models.size();+ }+ stream & num_models;++ if (stream.output()) {+ for (size_t i = 0; i < num_models - 1; ++i) {+ std::stringstream ss;+ mutable_pyramid->_compiled_models[i]->export_model(ss);+ std::string model_str = ss.str();+ stream & model_str;+ }+ } else if (num_models > 0) {+ mutable_pyramid->_compiled_models.resize(num_models);+ NPUW_ASSERT(submodel_ctx != nullptr);+ for (size_t i = 0; i < num_models - 1; ++i) {+ std::string model_str;+ stream & model_str;+ std::stringstream ss(model_str);+ mutable_pyramid->_compiled_models[i] =+ submodel_ctx->plugin->get_core()->import_model(ss,+ submodel_ctx->device,+ submodel_ctx->import_config);+ }+ if (submodel_ctx->compiled_model) {+ mutable_pyramid->_compiled_models[num_models - 1] = submodel_ctx->compiled_model;+ LOG_DEBUG("Reused compiled_model for the last pyramid attention model");+ }+ }+ }++ std::optional<ov::npuw::compiled::HostFlashAttention> hfa;+ if (const auto* state = get_compiled_hfa(context)) {+ hfa = *state;+ }+ stream & hfa;+ if (stream.input() && hfa.has_value()) {+ put_compiled_hfa(context, std::make_shared<ov::npuw::compiled::HostFlashAttention>(hfa.value()));+ }++ auto* mutable_hfa = get_compiled_hfa(context);+ if (mutable_hfa != nullptr) {+ bool has_compiled_model = false;+ if (stream.output()) {+ has_compiled_model = mutable_hfa->_compiled_tile_model != nullptr;+ }+ stream & has_compiled_model;+ if (has_compiled_model) {+ if (stream.output()) {+ std::stringstream ss;+ mutable_hfa->_compiled_tile_model->export_model(ss);+ std::string model_str = ss.str();+ stream & model_str;+ } else {+ NPUW_ASSERT(submodel_ctx != nullptr);+ std::string model_str;+ stream & model_str;+ std::stringstream ss(model_str);+ mutable_hfa->_compiled_tile_model =+ submodel_ctx->plugin->get_core()->import_model(ss,+ submodel_ctx->device,+ submodel_ctx->import_config);+ LOG_DEBUG("Imported compiled tile model for host flash attention");+ }+ }+ if (stream.input()) {+ NPUW_ASSERT(submodel_ctx != nullptr);+ mutable_hfa->_compiled_final_tile_model = submodel_ctx->compiled_model;+ LOG_DEBUG("Set compiled final tile model reference for host flash attention");+ }+ }+}+void attach_runtime_behavior(ov::npuw::v1::subgraphs::CompiledPipeline& compiled_pipeline,ov::npuw::v1::subgraphs::Context& compiled_context,BehaviorKind kind) {@@ -139,15 +1053,19 @@ std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> register_patternattn_behavior.tag = ov::npuw::patterns::attn::SDPA::isolation_tag();attn_behavior.partition_stage = [](ov::npuw::Function& f, ov::npuw::v1::subgraphs::Context& ctx) {if (f._attention.has_value()) {- ctx.put<ov::npuw::compiled::Attention>(ov::npuw::compiled::Attention(f._attention.value(), f._model));+ put_compiled_dynamic(ctx, std::make_shared<ov::npuw::compiled::Attention>(f._attention.value(), f._model));ctx.put<BehaviorKind>(BehaviorKind::Dynamic);return;}if (f._pyramid_attention.has_value()) {+ put_compiled_pyramid(ctx,+ std::make_shared<ov::npuw::compiled::PyramidAttention>(f._pyramid_attention.value()));ctx.put<BehaviorKind>(BehaviorKind::Pyramid);return;}if (f._host_flash_attention.has_value()) {+ put_compiled_hfa(ctx,+ std::make_shared<ov::npuw::compiled::HostFlashAttention>(f._host_flash_attention.value()));ctx.put<BehaviorKind>(BehaviorKind::HFA);}};diff --git a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.hpp b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.hppindex 5876a63136c..e5c0824a328 100644--- a/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/attn/attn_subgraph.hpp@@ -4,16 +4,49 @@#pragma once+#include <memory>#include <vector>#include "../v1/subgraph_pipeline.hpp"namespace ov {namespace npuw {+namespace compiled {+struct Attention;+struct PyramidAttention;+struct HostFlashAttention;+} // namespace compiled+namespace s11n {+class Stream;+struct SubmodelDeserializeCtx;+} // namespace s11nnamespace attn {enum class BehaviorKind { Dynamic, Pyramid, HFA };+using CompiledDynamicState = std::shared_ptr<ov::npuw::compiled::Attention>;+using CompiledPyramidState = std::shared_ptr<ov::npuw::compiled::PyramidAttention>;+using CompiledHFAState = std::shared_ptr<ov::npuw::compiled::HostFlashAttention>;++void put_compiled_dynamic(v1::subgraphs::Context& context, CompiledDynamicState state);+void put_compiled_pyramid(v1::subgraphs::Context& context, CompiledPyramidState state);+void put_compiled_hfa(v1::subgraphs::Context& context, CompiledHFAState state);++ov::npuw::compiled::Attention* get_compiled_dynamic(v1::subgraphs::Context& context);+const ov::npuw::compiled::Attention* get_compiled_dynamic(const v1::subgraphs::Context& context);++ov::npuw::compiled::PyramidAttention* get_compiled_pyramid(v1::subgraphs::Context& context);+const ov::npuw::compiled::PyramidAttention* get_compiled_pyramid(const v1::subgraphs::Context& context);++ov::npuw::compiled::HostFlashAttention* get_compiled_hfa(v1::subgraphs::Context& context);+const ov::npuw::compiled::HostFlashAttention* get_compiled_hfa(const v1::subgraphs::Context& context);++bool has_compiled_state(const v1::subgraphs::CompiledPipeline& pipeline);++void serialize_compiled_state(v1::subgraphs::Context& context,+ ov::npuw::s11n::Stream& stream,+ const ov::npuw::s11n::SubmodelDeserializeCtx* submodel_ctx);+std::vector<ov::npuw::v1::subgraphs::ScopedPatternRegistration> register_patterns(ov::npuw::v1::subgraphs::PatternRegistry& registry);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.cppindex 4c9130596b5..951ea2e5baa 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@@ -7,6 +7,7 @@#include <sstream>+#include "attn/attn_subgraph.hpp"#include "compiled_model.hpp"#include "infer_request_utils.hpp" // to utilize copy_tensor_by_dim#include "intel_npu/config/npuw.hpp"@@ -424,9 +425,6 @@ 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 -> TOstd::vector<std::pair<ov::SoPtr<ov::ITensor>, ov::Output<const ov::Node>>> copy_list;@@ -442,41 +440,6 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ});};- // Check if the given subgraph's input is dynamic- auto is_attn_param = [&](std::size_t sub_in_idx) -> bool {- if (!is_attention) {- return false; // Early return- }- auto& attn = proto_comp_model_desc.attention.value();- return std::any_of(attn.params.begin(), attn.params.end(), [&](const auto& p) -> bool {- return p.idx == sub_in_idx;- });- };-- auto is_pyramid_attn_param = [&](std::size_t sub_in_idx) -> bool {- if (!is_pyramid_attention) {- return false; // Early return- }-- auto pyramid_id = m_pyramid_selector->pyramid_id();- auto& pyramid_attn = proto_comp_model_desc.pyramid_attention.value()._attention_infos[pyramid_id];- return std::any_of(pyramid_attn.params.begin(), pyramid_attn.params.end(), [&](const auto& p) -> bool {- return p.idx == sub_in_idx;- });- };-- 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;@@ -498,12 +461,8 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ// function pipeliningNPUW_ASSERT(false && "Global parameter can't be spatial");m_spatial_io[real_idx].inputs.at(sub_in_idx) = g_tnsr;- } else if (is_attn_param(sub_in_idx) || 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 if (bind_behavior_input(idx, real_idx, sub_in_idx, g_tnsr, request)) {+ continue;} 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);@@ -541,16 +500,6 @@ void ov::npuw::IBaseInferRequest::bind_global_params(std::size_t idx, RqPtr requ// Run host-side quantized gather, if requiredhandle_quant_host_gather(idx, request);- // Handle attention inputs, if required- m_profile["attn(io)"].record([&]() {- bind_attention_inputs(idx, request);- });-- // Handle pyramid attention inputs, if required- m_profile["attn(io)"].record([&]() {- bind_pyramid_attention_inputs(idx, request);- });-LOG_DEBUG("Done");}@@ -645,175 +594,12 @@ void ov::npuw::IBaseInferRequest::handle_quant_host_gather(std::size_t idx, RqPt}}-void ov::npuw::IBaseInferRequest::bind_attention_inputs(std::size_t idx, RqPtr request) {- auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real(idx)];- if (!comp_model_desc.attention) {- return;- }-- LOG_DEBUG("Binding Attention inputs...");- LOG_BLOCK();-- const auto& dynamic = comp_model_desc.attention.value();- auto& r = request;-- const auto pos_id = m_attention_selector->length();- if (pos_id == -1) {- // Dynamic range couldn't be identified - fallback to the default- // (worst case) behavior- for (auto&& param : dynamic.params) {- const auto& iport = comp_model_desc.compiled_model->inputs()[param.idx];- const auto& input = m_attention_io[idx].inputs.at(param.idx);- r->set_tensor(iport, input);- }- } else {- const auto past_len = m_attention_selector->past_length();- const auto do_copy = needs_copy(idx) && !m_npuw_model->m_cfg.get<::intel_npu::NPUW_ATTN_NO_COPY>();-- // Set the past k/v values first- for (auto&& param : dynamic.params) {- const auto& iport = comp_model_desc.compiled_model->inputs()[param.idx];- const auto& input = m_attention_io[idx].inputs.at(param.idx);- const auto& view = ov::npuw::util::view(input, param.dim, 0, past_len);- const auto shape = view->get_shape();-- LOG_DEBUG(iport);- LOG_BLOCK();- if (do_copy && ov::shape_size(shape) > 0) {- // FIXME: Same devices that don't tolerate set_, also don't tolerate strided inputs- const auto& dst = r->get_tensor(iport);- const auto old_ptr = dst->data();- dst->set_shape(shape);- const auto new_ptr = dst->data();- if (old_ptr != new_ptr) {- m_footprint[m_npuw_model->submodel_device(real(idx))] += dst->get_byte_size();- }- LOG_DEBUG("Do copy: " << shape << "...");- view->copy_to(dst._ptr);- } else if (do_copy && ov::shape_size(shape) == 0) {- // Special case for 0ths chunk.- // Zero the tensor shape but not set to view- // (a view tensor can't be extended)- r->get_tensor(iport)->set_shape(shape);- } else {- r->set_tensor(iport, view);- }- } // for(params)- }-- LOG_DEBUG("Done");-}--void ov::npuw::IBaseInferRequest::bind_pyramid_attention_inputs(std::size_t idx, RqPtr request) {- auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real(idx)];- if (!comp_model_desc.pyramid_attention) {- return;- }-- LOG_DEBUG("Binding Pyramid Attention inputs...");- LOG_BLOCK();-- const auto pyramid_id = m_pyramid_selector->pyramid_id();- const auto& pyramid_attention = comp_model_desc.pyramid_attention.value();- const auto& attention_info = pyramid_attention._attention_infos[pyramid_id];- const auto& pyramid_model = pyramid_attention._compiled_models[pyramid_id];-- const auto pos_id = m_pyramid_selector->length();- if (pos_id == -1) {- // Pyramid dynamic range couldn't be identified - fallback to the default- // (worst case) behavior- for (auto&& param : attention_info.params) {- const auto& iport = pyramid_model->inputs()[param.idx];- const auto& input = m_attention_io[idx].inputs.at(param.idx);- request->set_tensor(iport, input);- }-- return;- }-- // Pyramid dynamic range identified- const auto past_len = m_pyramid_selector->past_length();- const auto infer_case = m_pyramid_selector->this_case();-- using namespace ov::npuw::runtime;-- // Process each KV parameter based on inference case- if (infer_case == pyramid_attention::Selector::Case::PREFILL) {- // PREFILL: Set or copy past KV to destination tensors- for (auto&& param : attention_info.params) {- const auto& iport = pyramid_model->inputs()[param.idx];- const auto& input = m_attention_io[idx].inputs.at(param.idx);- const auto& input_shape = input->get_shape();-- LOG_DEBUG(iport);- LOG_BLOCK();-- // Optimization for the last chunk: Direct tensor reuse when shapes match- if (static_cast<int64_t>(input_shape[param.dim]) == past_len) {- request->set_tensor(iport, input);- continue;- }-- // Create view of past KV data- const auto& view = ov::npuw::util::view(input, param.dim, 0, past_len);- const auto& shape = view->get_shape();-- // Handle empty shape case (first chunk)- if (ov::shape_size(shape) == 0) {- request->get_tensor(iport)->set_shape(shape);- continue;- }-- // Copy past KV to full destination tensor- LOG_DEBUG("Do copy: " << shape << "...");- const auto& dst = request->get_tensor(iport);- ov::npuw::util::copy_tensor_by_dim(view,- dst,- static_cast<uint32_t>(param.dim),- static_cast<uint32_t>(param.dim));- }- } else if (infer_case == pyramid_attention::Selector::Case::GENERATE) {- // GENERATE: Set or copy past KV, preserving existing data- for (auto&& param : attention_info.params) {- const auto& iport = pyramid_model->inputs()[param.idx];- const auto& input = m_attention_io[idx].inputs.at(param.idx);- const auto& input_shape = input->get_shape();-- LOG_DEBUG(iport);- LOG_BLOCK();-- // Validation: ensure space for new tokens- if (static_cast<int64_t>(input_shape[param.dim]) == past_len) {- NPUW_ASSERT(false && "Past KV is full, no space for generation");- }-- const auto& dst = request->get_tensor(iport);- const auto& dst_shape = dst->get_shape();-- // Optimization: Direct tensor reuse when destination matches input- if (dst_shape == input_shape) {- request->set_tensor(iport, input);- continue;- }-- // FIXME: No need to copy whole past KV, just the new part-- // Create view of past KV data- const auto& view = ov::npuw::util::view(input, param.dim, 0, past_len);-- // Copy past KV to sliced destination (preserve space for new tokens)- LOG_DEBUG("Do copy: " << view->get_shape() << "...");- const auto& dst_slice = ov::npuw::util::view(dst, param.dim, 0, past_len);- ov::npuw::util::copy_tensor_by_dim(view,- dst_slice,- static_cast<uint32_t>(param.dim),- static_cast<uint32_t>(param.dim));- }- } else {- NPUW_ASSERT(false && "Unsupported pyramid attention case");- }-- LOG_DEBUG("Done");+bool ov::npuw::IBaseInferRequest::bind_behavior_input(std::size_t,+ std::size_t,+ std::size_t,+ const ov::SoPtr<ov::ITensor>&,+ RqPtr) {+ return false;}void ov::npuw::IBaseInferRequest::bind_global_results(std::size_t idx, RqPtr request) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/base_sync_infer_request.hppindex a149721ca3f..e116f4b5890 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@@ -13,8 +13,6 @@#include <unordered_set>#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"@@ -81,6 +79,14 @@ public:return m_history_size;}+ std::size_t get_run_iteration() const {+ return m_run_iter;+ }++ bool should_copy_subgraph_input(std::size_t idx) const {+ return needs_copy(idx);+ }+protected:int64_t m_history_size = 0;@@ -136,34 +142,11 @@ protected:};std::vector<SpatialIO> m_spatial_io;- // FIXME: All comments for SpatialIO above apply here as well.- struct AttentionIO {- std::vector<ov::SoPtr<ov::ITensor>> inputs; // # of elements - # of graph-side inputs- };- std::vector<AttentionIO> m_attention_io;-- // 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 inforuntime::spatial::Selector::Ptr m_spatial_selector;- // Same thing about this one- runtime::attention::Selector::Ptr m_attention_selector;-- // Separate selector for pyramid attention- runtime::pyramid_attention::Selector::Ptr m_pyramid_selector;-- // 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@@ -196,12 +179,14 @@ protected:void unpack_closure(std::size_t idx, RqPtr request);virtual void bind_global_params(std::size_t idx, RqPtr request);virtual void bind_global_results(std::size_t idx, RqPtr request);+ virtual bool bind_behavior_input(std::size_t idx,+ std::size_t real_idx,+ std::size_t input_idx,+ const ov::SoPtr<ov::ITensor>& tensor,+ RqPtr request);void alloc_quant_gather_tensors(std::size_t idx, RqPtr request);void handle_quant_host_gather(std::size_t idx, RqPtr request);- void bind_attention_inputs(std::size_t idx, RqPtr request);- void bind_pyramid_attention_inputs(std::size_t idx, RqPtr request);-void dump_input_tensors(std::size_t idx);void dump_output_tensors(std::size_t idx);diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cppindex 1207e76703d..51b4e039e74 100644--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.cpp@@ -470,27 +470,6 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,m_compiled_submodels[id].spatial =compiled::Spatial(fcn_template._spatial.value(), fcn_template._model);}- // Does the same for dynamic. FIXME: This selection should be hidden here- // in the object semantics- if (fcn_template._attention) {- m_compiled_submodels[id].attention =- compiled::Attention(fcn_template._attention.value(), fcn_template._model);- }-- if (fcn_template._pyramid_attention) {- LOG_INFO("Creating compiled::PyramidAttention for Subgraph[" << id << "] (function "- << subgraph._funcall << ")");- m_compiled_submodels[id].pyramid_attention =- compiled::PyramidAttention(fcn_template._pyramid_attention.value());- }-- 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@@ -551,8 +530,9 @@ ov::npuw::CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,}// Fix tensor names for pyramid attention models- if (const auto& pyramid_attn = m_compiled_submodels[real_id].pyramid_attention) {- for (const auto& model : pyramid_attn.value()._models_to_compile) {+ if (const auto* pyramid_attn =+ ov::npuw::attn::get_compiled_pyramid(m_compiled_submodels[real_id].pipeline.context)) {+ for (const auto& model : pyramid_attn->_models_to_compile) {fix_tensor_names(model);}}@@ -777,82 +757,17 @@ void ov::npuw::CompiledModel::CompiledModelDesc::serialize(ov::npuw::s11n::Streastream & replaced_by & param_base & forced_to_fcall & host_gather.dst_idx & host_gather.src_idx &host_gather.idx_idx & quant_unpack_gather.dst_idx & quant_unpack_gather.src_w_idx &- quant_unpack_gather.src_z_idx & quant_unpack_gather.src_s_idx & quant_unpack_gather.idx_idx & spatial &- attention & pyramid_attention;-- if (pyramid_attention.has_value()) {- size_t num_models = 0;- if (stream.output()) {- num_models = pyramid_attention.value()._compiled_models.size();- }- stream & num_models;-- if (stream.output()) {- for (size_t i = 0; i < num_models - 1; ++i) {- std::stringstream ss;- pyramid_attention.value()._compiled_models[i]->export_model(ss);- std::string model_str = ss.str();- stream & model_str;- }- } else if (num_models > 0) {- pyramid_attention.value()._compiled_models.resize(num_models);- NPUW_ASSERT(submodel_ctx != nullptr);- for (size_t i = 0; i < num_models - 1; ++i) {- std::string model_str;- stream & model_str;- std::stringstream ss(model_str);- pyramid_attention->_compiled_models[i] =- submodel_ctx->plugin->get_core()->import_model(ss,- submodel_ctx->device,- submodel_ctx->import_config);- }- 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");- }- }- }+ quant_unpack_gather.src_z_idx & quant_unpack_gather.src_s_idx & quant_unpack_gather.idx_idx & spatial;ov::npuw::moe::serialize_compiled_state(pipeline.context, stream, submodel_ctx);-- stream & host_flash_attention;- if (host_flash_attention.has_value()) {- bool has_compiled_model = false;- if (stream.output()) {- has_compiled_model = host_flash_attention.value()._compiled_tile_model != nullptr;- }- stream & has_compiled_model;- if (has_compiled_model) {- if (stream.output()) {- std::stringstream ss;- host_flash_attention.value()._compiled_tile_model->export_model(ss);- std::string model_str = ss.str();- stream & model_str;- } else {- NPUW_ASSERT(submodel_ctx != nullptr);- std::string model_str;- 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,- submodel_ctx->import_config);- LOG_DEBUG("Imported compiled tile model for host flash attention");- }- }- if (stream.input()) {- NPUW_ASSERT(submodel_ctx != nullptr);- host_flash_attention->_compiled_final_tile_model = submodel_ctx->compiled_model;- LOG_DEBUG("Set compiled final tile model reference for host flash attention");- }- }+ ov::npuw::attn::serialize_compiled_state(pipeline.context, stream, submodel_ctx);if (stream.input()) {- if (attention.has_value()) {+ if (ov::npuw::attn::get_compiled_dynamic(pipeline.context) != nullptr) {ov::npuw::attn::attach_runtime_behavior(pipeline, pipeline.context, ov::npuw::attn::BehaviorKind::Dynamic);- } else if (pyramid_attention.has_value()) {+ } else if (ov::npuw::attn::get_compiled_pyramid(pipeline.context) != nullptr) {ov::npuw::attn::attach_runtime_behavior(pipeline, pipeline.context, ov::npuw::attn::BehaviorKind::Pyramid);- } else if (host_flash_attention.has_value()) {+ } else if (ov::npuw::attn::get_compiled_hfa(pipeline.context) != nullptr) {ov::npuw::attn::attach_runtime_behavior(pipeline, pipeline.context, ov::npuw::attn::BehaviorKind::HFA);}}@@ -1435,6 +1350,14 @@ std::size_t ov::npuw::CompiledModel::num_submodels() const {return m_compiled_submodels.size();}+bool ov::npuw::CompiledModel::attention_dynamic_enabled() const {+ return m_cfg.get<::intel_npu::NPUW_ATTN_DYN>();+}++bool ov::npuw::CompiledModel::attention_no_copy() const {+ return m_cfg.get<::intel_npu::NPUW_ATTN_NO_COPY>();+}+std::shared_ptr<ov::npuw::weights::Bank> ov::npuw::CompiledModel::get_weights_bank() const {return m_weights_bank;}@@ -1691,7 +1614,7 @@ bool ov::npuw::CompiledModel::compile_for_success(std::size_t id, const std::vecdump_on_fail(id, device, "Avoided due to workaround");continue;}- if (desc.attention.has_value()) {+ if (ov::npuw::attn::get_compiled_dynamic(desc.pipeline.context) != nullptr) {bool has_dynamic = false;for (const auto& input : desc.model->inputs()) {if (input.get_partial_shape().is_dynamic()) {@@ -1787,12 +1710,11 @@ bool ov::npuw::CompiledModel::compile_for_success(std::size_t id, const std::vecdesc.compiled_model = make_wrapped(desc.model, "", main_candidates);}- if (desc.pyramid_attention.has_value()) {+ if (auto* pyramid_attn = ov::npuw::attn::get_compiled_pyramid(desc.pipeline.context)) {LOG_INFO("Compiling pyramid attention submodels for Subgraph[" << id << "]...");LOG_BLOCK();- auto& pyramid_attn = desc.pyramid_attention.value();- const auto& pyramid_attn_models = pyramid_attn._models_to_compile;+ const auto& pyramid_attn_models = pyramid_attn->_models_to_compile;const size_t total_models = pyramid_attn_models.size();const size_t models_to_compile = total_models > 0 ? total_models - 1 : 0;@@ -1817,16 +1739,15 @@ bool ov::npuw::CompiledModel::compile_for_success(std::size_t id, const std::veccompiled_models[total_models - 1] = desc.compiled_model;}- pyramid_attn.set_compiled_models(std::move(compiled_models));+ pyramid_attn->set_compiled_models(std::move(compiled_models));LOG_INFO("Pyramid attention compilation complete for Subgraph[" << id << "]");}- if (desc.host_flash_attention.has_value()) {+ if (auto* hfa = ov::npuw::attn::get_compiled_hfa(desc.pipeline.context)) {LOG_INFO("Compiling host flash attention tile models for Subgraph[" << id << "]...");LOG_BLOCK();- auto& hfa = desc.host_flash_attention.value();- if (!hfa._tile_model_to_compile) {+ if (!hfa->_tile_model_to_compile) {LOG_WARN("Host flash attention tile model is null, skipping compilation");} else {for (const auto& device : devices) {@@ -1844,15 +1765,15 @@ bool ov::npuw::CompiledModel::compile_for_success(std::size_t id, const std::veccontinue;}- hfa._can_use_tensor_view = true;+ hfa->_can_use_tensor_view = true;auto strided_inputs_name = std::string(hfa_tile_input_id_to_string(HFATileInputId::K_TILE)) + "," +std::string(hfa_tile_input_id_to_string(HFATileInputId::V_TILE));m_meta_devices[device][ov::intel_npu::enable_strides_for.name()] = strided_inputs_name;LOG_INFO("Enabled using tensor view for device: " << device << " for inputs: " << strided_inputs_name);}- hfa.set_compiled_tile_model(make_wrapped(hfa._tile_model_to_compile, "/hfa_tile", devices));- hfa.set_compiled_final_tile_model(desc.compiled_model);+ hfa->set_compiled_tile_model(make_wrapped(hfa->_tile_model_to_compile, "/hfa_tile", devices));+ hfa->set_compiled_final_tile_model(desc.compiled_model);LOG_INFO("Host flash attention compilation complete for Subgraph[" << id << "]");}}@@ -1962,9 +1883,9 @@ void ov::npuw::CompiledModel::dump_subgraph_model(std::size_t id,LOG_INFO("Wrote " << model_dump_path);// Dump pyramid attention models if present- if (m_compiled_submodels[id].pyramid_attention) {+ if (const auto* pyramid_attn = ov::npuw::attn::get_compiled_pyramid(m_compiled_submodels[id].pipeline.context)) {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;+ const auto& pyramid_attention_models = pyramid_attn->_models_to_compile;for (std::size_t idx = 0; idx < pyramid_attention_models.size(); ++idx) {std::string pyramid_attention_model_name = format_subgraph_name(id, funcall) + "_pyramid_" +ov::npuw::util::fmt(idx, pyramid_attention_models.size()) +@@ -1977,16 +1898,15 @@ void ov::npuw::CompiledModel::dump_subgraph_model(std::size_t id,}// Dump host flash attention models if present- if (m_compiled_submodels[id].host_flash_attention) {+ if (const auto* hfa = ov::npuw::attn::get_compiled_hfa(m_compiled_submodels[id].pipeline.context)) {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;+ const auto& hfa_tile_model = hfa->_tile_model_to_compile;std::string hfa_tile_model_name = format_subgraph_name(id, funcall) + "_hfa_tile.xml";std::string hfa_tile_model_dump_path = ov::util::path_join({dump_dir, hfa_tile_model_name}).string();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;+ const auto& hfa_final_tile_model = hfa->_final_tile_model_to_compile;std::string hfa_final_tile_model_name = format_subgraph_name(id, funcall) + "_hfa_final_tile.xml";std::string hfa_final_tile_model_dump_path =ov::util::path_join({dump_dir, hfa_final_tile_model_name}).string();@@ -2035,14 +1955,15 @@ void ov::npuw::CompiledModel::dump_subgraph_composition(const std::vector<ov::np} else {base_subgraphs.push_back(base_name + ".xml");- if (m_compiled_submodels[real_id].pyramid_attention) {- const auto& pyramid_models = m_compiled_submodels[real_id].pyramid_attention.value()._models_to_compile;+ if (const auto* pyramid_attn =+ ov::npuw::attn::get_compiled_pyramid(m_compiled_submodels[real_id].pipeline.context)) {+ const auto& pyramid_models = pyramid_attn->_models_to_compile;for (std::size_t idx = 0; idx < pyramid_models.size(); ++idx) {attn_subgraphs.push_back(base_name + "_pyramid_" + ov::npuw::util::fmt(idx, pyramid_models.size()) +".xml");}}- if (m_compiled_submodels[real_id].host_flash_attention) {+ if (ov::npuw::attn::get_compiled_hfa(m_compiled_submodels[real_id].pipeline.context) != nullptr) {attn_subgraphs.push_back(base_name + "_hfa_tile.xml");attn_subgraphs.push_back(base_name + "_hfa_final_tile.xml");}diff --git a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hppindex e66c3c2d918..bc97a8f9046 100644--- a/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/compiled_model.hpp@@ -116,6 +116,8 @@ public:std::shared_ptr<IBaseInferRequest> internal_request) const override;std::string submodel_device(std::size_t idx) const override;std::size_t num_submodels() const override;+ bool attention_dynamic_enabled() const;+ bool attention_no_copy() const;std::shared_ptr<weights::Bank> get_weights_bank() const override;void set_weights_bank(std::shared_ptr<weights::Bank> bank) override;void finalize_weights_bank() override;@@ -230,33 +232,8 @@ private:Subgraph::Gather host_gather;Subgraph::QuantUnpackGather quant_unpack_gather;std::optional<ov::npuw::compiled::Spatial> spatial;- std::optional<ov::npuw::compiled::Attention> attention;- std::optional<ov::npuw::compiled::PyramidAttention> pyramid_attention;- std::optional<ov::npuw::compiled::HostFlashAttention> host_flash_attention;ov::npuw::v1::subgraphs::CompiledPipeline pipeline;- // Infer requests for pyramid attention models (if pyramid_attention is present)- std::vector<ov::SoPtr<ov::IAsyncInferRequest>> pyramid_infer_requests;-- // Pipeline infer requests for pyramid attention models (if pyramid_attention is present and pipelining is- // enabled)- std::vector<ov::SoPtr<ov::IAsyncInferRequest>> pyramid_pipeline_requests;-- // 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;-// Infer requests for MoE expert models with different chunk sizes (if MoE expert state is present)// Map: chunk_size -> infer_requeststd::map<size_t, ov::SoPtr<ov::IAsyncInferRequest>> moe_infer_requests;diff --git a/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/just_sync_infer_request.cppindex 006e4bd316f..f215b999f23 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@@ -10,6 +10,7 @@#include <memory>#include <string>+#include "attn/attn_subgraph.hpp"#include "compiled_model.hpp"#include "host_flash_attention.hpp"#include "infer_request_utils.hpp" // to utilize copy_tensor_by_dim@@ -57,6 +58,44 @@ std::string ov::npuw::JustInferRequest::subgraph_device(size_t idx) {return m_npuw_model->submodel_device(idx);}+void ov::npuw::JustInferRequest::set_active_subrequest(size_t idx, ov::SoPtr<ov::IAsyncInferRequest> request) {+ m_subrequests[idx] = std::move(request);+}++ov::SoPtr<ov::IAsyncInferRequest> ov::npuw::JustInferRequest::get_pipeline_subrequest(size_t idx) const {+ return idx < m_funcall_pipeline.size() ? m_funcall_pipeline[idx].subrequest : ov::SoPtr<ov::IAsyncInferRequest>{};+}++void ov::npuw::JustInferRequest::set_pipeline_subrequest(size_t idx, ov::SoPtr<ov::IAsyncInferRequest> request) {+ if (idx < m_funcall_pipeline.size()) {+ m_funcall_pipeline[idx].subrequest = std::move(request);+ }+}++bool ov::npuw::JustInferRequest::is_subrequest_pipelined(size_t idx) const {+ return is_pipelined(idx);+}++std::size_t ov::npuw::JustInferRequest::history_size() const {+ return get_history_size();+}++bool ov::npuw::JustInferRequest::subgraph_needs_copy(std::size_t idx) const {+ return needs_copy(idx);+}++const ov::SoPtr<ov::ICompiledModel>& ov::npuw::JustInferRequest::compiled_submodel(size_t idx) const {+ return m_npuw_model->m_compiled_submodels.at(idx).compiled_model;+}++const ov::npuw::v1::subgraphs::CompiledPipeline& ov::npuw::JustInferRequest::subgraph_pipeline(size_t idx) const {+ return m_npuw_model->m_compiled_submodels.at(idx).pipeline;+}++std::size_t ov::npuw::JustInferRequest::subgraph_param_base(size_t idx) const {+ return m_npuw_model->m_compiled_submodels.at(idx).param_base;+}+// ====================================================================================================// Memory Access Simulation & Function Memory Management// ====================================================================================================@@ -248,19 +287,11 @@ 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 requestsbool has_spatial = false;- bool has_dynamic = false;- bool has_pyramid = false;- bool has_hfa = false;bool has_moe = false;- std::size_t dynamic_sub_idx = -1;- std::size_t pyramid_sub_idx = -1;- std::size_t hfa_sub_idx = -1;std::size_t moe_real_idx = -1; // Track which real function has MoEfor (size_t i = 0; i < m_num_submodels; i++) {LOG_INFO("Creating infer request for Subgraph[" << i << "]...");@@ -308,40 +339,6 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Com}} // if(spatial)- // Initialize the dynamic IO placeholders, if required- if (proto_comp_model_desc.attention) {- // Sanity check first- if (has_dynamic && dynamic_sub_idx != real_idx) {- OPENVINO_THROW("Only single attention type is permitted for model");- }- has_dynamic = true;- dynamic_sub_idx = real_idx;- m_attention_io[i].inputs.resize(proto_comp_model_desc.param_base);- } // if(dynamic)-- if (proto_comp_model_desc.pyramid_attention) {- // Sanity check first- if (has_pyramid && pyramid_sub_idx != real_idx) {- OPENVINO_THROW("Only single pyramid attention type is permitted for model");- }- has_pyramid = true;- pyramid_sub_idx = real_idx;- m_attention_io[i].inputs.resize(proto_comp_model_desc.param_base);- } // if(pyramid)-- 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)-// Initialize the MoE IO placeholders, if requiredif (ov::npuw::moe::has_compiled_experts(proto_comp_model_desc.pipeline)) {// Sanity check: ensure only one MoE function type exists@@ -372,23 +369,6 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Comm_funcall_pipeline[i].subrequest = rqs.at(1);}- // Create pyramid attention infer requests if this function has pyramid attention- // IMPORTANT: Must be created AFTER main infer requests to enable direct reuse:- // The last pyramid infer request directly reuses the main infer request object- if (comp_model_desc.replaced_by) {- const auto real_idx = comp_model_desc.replaced_by.value();- auto& proto_comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];- if (proto_comp_model_desc.pyramid_attention) {- setup_pyramid_infer_requests(real_idx, is_piped);- }- // 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,- /* enable_hfa_optimizations */ true);- }- }-LOG_INFO("DONE");} // for(submodels)@@ -466,52 +446,6 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::ComLOG_VERB("Done");}- // Handle pyramid attention- if (has_pyramid) {- const auto& pyramid_dyn = m_npuw_model->m_compiled_submodels.at(pyramid_sub_idx).pyramid_attention.value();- const auto pyramid_count = pyramid_dyn._compiled_models.size();- if (!m_npuw_model->m_cfg.get<::intel_npu::NPUW_ATTN_DYN>()) {- // Even if the attention is detected and ready to go pyramid,- // force it on the full range- m_pyramid_selector.reset(new runtime::pyramid_attention::All(pyramid_count));- } else {- m_pyramid_selector = runtime::pyramid_attention::PositionIDs::find(pyramid_dyn, *this);- if (!m_pyramid_selector) {- LOG_WARN("Pyramid dynamic capability is enabled, but no run-time features were found.");- // Create All selector with the number of pyramid models- m_pyramid_selector.reset(new runtime::pyramid_attention::All(pyramid_count));- }- }- }-- 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");- }-- // Initialize the dynamic-attention selector eagerly so bind_attention_inputs() can use- // it from the pipelining (PREP-NEXT) path before DynAttnBehavior::prologue runs.- if (has_dynamic) {- const auto& dynamic = m_npuw_model->m_compiled_submodels.at(dynamic_sub_idx).attention.value();- if (!m_npuw_model->m_cfg.get<::intel_npu::NPUW_ATTN_DYN>()) {- m_attention_selector = std::make_shared<runtime::attention::All>();- } else {- m_attention_selector = runtime::attention::PositionIDs::find(dynamic, *this);- if (!m_attention_selector) {- LOG_WARN("Dynamic capability is enabled, but no run-time features were found.");- m_attention_selector = std::make_shared<runtime::attention::All>();- }- }- LOG_VERB("Done");- }-// Initialize MoE executor if MoE was detectedif (has_moe) {initialize_moe_executor();@@ -520,6 +454,7 @@ ov::npuw::JustInferRequest::JustInferRequest(const std::shared_ptr<ov::npuw::Comvoid ov::npuw::JustInferRequest::initialize_subgraph_behaviors() {m_subgraph_behaviors.resize(m_num_submodels);+ m_subgraph_runtime_states.resize(m_num_submodels);for (std::size_t idx = 0; idx < m_num_submodels; idx++) {const auto& comp_model_desc = m_npuw_model->m_compiled_submodels[idx];if (!comp_model_desc.compiled_model && !comp_model_desc.replaced_by) {@@ -550,22 +485,46 @@ void ov::npuw::JustInferRequest::initialize_subgraph_behaviors() {ov::npuw::v1::subgraphs::InferContext ov::npuw::JustInferRequest::make_behavior_context(std::size_t real_idx,std::size_t idx) {const bool is_function_call = m_npuw_model->m_compiled_submodels[idx].replaced_by.has_value();- return ov::npuw::v1::subgraphs::InferContext{*m_npuw_model,- *this,- idx,- real_idx,- [this, real_idx, idx]() {- legacy_infer(real_idx, idx);- },- is_function_call ? std::function<void()>{[this, idx]() {- function_prologue(idx);- }}- : std::function<void()>{},- [this, real_idx, idx]() {- OPENVINO_ASSERT(m_moe_executor != nullptr,- "Expected MoE executor for opaque MoE run");- m_moe_executor->run(real_idx, idx);- }};+ return ov::npuw::v1::subgraphs::InferContext{+ *m_npuw_model,+ *this,+ idx,+ real_idx,+ m_subrequests[real_idx],+ real_idx < m_subgraph_runtime_states.size() ? &m_subgraph_runtime_states[real_idx] : nullptr,+ [this, real_idx, idx]() {+ legacy_infer(real_idx, idx);+ },+ is_function_call ? std::function<void()>{[this, idx]() {+ function_prologue(idx);+ }}+ : std::function<void()>{},+ [this, real_idx, idx]() {+ OPENVINO_ASSERT(m_moe_executor != nullptr, "Expected MoE executor for opaque MoE run");+ m_moe_executor->run(real_idx, idx);+ }};+}++bool ov::npuw::JustInferRequest::bind_behavior_input(std::size_t idx,+ std::size_t real_idx,+ std::size_t input_idx,+ const ov::SoPtr<ov::ITensor>& tensor,+ RqPtr request) {+ auto* behavior = get_subgraph_behavior(idx);+ if (behavior == nullptr) {+ return false;+ }+ auto ctx = ov::npuw::v1::subgraphs::InferContext{+ *m_npuw_model,+ *this,+ idx,+ real_idx,+ std::move(request),+ real_idx < m_subgraph_runtime_states.size() ? &m_subgraph_runtime_states[real_idx] : nullptr,+ {},+ {},+ {}};+ return behavior->bind_function_input(ctx, input_idx, tensor);}const ov::npuw::v1::subgraphs::RuntimeBehaviorSpec* ov::npuw::JustInferRequest::get_runtime_behavior_spec(@@ -594,86 +553,6 @@ bool ov::npuw::JustInferRequest::behavior_handles_function_prologue(std::size_treturn spec != nullptr && spec->handles_function_prologue;}-bool ov::npuw::JustInferRequest::behavior_bind_dynamic_input(std::size_t real_idx,- std::size_t idx,- std::size_t input_idx,- const ov::SoPtr<ov::ITensor>& tensor) {- auto& func_desc = m_npuw_model->m_compiled_submodels[real_idx];- NPUW_ASSERT(func_desc.attention.has_value());-- const auto& dynamic = func_desc.attention.value();- const bool is_non_param_mask = std::none_of(dynamic.params.begin(),- dynamic.params.end(),- [&](auto&& param) {- return param.idx == input_idx;- }) &&- input_idx != dynamic.mask_idx;-- const auto& iport = func_desc.compiled_model->inputs()[input_idx];- if (is_non_param_mask) {- m_subrequests[real_idx]->set_tensor(iport, tensor);- } else {- m_attention_io[idx].inputs.at(input_idx) = tensor;- }- return true;-}--bool ov::npuw::JustInferRequest::behavior_bind_pyramid_input(std::size_t real_idx,- std::size_t idx,- std::size_t input_idx,- const ov::SoPtr<ov::ITensor>& tensor) {- auto& func_desc = m_npuw_model->m_compiled_submodels[real_idx];- NPUW_ASSERT(func_desc.pyramid_attention.has_value());- NPUW_ASSERT(m_pyramid_selector);-- const auto pyramid_id = m_pyramid_selector->pyramid_id();- const auto& info = func_desc.pyramid_attention.value()._attention_infos[pyramid_id];- const bool is_non_param_mask = std::none_of(info.params.begin(),- info.params.end(),- [&](auto&& param) {- return param.idx == input_idx;- }) &&- input_idx != info.mask_idx;-- const auto& iport = func_desc.compiled_model->inputs()[input_idx];- if (is_non_param_mask) {- m_subrequests[real_idx]->set_tensor(iport, tensor);- } else {- m_attention_io[idx].inputs.at(input_idx) = tensor;- }- return true;-}--bool ov::npuw::JustInferRequest::behavior_bind_hfa_input(std::size_t idx,- std::size_t input_idx,- const ov::SoPtr<ov::ITensor>& tensor) {- m_hfa_io[idx].inputs.at(input_idx) = tensor;- return true;-}--bool ov::npuw::JustInferRequest::behavior_bind_hfa_output(std::size_t idx,- std::size_t output_idx,- const ov::SoPtr<ov::ITensor>& tensor) {- m_hfa_io[idx].outputs.at(output_idx) = tensor;- return true;-}--void ov::npuw::JustInferRequest::behavior_prologue_dynamic(std::size_t real_idx, std::size_t idx) {- m_profile["attn(act)"] += ov::npuw::perf::ms_to_run([&]() {- function_prologue_attn(real_idx, idx);- });-}--void ov::npuw::JustInferRequest::behavior_prologue_pyramid(std::size_t real_idx, std::size_t idx) {- m_profile["attn(act)"] += ov::npuw::perf::ms_to_run([&]() {- function_prologue_pyramid_attn(real_idx, idx);- });-}--void ov::npuw::JustInferRequest::behavior_run_hfa(std::size_t real_idx, std::size_t idx) {- run_hfa_tiled_inference(real_idx, idx);-}-void ov::npuw::JustInferRequest::set_tensor(const ov::Output<const ov::Node>& port,const ov::SoPtr<ov::ITensor>& tensor) {std::unique_lock lock(m_io_storages_mutex);@@ -778,21 +657,20 @@ void ov::npuw::JustInferRequest::prepare_for_infer() {LOG_DEBUG("Preparing to infer...");LOG_BLOCK();- if (m_pyramid_selector) {- m_pyramid_selector->prepare(get_history_size());-- // Get the pyramid model ID based on current sequence length (updated in prepare())- auto pyramid_id = m_pyramid_selector->pyramid_id();+ // Adjust spatial input range, if supported+ if (m_spatial_selector) {+ m_spatial_selector->prepare();+ }- for (auto&& id : m_funcall_heads) {- auto& comp_model_desc = m_npuw_model->m_compiled_submodels[id];- if (comp_model_desc.pyramid_attention.has_value()) {- m_subrequests[id] = comp_model_desc.pyramid_infer_requests[pyramid_id];- if (is_pipelined(id)) {- m_funcall_pipeline[id].subrequest = comp_model_desc.pyramid_pipeline_requests[pyramid_id];- }- }+ for (std::size_t idx = 0; idx < m_num_submodels; idx++) {+ auto* behavior = get_subgraph_behavior(idx);+ if (behavior == nullptr) {+ continue;}+ auto& comp_model_desc = m_npuw_model->m_compiled_submodels[idx];+ const auto real_idx = comp_model_desc.replaced_by.value_or(idx);+ auto ctx = make_behavior_context(real_idx, idx);+ behavior->prepare(ctx);}// Submit global parameters (if needed) for the first subgraph@@ -805,27 +683,6 @@ void ov::npuw::JustInferRequest::prepare_for_infer() {unpack_closure(id, m_subrequests[id]);}- // Adjust spatial input range, if supported- if (m_spatial_selector) {- m_spatial_selector->prepare();- }-- // So do the dynamic range- if (m_attention_selector) {- 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 = {};-LOG_DEBUG("Done");}@@ -975,172 +832,6 @@ void ov::npuw::JustInferRequest::function_prologue(std::size_t idx) {LOG_DEBUG("Done");}-void ov::npuw::JustInferRequest::function_prologue_attn(std::size_t real_idx, std::size_t idx) {- auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];- NPUW_ASSERT(comp_model_desc.attention.has_value());-- auto& r = m_subrequests[real_idx];-- const auto& dynamic = comp_model_desc.attention.value();- auto mask_iport = comp_model_desc.compiled_model->inputs()[dynamic.mask_idx];-- const auto& graph_mask = m_attention_io[idx].inputs.at(dynamic.mask_idx);- const auto this_case = m_attention_selector->this_case();- auto pos_id = m_attention_selector->length();-- if (pos_id == -1) {- // Dynamic range couldn't be identified - fallback to the default- // (worst case) behavior- r->set_tensor(mask_iport, graph_mask);- } else {- const auto past_len = m_attention_selector->past_length();- const auto present_len = dynamic.query_size;- // FIXME: get the right dim- const uint32_t kv_dim = 3;-- auto set_or_copy = [&](const auto& view) {- if (!needs_copy(idx)) {- r->set_tensor(mask_iport, view);- } else {- const auto& dst = r->get_tensor(mask_iport);- dst->set_shape(view->get_shape());- view->copy_to(dst._ptr);- }- };-- // Now set the mask. Here comes very strong chunking & SDPA knowledge again- using namespace ov::npuw::runtime;- if (this_case == attention::Selector::Case::GENERATE) {- // Take a view from our "attend_all" mask- const auto& view = ov::npuw::util::view(ov::get_tensor_impl(dynamic.attend_all), kv_dim, 0, past_len + 1);- set_or_copy(view);- } else if (this_case == attention::Selector::Case::PREFILL) {- // Use our in-graph synthesized mask- if (m_cached_attention_mask) {- // All sub models are sharing the same attention mask, we can use the cached attention- // mask directly to avoid redundant tensor copy- m_subrequests[real_idx]->set_tensor(mask_iport, m_cached_attention_mask);- return;- }-- // Handle attention mask concatenation for SDPA:- // The attention mask is composed with 2 parts:- // The 1st part is for the "present", which is at the tail: starting from past_len to context_len- // The 2nd part is for the "past", which is at the beginning: starting from 0 to past_len- auto full_mask_shape = graph_mask->get_shape();- auto actual_mask_shape = full_mask_shape;- actual_mask_shape[kv_dim] = present_len + past_len;-- // Reshape the input to the proper shape- const auto& dst = r->get_tensor(mask_iport);- dst->set_shape(actual_mask_shape);-- // Copy "present" attention mask- const auto& present_dst_view = ov::npuw::util::view(dst, kv_dim, past_len, present_len);- const auto& present_src_view =- ov::npuw::util::view(graph_mask, kv_dim, full_mask_shape[kv_dim] - present_len, present_len);- present_src_view->copy_to(present_dst_view._ptr);-- // Copy "past" attention mask- if (past_len > 0) {- const auto& past_dst_view = ov::npuw::util::view(dst, kv_dim, 0, past_len);- const auto& past_src_view = ov::npuw::util::view(graph_mask, kv_dim, 0, past_len);- past_src_view->copy_to(past_dst_view._ptr);- }- m_cached_attention_mask = dst;- } else {- NPUW_ASSERT(false && "Reached the unreachable code");- }- }-}--void ov::npuw::JustInferRequest::function_prologue_pyramid_attn(std::size_t real_idx, std::size_t idx) {- auto& comp_model_desc = m_npuw_model->m_compiled_submodels[real_idx];- NPUW_ASSERT(comp_model_desc.pyramid_attention.has_value());-- auto& r = m_subrequests[real_idx];- auto pyramid_id = m_pyramid_selector->pyramid_id();-- const auto& dynamic = comp_model_desc.pyramid_attention.value()._attention_infos[pyramid_id];- auto mask_iport =- comp_model_desc.pyramid_attention.value()._compiled_models[pyramid_id]->inputs()[dynamic.mask_idx];-- const auto& graph_mask = m_attention_io[idx].inputs.at(dynamic.mask_idx);- const auto this_case = m_pyramid_selector->this_case();- const auto present_len = dynamic.query_size;-- // FIXME: get the right dim- const uint32_t kv_dim = 3;-- // Get destination tensor once for all code paths- const auto& dst = r->get_tensor(mask_iport);-- // Lambda: copy attention mask segment from source to destination- auto copy_mask_segment = [&](std::size_t dst_offset, std::size_t src_offset, std::size_t length) {- if (length == 0) {- return;- }- const auto& dst_view = ov::npuw::util::view(dst, kv_dim, dst_offset, length);- const auto& src_view = ov::npuw::util::view(graph_mask, kv_dim, src_offset, length);- ov::npuw::util::copy_tensor_by_dim(src_view, dst_view, kv_dim, kv_dim);- };-- auto pos_id = m_pyramid_selector->length();- if (pos_id == -1) {- // Pyramid dynamic range couldn't be identified - fallback to default behavior- r->set_tensor(mask_iport, graph_mask);- return;- }-- // Pyramid dynamic range identified- const auto past_len = m_pyramid_selector->past_length();-- // Early return: reuse cached attention mask if available- if (m_cached_attention_mask) {- // All sub models are sharing the same attention mask, we can use the cached attention- // mask directly to avoid redundant tensor copy- m_subrequests[real_idx]->set_tensor(mask_iport, m_cached_attention_mask);- return;- }-- // Now set the mask. Here comes very strong chunking & SDPA knowledge again- using namespace ov::npuw::runtime;- const auto full_mask_shape = graph_mask->get_shape();-- if (this_case == pyramid_attention::Selector::Case::GENERATE) {- const auto dst_shape = dst->get_shape();-- // Optimization: if shapes match, use the full mask directly- if (dst_shape == full_mask_shape) {- r->set_tensor(mask_iport, graph_mask);- m_cached_attention_mask = graph_mask;- return;- }-- // FIXME: No need to copy whole attention mask, just mark the new tokens to valid-- std::size_t dst_present_offset = dst_shape[kv_dim] - present_len;-- // Copy present mask: tail of source -> tail of destination- copy_mask_segment(dst_present_offset, full_mask_shape[kv_dim] - present_len, present_len);-- // Copy past mask: head of source [0, dst_present_offset) -> head of destination- copy_mask_segment(0, 0, dst_present_offset);-- m_cached_attention_mask = dst;- } else if (this_case == pyramid_attention::Selector::Case::PREFILL) {- // Copy present mask: tail of source -> [past_len, past_len + present_len)- copy_mask_segment(past_len, full_mask_shape[kv_dim] - present_len, present_len);-- // Copy past mask: head of source -> [0, past_len)- copy_mask_segment(0, 0, past_len);-- m_cached_attention_mask = dst;- } else {- NPUW_ASSERT(false && "Unsupported pyramid attention case");- }-}-void ov::npuw::JustInferRequest::initialize_moe_executor() {LOG_INFO("Creating MoE executor...");@@ -1171,207 +862,6 @@ void ov::npuw::JustInferRequest::initialize_moe_executor() {LOG_INFO("MoE executor initialized successfully");}-void ov::npuw::JustInferRequest::setup_pyramid_infer_requests(std::size_t real_idx, bool is_piped) {- auto& submodel_desc = m_npuw_model->m_compiled_submodels[real_idx];- if (!submodel_desc.pyramid_attention.has_value()) {- return;- }-- LOG_INFO("Creating pyramid infer requests...");- LOG_BLOCK();-- const auto& pyramid_models = submodel_desc.pyramid_attention.value()._compiled_models;- const size_t num_pyramid_models = pyramid_models.size();-- // Allocate storage for infer requests- submodel_desc.pyramid_infer_requests.resize(num_pyramid_models);- if (is_piped) {- submodel_desc.pyramid_pipeline_requests.resize(num_pyramid_models);- }-- // Create infer requests for all but the last pyramid model- for (size_t model_idx = 0; model_idx + 1 < num_pyramid_models; ++model_idx) {- submodel_desc.pyramid_infer_requests[model_idx] = pyramid_models[model_idx]->create_infer_request();- if (is_piped) {- submodel_desc.pyramid_pipeline_requests[model_idx] = pyramid_models[model_idx]->create_infer_request();- }-- // Share input tensors between pyramid and main infer requests- const size_t num_inputs = pyramid_models[model_idx]->inputs().size();- NPUW_ASSERT(num_inputs == submodel_desc.compiled_model->inputs().size());- for (size_t input_idx = 0; input_idx < num_inputs; ++input_idx) {- auto pyramid_input = pyramid_models[model_idx]->inputs()[input_idx];- auto main_input = submodel_desc.compiled_model->inputs()[input_idx];-- // Get tensor from main infer request and share its memory with the pyramid infer request- auto main_tensor_ptr = m_subrequests[real_idx]->get_tensor(main_input)->data();- auto pyramid_tensor = submodel_desc.pyramid_infer_requests[model_idx]->get_tensor(pyramid_input);- auto shared_tensor = ov::get_tensor_impl(- ov::Tensor(pyramid_tensor->get_element_type(), pyramid_tensor->get_shape(), main_tensor_ptr));- submodel_desc.pyramid_infer_requests[model_idx]->set_tensor(pyramid_input, shared_tensor);-- // Repeat for pipeline infer request if pipelined- if (is_piped) {- auto pipeline_tensor = submodel_desc.pyramid_pipeline_requests[model_idx]->get_tensor(pyramid_input);- auto pipeline_tensor_ptr = m_funcall_pipeline[real_idx].subrequest->get_tensor(main_input)->data();- auto shared_pipeline_tensor = ov::get_tensor_impl(- ov::Tensor(pipeline_tensor->get_element_type(), pipeline_tensor->get_shape(), pipeline_tensor_ptr));- submodel_desc.pyramid_pipeline_requests[model_idx]->set_tensor(pyramid_input, shared_pipeline_tensor);- }- }- }-- // For the last pyramid model, reuse the original model's infer requests- if (num_pyramid_models > 0) {- const size_t last_model_idx = num_pyramid_models - 1;- LOG_INFO("Reusing original infer requests for last pyramid model[" << last_model_idx << "]");- submodel_desc.pyramid_infer_requests[last_model_idx] = m_subrequests[real_idx];- if (is_piped) {- submodel_desc.pyramid_pipeline_requests[last_model_idx] = m_funcall_pipeline[real_idx].subrequest;- }-- // Anchor input tensors here; see m_pyramid_anchor_tensors.- const size_t num_inputs = submodel_desc.compiled_model->inputs().size();- for (size_t input_idx = 0; input_idx < num_inputs; ++input_idx) {- auto main_input = submodel_desc.compiled_model->inputs()[input_idx];- m_pyramid_anchor_tensors.emplace_back(real_idx, m_subrequests[real_idx]->get_tensor(main_input));- if (is_piped) {- m_pyramid_anchor_tensors.emplace_back(real_idx,- m_funcall_pipeline[real_idx].subrequest->get_tensor(main_input));- }- }- }-- if (num_pyramid_models > 0) {- LOG_INFO("Successfully created " << (num_pyramid_models - 1)- << " new pyramid infer requests and reused 1 original request");- }-}--void ov::npuw::JustInferRequest::setup_hfa_infer_requests(std::size_t real_idx,- bool is_piped,- 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("Creating HFA tile infer requests...");- LOG_BLOCK();-- const auto& hfa = submodel_desc.host_flash_attention.value();-- // 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);- }-- 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();- }-- // 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 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 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();- }-- LOG_INFO("Pre-allocating HFA mask tile buffers...");-- // Initialize pre-allocated buffers- m_hfa_runtime_ctx->initialize_mask_cache(- hfa,- m_npuw_model->submodel_device(real_idx),- [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,- m_npuw_model->submodel_device(real_idx),- [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) {auto& comp_model_desc = m_npuw_model->m_compiled_submodels[idx];const auto real_idx = comp_model_desc.replaced_by.value_or(idx);@@ -1414,7 +904,7 @@ void ov::npuw::JustInferRequest::run_subrequest_for_success(std::size_t idx) {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 && !comp_model_desc.host_flash_attention.has_value() &&+ if (!comp_model_desc.spatial && ov::npuw::attn::get_compiled_hfa(comp_model_desc.pipeline.context) == nullptr &&!ov::npuw::moe::has_compiled_experts(comp_model_desc.pipeline)) {// Normal: trigger request asynchronously, run `f` in this context// FIXME: dynamic could hit here too, but it has special logic@@ -1431,358 +921,6 @@ void ov::npuw::JustInferRequest::unsafe_during(std::size_t real_idx, std::size_t}}-// ====================================================================================================-// 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 if (hfa_desc._can_use_tensor_view) {- request->set_tensor(model->inputs()[tile_in.k],- ov::npuw::util::view(k_source, K_SEQ_DIM, kv_offset, tile_length));- } 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 if (hfa_desc._can_use_tensor_view) {- request->set_tensor(model->inputs()[tile_in.v],- ov::npuw::util::view(v_source, V_SEQ_DIM, kv_offset, tile_length));-- } 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());@@ -1891,8 +1029,6 @@ void ov::npuw::JustInferRequest::legacy_infer(std::size_t real_idx, std::size_tauto& 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.hppindex e5d0de39fbf..afbd3ef59de 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@@ -84,6 +84,15 @@ public:bool unpack_required(size_t idx, size_t cidx) override;bool needs_copy_closure(size_t idx, size_t cidx) override;std::string subgraph_device(size_t idx) override;+ void set_active_subrequest(size_t idx, ov::SoPtr<ov::IAsyncInferRequest> request);+ ov::SoPtr<ov::IAsyncInferRequest> get_pipeline_subrequest(size_t idx) const;+ void set_pipeline_subrequest(size_t idx, ov::SoPtr<ov::IAsyncInferRequest> request);+ bool is_subrequest_pipelined(size_t idx) const;+ std::size_t history_size() const;+ bool subgraph_needs_copy(std::size_t idx) const;+ const ov::SoPtr<ov::ICompiledModel>& compiled_submodel(size_t idx) const;+ const ov::npuw::v1::subgraphs::CompiledPipeline& subgraph_pipeline(size_t idx) const;+ std::size_t subgraph_param_base(size_t idx) const;protected:////////////////////////////////////@@ -111,62 +120,29 @@ protected:void bind_global_parameters(std::size_t idx);void bind_global_results(std::size_t idx);using IBaseInferRequest::bind_global_results;+ bool bind_behavior_input(std::size_t idx,+ std::size_t real_idx,+ std::size_t input_idx,+ const ov::SoPtr<ov::ITensor>& tensor,+ RqPtr request) override;void function_prologue(std::size_t idx);- void function_prologue_attn(std::size_t real_idx, std::size_t idx);- void function_prologue_pyramid_attn(std::size_t real_idx, std::size_t idx);void unsafe_during(std::size_t real_idx, std::size_t idx, const std::function<void()>& f);void unsafe_infer(std::size_t real_idx, std::size_t idx);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);void legacy_infer(std::size_t real_idx, std::size_t idx);ov::npuw::v1::subgraphs::InferContext make_behavior_context(std::size_t real_idx, std::size_t idx);const ov::npuw::v1::subgraphs::RuntimeBehaviorSpec* get_runtime_behavior_spec(std::size_t idx) const;ov::npuw::v1::subgraphs::ISubgraphBehavior* get_subgraph_behavior(std::size_t idx) const;bool behavior_handles_function_prologue(std::size_t idx) const;-public:- bool behavior_bind_dynamic_input(std::size_t real_idx,- std::size_t idx,- std::size_t input_idx,- const ov::SoPtr<ov::ITensor>& tensor);- bool behavior_bind_pyramid_input(std::size_t real_idx,- std::size_t idx,- std::size_t input_idx,- const ov::SoPtr<ov::ITensor>& tensor);- bool behavior_bind_hfa_input(std::size_t idx, std::size_t input_idx, const ov::SoPtr<ov::ITensor>& tensor);- bool behavior_bind_hfa_output(std::size_t idx, std::size_t output_idx, const ov::SoPtr<ov::ITensor>& tensor);- void behavior_prologue_dynamic(std::size_t real_idx, std::size_t idx);- void behavior_prologue_pyramid(std::size_t real_idx, std::size_t idx);- void behavior_run_hfa(std::size_t real_idx, std::size_t idx);-protected:- // HFA helper 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 initialize_subgraph_behaviors();- // Helper function to setup pyramid attention infer requests- void setup_pyramid_infer_requests(std::size_t real_idx, bool is_piped);-- // Helper function to setup host flash attention tile infer requests- void setup_hfa_infer_requests(std::size_t real_idx, bool is_piped, bool enable_hfa_optimizations = true);-// Helper function to initialize/reinitialize MoE executorvoid initialize_moe_executor();@@ -194,26 +170,11 @@ protected:// Cached check if we do FOLDing and need to update closures in the repeating blocksbool m_closure_update_required = false;- // Cached attention mask for SDPA operations to avoid recomputing- ov::SoPtr<ov::ITensor> m_cached_attention_mask;-- // HFA runtime context (holds cached masks, pre-allocated buffers, and state buffers)- std::optional<runtime::host_flash_attention::HFARuntimeContext> m_hfa_runtime_ctx;-// MoE executor (encapsulates MoE inference logic and profiling)std::unique_ptr<ov::npuw::moe::MoEExecutor> m_moe_executor;- // Anchor tensors that keep pyramid shared buffers alive.- // The pyramid infer requests share memory via raw pointers wrapped in ov::Tensor.- // Without these anchors the original tensor SoPtr can drop to zero when- // bind_pyramid_attention_inputs calls set_tensor on m_subrequests for the last chunk,- // freeing the buffer while pyramid requests still hold raw pointers into it.- // Each entry is {real_idx, tensor} so recreate can selectively remove by submodel.- std::vector<std::pair<std::size_t, ov::SoPtr<ov::ITensor>>> m_pyramid_anchor_tensors;-- // Foundation for the upcoming behavior-driven execution pipeline.- // These slots are populated now but legacy execution still owns the scheduling.std::vector<ov::npuw::v1::subgraphs::ISubgraphBehavior::Ptr> m_subgraph_behaviors;+ std::vector<ov::npuw::v1::subgraphs::Context> m_subgraph_runtime_states;};} // namespace npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cppindex b850f2ca025..b02421deee1 100644--- a/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/unfold_sync_infer_request.cpp@@ -4,6 +4,7 @@#include "unfold_sync_infer_request.hpp"+#include "attn/attn_subgraph.hpp"#include "compiled_model.hpp"#include "logging.hpp"#include "openvino/core/parallel.hpp"@@ -30,7 +31,7 @@ ov::npuw::UnfoldInferRequest::UnfoldInferRequest(const std::shared_ptr<ov::npuw:if (proto_comp_model_desc.spatial) {NPUW_ASSERT(false && "Spatial is not supported in unfold");}- if (proto_comp_model_desc.attention) {+ if (ov::npuw::attn::get_compiled_dynamic(proto_comp_model_desc.pipeline.context) != nullptr) {NPUW_ASSERT(false && "Dynamic is not supported in unfold");}} // if(replaced_by)diff --git a/src/plugins/intel_npu/src/plugin/npuw/v1/subgraph_pipeline.hpp b/src/plugins/intel_npu/src/plugin/npuw/v1/subgraph_pipeline.hppindex 2a4905221c5..05436febf9b 100644--- a/src/plugins/intel_npu/src/plugin/npuw/v1/subgraph_pipeline.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/v1/subgraph_pipeline.hpp@@ -24,6 +24,7 @@namespace ov {class Model;class ICompiledModel;+class IAsyncInferRequest;} // namespace ovnamespace ov::npuw {@@ -143,6 +144,7 @@ class ISubgraphBehavior {public:using Ptr = std::unique_ptr<ISubgraphBehavior>;+ virtual void prepare(InferContext&) {}virtual bool bind_function_input(InferContext&, std::size_t, const ov::SoPtr<ov::ITensor>&) {return false;}@@ -180,6 +182,8 @@ struct InferContext {ov::npuw::IBaseInferRequest& infer_request;std::size_t subgraph_idx = 0u;std::size_t real_subgraph_idx = 0u;+ ov::SoPtr<ov::IAsyncInferRequest> target_request;+ Context* runtime_state = nullptr;std::function<void()> legacy_infer;std::function<void()> opaque_prologue;std::function<void()> opaque_run;