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]Fix VLM accuracy issue on NPU. (#32562)
intelgaoxiong8c768f4abed3
diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cppindex 8a70c0e0d0a..3e6abb1dc1c 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@@ -185,6 +185,10 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCofor (const auto& input_port : m_prefill_request->get_compiled_model()->inputs()) {m_prefill_in_ports.emplace(input_port.get_any_name(), input_port);+ // Cache past_key_values ports for efficient clearing+ if (input_port.get_any_name().find(layer_names::past_key_values) != std::string::npos) {+ m_prefill_past_kv_ports.push_back(input_port);+ }}for (const auto& output_port : m_prefill_request->get_compiled_model()->outputs()) {m_prefill_out_ports.emplace(output_port.get_any_name(), output_port);@@ -381,6 +385,12 @@ void ov::npuw::LLMInferRequest::prepare_for_new_conversation() {}uu::fill_tensor<int64_t>(m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::attention_mask)), 0);uu::fill_tensor<int64_t>(m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::position_ids)), 0);++ // Clear all past_key_values tensors - use cached ports for efficiency+ for (const auto& port : m_prefill_past_kv_ports) {+ uu::fill_tensor_bytes(m_prefill_request->get_tensor(port), 0u);+ }+m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens = 0u;apply_lora();@@ -579,13 +589,8 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp// the chunk sizeauto current_prompts_len = std::min(remaining_prompts, chunk_prompt_len);- // Handle first chunk with prefix caching: adjust chunk size and populate attention mask for restored cache+ // Handle first chunk with prefix caching: populate attention mask for restored cacheif (enable_prefix_caching && cache_context.restore_prefix_cache) {- if (current_prompts_len == chunk_prompt_len) {- auto token_num_to_a_full_chunk =- m_prefix_caching_helper->adjust_chunk_size(kvcache_desc.num_stored_tokens, chunk_prompt_len);- current_prompts_len = token_num_to_a_full_chunk;- }m_prefix_caching_helper->populate_attention_mask_for_restored_cache(attention_mask,attn_mask_in_tensor,kvcache_desc.num_stored_tokens);@@ -613,6 +618,7 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpprefilled_bytes *= input_ids->get_shape().back();}+ ov::npuw::util::fill_tensor_bytes(input_ids_in_tensor, 0u);std::copy_n(reinterpret_cast<uint8_t*>(input_ids->data()) + prefilled_bytes,current_prefill_bytes,reinterpret_cast<uint8_t*>(input_ids_in_tensor->data()) + input_ids_in_tensor->get_byte_size() -@@ -627,7 +633,15 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpstatic_cast<uint32_t>(last_dim),kvcache_desc.num_stored_tokens,kvcache_desc.num_stored_tokens + static_cast<uint32_t>(current_prompts_len));- pad_position_ids(pos_ids_in_tensor, actual_position_ids_slice);++ auto pos_ids_slice =+ ov::npuw::util::make_tensor_slice(pos_ids_in_tensor,+ static_cast<uint32_t>(last_dim),+ static_cast<uint32_t>(chunk_prompt_len - current_prompts_len),+ static_cast<uint32_t>(chunk_prompt_len));++ // Copy with proper stride handling+ actual_position_ids_slice->copy_to(pos_ids_slice._ptr);// Update history size for dynamic context:// dynamic attention selector needs history size to determin the past KV shape and attention mask shapediff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hppindex 461c28b7cc6..3353099d0a5 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp@@ -100,6 +100,9 @@ protected:std::unordered_map<std::string, ov::Output<const ov::Node>> m_kvcache_out_ports;ov::Output<const ov::Node> m_lm_head_logits_port;+ // Cache past_key_values ports for efficient clearing in prepare_for_new_conversation+ std::vector<ov::Output<const ov::Node>> m_prefill_past_kv_ports;+// NB: It can be either input_ids(LLM) or inputs_embeds(VLM)std::string m_input_ids_name;diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.cppindex 0e2a37d1561..dd0a1372cec 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.cpp@@ -315,50 +315,6 @@ void PrefixCachingHelper::store_computed_blocks(size_t chunk_size,store_blocks(chunk_size, prompt_hashes, token_idx);}-size_t PrefixCachingHelper::adjust_chunk_size(size_t restored_token_num, size_t chunk_len) {- // This function calculates the number of tokens needed to complete a full chunk- // based on the current restored token number and the chunk prompt length.-- // Ensure that the past KV in the inference request can accommodate a full chunk after the first inference run.- // Consider the scenario when prefix caching is enabled:- // - The input prompt length is 1024, and the chunk size is 256. Initially, the present KV length in the inference- // request is 256, and the past KV length is 768.- // - Initially, 128 tokens have been restored from the cache, leaving 1024 - 128 = 896 tokens that need to be- // computed.- // Round 1:- // - 128 tokens are stored in the past KV.- // - Infer for 256 tokens in the present KV.- // - After updating the KV cache, the past KV will hold 128 + 256 tokens, leaving 896 - 256 = 640 tokens.- // Round 2:- // - 128 + 256 tokens are stored in the past KV.- // - Infer for another 256 tokens in the present KV.- // - After updating the KV cache, the past KV will hold 128 + 256 + 256 tokens, leaving 896 - 256 - 256 = 384- // tokens.- // Round 3:- // - 128 + 256 + 256 tokens are stored in the past KV.- // - Infer for another 256 tokens in the present KV.- // - KV cache update would fail because the past KV cannot accommodate 128 + 256 + 256 + 256 tokens.-- // To address this issue, ensure that the past KV can hold a full chunk after round 1:- // Round 1:- // - 128 tokens are stored in the past KV.- // - Infer for 128 tokens in the present KV.- // - After updating the KV cache, the past KV will hold 128 + 128 tokens, leaving 896 - 128 = 768 tokens.- // Round 2:- // - 256 tokens are stored in the past KV.- // - Infer for 256 tokens in the present KV.- // - After updating the KV cache, the past KV will hold 128 + 128 + 256 tokens, leaving 896 - 128 - 256 = 512- // tokens. Round 3:- // - 256 + 256 tokens are stored in the past KV.- // - Infer for 256 tokens in the present KV.- // - After updating the KV cache, the past KV will hold 128 + 128 + 256 + 256 tokens, leaving 896 - 128 - 256 - 256- // = 256 tokens. Round 4:- // - 128 + 128 + 256 + 256 tokens are stored in the past KV.- // - Infer for the last 256 tokens in the present KV, completing the prefill for all prompts.-- return chunk_len - restored_token_num % chunk_len;-}-void PrefixCachingHelper::print_cache_status(bool verbose) const {if (m_cache_manager) {m_cache_manager->print_cache_status(verbose);@@ -420,20 +376,23 @@ void PrefixCachingHelper::create_name_mapping() {}}-uint64_t PrefixCachingHelper::restore_blocks(const ov::SoPtr<ov::ITensor>& input_ids,- const std::vector<uint64_t>& prompt_hashes) {+std::vector<std::shared_ptr<KVBlock>> PrefixCachingHelper::find_cached_blocks(+ const ov::SoPtr<ov::ITensor>& input_ids,+ const std::vector<uint64_t>& prompt_hashes) {const uint64_t block_size = m_request.m_npuw_llm_compiled_model->m_prefix_caching_block_size;+ const uint64_t chunk_size = m_request.m_npuw_llm_compiled_model->m_prefill_chunk_size;auto& kvcache_desc = m_request.m_npuw_llm_compiled_model->m_kvcache_desc;size_t actual_token_num = input_ids->get_shape()[LLMInferRequest::layer_ids::INPUT_IDS_SEQ_LEN_DIM];size_t num_blocks = (actual_token_num + block_size - 1) / block_size;- uint64_t restored_token_num = 0;- size_t token_idx = 0;-uint64_t max_restored_token_num =kvcache_desc.max_prompt_size - m_request.m_npuw_llm_compiled_model->m_prefill_chunk_size;+ std::vector<std::shared_ptr<KVBlock>> cached_blocks;+ size_t token_idx = 0;+ uint64_t restored_token_num = 0;+for (size_t block_index = 0; block_index < num_blocks; ++block_index) {if ((actual_token_num - block_index * block_size) < block_size) {break; // Not a full block@@ -453,13 +412,54 @@ uint64_t PrefixCachingHelper::restore_blocks(const ov::SoPtr<ov::ITensor>& inputbreak;}- // Cache hit - restore KV tensors- auto token_start = retrieved_block->get_token_start();- const KVData& block_kv_data = retrieved_block->get_block_kv_data();- LOG_VERB("[PrefixCache] Cache hit for block hash " << block_hash << ", restored tokens start from position "- << token_start);+ LOG_VERB("[PrefixCache] Cache hit for block hash " << block_hash << ", tokens start from position "+ << retrieved_block->get_token_start());- ov::parallel_for(block_kv_data.size(), [&](size_t idx) {+ cached_blocks.push_back(retrieved_block);+ restored_token_num += block_size;++ // Ensure the cached tokens can be loaded into infer request+ if (restored_token_num + block_size > max_restored_token_num) {+ break;+ }++ // At least we should infer "1" token to generate "logit"+ if (restored_token_num == actual_token_num) {+ cached_blocks.pop_back(); // Remove the last block+ break;+ }+ }++ // Align restored token count down to chunk size boundary for consistency+ // This prevents KV cache mismatches that can occur when partial chunks use different padding strategies+ // between cache storage and runtime inference, ensuring exact numerical equivalence+ if (restored_token_num > 0 && restored_token_num % chunk_size != 0) {+ uint64_t aligned_token_num = (restored_token_num / chunk_size) * chunk_size;+ uint64_t blocks_to_remove = (restored_token_num - aligned_token_num) / block_size;++ LOG_VERB("[PrefixCache] Aligning restored token count from "+ << restored_token_num << " down to " << aligned_token_num << " (chunk size boundary), removing "+ << blocks_to_remove << " blocks");++ // Remove the excess blocks that don't align with chunk boundary+ for (uint64_t i = 0; i < blocks_to_remove; ++i) {+ cached_blocks.pop_back();+ }+ }++ return cached_blocks;+}++void PrefixCachingHelper::copy_cached_kv_data(const std::vector<std::shared_ptr<KVBlock>>& cached_blocks) {+ auto& kvcache_desc = m_request.m_npuw_llm_compiled_model->m_kvcache_desc;+ const uint64_t block_size = m_request.m_npuw_llm_compiled_model->m_prefix_caching_block_size;++ ov::parallel_for(cached_blocks.size(), [&](size_t block_idx) {+ const auto& block = cached_blocks[block_idx];+ auto token_start = block->get_token_start();+ const KVData& block_kv_data = block->get_block_kv_data();++ for (size_t idx = 0; idx < block_kv_data.size(); ++idx) {auto kv_per_layer = block_kv_data[idx];auto kv_out_name = kv_per_layer.first;const auto& kv_in_name = m_cached_input_name_map.at(kv_out_name);@@ -473,21 +473,24 @@ uint64_t PrefixCachingHelper::restore_blocks(const ov::SoPtr<ov::ITensor>& inputauto kv_dst_tensor = m_request.m_prefill_request->get_tensor(m_request.m_prefill_in_ports.at(kv_in_name));auto kv_dst_slice = ov::npuw::util::view(kv_dst_tensor, kv_dim, token_start, block_size);ov::npuw::util::copy_tensor_by_dim(kv_tensor, kv_dst_slice, kv_dim, kv_dim);- });+ }+ });+}- restored_token_num += block_size;+uint64_t PrefixCachingHelper::restore_blocks(const ov::SoPtr<ov::ITensor>& input_ids,+ const std::vector<uint64_t>& prompt_hashes) {+ // Find all cached blocks first+ auto cached_blocks = find_cached_blocks(input_ids, prompt_hashes);- // Ensure the cached tokens can be loaded into infer request- if (restored_token_num + block_size > max_restored_token_num) {- break;- }+ // Copy KV data from cached blocks to prefill request+ copy_cached_kv_data(cached_blocks);- // At least we should infer "1" token to generate "logit"- if (restored_token_num == actual_token_num) {- restored_token_num -= block_size;- break;- }- }+ // Calculate total restored token number+ const uint64_t block_size = m_request.m_npuw_llm_compiled_model->m_prefix_caching_block_size;+ uint64_t restored_token_num = cached_blocks.size() * block_size;++ LOG_VERB("[PrefixCache] Successfully found " << cached_blocks.size() << " cached blocks, "+ << "restored " << restored_token_num << " tokens");return restored_token_num;}@@ -501,6 +504,13 @@ void PrefixCachingHelper::store_blocks(size_t chunk_size,return;}+ // Skip caching for partial chunks to maintain KV cache consistency+ // Partial chunks involve padding operations during inference that can introduce numerical variations+ // Caching only full chunks ensures deterministic behavior and avoids subtle differences+ if (chunk_size < m_request.m_npuw_llm_compiled_model->m_prefill_chunk_size) {+ return;+ }+auto& kvcache_desc = m_request.m_npuw_llm_compiled_model->m_kvcache_desc;const auto& prefill_compiled = m_request.m_prefill_request->get_compiled_model();const uint64_t chunk_prompt_len = m_request.m_npuw_llm_compiled_model->m_prefill_chunk_size;diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.hppindex 5913870c3a6..e798b713765 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_prefix_caching.hpp@@ -206,11 +206,6 @@ public:*/void store_computed_blocks(size_t chunk_size, const std::vector<uint64_t>& prompt_hashes, size_t& token_idx);- /**- * @brief Adjust chunk size for optimal prefix caching alignment- */- size_t adjust_chunk_size(size_t restored_token_num, size_t chunk_len);-/*** @brief Print the current status of the prefix cache*/@@ -235,6 +230,22 @@ private:std::vector<uint64_t> calculate_hashes(const ov::SoPtr<ov::ITensor>& input_ids);void create_name_mapping();++ /**+ * @brief Find cached KV blocks from cache manager+ * @param input_ids Input token tensor+ * @param prompt_hashes Precomputed hash values for all tokens+ * @return Vector of cached KV blocks found in cache+ */+ std::vector<std::shared_ptr<KVBlock>> find_cached_blocks(const ov::SoPtr<ov::ITensor>& input_ids,+ const std::vector<uint64_t>& prompt_hashes);++ /**+ * @brief Copy KV data from cached blocks to prefill request tensors+ * @param cached_blocks Vector of cached KV blocks to copy from+ */+ void copy_cached_kv_data(const std::vector<std::shared_ptr<KVBlock>>& cached_blocks);+uint64_t restore_blocks(const ov::SoPtr<ov::ITensor>& input_ids, const std::vector<uint64_t>& prompt_hashes);void store_blocks(size_t chunk_size, const std::vector<uint64_t>& prompt_hashes, size_t& token_idx);};