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][Pyramid decoding]Handle dynamic context with variants kv cache infer requests. (#32795)
intelgaoxiongcdbdf5f592e2
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hppindex 9c32c98f7ce..134534a1bf0 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw.hpp@@ -146,6 +146,7 @@ DEFINE_OPT(NPUW_LLM_MAX_GENERATION_TOKEN_LEN, uint32_t, 1, npuw::llm::max_generaDEFINE_OPT(NPUW_LLM_MIN_RESPONSE_LEN, uint32_t, 128, npuw::llm::min_response_len, RunTime);DEFINE_OPT(NPUW_LLM_OPTIMIZE_V_TENSORS, bool, true, npuw::llm::optimize_v_tensors, RunTime);DEFINE_OPT(NPUW_LLM_CACHE_ROPE, bool, true, npuw::llm::cache_rope, RunTime);+DEFINE_OPT(NPUW_LLM_GENERATE_PYRAMID, bool, false, npuw::llm::generate_pyramid, RunTime);DEFINE_OPT(NPUW_LLM_PREFILL_CHUNK_SIZE, uint64_t, 1024, npuw::llm::prefill_chunk_size, RunTime);DEFINE_OPT(NPUW_LLM_SHARED_HEAD, bool, true, npuw::llm::shared_lm_head, RunTime);DEFINE_OPT(NPUW_LLM_MAX_LORA_RANK, uint32_t, 32, npuw::llm::max_lora_rank, RunTime);diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp b/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hppindex 041171903f5..3e56df01cdd 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp+++ b/src/plugins/intel_npu/src/al/include/intel_npu/npuw_private_properties.hpp@@ -496,6 +496,16 @@ static constexpr ov::Property<bool> optimize_v_tensors{"NPUW_LLM_OPTIMIZE_V_TENS*/static constexpr ov::Property<bool> cache_rope{"NPUW_LLM_CACHE_ROPE"};+/**+ * @brief+ * Type: boolean+ * Enable multiple generate model variants with different static shapes (1K, 2K, 4K, 8K stepping).+ * When enabled, multiple generate models will be compiled and the appropriate one will be+ * selected at runtime based on the required KV cache size.+ * Default value: false.+ */+static constexpr ov::Property<bool> generate_pyramid{"NPUW_LLM_GENERATE_PYRAMID"};+/*** @brief* Type: uint64_t.diff --git a/src/plugins/intel_npu/src/al/src/config/npuw.cpp b/src/plugins/intel_npu/src/al/src/config/npuw.cppindex bc8e178384f..73075e39633 100644--- a/src/plugins/intel_npu/src/al/src/config/npuw.cpp+++ b/src/plugins/intel_npu/src/al/src/config/npuw.cpp@@ -69,6 +69,7 @@ void intel_npu::registerNPUWLLMOptions(OptionsDesc& desc) {desc.add<NPUW_LLM_MAX_LORA_RANK>();desc.add<NPUW_LLM_OPTIMIZE_V_TENSORS>();desc.add<NPUW_LLM_CACHE_ROPE>();+ desc.add<NPUW_LLM_GENERATE_PYRAMID>();desc.add<NPUW_LLM_PREFILL_CHUNK_SIZE>();desc.add<NPUW_LLM_ENABLE_PREFIX_CACHING>();desc.add<NPUW_LLM_PREFIX_CACHING_BLOCK_SIZE>();diff --git a/src/plugins/intel_npu/src/plugin/include/properties.hpp b/src/plugins/intel_npu/src/plugin/include/properties.hppindex 52f3d95227c..438ccd716d1 100644--- a/src/plugins/intel_npu/src/plugin/include/properties.hpp+++ b/src/plugins/intel_npu/src/plugin/include/properties.hpp@@ -122,6 +122,7 @@ private:ov::intel_npu::npuw::llm::min_response_len.name(),ov::intel_npu::npuw::llm::optimize_v_tensors.name(),ov::intel_npu::npuw::llm::cache_rope.name(),+ ov::intel_npu::npuw::llm::generate_pyramid.name(),ov::intel_npu::npuw::llm::prefill_chunk_size.name(),ov::intel_npu::npuw::llm::shared_lm_head.name(),ov::intel_npu::npuw::llm::max_lora_rank.name(),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 91bde509edb..0f9b06e03c1 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@@ -833,13 +833,6 @@ void patch_phi3_sliding_mask(const std::shared_ptr<ov::Model>& model) {}} // namespace-namespace {-struct KVAxesPosition {- uint32_t batch;- uint32_t seq_len;-};-} // anonymous namespace-class CutLMHead : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::CutLMHead");@@ -1331,6 +1324,103 @@ void ov::npuw::LLMCompiledModel::gemma_transformations(const std::shared_ptr<ov:}}+std::vector<std::shared_ptr<ov::Model>> ov::npuw::LLMCompiledModel::create_generate_model_variants(+ const std::shared_ptr<ov::Model>& generate_model,+ const KVAxesPosition& axes,+ const uint32_t whisper_lhs_seq_size) {+ const uint32_t total_kv_size = m_kvcache_desc.total_size;+ const uint32_t min_response_len = total_kv_size - m_kvcache_desc.max_prompt_size;+ const uint32_t max_generation_token_len = m_kvcache_desc.max_generation_token_len;+ const bool enable_generate_pyramid = m_cfg.get<::intel_npu::NPUW_LLM_GENERATE_PYRAMID>();++ // Check if generate pyramid feature is enabled+ if (enable_generate_pyramid) {+ LOG_INFO("Generate pyramid feature is ENABLED");+ LOG_INFO(+ "Creating multiple generate model variants with stepping: 1K+min_response_len, 2K+min_response_len, etc.");++ // Determine KV cache size steps: (1K + min_response_len), (2K + min_response_len), (4K + min_response_len), (8K+ // + min_response_len), etc.+ std::vector<uint32_t> kv_size_steps;+ for (uint32_t base_size = 1024; base_size + min_response_len <= total_kv_size; base_size *= 2) {+ kv_size_steps.push_back(base_size + min_response_len);+ }+ // Always include the total size if it's not already in the list+ if (kv_size_steps.empty() || kv_size_steps.back() < total_kv_size) {+ kv_size_steps.push_back(total_kv_size);+ }++ LOG_DEBUG("KV cache size variants: ");+ for (const auto& size : kv_size_steps) {+ LOG_DEBUG(" - " << size);+ }++ // Store the sizes for runtime selection+ m_kvcache_sizes = std::move(kv_size_steps);+ } else {+ LOG_INFO("KV cache variants feature is DISABLED - using single model");+ // Use only the total size (traditional single-model approach)+ m_kvcache_sizes = {total_kv_size};+ }++ // Create generate model variants+ LOG_INFO("Creating " << m_kvcache_sizes.size() << " generate model variants...");+ std::vector<std::shared_ptr<ov::Model>> generate_model_variants;+ generate_model_variants.reserve(m_kvcache_sizes.size());++ for (size_t i = 0; i < m_kvcache_sizes.size(); ++i) {+ const uint32_t kv_size = m_kvcache_sizes[i];++ auto generate_variant = (kv_size == total_kv_size) ? generate_model : generate_model->clone();+ LOG_DEBUG("Variant " << (i + 1) << "/" << m_kvcache_sizes.size() << " (size=" << kv_size+ << "): reshaping to static");++ // Reshape to target size+ reshape_to_static(generate_variant,+ max_generation_token_len,+ kv_size,+ axes,+ m_max_lora_rank,+ whisper_lhs_seq_size);++ // Set unique name for this variant+ generate_variant->set_friendly_name(generate_model->get_friendly_name() + "_kv" + std::to_string(kv_size));+ generate_model_variants.push_back(generate_variant);+ }+ LOG_INFO("Created all generate model variants");++ return generate_model_variants;+}++void ov::npuw::LLMCompiledModel::compile_generate_model_variants(+ const std::vector<std::shared_ptr<ov::Model>>& generate_model_variants,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ const ov::AnyMap& generate_config) {+ // Compile multiple generate model variants with different sizes+ LOG_INFO("Compiling " << m_kvcache_sizes.size() << " generate model variants...");+ m_generate_compiled_variants.reserve(m_kvcache_sizes.size());++ for (size_t i = 0; i < m_kvcache_sizes.size(); ++i) {+ const uint32_t kv_size = m_kvcache_sizes[i];+ LOG_DEBUG("Compiling generate variant " << (i + 1) << "/" << m_kvcache_sizes.size()+ << " with size: " << kv_size);++ // Use the already prepared variant model+ auto& generate_variant = generate_model_variants[i];++ // Compile the variant+ auto compiled_variant = std::dynamic_pointer_cast<ov::npuw::CompiledModel>(+ ov::npuw::ICompiledModel::create(generate_variant, plugin, generate_config));+ NPUW_ASSERT(compiled_variant && "Can't create ov::npuw::CompiledModel for generate variant!");++ m_generate_compiled_variants.push_back(compiled_variant);+ LOG_DEBUG("Successfully compiled generate variant with size: " << kv_size);+ }++ // Keep the original compiled model for backward compatibility (using the largest size)+ m_kvcache_compiled = m_generate_compiled_variants.back();+}+ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& model,const std::shared_ptr<const ov::IPlugin>& plugin,const ov::AnyMap& properties)@@ -1490,15 +1580,15 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mwhisper_lhs_seq_size);}LOG_DEBUG("Make kvcache model with static shapes");- reshape_to_static(kvcache_model,- m_kvcache_desc.max_generation_token_len,- m_kvcache_desc.total_size,- axes,- m_max_lora_rank,- whisper_lhs_seq_size);+ // Create generate model variants with different sizes+ auto generate_model_variants = create_generate_model_variants(kvcache_model, axes, whisper_lhs_seq_size);++ // Apply transformations to all generate variantsLOG_DEBUG("Try parametrize Gemma sliding window mask, if it exists.");- gemma_transformations(kvcache_model);+ for (auto& model_variant : generate_model_variants) {+ gemma_transformations(model_variant);+ }if (lm_head_model) {LOG_DEBUG("Shared LM head: slice the prefill output");@@ -1511,7 +1601,9 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mLOG_DEBUG("5.1, decompose GroupQueryAttention OP");decompose_GQA(prefill_model, true);- decompose_GQA(kvcache_model, false);+ for (auto& model_variant : generate_model_variants) {+ decompose_GQA(model_variant, false);+ }const auto prefill_attn_hint = m_cfg.get<::intel_npu::NPUW_LLM_PREFILL_ATTENTION_HINT>();const auto generate_attn_hint = m_cfg.get<::intel_npu::NPUW_LLM_GENERATE_ATTENTION_HINT>();@@ -1526,9 +1618,31 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mLOG_DEBUG("Check and apply opt layout");LOG_BLOCK();// Only optimize V tensors for static attention types- if (!generate_attn_dyn && ov::npuw::util::optimize_value_tensors(kvcache_model, false)) {- LOG_DEBUG("V-tensors tranposed in generate model");- m_kvcache_desc.v_tensors_transposed_gen = true;+ if (!generate_attn_dyn) {+ // Apply optimization to all variants and track results+ size_t optimized_count = 0;+ for (auto& model_variant : generate_model_variants) {+ if (ov::npuw::util::optimize_value_tensors(model_variant, false)) {+ ++optimized_count;+ }+ }++ // Check consistency: either all or none should be optimized+ if (optimized_count == generate_model_variants.size()) {+ LOG_DEBUG("V-tensors transposed in generate model variants");+ m_kvcache_desc.v_tensors_transposed_gen = true;+ } else if (optimized_count == 0) {+ LOG_DEBUG("No V-tensors were optimized");+ m_kvcache_desc.v_tensors_transposed_gen = false;+ } else {+ // Partial optimization is not allowed+ OPENVINO_ASSERT(false,+ "Partial optimization detected: ",+ optimized_count,+ " out of ",+ generate_model_variants.size(),+ " variants were optimized, which is not allowed.");+ }}if (!prefill_attn_dyn && ov::npuw::util::optimize_value_tensors(prefill_model, true)) {LOG_DEBUG("V-tensors tranposed in prefill model");@@ -1546,10 +1660,14 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mprefill_model = redirect_new_kv_to_output(prefill_model);}- LOG_DEBUG("Optimize kvcache model to output key/values for new token.");- kvcache_model = redirect_new_kv_to_output(kvcache_model);- LOG_DEBUG("Converting KV-cache in kvcache model to FP16.");- kvcache_model = cvt_kvcache_to_fp16(kvcache_model);+ LOG_DEBUG("Optimize generate model to output key/values for new token.");+ for (size_t i = 0; i < generate_model_variants.size(); ++i) {+ generate_model_variants[i] = redirect_new_kv_to_output(generate_model_variants[i]);+ }+ LOG_DEBUG("Converting KV-cache in generate model to FP16.");+ for (size_t i = 0; i < generate_model_variants.size(); ++i) {+ generate_model_variants[i] = cvt_kvcache_to_fp16(generate_model_variants[i]);+ }LOG_DEBUG("Converting KV-cache in prefill model to FP16.");prefill_model = cvt_kvcache_to_fp16(prefill_model);@@ -1622,20 +1740,27 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mrope_prefill_cacher.run_on_model(prefill_model);}- if (const uint32_t ctx_len = max_prompt_len + min_response_len; !is_best || (ctx_len >= CACHE_ROPE_START)) {- LOG_DEBUG("Enable RoPE Cache for kvcache");- ov::npuw::patterns::pre_compute::RopeCache rope_generate_cacher(ctx_len);- rope_generate_cacher.run_on_model(kvcache_model);+ // Apply RoPE Cache to all generate variant models+ for (size_t i = 0; i < generate_model_variants.size(); ++i) {+ const uint32_t kv_size = m_kvcache_sizes[i];+ if (!is_best || (kv_size >= CACHE_ROPE_START)) {+ LOG_DEBUG("Enable RoPE Cache for generate variant with size: " << kv_size);+ ov::npuw::patterns::pre_compute::RopeCache rope_cacher(kv_size);+ rope_cacher.run_on_model(generate_model_variants[i]);+ }}}// Regularize models for the better partitioning assuming it is a transformer+ // Apply these transformations to all variant models{ov::pass::GraphRewrite rewr;rewr.add_matcher<ov::npuw::patterns::regularize::AttentionBroadcast>();rewr.add_matcher<ov::npuw::patterns::regularize::AttentionBroadcast2>();if (generate_attn_dyn || generate_attn_pyramid) {- rewr.run_on_model(kvcache_model);+ for (auto& model_variant : generate_model_variants) {+ rewr.run_on_model(model_variant);+ }}if (prefill_attn_dyn || prefill_attn_pyramid) {rewr.run_on_model(prefill_model);@@ -1646,14 +1771,15 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m// while AttentionBroadcast patterns might break the partitioning (related to F16IC).ov::pass::GraphRewrite rewr2;rewr2.add_matcher<ov::npuw::patterns::regularize::ShapeOfParameter>();- rewr2.run_on_model(kvcache_model);+ for (auto& model_variant : generate_model_variants) {+ rewr2.run_on_model(model_variant);+ }rewr2.run_on_model(prefill_model);}- m_kvcache_compiled = std::dynamic_pointer_cast<ov::npuw::CompiledModel>(- ov::npuw::ICompiledModel::create(kvcache_model, plugin, generate_config));- NPUW_ASSERT(m_kvcache_compiled && "Can't create ov::npuw::CompiledModel for passed kvcache "- "model and its config, please check passed config.");+ // Compile multiple generate model variants with different sizes+ compile_generate_model_variants(generate_model_variants, plugin, generate_config);+m_prefill_compiled = std::dynamic_pointer_cast<ov::npuw::CompiledModel>(ov::npuw::ICompiledModel::create(prefill_model, plugin, prefill_config));NPUW_ASSERT(m_prefill_compiled && "Can't create ov::npuw::CompiledModel for passed prefill "@@ -1785,10 +1911,19 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& stream, const ov::npuw:// Write configwrite(model_stream, m_cfg);+ // Serialize KV cache model variants+ write(model_stream, m_kvcache_sizes);+ write(model_stream, static_cast<uint32_t>(m_generate_compiled_variants.size()));+// Serialize CompiledModels// Note: no need to pass any encryption here as it's done in export_model()CompiledContext enc_ctx(false, nullptr, nullptr, m_bf16_consts);- m_kvcache_compiled->serialize(model_stream, enc_ctx);++ // Serialize all generate variants+ for (const auto& compiled_variant : m_generate_compiled_variants) {+ compiled_variant->serialize(model_stream, enc_ctx);+ }+m_prefill_compiled->serialize(model_stream, enc_ctx);const bool is_shared_lm_head = m_lm_head_compiled != nullptr;write(model_stream, is_shared_lm_head);@@ -1885,15 +2020,16 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::import_mif (is_weightless) {auto bank = ov::npuw::weights::bank(bank_name, compiled->get_plugin()->get_core(), "");- compiled->m_kvcache_compiled->m_weights_bank = bank;- compiled->m_prefill_compiled->m_weights_bank = bank;+ for (const auto& compiled_variant : compiled->m_generate_compiled_variants) {+ compiled_variant->m_weights_bank = bank;+ compiled_variant->finalize_weights_bank();+ }- compiled->m_kvcache_compiled->finalize_weights_bank();+ compiled->m_prefill_compiled->m_weights_bank = bank;compiled->m_prefill_compiled->finalize_weights_bank();if (compiled->m_lm_head_compiled) {compiled->m_lm_head_compiled->m_weights_bank = bank;-compiled->m_lm_head_compiled->finalize_weights_bank();}} else {@@ -1901,14 +2037,16 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::import_mov::npuw::weights::Bank::deserialize(model_stream, compiled->get_plugin()->get_core(), bank_name);compiled->m_kvcache_compiled->m_weights_bank = bank;- compiled->m_prefill_compiled->m_weights_bank = bank;+ for (const auto& compiled_variant : compiled->m_generate_compiled_variants) {+ compiled_variant->m_weights_bank = bank;+ compiled_variant->reconstruct_closure();+ }- compiled->m_kvcache_compiled->reconstruct_closure();+ compiled->m_prefill_compiled->m_weights_bank = bank;compiled->m_prefill_compiled->reconstruct_closure();if (compiled->m_lm_head_compiled) {compiled->m_lm_head_compiled->m_weights_bank = bank;-compiled->m_lm_head_compiled->reconstruct_closure();}}@@ -1998,10 +2136,28 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserialread(model_stream, compiled->m_cfg);compiled->implement_properties();+ // Deserialize KV cache model variants+ read(model_stream, compiled->m_kvcache_sizes);+ uint32_t num_variants = 0;+ read(model_stream, num_variants);++ compiled->m_generate_compiled_variants.reserve(num_variants);+// Deserialize CompiledModels// Note: no need to pass any encryption here as it's done in import_model()CompiledContext enc_ctx(false, nullptr, nullptr);- compiled->m_kvcache_compiled = ov::npuw::CompiledModel::deserialize(model_stream, plugin, properties, enc_ctx);++ // Deserialize all generate variants+ for (uint32_t i = 0; i < num_variants; ++i) {+ auto compiled_variant = ov::npuw::CompiledModel::deserialize(model_stream, plugin, properties, enc_ctx);+ compiled->m_generate_compiled_variants.push_back(compiled_variant);+ }++ // Set the main kvcache_compiled to the largest variant for backward compatibility+ if (!compiled->m_generate_compiled_variants.empty()) {+ compiled->m_kvcache_compiled = compiled->m_generate_compiled_variants.back();+ }+compiled->m_prefill_compiled = ov::npuw::CompiledModel::deserialize(model_stream, plugin, properties, enc_ctx);bool is_shared_lm_head = false;read(model_stream, is_shared_lm_head);@@ -2082,6 +2238,8 @@ void ov::npuw::LLMCompiledModel::implement_properties() {BIND(npuw::llm::max_prompt_len, NPUW_LLM_MAX_PROMPT_LEN, get),BIND(npuw::llm::min_response_len, NPUW_LLM_MIN_RESPONSE_LEN, get),BIND(npuw::llm::optimize_v_tensors, NPUW_LLM_OPTIMIZE_V_TENSORS, get),+ BIND(npuw::llm::cache_rope, NPUW_LLM_CACHE_ROPE, get),+ BIND(npuw::llm::generate_pyramid, NPUW_LLM_GENERATE_PYRAMID, get),BIND(npuw::llm::prefill_chunk_size, NPUW_LLM_PREFILL_CHUNK_SIZE, get),BIND(npuw::llm::prefill_hint, NPUW_LLM_PREFILL_HINT, getString),BIND(npuw::llm::generate_hint, NPUW_LLM_GENERATE_HINT, getString),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 f3888ebf254..6294881ca1e 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@@ -8,6 +8,13 @@#include "compiled_model.hpp"+namespace {+struct KVAxesPosition {+ uint32_t batch;+ uint32_t seq_len;+};+} // anonymous namespace+namespace ov {namespace npuw {@@ -86,6 +93,10 @@ private:// This model is optional, so can be null.std::shared_ptr<ov::npuw::CompiledModel> m_lm_head_compiled;+ // Multiple generate models with different static KV cache shapes (1K, 2K, 4K, 8K stepping)+ std::vector<std::shared_ptr<ov::npuw::CompiledModel>> m_generate_compiled_variants;+ std::vector<uint32_t> m_kvcache_sizes; // Corresponding KV cache sizes for each variant+// Support LoRAvoid convert_stateful_lora_to_stateless(std::shared_ptr<ov::Model>& model);uint32_t m_max_lora_rank = 32;@@ -102,6 +113,17 @@ private:int32_t m_gemma_sliding_window_size = 0;bool m_is_whisper = false;++ // Create generate model variants with different sizes+ std::vector<std::shared_ptr<ov::Model>> create_generate_model_variants(+ const std::shared_ptr<ov::Model>& generate_model,+ const KVAxesPosition& axes,+ const uint32_t whisper_lhs_seq_size);++ // Compile multiple generate model variants+ void compile_generate_model_variants(const std::vector<std::shared_ptr<ov::Model>>& generate_model_variants,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ const ov::AnyMap& generate_config);};} // 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 3e6abb1dc1c..037bf86fa16 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@@ -178,7 +178,8 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCom_input_ids_name = layer_names::inputs_embeds;}- m_kvcache_request = compiled_model->m_kvcache_compiled->create_infer_request();+ // Create and initialize generate request variants with memory sharing+ create_generate_request_variants(compiled_model);m_prefill_base_request = compiled_model->m_prefill_compiled->create_base_infer_request();m_prefill_request = compiled_model->m_prefill_compiled->wrap_async_infer_request(m_prefill_base_request);@@ -194,13 +195,6 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCom_prefill_out_ports.emplace(output_port.get_any_name(), output_port);}- for (const auto& input_port : m_kvcache_request->get_compiled_model()->inputs()) {- m_kvcache_in_ports.emplace(input_port.get_any_name(), input_port);- }- for (const auto& output_port : m_kvcache_request->get_compiled_model()->outputs()) {- m_kvcache_out_ports.emplace(output_port.get_any_name(), output_port);- }-init_lora_states();const bool use_chunk_prefill = m_npuw_llm_compiled_model->m_use_chunk_prefill;@@ -219,8 +213,13 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCom_lm_head_logits_port = m_lm_head_request->get_outputs()[0];m_prefill_request->set_tensor(m_prefill_out_ports.at(layer_names::output_embeds),m_lm_head_request->get_tensor(lm_head_embed_port));- m_kvcache_request->set_tensor(m_kvcache_out_ports.at(layer_names::output_embeds),- m_lm_head_request->get_tensor(lm_head_embed_port));++ // Set output_embeds tensor for all generate variants+ for (auto& generate_req : m_generate_requests) {+ const auto& variant_out_ports = m_generate_variant_out_ports.at(generate_req);+ generate_req->set_tensor(variant_out_ports.at(layer_names::output_embeds),+ m_lm_head_request->get_tensor(lm_head_embed_port));+ }}// FIXME: E-177589@@ -243,16 +242,20 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCo}if (enable_cpu_wa) {- const auto& kvcache_compiled = m_kvcache_request->get_compiled_model();- // FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs exist+ // Apply CPU workaround only for the largest variant since all variants share its past KV tensors+ auto& largest_kvcache_req = m_generate_requests.back();+ const auto& kvcache_compiled = largest_kvcache_req->get_compiled_model();+ const auto& variant_in_ports = m_generate_variant_in_ports.at(largest_kvcache_req);+ // FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs+ // existfor (std::size_t i = layer_ids::kStartOutputKVCacheLayers; i < kvcache_compiled->outputs().size(); ++i) {const auto& output_name = kvcache_compiled->outputs()[i].get_any_name();const auto& input_name =std::regex_replace(output_name, std::regex("present"), layer_names::past_key_values);- if (m_kvcache_in_ports.find(input_name) == m_kvcache_in_ports.end()) {+ if (variant_in_ports.find(input_name) == variant_in_ports.end()) {continue;}- auto kvcache_in_tensor = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(input_name));+ auto kvcache_in_tensor = largest_kvcache_req->get_tensor(variant_in_ports.at(input_name));ov::npuw::util::fill_tensor<ov::float16>(kvcache_in_tensor, 0);}}@@ -261,6 +264,106 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCom_gemma_sliding_window_size = compiled_model->m_gemma_sliding_window_size;}+void ov::npuw::LLMInferRequest::create_generate_request_variants(+ const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled_model) {+ // Create multiple generate model variants' requests+ m_generate_requests.reserve(compiled_model->m_generate_compiled_variants.size());++ // First, create the largest variant request (last one in the list)+ auto largest_generate_request = compiled_model->m_generate_compiled_variants.back()->create_infer_request();++ // Store past KV tensors from the largest variant for sharing+ std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> largest_past_kv_tensors;+ for (const auto& input_port : largest_generate_request->get_compiled_model()->inputs()) {+ const auto& input_name = input_port.get_any_name();+ if (input_name.find(layer_names::past_key_values) != std::string::npos) {+ largest_past_kv_tensors[input_name] = largest_generate_request->get_tensor(input_port);+ }+ }++ // Create all variant requests and share past KV tensors+ for (size_t i = 0; i < compiled_model->m_generate_compiled_variants.size(); ++i) {+ std::shared_ptr<ov::IAsyncInferRequest> generate_request;++ if (i == compiled_model->m_generate_compiled_variants.size() - 1) {+ // Use the already created largest variant+ generate_request = largest_generate_request;+ } else {+ // Create smaller variant+ generate_request = compiled_model->m_generate_compiled_variants[i]->create_infer_request();++ // Share past KV tensors from the largest variant+ for (const auto& input_port : generate_request->get_compiled_model()->inputs()) {+ const auto& input_name = input_port.get_any_name();+ if (input_name.find(layer_names::past_key_values) != std::string::npos) {+ if (largest_past_kv_tensors.find(input_name) != largest_past_kv_tensors.end()) {+ auto largest_tensor = largest_past_kv_tensors[input_name];+ auto small_shape = input_port.get_shape();++ // Wrap the largest tensor's data pointer with smaller shape+ auto shared_tensor = ov::SoPtr<ov::ITensor>(+ ov::make_tensor(input_port.get_element_type(), small_shape, largest_tensor->data()),+ nullptr);++ generate_request->set_tensor(input_port, shared_tensor);+ } else {+ OPENVINO_ASSERT(false, "Unexpected input name: ", input_name);+ }+ }+ }+ }++ m_generate_requests.push_back(generate_request);++ // Build input/output ports mapping for this variant+ std::unordered_map<std::string, ov::Output<const ov::Node>> variant_in_ports;+ std::unordered_map<std::string, ov::Output<const ov::Node>> variant_out_ports;++ for (const auto& input_port : generate_request->get_compiled_model()->inputs()) {+ variant_in_ports.emplace(input_port.get_any_name(), input_port);+ }+ for (const auto& output_port : generate_request->get_compiled_model()->outputs()) {+ variant_out_ports.emplace(output_port.get_any_name(), output_port);+ }++ m_generate_variant_in_ports.emplace(generate_request, std::move(variant_in_ports));+ m_generate_variant_out_ports.emplace(generate_request, std::move(variant_out_ports));+ }++ // Set default to the largest variant for backward compatibility+ m_kvcache_request = m_generate_requests.back();+}++std::shared_ptr<ov::IAsyncInferRequest> ov::npuw::LLMInferRequest::select_generate_request(int64_t prompt_length) {+ // Select the largest variant if prompt_length is 0 (unknown)+ if (prompt_length == 0) {+ LOG_DEBUG("Prompt length unknown, using largest variant");+ return m_generate_requests.back();+ }++ auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;+ // Calculate expected total tokens: prompt + min_response_len+ // min_response_len = total_size - max_prompt_size+ uint32_t min_response_len = kvcache_desc.total_size - kvcache_desc.max_prompt_size;+ int64_t expected_total_tokens = prompt_length + min_response_len;++ const auto& kvcache_sizes = m_npuw_llm_compiled_model->m_kvcache_sizes;+ // Find the smallest variant that can accommodate the expected token count+ for (size_t i = 0; i < kvcache_sizes.size(); ++i) {+ if (expected_total_tokens <= kvcache_sizes[i]) {+ LOG_DEBUG("Selected generate request " << (i + 1) << "/" << kvcache_sizes.size() << " with size "+ << kvcache_sizes[i] << " for prompt_length=" << prompt_length+ << " (expected_total=" << expected_total_tokens << " tokens)");+ return m_generate_requests[i];+ }+ }++ // Fallback to the largest variant if expected_total_tokens exceeds all predefined sizes+ LOG_WARN("No suitable generate request found for expected_total_tokens="+ << expected_total_tokens << " (prompt_length=" << prompt_length << "), using largest variant");+ return m_generate_requests.back();+}+void ov::npuw::LLMInferRequest::init_tensor(const ov::Output<const ov::Node>& port) {ov::SoPtr<ITensor> tensor;tensor = ov::ISyncInferRequest::get_tensor(port);@@ -377,6 +480,10 @@ void ov::npuw::LLMInferRequest::apply_lora() {}void ov::npuw::LLMInferRequest::prepare_for_new_conversation() {+ prepare_for_new_conversation(0);+}++void ov::npuw::LLMInferRequest::prepare_for_new_conversation(int64_t prompt_length) {namespace uu = ov::npuw::util;uu::fill_tensor_bytes(m_prefill_request->get_tensor(m_prefill_in_ports.at(m_input_ids_name)), 0u);if (auto type_ids_port = m_prefill_in_ports.find(layer_names::token_type_ids);@@ -393,6 +500,12 @@ void ov::npuw::LLMInferRequest::prepare_for_new_conversation() {m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens = 0u;+ // Select the appropriate generate inference request variant based on prompt length+ // The function internally calculates expected total tokens (prompt + min_response_len)+ m_kvcache_request = select_generate_request(prompt_length);+ m_kvcache_in_ports = m_generate_variant_in_ports.at(m_kvcache_request);+ m_kvcache_out_ports = m_generate_variant_out_ports.at(m_kvcache_request);+apply_lora();}@@ -729,15 +842,16 @@ void ov::npuw::LLMInferRequest::infer_prefill(ov::SoPtr<ov::ITensor> input_ids,LOG_DEBUG("Calling inference for prefill model...");LOG_BLOCK();+ const auto prompt_length = input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM];auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;- if (input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM] > kvcache_desc.max_prompt_size) {+ if (prompt_length > kvcache_desc.max_prompt_size) {OPENVINO_THROW("Input prompt is longer than configured \"NPUW_LLM_MAX_PROMPT_LEN\": ",kvcache_desc.max_prompt_size,".\nPlease either setup bigger ""\"NPUW_LLM_MAX_PROMPT_LEN\" or shorten the prompt.");}- prepare_for_new_conversation();+ prepare_for_new_conversation(prompt_length);const bool use_chunk_prefill = m_npuw_llm_compiled_model->m_use_chunk_prefill;if (use_chunk_prefill) {@@ -776,6 +890,9 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,".\nPlease adjust it.");}+ // Note: m_kvcache_request, m_kvcache_in_ports, and m_kvcache_out_ports are selected in+ // prepare_for_new_conversation()+if (!m_generate_initialized) {LOG_DEBUG("Copy kv-cache from prefill to generate model.");if (kvcache_desc.num_stored_tokens > 0) {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 3353099d0a5..6c4af7feedd 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@@ -50,6 +50,7 @@ public:protected:virtual void prepare_for_new_conversation();+ void prepare_for_new_conversation(int64_t prompt_length);void apply_lora();@@ -57,6 +58,15 @@ protected:void init_tensor(const ov::Output<const ov::Node>& port);void copy_kvcache();++ // Create and initialize generate variant requests with memory sharing+ void create_generate_request_variants(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled_model);++ // Select appropriate generate request variant based on prompt length+ // Internally calculates expected total tokens (prompt + min_response_len) to ensure+ // sufficient capacity for both input prompt and minimum response generation+ std::shared_ptr<ov::IAsyncInferRequest> select_generate_request(int64_t prompt_length);+void update_kvcache_for(std::shared_ptr<ov::IAsyncInferRequest> request,const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,const std::unordered_map<std::string, ov::Output<const ov::Node>>& out_ports,@@ -83,7 +93,13 @@ protected:ov::SoPtr<ov::ITensor> position_ids,ov::SoPtr<ov::ITensor> input_token_ids);+ // Multiple generate inference request variants, each with a different KV cache size+ std::vector<std::shared_ptr<ov::IAsyncInferRequest>> m_generate_requests;++ // Currently selected generate inference request variant (selected in prepare_for_new_conversation based on prompt+ // length)std::shared_ptr<ov::IAsyncInferRequest> m_kvcache_request;+std::shared_ptr<ov::IAsyncInferRequest> m_prefill_request;// Base infer request for prefill, used to update history size for dynamic context.// NOTE: This is just a casted pointer for convenience. In fact it points to the@@ -96,8 +112,20 @@ protected:std::unordered_map<std::string, ov::Output<const ov::Node>> m_prefill_in_ports;std::unordered_map<std::string, ov::Output<const ov::Node>> m_prefill_out_ports;++ // Ports for the currently selected generate model variant (set once per conversation in+ // prepare_for_new_conversation)std::unordered_map<std::string, ov::Output<const ov::Node>> m_kvcache_in_ports;std::unordered_map<std::string, ov::Output<const ov::Node>> m_kvcache_out_ports;++ // Ports for all generate model variants - maps from request pointer to its input/output ports+ std::unordered_map<std::shared_ptr<ov::IAsyncInferRequest>,+ std::unordered_map<std::string, ov::Output<const ov::Node>>>+ m_generate_variant_in_ports;+ std::unordered_map<std::shared_ptr<ov::IAsyncInferRequest>,+ std::unordered_map<std::string, ov::Output<const ov::Node>>>+ m_generate_variant_out_ports;+ov::Output<const ov::Node> m_lm_head_logits_port;// Cache past_key_values ports for efficient clearing in prepare_for_new_conversationdiff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hppindex 81cba881004..155980ea98a 100644--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp@@ -34,7 +34,7 @@ const constexpr ov::npuw::s11n::IndicatorType NPUW_COMPILED_MODEL_INDICATOR =const constexpr ov::npuw::s11n::IndicatorType NPUW_LLM_COMPILED_MODEL_INDICATOR ={char{0x4c}, char{0x4c}, char{0x4d}, char{0x43}, char{0x4d}, char{0x4f}};-const constexpr char* NPUW_SERIALIZATION_VERSION = "0.14";+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.15";// Forward declarationnamespace intel_npu {diff --git a/src/plugins/intel_npu/src/plugin/src/plugin.cpp b/src/plugins/intel_npu/src/plugin/src/plugin.cppindex 97c6a7e09ce..816c34b7a29 100644--- a/src/plugins/intel_npu/src/plugin/src/plugin.cpp+++ b/src/plugins/intel_npu/src/plugin/src/plugin.cpp@@ -374,6 +374,7 @@ void Plugin::init_options() {REGISTER_OPTION(NPUW_LLM_MIN_RESPONSE_LEN);REGISTER_OPTION(NPUW_LLM_OPTIMIZE_V_TENSORS);REGISTER_OPTION(NPUW_LLM_CACHE_ROPE);+ REGISTER_OPTION(NPUW_LLM_GENERATE_PYRAMID);REGISTER_OPTION(NPUW_LLM_PREFILL_CHUNK_SIZE);REGISTER_OPTION(NPUW_LLM_SHARED_HEAD);REGISTER_OPTION(NPUW_LLM_MAX_LORA_RANK);diff --git a/src/plugins/intel_npu/src/plugin/src/properties.cpp b/src/plugins/intel_npu/src/plugin/src/properties.cppindex d522bc14984..55be8533d00 100644--- a/src/plugins/intel_npu/src/plugin/src/properties.cpp+++ b/src/plugins/intel_npu/src/plugin/src/properties.cpp@@ -463,6 +463,7 @@ void Properties::registerPluginProperties() {TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::min_response_len, NPUW_LLM_MIN_RESPONSE_LEN);TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::optimize_v_tensors, NPUW_LLM_OPTIMIZE_V_TENSORS);TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::cache_rope, NPUW_LLM_CACHE_ROPE);+ TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::generate_pyramid, NPUW_LLM_GENERATE_PYRAMID);TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::prefill_chunk_size, NPUW_LLM_PREFILL_CHUNK_SIZE);TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::shared_lm_head, NPUW_LLM_SHARED_HEAD);TRY_REGISTER_SIMPLE_PROPERTY(ov::intel_npu::npuw::llm::max_lora_rank, NPUW_LLM_MAX_LORA_RANK);