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] Implementing prefix caching for long rope (#36758)
Alexander Kalistratov934b1cc6a576
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 0cdb064e9f4..809935aa4f7 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@@ -559,16 +559,6 @@ std::shared_ptr<ov::Model> check_and_cut_lm_head(const std::shared_ptr<ov::Modelreturn lm_head_model;}-bool has_phi_v5_longrope_pattern(const std::shared_ptr<ov::Model>& model) {- auto long_rope = std::make_shared<ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5>();- bool matched = false;- long_rope->transform_cb = [&]() {- matched = true;- };- long_rope->run_on_model(model);- return matched;-}-} // namespace// Apply DEVICE_ROUTED MoE transformations to models@@ -1112,11 +1102,17 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mupdate_config_for_text_embed(prefill_config);}+ m_longrope_context_limit =+ ov::npuw::patterns::pre_compute::extract_phi_v5_longrope_context_limit(prefill_model).value_or(0u);+ if (m_longrope_context_limit > 0u) {+ LOG_INFO("Detected long-rope context limit: " << m_longrope_context_limit);+ }+if (m_cfg.get<::intel_npu::NPUW_LLM_CACHE_ROPE>()) {LOG_DEBUG("Caching preROPE ");const uint32_t CACHE_ROPE_START = 2048;const bool is_best = (generate_hint == ::intel_npu::npuw::llm::GenerateHint::BEST_PERF);- const bool force_rope_cache = has_phi_v5_longrope_pattern(prefill_model);+ const bool force_rope_cache = m_longrope_context_limit > 0u;if (!is_best || (max_prompt_len >= CACHE_ROPE_START || force_rope_cache)) {LOG_DEBUG("Enable RoPE Cache for prefill");@@ -1314,8 +1310,9 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& raw_stream, const ov::nstream & m_kvcache_desc.max_prompt_size & m_kvcache_desc.total_size & m_kvcache_desc.num_stored_tokens &m_kvcache_desc.dim & m_kvcache_desc.max_generation_token_len & m_kvcache_desc.v_tensors_transposed_pre &m_kvcache_desc.v_tensors_transposed_gen & m_prefill_chunk_size & m_use_chunk_prefill & m_max_lora_rank &- m_enable_prefix_caching & m_prefix_caching_block_size & m_prefix_caching_max_num_blocks & m_is_whisper &- m_eos_token_id & m_decomposed_sdpa_size & m_is_eagle & m_is_embedding & m_is_block_kv_cache;+ m_enable_prefix_caching & m_prefix_caching_block_size & m_prefix_caching_max_num_blocks &+ m_longrope_context_limit & m_is_whisper & m_eos_token_id & m_decomposed_sdpa_size & m_is_eagle &+ m_is_embedding & m_is_block_kv_cache;// Write configstream & m_cfg;@@ -1533,9 +1530,10 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserialcompiled->m_kvcache_desc.max_generation_token_len & compiled->m_kvcache_desc.v_tensors_transposed_pre &compiled->m_kvcache_desc.v_tensors_transposed_gen & compiled->m_prefill_chunk_size &compiled->m_use_chunk_prefill & compiled->m_max_lora_rank & compiled->m_enable_prefix_caching &- compiled->m_prefix_caching_block_size & compiled->m_prefix_caching_max_num_blocks & compiled->m_is_whisper &- compiled->m_eos_token_id & compiled->m_decomposed_sdpa_size & compiled->m_is_eagle &- compiled->m_is_embedding & compiled->m_is_block_kv_cache;+ compiled->m_prefix_caching_block_size & compiled->m_prefix_caching_max_num_blocks &+ compiled->m_longrope_context_limit & compiled->m_is_whisper & compiled->m_eos_token_id &+ compiled->m_decomposed_sdpa_size & compiled->m_is_eagle & compiled->m_is_embedding &+ compiled->m_is_block_kv_cache;// Deserialize configstream & compiled->m_cfg;diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hppindex 62bf2ec75dc..5fda107ecb2 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp@@ -123,6 +123,7 @@ private:bool m_enable_prefix_caching = false;uint64_t m_prefix_caching_block_size = 0;uint64_t m_prefix_caching_max_num_blocks = 0;+ uint64_t m_longrope_context_limit = 0;// Friend declarations for PrefixCachingHelper to access protected membersfriend class PrefixCachingHelper;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 fd2b197849b..2e0ca64bc32 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@@ -20,6 +20,12 @@namespace {using ov::npuw::LLMInferRequest;+int64_t get_max_position_id(const ov::SoPtr<ov::ITensor>& position_ids) {+ OPENVINO_ASSERT(position_ids->get_size() > 0, "position_ids tensor must not be empty");+ auto* pos_ids_data = position_ids->data<int64_t>();+ return *std::max_element(pos_ids_data, pos_ids_data + position_ids->get_size());+}+void copy_columns_by_row_chunks_2d(ov::SoPtr<ov::ITensor> src, ov::SoPtr<ov::ITensor>& dst) {const auto& src_shape = src->get_shape();@@ -214,13 +220,8 @@ void process_longrope(const std::shared_ptr<ov::IAsyncInferRequest>& infer_req,const ov::SoPtr<ov::ITensor>& position_ids) {if (auto longrope_port_it = ports.find(LLMInferRequest::layer_names::longrope_input);longrope_port_it != ports.end()) {- auto* pos_ids_data = position_ids->data<int64_t>();- // assuming position_ids are constantly non-deacreasing.- // this potentially could be not true. Alternative is to find max value in position_ids- auto max_pos_id = pos_ids_data[position_ids->get_size() - 1];-auto longrope_input = infer_req->get_tensor(longrope_port_it->second);- longrope_input->data<int64_t>()[0] = max_pos_id;+ longrope_input->data<int64_t>()[0] = get_max_position_id(position_ids);}}} // anonymous namespace@@ -319,7 +320,11 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCom_kvcache_strategy->on_initialize();if (m_npuw_llm_compiled_model->m_enable_prefix_caching) {- m_prefix_caching_helper = std::make_unique<PrefixCachingHelper>(*this);+ const size_t prefix_cache_count = m_npuw_llm_compiled_model->m_longrope_context_limit > 0u ? 2u : 1u;+ m_prefix_caching_helpers.reserve(prefix_cache_count);+ for (size_t i = 0; i < prefix_cache_count; ++i) {+ m_prefix_caching_helpers.push_back(std::make_unique<PrefixCachingHelper>(*this));+ }}if (compiled_model->m_lm_head_compiled) {@@ -379,6 +384,26 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCom_llm_profile.area = "LLM/execution";}+bool ov::npuw::LLMInferRequest::use_longrope_prefix_cache(const ov::SoPtr<ov::ITensor>& position_ids) const {+ const auto context_limit = m_npuw_llm_compiled_model->m_longrope_context_limit;+ if (context_limit == 0u || m_prefix_caching_helpers.size() < 2u) {+ return false;+ }++ const auto max_position_id = get_max_position_id(position_ids);+ return max_position_id >= 0 && static_cast<uint64_t>(max_position_id) >= context_limit;+}++ov::npuw::PrefixCachingHelper* ov::npuw::LLMInferRequest::get_prefix_caching_helper(+ const ov::SoPtr<ov::ITensor>& position_ids) {+ if (m_prefix_caching_helpers.empty()) {+ return nullptr;+ }++ const size_t cache_index = use_longrope_prefix_cache(position_ids) ? 1u : 0u;+ return m_prefix_caching_helpers.at(cache_index).get();+}+std::string ov::npuw::LLMInferRequest::init_pre_alloc_device() {bool pre_alloc_on_npu = true;const auto& kvcache_compiled = m_npuw_llm_compiled_model->m_kvcache_compiled;@@ -808,11 +833,12 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpuint64_t remaining_prompts = input_prompt_len;- const bool enable_prefix_caching = m_npuw_llm_compiled_model->m_enable_prefix_caching;+ auto* prefix_caching_helper = get_prefix_caching_helper(position_ids);+ const bool enable_prefix_caching = prefix_caching_helper != nullptr;PrefixCacheRestorationContext cache_context;if (enable_prefix_caching) {// Prepare and restore prefix cache using helper- cache_context = m_prefix_caching_helper->prepare_and_restore(input_ids, input_prompt_len);+ cache_context = prefix_caching_helper->prepare_and_restore(input_ids, input_prompt_len);remaining_prompts = cache_context.remaining_prompts;}@@ -834,9 +860,9 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpm_llm_profile["1/prefill:3a.prepare_chunk"].record([&]() {// Handle first chunk with prefix caching: populate attention mask for restored cacheif (enable_prefix_caching && cache_context.restore_prefix_cache) {- m_prefix_caching_helper->populate_attention_mask_for_restored_cache(attention_mask,- attn_mask_in_tensor,- kvcache_desc.num_stored_tokens);+ prefix_caching_helper->populate_attention_mask_for_restored_cache(attention_mask,+ attn_mask_in_tensor,+ kvcache_desc.num_stored_tokens);cache_context.restore_prefix_cache = false;}@@ -943,9 +969,9 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inp}if (enable_prefix_caching) {- m_prefix_caching_helper->store_computed_blocks(current_prompts_len,- cache_context.prompt_hashes,- cache_context.token_idx);+ prefix_caching_helper->store_computed_blocks(current_prompts_len,+ cache_context.prompt_hashes,+ cache_context.token_idx);}});@@ -978,7 +1004,7 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpLOG_DEBUG("Done.");if (enable_prefix_caching) {- m_prefix_caching_helper->print_cache_status();+ prefix_caching_helper->print_cache_status();}}diff --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 d219f049ca0..b73a7fb66d0 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@@ -57,6 +57,8 @@ protected:ov::SoPtr<ov::ITensor> per_layer_inputs,ov::SoPtr<ov::ITensor> visual_pos_masks,ov::SoPtr<ov::ITensor> deepstack_visual_embeds);+ PrefixCachingHelper* get_prefix_caching_helper(const ov::SoPtr<ov::ITensor>& position_ids);+ bool use_longrope_prefix_cache(const ov::SoPtr<ov::ITensor>& position_ids) const;void infer_whole_prefill(ov::SoPtr<ov::ITensor> input_ids,ov::SoPtr<ov::ITensor> attention_mask,@@ -146,7 +148,7 @@ protected:std::string init_pre_alloc_device();// Support prefix caching- std::unique_ptr<PrefixCachingHelper> m_prefix_caching_helper;+ std::vector<std::unique_ptr<PrefixCachingHelper>> m_prefix_caching_helpers;// LLM-level profiling for 1st token generation analysisusing MS = ov::npuw::perf::metric<ov::npuw::perf::MSec>;diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cppindex 40b9b1bc8d0..5f6bfb7fc2c 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.cpp@@ -239,8 +239,9 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5::LongRopePatternPhi_v5()const std::shared_ptr<ov::Node>& power_const) {auto red_max = opp::wrap_type<ov::op::v1::ReduceMax>({position_ids, MakeConstant()});auto add = opp::wrap_type<ov::op::v1::Add>({red_max, MakeConstant()});+ auto context_limit = MakeConstant();// max(position_ids) + 1 > original_max_position_embeddings- auto greater = opp::wrap_type<ov::op::v1::Greater>({add, MakeConstant()});+ auto greater = opp::wrap_type<ov::op::v1::Greater>({add, context_limit});auto short_factor_conv = opp::optional<ov::op::v0::Convert>({short_factor->output(0)});auto long_factor_conv = opp::optional<ov::op::v0::Convert>({long_factor->output(0)});@@ -252,7 +253,7 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5::LongRopePatternPhi_v5()auto unsqueeze = opp::optional<ov::op::v0::Unsqueeze>({power, MakeConstant()});auto unsqueeze_1 = opp::optional<ov::op::v0::Unsqueeze>({unsqueeze, MakeConstant()});- return std::make_tuple(unsqueeze_1, greater, red_max);+ return std::make_tuple(unsqueeze_1, greater, red_max, context_limit);};auto position_ids = opp::wrap_type<ov::op::v0::Parameter>();@@ -268,6 +269,7 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5::LongRopePatternPhi_v5()auto select = std::get<0>(select_cond_max_pos_id);auto cond = std::get<1>(select_cond_max_pos_id);auto max_pos_id = std::get<2>(select_cond_max_pos_id);+ auto context_limit = std::get<3>(select_cond_max_pos_id);auto shape_of = opp::wrap_type<ov::op::v3::ShapeOf>({opp::any_input()});auto gather = opp::wrap_type<ov::op::v8::Gather>({shape_of, opp::any_input(), opp::any_input()});@@ -290,6 +292,7 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5::LongRopePatternPhi_v5()this->matched_concat = map_sin.at(concat_1).get_node_shared_ptr();this->matched_short_factor = map_sin.at(short_factor).get_node_shared_ptr();this->matched_long_factor = map_sin.at(long_factor).get_node_shared_ptr();+ this->matched_context_limit = map_sin.at(context_limit).get_node_shared_ptr();this->matched_multiply_const = map_sin.at(multiply_const).get_node_shared_ptr();this->matched_power_const = map_sin.at(power_const).get_node_shared_ptr();this->matched_cond = map_sin.at(cond).get_node_shared_ptr();@@ -306,6 +309,32 @@ ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5::LongRopePatternPhi_v5()matcher.register_patterns({output_sin, output_cos}, make_matcher_callback());}+std::optional<uint64_t> ov::npuw::patterns::pre_compute::extract_phi_v5_longrope_context_limit(+ const std::shared_ptr<ov::Model>& model) {+ auto long_rope = std::make_shared<ov::npuw::patterns::pre_compute::LongRopePatternPhi_v5>();+ std::optional<uint64_t> context_limit;+ long_rope->transform_cb = [&]() {+ auto limit_const = ov::as_type_ptr<ov::op::v0::Constant>(long_rope->matched_context_limit);+ OPENVINO_ASSERT(limit_const, "Invalid LongRopePatternPhi_v5 match, expected constant context limit");++ const auto limit_values = limit_const->cast_vector<int64_t>();+ OPENVINO_ASSERT(limit_values.size() == 1,+ "Invalid LongRopePatternPhi_v5 context limit, expected a single scalar value");+ OPENVINO_ASSERT(limit_values.front() >= 0,+ "Invalid LongRopePatternPhi_v5 context limit, expected a non-negative value");++ const auto matched_limit = static_cast<uint64_t>(limit_values.front());+ if (context_limit.has_value()) {+ OPENVINO_ASSERT(context_limit.value() == matched_limit,+ "Inconsistent LongRopePatternPhi_v5 context limits detected in the model");+ } else {+ context_limit = matched_limit;+ }+ };+ long_rope->run_on_model(model);+ return context_limit;+}+ov::npuw::patterns::pre_compute::RopeCacheMatcher::RopeCacheMatcher(const uint32_t max_prompt_len,const std::shared_ptr<ov::Model>& model,const std::string& longrope_input_name) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hppindex a1c6419b861..7af37ab027b 100644--- a/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/partitioning/patterns/pre_compute.hpp@@ -4,6 +4,8 @@#pragma once+#include <cstdint>+#include <optional>#include <string>#include "openvino/pass/pattern/multi_matcher.hpp"@@ -42,6 +44,7 @@ class LongRopev5PatternDesc : public RopePatternDesc {public:std::shared_ptr<ov::Node> matched_short_factor;std::shared_ptr<ov::Node> matched_long_factor;+ std::shared_ptr<ov::Node> matched_context_limit;std::shared_ptr<ov::Node> matched_cond;std::shared_ptr<ov::Node> max_pos_id;std::shared_ptr<ov::Node> matched_multiply_const;@@ -81,6 +84,11 @@ public:}};+// Runs LongRopePatternPhi_v5 on the model and, if matched, extracts the+// original_max_position_embeddings context limit constant it captures.+// Returns std::nullopt if the pattern doesn't match.+std::optional<uint64_t> extract_phi_v5_longrope_context_limit(const std::shared_ptr<ov::Model>& model);+class RopeCacheMatcher {public:RopeCacheMatcher(const uint32_t max_prompt_len,diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hppindex c06f7867a63..c4f613a7ed7 100644--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp@@ -48,7 +48,7 @@ const constexpr ov::npuw::s11n::IndicatorType NPUW_LLM_COMPILED_MODEL_INDICATORconst constexpr ov::npuw::s11n::IndicatorType NPUW_GQA_COMPILED_MODEL_INDICATOR ={char{0x47}, char{0x51}, char{0x41}, char{0x43}, char{0x4d}, char{0x4f}};-const constexpr char* NPUW_SERIALIZATION_VERSION = "0.27";+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.28";// Forward declarationnamespace intel_npu {