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] Support Eagle3 Topk (#34349)
Guoliang Shi9313439cc2d6
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cppindex 849a74bdce5..6b7b388e312 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp@@ -812,14 +812,17 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mov::npuw::ReshapeToStatic(static_cast<uint32_t>(m_prefill_chunk_size),m_kvcache_desc.max_prompt_size,axes,- m_max_lora_rank)+ m_max_lora_rank,+ 0,+ true).run_on_model(prefill_model);} else {ov::npuw::ReshapeToStatic(m_kvcache_desc.max_prompt_size,m_kvcache_desc.max_prompt_size,axes,m_max_lora_rank,- whisper_lhs_seq_size)+ whisper_lhs_seq_size,+ true).run_on_model(prefill_model);}LOG_DEBUG("Make kvcache model with static shapes");diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.cppindex 87a50cf623e..9e431b599ce 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.cpp@@ -19,13 +19,18 @@ bool matchEagle3HiddenStatesString(const std::string& input) {return input == Eagle3LayerNames::hidden_states;}+bool matchEagle3TreeMaskString(const std::string& input) {+ return input == Eagle3LayerNames::eagle_tree_mask;+}+ov::PartialShape Eagle3Extension::get_static_input(const std::shared_ptr<ov::Model>& model,const ov::Output<ov::Node>& input,- uint32_t input_size) {+ uint32_t input_size,+ uint32_t kvcache_size,+ bool is_prefill) {const auto& input_name = input.get_any_name();const auto& input_shape = input.get_partial_shape();- // Check if this is an Eagle3 hidden_states inputif (matchEagle3HiddenStatesString(input_name)) {OPENVINO_ASSERT(input_shape.size() == 3u,"Eagle3 hidden_states must have 3 dimensions: [batch, seq_len, hidden_size]");@@ -49,29 +54,52 @@ ov::PartialShape Eagle3Extension::get_static_input(const std::shared_ptr<ov::Mod"could not be inferred from last_hidden_state output");}- return ov::PartialShape();-}+ if (matchEagle3TreeMaskString(input_name)) {+ // During prefill (including chunked prefill) the tree mask degenerates to a single 1×1 entry.+ // During generation the mask covers all past KV positions for each token.+ if (is_prefill) {+ return ov::PartialShape({1, 1, 1, 1});+ }+ return ov::PartialShape({1, 1, input_size, kvcache_size});+ }-void Eagle3Extension::validate_hidden_state_tensor(const ov::SoPtr<ov::ITensor>& tensor, const std::string& name) {- OPENVINO_ASSERT(ov::element::f32 == tensor->get_element_type() || ov::element::f16 == tensor->get_element_type(),- name + " input must be float32 or float16");- OPENVINO_ASSERT(tensor->get_shape().size() == 3,- name + " input must have 3 dimensions: [batch, token_length, embedding_size]");+ OPENVINO_THROW("Eagle3Extension::get_static_input called with unexpected input name '",+ input_name,+ "'. Expected '",+ Eagle3LayerNames::hidden_states,+ "' or '",+ Eagle3LayerNames::eagle_tree_mask,+ "'.");}-void Eagle3Extension::store_hidden_state_inputs(const ov::IInferRequest& request,- const std::vector<ov::Output<const ov::Node>>& inputs) {- // Only draft models need hidden state inputs- if (m_role != Eagle3ModelRole::Draft) {- return;+void Eagle3Extension::store_user_inputs(const ov::IInferRequest& request,+ const std::vector<ov::Output<const ov::Node>>& inputs) {+ // Store eagle_tree_mask for both Draft and Target models+ auto tree_mask_port = util::find_port_by_name(inputs, Eagle3LayerNames::eagle_tree_mask);+ if (tree_mask_port.has_value()) {+ auto tensor = request.get_tensor(tree_mask_port.value());+ OPENVINO_ASSERT(+ tensor->get_element_type() == ov::element::f32 || tensor->get_element_type() == ov::element::f16,+ "eagle_tree_mask input must be float32 or float16");+ OPENVINO_ASSERT(tensor->get_shape().size() == 4,+ "eagle_tree_mask must have 4 dimensions: [batch, 1, input_size, kvcache_size]");+ OPENVINO_ASSERT(tensor->get_shape()[0] == 1, "eagle_tree_mask batch dimension must be 1");+ OPENVINO_ASSERT(tensor->get_shape()[1] == 1, "eagle_tree_mask second dimension must be 1");+ m_eagle_tree_mask = tensor;}+ // Store hidden_states for Draft model onlyauto hidden_states_port = util::find_port_by_name(inputs, Eagle3LayerNames::hidden_states);- OPENVINO_ASSERT(hidden_states_port.has_value(),- "Eagle3 Draft model requires 'hidden_states' input to be provided by user");- auto hidden_states_tensor = request.get_tensor(hidden_states_port.value());- validate_hidden_state_tensor(hidden_states_tensor, "hidden_states");- m_hidden_states = hidden_states_tensor;+ if (hidden_states_port.has_value()) {+ auto tensor = request.get_tensor(hidden_states_port.value());+ OPENVINO_ASSERT(+ tensor->get_element_type() == ov::element::f32 || tensor->get_element_type() == ov::element::f16,+ "hidden_states input must be float32 or float16");+ OPENVINO_ASSERT(tensor->get_shape().size() == 3,+ "hidden_states must have 3 dimensions: [batch, token_length, embedding_size]");+ OPENVINO_ASSERT(tensor->get_shape()[0] == 1, "hidden_states batch dimension must be 1");+ m_hidden_states = tensor;+ }}} // namespace npuw@@ -79,29 +107,72 @@ void Eagle3Extension::store_hidden_state_inputs(const ov::IInferRequest& requestnamespace {+// Represents a contiguous run of accepted tokens within the speculative decoding mask+struct KVCacheSegment {+ uint32_t start_idx; ///< Index in the acceptance mask where this run begins+ uint32_t length; ///< Number of consecutive accepted tokens+};+void pad_hidden_state_input(const ov::SoPtr<ov::ITensor>& hidden_state,const ov::SoPtr<ov::ITensor>& padded_hidden_state) {- // Pad the token_length dimension (dimension 1) of hidden state input [batch, token_length, embedding_size]- auto hidden_state_shape = hidden_state->get_shape();- auto padded_shape = padded_hidden_state->get_shape();- OPENVINO_ASSERT(hidden_state_shape.size() == 3,- "Hidden state input should have 3 dimensions: [batch, token_length, embedding_size]");- OPENVINO_ASSERT(padded_shape.size() == 3,- "Padded hidden state should have 3 dimensions: [batch, token_length, embedding_size]");+ // Pad the token_length dimension of hidden state input [batch, token_length, embedding_size].+ // Caller guarantees both tensors are rank-3 with batch=1 (validated in store_user_inputs).+ constexpr size_t kTokenDim = 1;+ constexpr size_t kEmbedDim = 2;- OPENVINO_ASSERT(hidden_state_shape[0] == 1, "Batch size must be 1 for Eagle3 hidden states");- OPENVINO_ASSERT(padded_shape[0] == 1, "Padded batch size must be 1 for Eagle3 hidden states");+ const auto& src_shape = hidden_state->get_shape();+ const auto& dst_shape = padded_hidden_state->get_shape();- OPENVINO_ASSERT(padded_shape[2] == hidden_state_shape[2], "Embedding size must match");- OPENVINO_ASSERT(padded_shape[1] >= hidden_state_shape[1], "Padded token length must be >= input token length");+ OPENVINO_ASSERT(dst_shape[kEmbedDim] == src_shape[kEmbedDim], "Embedding size must match");+ OPENVINO_ASSERT(dst_shape[kTokenDim] >= src_shape[kTokenDim], "Padded token length must be >= input token length");- // Zero-fill the padded tensorov::npuw::util::fill_tensor_bytes(padded_hidden_state, 0u);- // Copy hidden state data to the right side+ // Tokens are right-aligned: copy src flush to the right end of dst.ov::npuw::util::copy_to_right(hidden_state, padded_hidden_state);}+void pad_tree_mask_input(const ov::SoPtr<ov::ITensor>& tree_mask, const ov::SoPtr<ov::ITensor>& padded_tree_mask) {+ // Pad the tree mask tensor [batch, 1, input_size, kvcache_size].+ // The user-provided mask is placed in the bottom-right corner of the padded tensor;+ // the remaining entries are zero-filled.+ // This handles both prefill (padded shape {1,1,1,1}) and generate phases uniformly.+ // Caller guarantees both tensors are rank-4 with batch=1 and heads=1 (validated in store_user_inputs).+ constexpr size_t kInputSizeDim = 2;+ constexpr size_t kKVSizeDim = 3;++ const auto& src_shape = tree_mask->get_shape();+ const auto& dst_shape = padded_tree_mask->get_shape();++ OPENVINO_ASSERT(dst_shape[kInputSizeDim] >= src_shape[kInputSizeDim],+ "Padded input_size must be >= original input_size");+ OPENVINO_ASSERT(dst_shape[kKVSizeDim] >= src_shape[kKVSizeDim],+ "Padded kvcache_size must be >= original kvcache_size");++ const size_t input_size = src_shape[kInputSizeDim];+ const size_t padded_input_size = dst_shape[kInputSizeDim];+ const size_t kvcache_size = src_shape[kKVSizeDim];+ const size_t padded_kvcache_size = dst_shape[kKVSizeDim];+ const size_t elem_size = tree_mask->get_element_type().size();++ const uint8_t* src_data = reinterpret_cast<const uint8_t*>(tree_mask->data());+ uint8_t* dst_data = reinterpret_cast<uint8_t*>(padded_tree_mask->data());++ std::memset(dst_data, 0, padded_tree_mask->get_byte_size());++ // Place source rows in the bottom-right corner: left-pad rows by row_padding,+ // left-pad columns by col_padding. This matches the causal attention convention+ // where new query tokens attend to all prior KV positions (top-left is oldest context).+ const size_t row_padding = padded_input_size - input_size;+ const size_t col_padding = padded_kvcache_size - kvcache_size;++ for (size_t i = 0; i < input_size; ++i) {+ const uint8_t* src_row = src_data + i * kvcache_size * elem_size;+ uint8_t* dst_row = dst_data + (i + row_padding) * padded_kvcache_size * elem_size + col_padding * elem_size;+ std::memcpy(dst_row, src_row, kvcache_size * elem_size);+ }+}+} // anonymous namespacenamespace ov {@@ -117,34 +188,47 @@ void Eagle3Extension::initialize(bool is_eagle_model,// It's an Eagle3 model, now determine if it's Draft or Target based on inputs/outputsbool has_hidden_states_input = in_ports.find(Eagle3LayerNames::hidden_states) != in_ports.end();+ bool has_eagle_tree_mask_input = in_ports.find(Eagle3LayerNames::eagle_tree_mask) != in_ports.end();bool has_last_hidden_state_output = out_ports.find(Eagle3LayerNames::last_hidden_state) != out_ports.end();- if (has_hidden_states_input && has_last_hidden_state_output) {+ if (has_hidden_states_input && has_eagle_tree_mask_input && has_last_hidden_state_output) {m_role = Eagle3ModelRole::Draft;LOG_INFO("Eagle3 Draft Model detected");- } else if (!has_hidden_states_input && has_last_hidden_state_output) {+ } else if (!has_hidden_states_input && has_eagle_tree_mask_input && has_last_hidden_state_output) {m_role = Eagle3ModelRole::Target;LOG_INFO("Eagle3 Target Model detected");} else {OPENVINO_THROW("Eagle3 mode enabled via NPUW_EAGLE property, but model structure doesn't match Draft or Target pattern. "- "Draft requires: hidden_states input + last_hidden_state output. "- "Target requires: last_hidden_state output only.");+ "Draft requires: hidden_states input + eagle_tree_mask input + last_hidden_state output. "+ "Target requires: eagle_tree_mask input + last_hidden_state output.");}++ // Create sampling state for external pipeline communication+ m_sampling_state = std::make_shared<Eagle3SamplingState>();}void Eagle3Extension::prepare_inputs(const std::shared_ptr<ov::IAsyncInferRequest>& request,const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports) {- // Only draft models need to prepare Eagle3 inputs- if (m_role != Eagle3ModelRole::Draft) {- return;+ // Eagle3 models (both Draft and Target) MUST have eagle_tree_mask+ auto tree_mask_it = in_ports.find(Eagle3LayerNames::eagle_tree_mask);+ OPENVINO_ASSERT(tree_mask_it != in_ports.end(), "Eagle3 model must have eagle_tree_mask input port");+ OPENVINO_ASSERT(m_eagle_tree_mask, "Eagle3 model requires eagle_tree_mask tensor to be provided by user");++ auto padded_tree_mask = request->get_tensor(tree_mask_it->second);+ pad_tree_mask_input(m_eagle_tree_mask, padded_tree_mask);+ LOG_VERB("Eagle3: Set eagle_tree_mask input tensor");++ // Draft models MUST have hidden_states+ if (m_role == Eagle3ModelRole::Draft) {+ auto hidden_states_it = in_ports.find(Eagle3LayerNames::hidden_states);+ OPENVINO_ASSERT(hidden_states_it != in_ports.end(), "Eagle3 Draft model must have hidden_states input port");+ OPENVINO_ASSERT(m_hidden_states, "Eagle3 Draft model requires hidden_states tensor to be provided by user");++ auto padded_hidden_states = request->get_tensor(hidden_states_it->second);+ pad_hidden_state_input(m_hidden_states, padded_hidden_states);+ LOG_VERB("Eagle3: Set hidden_states input tensor");}-- auto hidden_states_it = in_ports.find(Eagle3LayerNames::hidden_states);- OPENVINO_ASSERT(hidden_states_it != in_ports.end(), "Eagle3 Draft model must have hidden_states input port");- OPENVINO_ASSERT(m_hidden_states, "Eagle3 Draft model requires hidden_states input tensor to be provided");- auto padded_hidden_states = request->get_tensor(hidden_states_it->second);- pad_hidden_state_input(m_hidden_states, padded_hidden_states);}void Eagle3Extension::update_last_hidden_state(@@ -164,10 +248,6 @@ void Eagle3Extension::accumulate_chunk_last_hidden_state(const std::unordered_map<std::string, ov::Output<const ov::Node>>& out_ports,uint32_t chunk_token_count,uint32_t total_seq_len) {- if (m_role == Eagle3ModelRole::None) {- return;- }-auto last_hidden_state_it = out_ports.find(Eagle3LayerNames::last_hidden_state);OPENVINO_ASSERT(last_hidden_state_it != out_ports.end(), "Eagle3 model must have last_hidden_state output port");@@ -176,10 +256,13 @@ void Eagle3Extension::accumulate_chunk_last_hidden_state(OPENVINO_ASSERT(chunk_shape.size() == 3, "last_hidden_state must have 3 dimensions: [batch, seq_len, hidden_size]");- const uint32_t batch_size = static_cast<uint32_t>(chunk_shape[0]);- const uint32_t chunk_seq_len = static_cast<uint32_t>(chunk_shape[1]);- const uint32_t hidden_size = static_cast<uint32_t>(chunk_shape[2]);+ constexpr size_t kBatchDim = 0;+ constexpr size_t kSeqDim = 1;+ constexpr size_t kHiddenDim = 2;+ const uint32_t batch_size = static_cast<uint32_t>(chunk_shape[kBatchDim]);+ const uint32_t chunk_seq_len = static_cast<uint32_t>(chunk_shape[kSeqDim]);+ const uint32_t hidden_size = static_cast<uint32_t>(chunk_shape[kHiddenDim]);OPENVINO_ASSERT(batch_size == 1, "Batch size must be 1 for Eagle3");OPENVINO_ASSERT(chunk_token_count <= chunk_seq_len, "chunk_token_count must be <= chunk_seq_len");@@ -230,16 +313,24 @@ void Eagle3Extension::prepare_inputs_for_chunk(const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,uint32_t chunk_start_token,uint32_t chunk_token_count) {- // Only draft models need chunk-specific input preparation+ // Eagle3 models (both Draft and Target) MUST have eagle_tree_mask+ auto tree_mask_it = in_ports.find(Eagle3LayerNames::eagle_tree_mask);+ OPENVINO_ASSERT(tree_mask_it != in_ports.end(), "Eagle3 model must have eagle_tree_mask input port");+ OPENVINO_ASSERT(m_eagle_tree_mask, "Eagle3 model requires eagle_tree_mask tensor to be provided by user");++ auto padded_tree_mask = request->get_tensor(tree_mask_it->second);+ pad_tree_mask_input(m_eagle_tree_mask, padded_tree_mask);+ LOG_VERB("Eagle3 Chunk: Set eagle_tree_mask input tensor (full mask, not chunked)");++ // Draft models MUST have hidden_states for chunked prefillif (m_role != Eagle3ModelRole::Draft) {return;}- OPENVINO_ASSERT(chunk_token_count > 0, "Chunk token count must be greater than 0");- OPENVINO_ASSERT(m_hidden_states, "Eagle3 Draft model requires hidden_states input tensor to be provided");-auto hidden_states_it = in_ports.find(Eagle3LayerNames::hidden_states);OPENVINO_ASSERT(hidden_states_it != in_ports.end(), "Eagle3 Draft model must have hidden_states input port");+ OPENVINO_ASSERT(m_hidden_states, "Eagle3 Draft model requires hidden_states tensor to be provided by user");+ OPENVINO_ASSERT(chunk_token_count > 0, "Chunk token count must be greater than 0");auto padded_tensor = request->get_tensor(hidden_states_it->second);@@ -266,5 +357,188 @@ void Eagle3Extension::prepare_inputs_for_chunk(<< "] for chunk processing");}+void Eagle3Extension::adjust_kvcache_before_infer(+ std::shared_ptr<ov::IAsyncInferRequest> request,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,+ uint32_t& num_stored_tokens,+ bool v_transposed,+ uint32_t kv_dim) {+ LOG_DEBUG("Eagle3: Adjusting KV cache based on sampling result");+ LOG_BLOCK();++ auto& result = m_pending_sampling_result;++ if (result.num_total_generated == 0 || result.accepted_token_mask.empty()) {+ LOG_DEBUG("Eagle3: No pending sampling result, skipping KV cache adjustment");+ return;+ }++ OPENVINO_ASSERT(result.accepted_token_mask.size() == result.num_total_generated,+ "Eagle3: accepted_token_mask size must equal num_total_generated");++ // Verify the header fields are consistent with the mask contents.+ const uint32_t actual_accepted =+ static_cast<uint32_t>(std::count(result.accepted_token_mask.begin(), result.accepted_token_mask.end(), true));+ OPENVINO_ASSERT(actual_accepted == result.num_accepted_tokens,+ "Eagle3: num_accepted_tokens (" + std::to_string(result.num_accepted_tokens) ++ ") must equal the number of true values in accepted_token_mask (" ++ std::to_string(actual_accepted) + ")");++ uint32_t tokens_to_discard = result.num_total_generated - result.num_accepted_tokens;++ if (tokens_to_discard == 0) {+ LOG_DEBUG("Eagle3: All generated tokens were accepted, no KV cache adjustment needed");+ result = SamplingResult();+ return;+ }++ LOG_DEBUG("Eagle3: Discarding " << tokens_to_discard << " tokens, keeping " << result.num_accepted_tokens+ << " tokens");++ // Fast path: accepted tokens are contiguous from the start — num_stored_tokens already+ // equals (gen_start_pos + num_accepted_tokens) as set by the pipeline, so no KV+ // rearrangement is needed; just clear the result and return.+ // Complex path: non-contiguous — physically move accepted token entries together.+ const bool contiguous =+ std::is_partitioned(result.accepted_token_mask.begin(), result.accepted_token_mask.end(), [](bool v) {+ return v;+ });+ if (!contiguous) {+ LOG_DEBUG("Eagle3: Accepted tokens are non-contiguous, rearranging KV cache");+ trim_kvcache_by_sampling(request, in_ports, num_stored_tokens, v_transposed, kv_dim);+ } else {+ LOG_DEBUG("Eagle3: Accepted tokens are contiguous, using fast rollback (num_stored_tokens already correct)");+ }++ // Clear the processed sampling result+ result = SamplingResult();+ LOG_DEBUG("Eagle3: KV cache adjustment complete, new num_stored_tokens: " << num_stored_tokens);+}++void Eagle3Extension::trim_kvcache_by_sampling(+ std::shared_ptr<ov::IAsyncInferRequest> request,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,+ uint32_t& num_stored_tokens,+ bool v_transposed,+ uint32_t kv_dim) {+ namespace uu = ov::npuw::util;++ auto& result = m_pending_sampling_result;+ auto& mask = result.accepted_token_mask;++ auto& compiled = request->get_compiled_model();++ // num_stored_tokens is the first input position id for this round, set by the pipeline+ // to (prompt_len + num_accepted_tokens). Therefore the position where draft tokens begin+ // in the KV cache is:+ // gen_start_pos = num_stored_tokens - num_accepted_tokens+ //+ // Example: prompt=14 tokens, 8 drafted, 2 accepted+ // Physical KV cache length = 14 + 8 = 22+ // num_stored_tokens = 14 + 2 = 16 (set by pipeline)+ // gen_start_pos = 16 - 2 = 14+ OPENVINO_ASSERT(num_stored_tokens >= result.num_accepted_tokens,+ "Eagle3: inconsistent token counts: num_stored_tokens (" + std::to_string(num_stored_tokens) ++ ") < num_accepted_tokens (" + std::to_string(result.num_accepted_tokens) + ")");+ uint32_t gen_start_pos = num_stored_tokens - result.num_accepted_tokens;++ LOG_VERB("Eagle3: Rearranging KV cache, gen_start_pos=" << gen_start_pos+ << ", num_stored_tokens=" << num_stored_tokens);++ // Build contiguous runs of accepted tokens (segments) for batch copying.+ // Each segment maps directly to a slice copy within each KV cache layer.+ std::vector<KVCacheSegment> segments;+ for (uint32_t idx = 0; idx < static_cast<uint32_t>(mask.size()); ++idx) {+ if (!mask[idx]) {+ continue;+ }+ uint32_t start = idx;+ while (idx < static_cast<uint32_t>(mask.size()) && mask[idx]) {+ ++idx;+ }+ segments.push_back({start, idx - start});+ }++ LOG_VERB("Eagle3: Found " << segments.size() << " contiguous segments to copy");++ // Iterate through all KV cache outputs.+ // Each "present.<layer>" output corresponds to a "past_key_values.<layer>" input.+ // Non-KV outputs (e.g. logits) are filtered out by the prefix check below.+ static const std::string present_prefix = "present";+ for (const auto& output : compiled->outputs()) {+ const auto& output_name = output.get_any_name();++ // Convert present layer name to past layer name:+ // "present.<layer>" -> "past_key_values.<layer>"+ if (output_name.compare(0, present_prefix.size(), present_prefix) != 0) {+ continue; // Not a present KV layer+ }+ const std::string input_name = "past_key_values" + output_name.substr(present_prefix.size());++ auto in_port_it = in_ports.find(input_name);+ OPENVINO_ASSERT(in_port_it != in_ports.end(),+ "Eagle3: KV cache output '" + output_name + "' has no matching input '" + input_name ++ "'. Model configuration is incorrect.");++ auto past_kv_tensor = request->get_tensor(in_port_it->second);++ // Determine the dimension for KV cache (value layers might be transposed)+ const auto& current_kv_dim = (output_name.find("value") != std::string::npos && v_transposed) ? 3u : kv_dim;++ LOG_VERB("Eagle3: Processing layer " << input_name << " on dimension " << current_kv_dim);++ // Write accepted segments contiguously starting at gen_start_pos,+ // compacting the KV cache in-place to remove rejected-token entries.+ uint32_t write_pos = gen_start_pos;+ for (const auto& seg : segments) {+ uint32_t read_start = gen_start_pos + seg.start_idx;+ uint32_t read_end = read_start + seg.length;++ if (write_pos != read_start) {+ auto src_slice = uu::make_tensor_slice(past_kv_tensor, current_kv_dim, read_start, read_end);+ auto dst_slice =+ uu::make_tensor_slice(past_kv_tensor, current_kv_dim, write_pos, write_pos + seg.length);+ uu::copy_tensor_by_dim(src_slice, dst_slice, current_kv_dim, current_kv_dim);+ LOG_VERB("Eagle3: Copied segment [" << read_start << ":" << read_end << "] to [" << write_pos << ":"+ << (write_pos + seg.length) << "]");+ } else {+ LOG_VERB("Eagle3: Segment [" << read_start << ":" << read_end+ << "] already in correct position, skipping");+ }++ write_pos += seg.length;+ }+ }++ // num_stored_tokens was set by the pipeline to (gen_start_pos + num_accepted_tokens)+ // and is already the correct post-trim value — no update needed.+ LOG_VERB("Eagle3: KV cache rearrangement complete, num_stored_tokens=" << num_stored_tokens);+}++bool Eagle3Extension::process_sampling_result_from_state(+ std::shared_ptr<ov::IAsyncInferRequest> request,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,+ uint32_t& num_stored_tokens,+ bool v_transposed,+ uint32_t kv_dim) {+ if (!m_sampling_state) {+ return false;+ }++ SamplingResult result;+ if (!m_sampling_state->extract_sampling_result(result.accepted_token_mask,+ result.num_total_generated,+ result.num_accepted_tokens)) {+ return false;+ }++ LOG_DEBUG("Eagle3: Retrieved sampling result from VariableState: "+ << result.num_accepted_tokens << "/" << result.num_total_generated << " tokens accepted");++ m_pending_sampling_result = std::move(result);+ adjust_kvcache_before_infer(request, in_ports, num_stored_tokens, v_transposed, kv_dim);+ return true;+}+} // namespace npuw} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.hppindex 1312a423d7b..c7a979f2c3d 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_eagle3_extension.hpp@@ -6,7 +6,6 @@#include <algorithm>#include <memory>-#include <optional>#include <string>#include <unordered_map>#include <vector>@@ -15,6 +14,8 @@#include "openvino/core/descriptor/output.hpp"#include "openvino/runtime/iasync_infer_request.hpp"#include "openvino/runtime/itensor.hpp"+#include "openvino/runtime/ivariable_state.hpp"+#include "openvino/runtime/make_tensor.hpp"namespace ov {namespace npuw {@@ -23,10 +24,12 @@ namespace npuw {struct Eagle3LayerNames {static constexpr const char* hidden_states = "hidden_states";static constexpr const char* last_hidden_state = "last_hidden_state";+ static constexpr const char* eagle_tree_mask = "eagle_tree_mask";};// Utility functions for Eagle3 layer name matchingbool matchEagle3HiddenStatesString(const std::string& input);+bool matchEagle3TreeMaskString(const std::string& input);// Model roles for Eagle3 speculative decodingenum class Eagle3ModelRole {@@ -35,14 +38,130 @@ enum class Eagle3ModelRole {Draft ///< Draft model: has hidden_states as input, and outputs last_hidden_state};+// Special VariableState for Eagle3 sampling result communication.+// Allows external pipelines to pass sampling results through the standard OpenVINO API.+//+// Tensor layout (element type: int64):+// [0] num_total_generated+// [1] num_accepted_tokens+// [2 .. 2+N-1] accepted_token_mask (1 = accepted, 0 = rejected), N = num_total_generated+//+// Usage example (write path — call before the next infer()):+// auto states = infer_request.query_state();+// for (auto& state : states) {+// if (state->get_name() == "npuw_eagle3_sampling_result") {+// const size_t N = num_total_generated;+// ov::Tensor tensor(ov::element::i64,+// ov::Shape{Eagle3SamplingState::kHeaderSize + N});+// auto* data = tensor.data<int64_t>();+// data[0] = static_cast<int64_t>(N);+// data[1] = static_cast<int64_t>(num_accepted_tokens);+// for (size_t i = 0; i < N; ++i)+// data[Eagle3SamplingState::kHeaderSize + i] = mask[i] ? 1 : 0;+// state->set_state(ov::get_tensor_impl(tensor));+// break;+// }+// }+//+// get_state() returns a tensor sized to kHeaderSize + num_total_generated,+// reflecting only the valid portion of the internal buffer.+class Eagle3SamplingState : public ov::IVariableState {+public:+ // Maximum number of tokens in a single speculative decoding round.+ // Format: [num_total_generated, num_accepted_tokens, mask[0], mask[1], ...]+ static constexpr size_t kMaxSpecTokens = 512;+ static constexpr size_t kHeaderSize = 2; // num_total_generated + num_accepted_tokens++ Eagle3SamplingState() : ov::IVariableState("npuw_eagle3_sampling_result") {+ auto tensor = ov::Tensor(ov::element::i64, ov::Shape{kHeaderSize + kMaxSpecTokens});+ m_state = ov::get_tensor_impl(tensor);+ reset();+ }++ void reset() override {+ std::fill_n(m_state->data<int64_t>(), m_state->get_size(), 0);+ }++ // Returns a tensor sized to kHeaderSize + num_total_generated, so the returned+ // size is symmetric with what set_state() accepts — no fixed-size padding exposed.+ ov::SoPtr<ov::ITensor> get_state() const override {+ const auto* data = m_state->data<int64_t>();+ const uint32_t num_total = data[0] > 0 ? static_cast<uint32_t>(data[0]) : 0u;+ OPENVINO_ASSERT(num_total <= kMaxSpecTokens,+ "Eagle3SamplingState: num_total_generated (" + std::to_string(num_total) ++ ") exceeds kMaxSpecTokens (" + std::to_string(kMaxSpecTokens) + ")");+ const size_t actual_size = kHeaderSize + num_total;+ auto result = ov::Tensor(ov::element::i64, ov::Shape{actual_size});+ std::copy_n(data, actual_size, result.data<int64_t>());+ return ov::get_tensor_impl(result);+ }++ void set_state(const ov::SoPtr<ov::ITensor>& state) override {+ // Copy the caller-provided tensor into our fixed-size internal buffer.+ OPENVINO_ASSERT(state->get_element_type() == ov::element::i64, "Eagle3SamplingState expects int64 tensor");+ OPENVINO_ASSERT(state->get_size() >= kHeaderSize, "Eagle3SamplingState tensor must have at least 2 elements");+ OPENVINO_ASSERT(state->get_size() <= m_state->get_size(),+ "Eagle3SamplingState: input tensor size (" + std::to_string(state->get_size()) ++ ") exceeds maximum capacity (" + std::to_string(m_state->get_size()) ++ "). Consider increasing kMaxSpecTokens.");+ // Validate that the tensor is large enough to hold the mask entries declared in the header.+ const auto* src = state->data<int64_t>();+ const uint32_t declared_total = static_cast<uint32_t>(src[0]);+ OPENVINO_ASSERT(state->get_size() >= kHeaderSize + declared_total,+ "Eagle3SamplingState: tensor size (" + std::to_string(state->get_size()) ++ ") is too small for declared num_total_generated (" + std::to_string(declared_total) + ")");+ // Zero the full internal buffer first to avoid stale mask data from a previous+ // set_state() call influencing a later extract when the new tensor is smaller.+ std::fill_n(m_state->data<int64_t>(), m_state->get_size(), int64_t{0});+ std::copy_n(src, state->get_size(), m_state->data<int64_t>());+ }++ // Extract sampling result and clear the state+ bool extract_sampling_result(std::vector<bool>& mask, uint32_t& num_total, uint32_t& num_accepted) {+ if (!has_result()) {+ return false;+ }++ auto* data = m_state->data<int64_t>();+ num_total = static_cast<uint32_t>(data[0]);+ num_accepted = static_cast<uint32_t>(data[1]);++ OPENVINO_ASSERT(num_total <= kMaxSpecTokens,+ "Eagle3SamplingState: num_total_generated (" + std::to_string(num_total) ++ ") exceeds kMaxSpecTokens (" + std::to_string(kMaxSpecTokens) + ")");+ OPENVINO_ASSERT(num_accepted <= num_total,+ "Eagle3SamplingState: num_accepted_tokens (" + std::to_string(num_accepted) ++ ") cannot exceed num_total_generated (" + std::to_string(num_total) + ")");++ mask.clear();+ mask.reserve(num_total);+ for (uint32_t i = 0; i < num_total; ++i) {+ mask.push_back(data[kHeaderSize + i] != 0);+ }++ reset();+ return true;+ }++private:+ // Returns true if the state tensor contains a valid (non-empty) sampling result+ bool has_result() const {+ return m_state->data<int64_t>()[0] > 0; // num_total_generated > 0+ }+};+// Extension for Eagle3 speculative decoding// Handles Eagle3-specific input/output logic for draft and target modelsclass Eagle3Extension {public:- // Get static shape for Eagle3 input tensors+ // Compute the static shape for Eagle3-specific inputs (hidden_states, eagle_tree_mask).+ // is_prefill drives eagle_tree_mask shape: prefill uses {1,1,1,1}+ // generate uses {1,1,input_size,kvcache_size}static ov::PartialShape get_static_input(const std::shared_ptr<ov::Model>& model,const ov::Output<ov::Node>& input,- uint32_t input_size);+ uint32_t input_size,+ uint32_t kvcache_size,+ bool is_prefill);// Detect Eagle3 model role (Draft/Target/None) based on is_eagle flag and inputs/outputsvoid initialize(bool is_eagle_model,@@ -54,13 +173,9 @@ public:return m_role != Eagle3ModelRole::None;}- Eagle3ModelRole get_role() const {- return m_role;- }-- // Store hidden state inputs from user request (must be called before prepare_inputs/prepare_inputs_for_chunk)- void store_hidden_state_inputs(const ov::IInferRequest& request,- const std::vector<ov::Output<const ov::Node>>& inputs);+ // Store eagle3 specific inputs (eagle_tree_mask, hidden_states) from the inference request+ // Must be called before prepare_inputs/prepare_inputs_for_chunk+ void store_user_inputs(const ov::IInferRequest& request, const std::vector<ov::Output<const ov::Node>>& inputs);// Prepare Eagle3 new input tensors (hidden_states)void prepare_inputs(const std::shared_ptr<ov::IAsyncInferRequest>& request,@@ -91,20 +206,60 @@ public:m_chunked_seq_offset = 0;}+ // Returns the last_hidden_state tensor from the most recent inference.+ // For chunked prefill, this is the fully-assembled tensor across all chunks.ov::SoPtr<ov::ITensor> get_last_hidden_state() const {return m_last_hidden_state;}+ // Returns the Eagle3SamplingState VariableState exposed via query_state().+ // External pipelines write sampling results into this state; the plugin reads+ // them back in process_sampling_result_from_state() before the next inference.+ std::shared_ptr<Eagle3SamplingState> get_sampling_state() const {+ return m_sampling_state;+ }++ // Read the sampling result from the Eagle3SamplingState VariableState and apply+ // any required KV cache adjustment (discard rejected draft tokens) before infer.+ bool process_sampling_result_from_state(std::shared_ptr<ov::IAsyncInferRequest> request,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,+ uint32_t& num_stored_tokens,+ bool v_transposed,+ uint32_t kv_dim);+private:- void validate_hidden_state_tensor(const ov::SoPtr<ov::ITensor>& tensor, const std::string& name);+ // Internal representation of a speculative decoding sampling result+ struct SamplingResult {+ std::vector<bool> accepted_token_mask; ///< true = token accepted, false = rejected+ uint32_t num_total_generated = 0; ///< Total tokens generated (== accepted_token_mask.size())+ uint32_t num_accepted_tokens = 0; ///< Count of accepted tokens (== count of true in mask)+ };++ // Adjust KV cache based on sampling result before inference+ void adjust_kvcache_before_infer(std::shared_ptr<ov::IAsyncInferRequest> request,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,+ uint32_t& num_stored_tokens,+ bool v_transposed,+ uint32_t kv_dim);++ // Trim KV cache by rearranging only accepted tokens+ void trim_kvcache_by_sampling(std::shared_ptr<ov::IAsyncInferRequest> request,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,+ uint32_t& num_stored_tokens,+ bool v_transposed,+ uint32_t kv_dim);Eagle3ModelRole m_role = Eagle3ModelRole::None;ov::SoPtr<ov::ITensor> m_hidden_states; ///< Draft model input: hidden_states+ ov::SoPtr<ov::ITensor> m_eagle_tree_mask; ///< Draft/Target model input: eagle_tree_maskov::SoPtr<ov::ITensor> m_last_hidden_state; ///< Draft/Target model output: last_hidden_state// For chunked prefill: track the write offset in the pre-allocated tensoruint32_t m_chunked_seq_offset = 0;++ SamplingResult m_pending_sampling_result; ///< Pending sampling result from previous inference+ std::shared_ptr<Eagle3SamplingState> m_sampling_state; ///< VariableState for external pipeline communication};} // namespace npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cppindex f6afd3ab063..40928285ee9 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp@@ -596,8 +596,8 @@ void ov::npuw::LLMInferRequest::trim_kvcache_for_speculative_decoding(ov::SoPtr<auto position_id = position_ids->data<int64_t>()[0];auto dirty_num = kvcache_desc.num_stored_tokens - static_cast<uint32_t>(position_id);if (dirty_num > 0) {- LOG_DEBUG("Trim kv cache from " << kvcache_desc.num_stored_tokens << " length"- << " to " << position_id << " length");+ LOG_DEBUG("Trim kv cache from " << kvcache_desc.num_stored_tokens << " length" << " to " << position_id+ << " length");}kvcache_desc.num_stored_tokens -= dirty_num;}@@ -905,6 +905,16 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,// Note: m_kvcache_request, m_kvcache_in_ports, and m_kvcache_out_ports are selected in// prepare_for_new_conversation()++ // Eagle3: Check for sampling result from external pipeline via VariableState+ if (m_eagle3_ext.is_eagle3_model() && m_generate_initialized) {+ m_eagle3_ext.process_sampling_result_from_state(m_kvcache_request,+ m_kvcache_in_ports,+ kvcache_desc.num_stored_tokens,+ kvcache_desc.v_tensors_transposed_gen,+ kvcache_desc.dim);+ }+m_llm_profile["N/generate:1.prepare"].record([&]() {if (!m_generate_initialized) {LOG_DEBUG("Copy kv-cache from prefill to generate model.");@@ -1040,8 +1050,10 @@ void ov::npuw::LLMInferRequest::infer() {OPENVINO_ASSERT(ov::element::i64 == attention_mask->get_element_type());OPENVINO_ASSERT(ov::element::i64 == position_ids->get_element_type());- // Eagle3: Accept and validate hidden state inputs- m_eagle3_ext.store_hidden_state_inputs(*this, inputs);+ // Eagle3: Store Eagle3 specific inputs with pre-validation+ if (m_eagle3_ext.is_eagle3_model()) {+ m_eagle3_ext.store_user_inputs(*this, inputs);+ }if (m_first_run) {// Most of the models have position_ids->data<int64_t>()[0] == 0 for the first infer@@ -1114,5 +1126,13 @@ ov::SoPtr<ov::ITensor> ov::npuw::LLMInferRequest::get_tensor(const ov::Output<co}std::vector<ov::SoPtr<ov::IVariableState>> ov::npuw::LLMInferRequest::query_state() const {- return m_variableStates;+ auto states = m_variableStates;++ // Add Eagle3 sampling state if available+ auto eagle3_state = m_eagle3_ext.get_sampling_state();+ if (eagle3_state) {+ states.push_back(eagle3_state);+ }++ return states;}diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cppindex 023b991a2cd..3491d8b2258 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.cpp@@ -16,7 +16,8 @@ void reshape_to_static(std::shared_ptr<ov::Model> model,const uint32_t kvcache_size,const ov::npuw::KVAxesPosition& kv_axes_position,const uint32_t lora_rank,- const uint32_t lhs_seq_size = 0) {+ const uint32_t lhs_seq_size = 0,+ const bool is_prefill = false) {std::map<std::string, ov::PartialShape> new_shapes;for (const auto& input : model->inputs()) {const auto& input_name = input.get_any_name();@@ -51,8 +52,9 @@ void reshape_to_static(std::shared_ptr<ov::Model> model,const auto& partial_shape = input.get_partial_shape();new_shape = partial_shape;new_shape[0] = 1; // batch_dim- } else if (ov::npuw::matchEagle3HiddenStatesString(input_name)) {- new_shape = ov::npuw::Eagle3Extension::get_static_input(model, input, input_size);+ } else if (ov::npuw::matchEagle3HiddenStatesString(input_name) ||+ ov::npuw::matchEagle3TreeMaskString(input_name)) {+ new_shape = ov::npuw::Eagle3Extension::get_static_input(model, input, input_size, kvcache_size, is_prefill);} else if (ov::npuw::util::matchLoRAMatMulAString(input_name)) {new_shape = ov::PartialShape({lora_rank, input.get_partial_shape()[1]});} else if (ov::npuw::util::matchLoRAMatMulAlphaString(input_name)) {@@ -84,15 +86,23 @@ ReshapeToStatic::ReshapeToStatic(const uint32_t input_size,const uint32_t kvcache_size,const KVAxesPosition& kv_axes_position,const uint32_t lora_rank,- const uint32_t lhs_seq_size)+ const uint32_t lhs_seq_size,+ const bool is_prefill): m_input_size(input_size),m_kvcache_size(kvcache_size),m_kv_axes_position(kv_axes_position),m_lora_rank(lora_rank),- m_lhs_seq_size(lhs_seq_size) {}+ m_lhs_seq_size(lhs_seq_size),+ m_is_prefill(is_prefill) {}bool ReshapeToStatic::run_on_model(const std::shared_ptr<ov::Model>& model) {- reshape_to_static(model, m_input_size, m_kvcache_size, m_kv_axes_position, m_lora_rank, m_lhs_seq_size);+ reshape_to_static(model,+ m_input_size,+ m_kvcache_size,+ m_kv_axes_position,+ m_lora_rank,+ m_lhs_seq_size,+ m_is_prefill);return true;}diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.hppindex 83aa06f4eda..56d4fc34221 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/reshape_to_static.hpp@@ -15,6 +15,7 @@ class ReshapeToStatic : public ov::pass::ModelPass {KVAxesPosition m_kv_axes_position;uint32_t m_lora_rank;uint32_t m_lhs_seq_size;+ bool m_is_prefill;public:OPENVINO_MODEL_PASS_RTTI("ov::npuw::ReshapeToStatic");@@ -22,7 +23,8 @@ public:const uint32_t kvcache_size,const KVAxesPosition& kv_axes_position,const uint32_t lora_rank,- const uint32_t lhs_seq_size = 0);+ const uint32_t lhs_seq_size = 0,+ const bool is_prefill = false);bool run_on_model(const std::shared_ptr<ov::Model>& model) override;};