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] i8-kvcache accuracy regression + tests (#35451)
Eugene Smirnov786052d995f8
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 7bd0023dbd7..46a9662f9d1 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@@ -1182,10 +1182,12 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m}LOG_DEBUG("Converting KV-cache in generate model to" << kv_kache_storage_type);for (size_t i = 0; i < generate_model_variants.size(); ++i) {- ov::npuw::ConvertKVCacheToPrecision(kv_kache_storage_type).run_on_model(generate_model_variants[i]);+ ov::npuw::ConvertKVCacheToPrecision(kv_kache_storage_type, m_kvcache_desc.v_tensors_transposed_gen)+ .run_on_model(generate_model_variants[i]);}LOG_DEBUG("Converting KV-cache in prefill model to" << kv_kache_storage_type);- ov::npuw::ConvertKVCacheToPrecision(kv_kache_storage_type).run_on_model(prefill_model);+ ov::npuw::ConvertKVCacheToPrecision(kv_kache_storage_type, m_kvcache_desc.v_tensors_transposed_pre)+ .run_on_model(prefill_model);std::optional<std::string> user_compilation_mode_params = std::nullopt;if (const auto it = other_props.find("NPU_COMPILATION_MODE_PARAMS"); it != other_props.end()) {@@ -1398,6 +1400,10 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m// Apply block-based KV cache transformation for chunk prefill after ShapeOfParameter// This ensures ShapeOf nodes are already regularized before transformationif (m_cfg.get<::intel_npu::NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE>()) {+ const bool integer_kv_cache =+ kv_kache_storage_type == ov::element::i8 || kv_kache_storage_type == ov::element::u8;+ OPENVINO_ASSERT(!integer_kv_cache,+ "NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE cannot be combined with integer KV-cache precision.");OPENVINO_ASSERT(!m_enable_prefix_caching,"NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE and NPUW_LLM_ENABLE_PREFIX_CACHING ""cannot be enabled simultaneously — this combination is not yet supported. "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 653ad387a48..fbe034f18ba 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@@ -85,7 +85,7 @@ public:void set_property(const ov::AnyMap& properties) override;ov::Any get_property(const std::string& name) const override;-private:+protected:friend class LLMInferBaseRequest;friend class LLMInferRequest;friend class WhisperInferRequest;diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cppindex b257c4c01f9..ae1a051ca90 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cpp@@ -26,7 +26,8 @@ void LLMContinuousKVCacheStrategy::on_initialize() {m_kv_pairs.clear();m_kv_pairs.reserve(m_req.m_kvcache_past_names.size());for (const auto& name : m_req.m_kvcache_past_names) {- m_kv_pairs.push_back({name, ov::npuw::util::isPastValueParam(name)});+ const bool is_value = ov::npuw::util::isPastValueParam(name) || ov::npuw::util::isDQScaleOrZPValue(name);+ m_kv_pairs.push_back({name, is_value});}// Step 1: share past KV buffers across generate variants.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 adf4cab7aae..1c6cc05a56f 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@@ -28,6 +28,14 @@ int64_t get_max_position_id(const ov::SoPtr<ov::ITensor>& position_ids) {return *std::max_element(pos_ids_data, pos_ids_data + position_ids->get_size());}+std::optional<std::string> resolve_kv_input_name(+ const std::string& output_name,+ const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports) {+ return ov::npuw::util::resolveKVInputName(output_name, [&in_ports](const std::string& name) {+ return in_ports.find(name) != in_ports.end();+ });+}+void copy_columns_by_row_chunks_2d(ov::SoPtr<ov::ITensor> src, ov::SoPtr<ov::ITensor>& dst) {const auto& src_shape = src->get_shape();@@ -406,7 +414,6 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCom_lm_head_request->get_tensor(lm_head_embed_port));}}-// FIXME: E-177589// FIXME: "fixes"/workarounds caching import on CPU (also might be related to bf16 weights).// Unclear how it's related. Previously fill_tensor()@@ -419,13 +426,11 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCobreak;}}-ov::Any kvcache_weight_bank_alloc =compiled_model->m_kvcache_compiled->get_property(ov::intel_npu::npuw::weights_bank_alloc.name());if (kvcache_weight_bank_alloc.as<std::string>() == "CPU") {enable_cpu_wa = true;}-if (enable_cpu_wa) {// Apply CPU workaround only for the largest variant since all variants share its past KV tensorsauto& largest_kvcache_req = m_generate_requests.back();@@ -498,7 +503,7 @@ void ov::npuw::LLMInferRequest::init_past_name_lists() {m_swa_past_names.push_back(name);break;}- if (ov::npuw::util::starts_with(name, layer_names::past_key_values)) {+ if (ov::npuw::util::isKVCacheName(name)) {m_kvcache_past_names.push_back(name);break;}@@ -734,16 +739,19 @@ void ov::npuw::LLMInferRequest::copy_kvcache() {auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;// FIXME: Find only matching by names outputs and copy them, having previously checked that such inputs existov::parallel_for(m_kvcache_past_names.size(), [&](size_t out_idx) {- const auto& input_name = m_kvcache_past_names[out_idx];- auto kvcache_in_tensor = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(input_name));+ const auto& past_input_name = m_kvcache_past_names[out_idx];- const auto& output_name = std::regex_replace(input_name, std::regex(layer_names::past_key_values), "present");+ const auto output_name = ov::npuw::util::past_key_values_to_present_name(past_input_name);OPENVINO_ASSERT(m_prefill_out_ports.find(output_name) != m_prefill_out_ports.end(),- "Incosistent input/output naming for KV cache: ",- output_name,- " not found in prefill model outputs.");+ "Inconsistent input/output naming for KV cache: ",+ past_input_name,+ " has no matching output in prefill model.");auto prefill_out_tensor = m_prefill_request->get_tensor(m_prefill_out_ports.at(output_name));-+ const auto input_name = resolve_kv_input_name(output_name, m_kvcache_in_ports);+ if (!input_name.has_value()) {+ LOG_DEBUG("Output name " << output_name << " has no matching past kv-cache input. Skipping.");+ return;+ }const auto is_value_tensor = output_name.find("value") != std::string::npos;const auto kv_dim = [&](bool v_trans) -> uint32_t {return (is_value_tensor && v_trans) ? 3u : kvcache_desc.dim;@@ -751,6 +759,7 @@ void ov::npuw::LLMInferRequest::copy_kvcache() {const auto& pre_kv_dim = kv_dim(kvcache_desc.v_tensors_transposed_pre);const auto& gen_kv_dim = kv_dim(kvcache_desc.v_tensors_transposed_gen);+ auto kvcache_in_tensor = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(input_name.value()));const auto prefill_chunk_size = m_npuw_llm_compiled_model->m_prefill_chunk_size;const bool use_chunk_prefill = m_npuw_llm_compiled_model->m_use_chunk_prefill;@@ -766,7 +775,7 @@ void ov::npuw::LLMInferRequest::copy_kvcache() {if (tokens_in_past_chunks > 0) {// Create backup of past KV tensor when buffer sharing is enabled to prevent data corruption// This is necessary because subsequent copy operations would overwrite the shared buffer- auto prefill_past_kv = m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name));+ auto prefill_past_kv = m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name.value()));ov::SoPtr<ov::ITensor> tmp_dense_kv_tensor;ov::SoPtr<ov::ITensor> prefill_past_kv_chunks;if (m_past_kv_bound) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.cppindex 720336a65a8..12a211be059 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.cpp@@ -67,7 +67,8 @@ public:};std::shared_ptr<ov::Model> cvt_kvcache_to_low_precision(const std::shared_ptr<ov::Model>& model,- const ov::element::Type lptype) {+ const ov::element::Type lptype,+ const bool v_tensors_transposed) {// Resolve storage types first and apply them through PPP for both inputs and outputs.// Default path keeps KV cache in f16; integer hint uses key=i8/u8 and value=i4.auto key_storage_type = lptype;@@ -109,7 +110,7 @@ std::shared_ptr<ov::Model> cvt_kvcache_to_low_precision(const std::shared_ptr<ovLOG_DEBUG("Running KV-cache compression passes: key=" << key_storage_type << ", value=" << value_storage_type<< " on model[" << model->get_friendly_name() << "]");- ov::npuw::run_kv_cache_dynamic_quantization_passes(new_model, dq_params);+ ov::npuw::run_kv_cache_dynamic_quantization_passes(new_model, dq_params, v_tensors_transposed);}return new_model;}@@ -161,10 +162,12 @@ ov::element::Type optimize_kv_cache_storage(const std::shared_ptr<ov::Model>& monamespace ov::npuw {-ConvertKVCacheToPrecision::ConvertKVCacheToPrecision(const ov::element::Type lptype) : m_lp_type(lptype) {}+ConvertKVCacheToPrecision::ConvertKVCacheToPrecision(const ov::element::Type lptype, bool v_tensors_transposed)+ : m_lp_type(lptype),+ m_v_tensors_transposed(v_tensors_transposed) {}bool ConvertKVCacheToPrecision::run_on_model(const std::shared_ptr<ov::Model>& model) {- auto ppp_result = cvt_kvcache_to_low_precision(model, m_lp_type);+ auto ppp_result = cvt_kvcache_to_low_precision(model, m_lp_type, m_v_tensors_transposed);// PrePostProcessor currently always modifies the model in-place and returns the same model pointer, but let's// be defensive here and check it just in caseOPENVINO_ASSERT(ppp_result == model,diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.hppindex 6ebb1a8a0a2..5e5edfe5858 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/convert_kvcache_to_precision.hpp@@ -14,10 +14,11 @@ ov::element::Type optimize_kv_cache_storage(const std::shared_ptr<ov::Model>& moclass ConvertKVCacheToPrecision : public ov::pass::ModelPass {ov::element::Type m_lp_type;+ bool m_v_tensors_transposed = false;public:OPENVINO_MODEL_PASS_RTTI("ov::npuw::ConvertKVCacheToPrecision");- explicit ConvertKVCacheToPrecision(const ov::element::Type lptype);+ explicit ConvertKVCacheToPrecision(const ov::element::Type lptype, bool v_tensors_transposed = false);bool run_on_model(const std::shared_ptr<ov::Model>& model) override;};diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_cache_compressed.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_cache_compressed.cppindex 8fea041173b..1e0243e6462 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_cache_compressed.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_cache_compressed.cpp@@ -30,6 +30,13 @@ constexpr auto g_value_cache_name = "value";constexpr auto g_past_name = "past_key_values";constexpr auto g_present_name = "present";+size_t get_kv_embedding_index(bool is_key, bool v_tensors_transposed) {+ if (is_key) {+ return 3u;+ }+ return v_tensors_transposed ? 2u : 3u;+}+bool isKey(const std::string& n) {return n.find(g_key_cache_name) != std::string::npos;}@@ -176,7 +183,7 @@ ov::OutputVector dynamic_quantize_linear_v3(const ov::Output<ov::Node>& input,// ── V2: ONNX DynamicQuantizeLinear style, u8 [0, 255] ────────────────────────-ov::npuw::DecomposeDynamicQuantize2::DecomposeDynamicQuantize2() {+ov::npuw::DecomposeDynamicQuantize2::DecomposeDynamicQuantize2(bool v_tensors_transposed) {auto dynamic_quantize = opp::wrap_type<ov::op::internal::DynamicQuantize>({opp::any_input()});auto callback = [=](opp::Matcher& m) {auto& node_to_output = m.get_pattern_value_map();@@ -193,10 +200,7 @@ ov::npuw::DecomposeDynamicQuantize2::DecomposeDynamicQuantize2() {LOG_DEBUG("Found DynamicQuantize : " << dq_ptr->get_friendly_name() << " decomposing");LOG_BLOCK();- constexpr size_t k_embedding_index = 3;- constexpr size_t v_embedding_index = 2;-- auto reduction_axis = isKey(dq_ptr->get_friendly_name()) ? k_embedding_index : v_embedding_index;+ const auto reduction_axis = get_kv_embedding_index(isKey(dq_ptr->get_friendly_name()), v_tensors_transposed);auto dq_input = dq_ptr->input_value(0);auto has_zp = dq_ptr->outputs().size() == 3;@@ -217,7 +221,7 @@ ov::npuw::DecomposeDynamicQuantize2::DecomposeDynamicQuantize2() {// ── V3: compiler pattern style, i8 [-128, 127] ───────────────────────────────-ov::npuw::DecomposeDynamicQuantize3::DecomposeDynamicQuantize3() {+ov::npuw::DecomposeDynamicQuantize3::DecomposeDynamicQuantize3(bool v_tensors_transposed) {auto dynamic_quantize = opp::wrap_type<ov::op::internal::DynamicQuantize>({opp::any_input()});auto callback = [=](opp::Matcher& m) {auto& node_to_output = m.get_pattern_value_map();@@ -240,10 +244,7 @@ ov::npuw::DecomposeDynamicQuantize3::DecomposeDynamicQuantize3() {LOG_DEBUG("Found DynamicQuantize : " << dq_ptr->get_friendly_name() << " decomposing");LOG_BLOCK();- constexpr size_t k_embedding_index = 3;- constexpr size_t v_embedding_index = 2;-- auto reduction_axis = isKey(dq_ptr->get_friendly_name()) ? k_embedding_index : v_embedding_index;+ const auto reduction_axis = get_kv_embedding_index(isKey(dq_ptr->get_friendly_name()), v_tensors_transposed);auto dq_input = dq_ptr->input_value(0);auto has_zp = dq_ptr->outputs().size() == 3;@@ -265,7 +266,7 @@ ov::npuw::DecomposeDynamicQuantize3::DecomposeDynamicQuantize3() {// ── V1: handcrafted symmetric-style, i8 [-127, 127] ──────────────────────────-ov::npuw::DecomposeDynamicQuantize::DecomposeDynamicQuantize() {+ov::npuw::DecomposeDynamicQuantize::DecomposeDynamicQuantize(bool v_tensors_transposed) {auto dynamic_quantize = opp::wrap_type<ov::op::internal::DynamicQuantize>({opp::any_input()});auto callback = [=](opp::Matcher& m) {@@ -294,10 +295,7 @@ ov::npuw::DecomposeDynamicQuantize::DecomposeDynamicQuantize() {LOG_BLOCK();// dequantize k and v caches in different layouts- constexpr size_t k_embedding_index = 3;- constexpr size_t v_embedding_index = 2;-- auto reduction_axis = isKey(dq_ptr->get_friendly_name()) ? k_embedding_index : v_embedding_index;+ const auto reduction_axis = get_kv_embedding_index(isKey(dq_ptr->get_friendly_name()), v_tensors_transposed);//auto cst_0 =@@ -399,7 +397,8 @@ ov::npuw::DecomposeDynamicQuantize::DecomposeDynamicQuantize() {// inject DynamicQuantize/Dynamic dequantize ops on kv-cache passes before matmulsvoid ov::npuw::run_kv_cache_dynamic_quantization_passes(const std::shared_ptr<ov::Model>& model,- const KVCacheCompressionParams& params) {+ const KVCacheCompressionParams& params,+ bool v_tensors_transposed) {// Validate SDPA patterns and extract key nodesauto pattern_nodes_list = ov::npuw::util::find_all_sdpa_pattern_nodes(model);@@ -409,13 +408,11 @@ void ov::npuw::run_kv_cache_dynamic_quantization_passes(const std::shared_ptr<ov<< ". Will skip past-cache dequantization rewiring and keep present-cache quantization only.");}- // in per token quantization lets use 1 scale/zp per token, effectively means shape should be clear from embeddings- auto clear_embedding_index = [](auto shape_node, bool k_tensor) {+ auto clear_embedding_index = [v_tensors_transposed](auto shape_node, bool k_tensor) {constexpr int64_t k_embedding_index = 3;- constexpr int64_t v_embedding_index = 2;auto kv_shape = shape_node->get_output_partial_shape(0);- auto embedding_index = k_tensor ? k_embedding_index : v_embedding_index;+ auto embedding_index = k_tensor ? k_embedding_index : (v_tensors_transposed ? 2 : 3);std::vector<ov::Dimension> new_dims;for (int64_t i = 0; i < kv_shape.rank().get_length(); ++i) {@@ -635,8 +632,8 @@ void ov::npuw::run_kv_cache_dynamic_quantization_passes(const std::shared_ptr<ov// TODO: for now internal op DynamicQuantize not easily gets converted into IE so run decompose hereov::pass::Manager manager("insert_dq_internal_ops");- manager.register_pass<ov::npuw::DecomposeDynamicQuantize2>(); // asymmetric u8- manager.register_pass<ov::npuw::DecomposeDynamicQuantize>(); // symmetric i8/i4+ manager.register_pass<ov::npuw::DecomposeDynamicQuantize2>(v_tensors_transposed); // asymmetric u8+ manager.register_pass<ov::npuw::DecomposeDynamicQuantize>(v_tensors_transposed); // symmetric i8/i4manager.run_passes(model);model->validate_nodes_and_infer_types();diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_cache_compressed.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_cache_compressed.hppindex 5bb4611c7b6..2ddeba384b2 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_cache_compressed.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_cache_compressed.hpp@@ -34,7 +34,8 @@ struct KVCacheCompressionParams {// to be identifiable for later kv_cache_copy mechanics.void run_kv_cache_dynamic_quantization_passes(const std::shared_ptr<ov::Model>& model,- const KVCacheCompressionParams& params);+ const KVCacheCompressionParams& params,+ bool v_tensors_transposed = false);/// Decomposition passes for ov::op::internal::DynamicQuantize.@@ -42,21 +43,21 @@ void run_kv_cache_dynamic_quantization_passes(const std::shared_ptr<ov::Model>&class DecomposeDynamicQuantize : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::DecomposeDynamicQuantize");- DecomposeDynamicQuantize();+ explicit DecomposeDynamicQuantize(bool v_tensors_transposed = false);};/// V2: ONNX DynamicQuantizeLinear style, u8 [0, 255]class DecomposeDynamicQuantize2 : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::DecomposeDynamicQuantize2");- DecomposeDynamicQuantize2();+ explicit DecomposeDynamicQuantize2(bool v_tensors_transposed = false);};/// V3: compiler pattern style, i8 [-128, 127]class DecomposeDynamicQuantize3 : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::DecomposeDynamicQuantize3");- DecomposeDynamicQuantize3();+ explicit DecomposeDynamicQuantize3(bool v_tensors_transposed = false);};// NOLINTNEXTLINE(readability/namespace)diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cppindex 9ac8da0e646..3a937803d82 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp@@ -1092,6 +1092,67 @@ std::optional<int> ov::npuw::util::isPresentKeyValuesValue(const std::string& streturn std::nullopt;}+bool ov::npuw::util::isKVCacheName(const std::string& str) {+ return isPastKeyValuesKey(str).has_value() || isPastKeyValuesValue(str).has_value() ||+ isPresentKeyValuesKey(str).has_value() || isPresentKeyValuesValue(str).has_value() ||+ str.find("/" + std::string(constants::past_key_values) + "/") != std::string::npos ||+ str.find("/" + std::string(constants::present) + "/") != std::string::npos;+}++std::string ov::npuw::util::present_to_past_key_values_name(const std::string& output_name) {+ const std::string present_prefix = constants::present;+ const std::string past_prefix = constants::past_key_values;++ if (output_name.rfind(present_prefix, 0) == 0) {+ return past_prefix + output_name.substr(present_prefix.size());+ }++ auto mapped_name = output_name;+ const auto pos = mapped_name.find(present_prefix);+ if (pos != std::string::npos) {+ mapped_name.replace(pos, present_prefix.size(), past_prefix);+ }+ return mapped_name;+}++std::string ov::npuw::util::past_key_values_to_present_name(const std::string& input_name) {+ const std::string present_prefix = constants::present;+ const std::string past_prefix = constants::past_key_values;++ if (input_name.rfind(past_prefix, 0) == 0) {+ return present_prefix + input_name.substr(past_prefix.size());+ }++ auto mapped_name = input_name;+ const auto pos = mapped_name.find(past_prefix);+ if (pos != std::string::npos) {+ mapped_name.replace(pos, past_prefix.size(), present_prefix);+ }+ return mapped_name;+}++std::optional<std::string> ov::npuw::util::resolveKVInputName(+ const std::string& output_name,+ const std::function<bool(const std::string&)>& has_input_name) {+ auto input_name = present_to_past_key_values_name(output_name);+ if (has_input_name(input_name)) {+ return input_name;+ }++ const auto marker = std::string(constants::past_key_values);+ const auto marker_pos = input_name.find(marker);+ if (marker_pos == std::string::npos) {+ return std::nullopt;+ }++ auto canonical_name = input_name.substr(marker_pos);+ if (has_input_name(canonical_name)) {+ return canonical_name;+ }++ return std::nullopt;+}+namespace {std::vector<ov::npuw::util::SDPAPatternNodes> find_sdpa_pattern_nodes_internal(const std::shared_ptr<ov::Model>& model,diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.hpp b/src/plugins/intel_npu/src/plugin/npuw/util.hppindex 3647e4d6c92..f24d6bc4f92 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.hpp@@ -357,6 +357,17 @@ inline std::optional<int> isPastKeyValuesValue(const std::string& str) {std::optional<int> isPresentKeyValuesKey(const std::string& str);std::optional<int> isPresentKeyValuesValue(const std::string& str);+bool isKVCacheName(const std::string& str);++namespace constants {+inline constexpr const char* past_key_values = "past_key_values";+inline constexpr const char* present = "present";+} // namespace constants++std::string present_to_past_key_values_name(const std::string& output_name);+std::string past_key_values_to_present_name(const std::string& input_name);+std::optional<std::string> resolveKVInputName(const std::string& output_name,+ const std::function<bool(const std::string&)>& has_input_name);// Matches any past key param: contiguous (past_key_values.N.key) or block-split (key_block_M).bool isPastKeyParam(const std::string& str);diff --git a/src/plugins/intel_npu/tests/unit/npuw/batched_element_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/batched_element_test.cppindex 833d7844dfc..003be99cfc1 100644--- a/src/plugins/intel_npu/tests/unit/npuw/batched_element_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/batched_element_test.cpp@@ -695,8 +695,9 @@ TEST(NPUWBatchedElementRoundTrip, ExportImportRebuildsTheWrapAndStacks) {std::filesystem::create_directories(tmp);const auto xml = tmp / "model.xml";const auto bin = tmp / "model.bin";- ov::serialize(build_llm_test_model(), xml.string(), bin.string());- auto model = core.read_model(xml.string());+ auto model = build_llm_test_model();+ ov::serialize(model, xml.string(), bin.string());+ model = core.read_model(xml.string(), bin.string());// The online partitioner's repeated-block detection does not cope with the// synthetic model, so the sub-models are compiled whole on CPU.const ov::AnyMap props = {{"NPU_USE_NPUW", "YES"},diff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_continued_prefill_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_continued_prefill_test.cppindex db7cb20b7fe..f65da7cd190 100644--- a/src/plugins/intel_npu/tests/unit/npuw/llm_continued_prefill_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_continued_prefill_test.cpp@@ -353,13 +353,15 @@ protected:uint32_t generate_seq_dim(const std::string& past_name) {const auto& desc = LLMContinuedPrefillTestAccess::desc(*m_request);- const bool is_value = ov::npuw::util::isPastValueParam(past_name);+ const bool is_value = ov::npuw::util::isPastValueParam(past_name) ||+ ov::npuw::util::isDQScaleOrZPValue(past_name);return (is_value && desc.v_tensors_transposed_gen) ? 3u : desc.dim;}uint32_t prefill_seq_dim(const std::string& past_name) {const auto& desc = LLMContinuedPrefillTestAccess::desc(*m_request);- const bool is_value = ov::npuw::util::isPastValueParam(past_name);+ const bool is_value = ov::npuw::util::isPastValueParam(past_name) ||+ ov::npuw::util::isDQScaleOrZPValue(past_name);return (is_value && desc.v_tensors_transposed_pre) ? 3u : desc.dim;}@@ -519,6 +521,52 @@ TEST_F(LLMContinuedPrefillTest, InjectedApplyFailureRecoversAfterReset) {EXPECT_EQ(stored_tokens(), 81);}+class LLMQuantizedContinuedPrefillTest : public LLMContinuedPrefillTest {+protected:+ void SetUp() override {+ init({{ov::hint::kv_cache_precision.name(), ov::element::i8}});+ }+};++TEST_F(LLMQuantizedContinuedPrefillTest, QuantizedKvCacheSupportsContinuousPrefillFlow) {+ auto& req = request();+ bool saw_quantized_aux_tensor = false;+ for (const auto& name : LLMContinuedPrefillTestAccess::past_names(req)) {+ saw_quantized_aux_tensor = saw_quantized_aux_tensor || ov::npuw::util::isDQScaleOrZPValue(name);+ }+ ASSERT_TRUE(saw_quantized_aux_tensor) << "The quantized fixture must expose scale or zero-point past tensors";++ run_full_prefill(72);+ EXPECT_EQ(stored_tokens(), 72);+ run_generate_step(72);+ EXPECT_EQ(stored_tokens(), 73);++ constexpr uint32_t kKeep = 64u;+ std::unordered_map<std::string, std::vector<uint8_t>> expected_kv_bytes;+ uint8_t seed = 23u;+ for (const auto& name : LLMContinuedPrefillTestAccess::past_names(req)) {+ auto src = LLMContinuedPrefillTestAccess::generate_past(req, name);+ auto src_slice = ov::npuw::util::make_tensor_slice(src, generate_seq_dim(name), 0u, kKeep);+ fill_tensor_pattern(src_slice, seed);+ expected_kv_bytes.emplace(name, materialize_bytes(src_slice));+ seed = static_cast<uint8_t>(seed + 41u);+ }++ propose(73);+ EXPECT_EQ(stored_tokens(), kKeep);+ run_delta_prefill(kKeep, 40);+ EXPECT_EQ(stored_tokens(), 104);++ for (const auto& name : LLMContinuedPrefillTestAccess::past_names(req)) {+ auto dst = LLMContinuedPrefillTestAccess::prefill_past(req, name);+ auto dst_slice = ov::npuw::util::make_tensor_slice(dst, prefill_seq_dim(name), 0u, kKeep);+ EXPECT_EQ(materialize_bytes(dst_slice), expected_kv_bytes.at(name)) << name;+ }++ run_generate_step(104);+ EXPECT_EQ(stored_tokens(), 105);+}+// Block-mode variant of the fixture: the same synthetic model compiled with the// pyramid attention hint so SplitKVCacheIntoBlocks applies, giving the block// strategy a real block pool under the fake factory. Every sub-request comesdiff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cppindex 1e17dbf0828..6a1c8bdef10 100644--- a/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_infer_request_variant_switch_test.cpp@@ -48,7 +48,10 @@ struct LLMVariantSwitchTestAccess {static uint32_t kv_dim_for_name(const ov::npuw::LLMInferRequest& req, const std::string& name) {const auto& desc = req.m_npuw_llm_compiled_model->m_kvcache_desc;- return (ov::npuw::util::isPastValueParam(name) && desc.v_tensors_transposed_gen) ? 3u : desc.dim;+ // Mirror copy_kvcache()/on_generate_variant_switch(): classify via the present name so+ // quantized aux inputs (e.g. DynamicQuantize/0/past_key_values/value/scale) resolve too.+ const auto present = ov::npuw::util::past_key_values_to_present_name(name);+ return (present.find("value") != std::string::npos && desc.v_tensors_transposed_gen) ? 3u : desc.dim;}static void select_smallest_generate_variant(ov::npuw::LLMInferRequest& req) {@@ -308,42 +311,60 @@ protected:}std::shared_ptr<ov::IPlugin> m_plugin;-};-TEST_F(LLMInferRequestVariantSwitchTest, ContinuousKvSwitchMigratesStoredTokensToLargerVariant) {- VariantSwitchFactory factory;- auto compiled = create_compiled_model({}, factory);- ASSERT_NE(compiled, nullptr);- ASSERT_EQ(LLMVariantSwitchTestAccess::generate_variant_count(compiled), 2u);-- ov::npuw::LLMInferRequest req(compiled);- LLMVariantSwitchTestAccess::select_smallest_generate_variant(req);+ // Fills stored KV of the smallest variant, switches to the next variant, and verifies the+ // migrated bytes match. When expect_aux is set, at least one quantized aux (scale/zp) past+ // input must participate, so the check exercises the aux name mapping too.+ void check_continuous_switch_migration(const ov::AnyMap& extra_props, bool expect_aux) {+ VariantSwitchFactory factory;+ auto compiled = create_compiled_model(extra_props, factory);+ ASSERT_NE(compiled, nullptr);+ ASSERT_EQ(LLMVariantSwitchTestAccess::generate_variant_count(compiled), 2u);++ ov::npuw::LLMInferRequest req(compiled);+ LLMVariantSwitchTestAccess::select_smallest_generate_variant(req);++ const uint32_t stored_tokens = LLMVariantSwitchTestAccess::current_variant_capacity(req);+ LLMVariantSwitchTestAccess::set_num_stored_tokens(compiled, stored_tokens);++ bool saw_aux = false;+ std::unordered_map<std::string, std::vector<uint8_t>> expected_kv_bytes;+ uint8_t seed = 17u;+ for (const auto& name : LLMVariantSwitchTestAccess::kvcache_past_names(req)) {+ saw_aux = saw_aux || name.find("scale") != std::string::npos || name.find("zp") != std::string::npos;+ auto src = LLMVariantSwitchTestAccess::kvcache_request(req)->get_tensor(+ LLMVariantSwitchTestAccess::kvcache_in_ports(req).at(name));+ auto src_slice = ov::npuw::util::make_tensor_slice(+ src, LLMVariantSwitchTestAccess::kv_dim_for_name(req, name), 0u, stored_tokens);+ fill_tensor_pattern(src_slice, seed);+ expected_kv_bytes.emplace(name, materialize_bytes(src_slice));+ seed = static_cast<uint8_t>(seed + 37u);+ }+ if (expect_aux) {+ ASSERT_TRUE(saw_aux) << "Quantized model must expose scale/zero-point past inputs";+ }- const uint32_t stored_tokens = LLMVariantSwitchTestAccess::current_variant_capacity(req);- LLMVariantSwitchTestAccess::set_num_stored_tokens(compiled, stored_tokens);+ ASSERT_TRUE(LLMVariantSwitchTestAccess::try_switch_to_larger_variant(req));+ EXPECT_EQ(LLMVariantSwitchTestAccess::current_variant_index(req), 1u);- std::unordered_map<std::string, std::vector<uint8_t>> expected_kv_bytes;- uint8_t seed = 17u;- for (const auto& name : LLMVariantSwitchTestAccess::kvcache_past_names(req)) {- auto src = LLMVariantSwitchTestAccess::kvcache_request(req)->get_tensor(- LLMVariantSwitchTestAccess::kvcache_in_ports(req).at(name));- auto src_slice = ov::npuw::util::make_tensor_slice(- src, LLMVariantSwitchTestAccess::kv_dim_for_name(req, name), 0u, stored_tokens);- fill_tensor_pattern(src_slice, seed);- expected_kv_bytes.emplace(name, materialize_bytes(src_slice));- seed = static_cast<uint8_t>(seed + 37u);+ for (const auto& name : LLMVariantSwitchTestAccess::kvcache_past_names(req)) {+ auto dst = LLMVariantSwitchTestAccess::kvcache_request(req)->get_tensor(+ LLMVariantSwitchTestAccess::kvcache_in_ports(req).at(name));+ auto dst_slice = ov::npuw::util::make_tensor_slice(+ dst, LLMVariantSwitchTestAccess::kv_dim_for_name(req, name), 0u, stored_tokens);+ EXPECT_EQ(materialize_bytes(dst_slice), expected_kv_bytes.at(name)) << name;+ }}+};- ASSERT_TRUE(LLMVariantSwitchTestAccess::try_switch_to_larger_variant(req));- EXPECT_EQ(LLMVariantSwitchTestAccess::current_variant_index(req), 1u);+TEST_F(LLMInferRequestVariantSwitchTest, ContinuousKvSwitchMigratesStoredTokensToLargerVariant) {+ check_continuous_switch_migration({}, /*expect_aux=*/false);+}- for (const auto& name : LLMVariantSwitchTestAccess::kvcache_past_names(req)) {- auto dst = LLMVariantSwitchTestAccess::kvcache_request(req)->get_tensor(- LLMVariantSwitchTestAccess::kvcache_in_ports(req).at(name));- auto dst_slice = ov::npuw::util::make_tensor_slice(- dst, LLMVariantSwitchTestAccess::kv_dim_for_name(req, name), 0u, stored_tokens);- EXPECT_EQ(materialize_bytes(dst_slice), expected_kv_bytes.at(name)) << name;- }+// Same migration path, but for an i8-quantized KV cache: on_generate_variant_switch() must also+// migrate the quantized aux (scale/zero-point) past tensors to the larger variant.+TEST_F(LLMInferRequestVariantSwitchTest, ContinuousKvSwitchMigratesQuantizedAuxTensors) {+ check_continuous_switch_migration({{ov::hint::kv_cache_precision.name(), ov::element::i8}}, /*expect_aux=*/true);}TEST_F(LLMInferRequestVariantSwitchTest, BlockKvVariantsExposeCompatibleBindingsAcrossSwitchBoundary) {@@ -393,6 +414,27 @@ TEST_F(LLMInferRequestVariantSwitchTest, BlockKvVariantsExposeCompatibleBindingsEXPECT_EQ(small_value_block0, large_value_block0);}+// Block-based KV cache relies on SplitKVCacheIntoBlocks, whose pattern no longer matches once the+// KV cache is precision-converted to i8. The two features are mutually exclusive, so enabling both+// must be rejected at compile time (guards against silently producing an unblocked / unquantized+// model). This is why the block strategy never has to handle quantized aux tensors.+TEST_F(LLMInferRequestVariantSwitchTest, BlockKvCacheRejectsQuantizedKvCache) {+ VariantSwitchFactory factory;+ try {+ create_compiled_model({{"NPUW_LLM_PREFILL_HINT", "DYNAMIC"},+ {"NPUW_LLM_PREFILL_CHUNK_SIZE", "512"},+ {"NPUW_LLM_PREFILL_ATTENTION_HINT", "PYRAMID"},+ {"NPUW_LLM_GENERATE_ATTENTION_HINT", "PYRAMID"},+ {"NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE", "YES"},+ {ov::hint::kv_cache_precision.name(), ov::element::i8}},+ factory);+ FAIL() << "Expected block-based KV cache with integer KV-cache precision to be rejected";+ } catch (const ov::Exception& ex) {+ EXPECT_NE(std::string(ex.what()).find("cannot be combined with integer KV-cache precision"), std::string::npos)+ << ex.what();+ }+}+// The deserializer restores m_kvcache_sizes and the generate-variant count as two independent blob// fields. A corrupted blob can therefore declare a size table that disagrees with the variant count,// which downstream turns into an out-of-bounds read. LLMCompiledModel::deserialize() now rejects thediff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hppindex d7d809b11ea..34d4b8547e1 100644--- a/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_test_helpers.hpp@@ -5,12 +5,14 @@#pragma once#include <algorithm>+#include <cstring>#include <memory>#include <string>#include <string_view>#include <vector>#include "compiled_model.hpp"+#include "executor.hpp"#include "llm_compiled_model.hpp"#include "model_builder.hpp"#include "openvino/op/add.hpp"@@ -20,7 +22,9 @@#include "openvino/op/result.hpp"#include "openvino/op/scaled_dot_product_attention.hpp"#include "openvino/pass/stateful_to_stateless.hpp"+#include "openvino/runtime/iasync_infer_request.hpp"#include "openvino/runtime/iplugin.hpp"+#include "openvino/runtime/isync_infer_request.hpp"#include "serialization.hpp"#include "weights_bank.hpp"@@ -355,30 +359,60 @@ public:}};+class MockSubCompiledModel;++// Minimal working sub-request used by MockSubCompiledModel. Allocates a backing+// tensor for every input/output port so a real LLMInferRequest can be built on+// top of models compiled through RecordingFactory and exercise runtime paths+// (e.g. copy_kvcache) without a real device.+class MockSubInferRequest final : public ov::ISyncInferRequest {+public:+ explicit MockSubInferRequest(std::shared_ptr<const MockSubCompiledModel> compiled_model);++ void infer() override;+ ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override {+ return ov::ISyncInferRequest::get_tensor(port);+ }+ void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override {+ ov::ISyncInferRequest::set_tensor(port, tensor);+ }+ void check_tensors() const override {}+ std::vector<ov::SoPtr<ov::IVariableState>> query_state() const override {+ return {};+ }+ std::vector<ov::ProfilingInfo> get_profiling_info() const override {+ return {};+ }+};+class MockSubCompiledModel : public ov::npuw::ICompiledModel_v0 {public:MockSubCompiledModel(const std::shared_ptr<ov::Model>& model,const std::shared_ptr<const ov::IPlugin>& plugin,const ov::AnyMap&)- : ov::npuw::ICompiledModel_v0(model, plugin) {}+ : ov::npuw::ICompiledModel_v0(model, plugin),+ m_model(model) {}void export_model(std::ostream&) const override {}std::shared_ptr<const ov::Model> get_runtime_model() const override {- return {};+ return m_model;}void set_property(const ov::AnyMap&) override {}ov::Any get_property(const std::string&) const override {return {};}std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override {- return {};+ auto self = std::static_pointer_cast<const MockSubCompiledModel>(shared_from_this());+ return std::make_shared<MockSubInferRequest>(std::move(self));}std::shared_ptr<ov::npuw::IBaseInferRequest> create_base_infer_request() const override {return {};}std::shared_ptr<ov::IAsyncInferRequest> wrap_async_infer_request(std::shared_ptr<ov::npuw::IBaseInferRequest>) const override {- return {};+ return std::make_shared<ov::IAsyncInferRequest>(create_sync_infer_request(),+ ::intel_npu::make_executor("mock_sub_task", 1),+ ::intel_npu::make_executor("mock_sub_callback", 1));}std::string submodel_device(std::size_t) const override {return "CPU";@@ -393,8 +427,31 @@ public:void finalize_weights_bank() override {}void reconstruct_closure() override {}void serialize(std::ostream&, const ov::npuw::s11n::CompiledContext&) const override {}++private:+ std::shared_ptr<ov::Model> m_model;};+inline MockSubInferRequest::MockSubInferRequest(std::shared_ptr<const MockSubCompiledModel> compiled_model)+ : ov::ISyncInferRequest(std::move(compiled_model)) {+ for (const auto& input : get_compiled_model()->inputs()) {+ ov::ISyncInferRequest::set_tensor(input,+ ov::get_tensor_impl(ov::Tensor(input.get_element_type(), input.get_shape())));+ }+ for (const auto& output : get_compiled_model()->outputs()) {+ ov::ISyncInferRequest::set_tensor(+ output,+ ov::get_tensor_impl(ov::Tensor(output.get_element_type(), output.get_shape())));+ }+}++inline void MockSubInferRequest::infer() {+ for (const auto& output : get_compiled_model()->outputs()) {+ auto tensor = ov::ISyncInferRequest::get_tensor(output);+ std::memset(tensor->data(), 0, tensor->get_byte_size());+ }+}+struct CompileCall {std::string friendly_name;ov::AnyMap props;diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/convert_kvcache_to_precision_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/convert_kvcache_to_precision_test.cppindex fb36080fe44..cf6f7ebc8b6 100644--- a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/convert_kvcache_to_precision_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/convert_kvcache_to_precision_test.cpp@@ -6,11 +6,20 @@#include <gtest/gtest.h>+#include <algorithm>#include <map>+#include <cstring>+#include <regex>+#include <optional>#include <sstream>#include <string>+#include <unordered_set>+#include <vector>#include "../util.hpp"+#include "infer_request_utils.hpp"+#include "llm_test_helpers.hpp"+#include "llm_infer_request.hpp"#include "llm_pass_test_fixture.hpp"#include "openvino/pass/stateful_to_stateless.hpp"#include "openvino/runtime/properties.hpp"@@ -37,6 +46,181 @@ bool any_name_contains(const ov::Output<const ov::Node>& port, std::string_viewreturn false;}+std::optional<std::string> resolve_kv_input_name_for_test(const std::string& output_name,+ const std::unordered_set<std::string>& input_names) {+ auto input_name = ov::npuw::util::present_to_past_key_values_name(output_name);+ if (input_names.find(input_name) != input_names.end()) {+ return input_name;+ }++ const auto marker = std::string(ov::npuw::util::constants::past_key_values);+ const auto marker_pos = input_name.find(marker);+ if (marker_pos == std::string::npos) {+ return std::nullopt;+ }++ auto canonical_name = input_name.substr(marker_pos);+ if (input_names.find(canonical_name) != input_names.end()) {+ return canonical_name;+ }++ return std::nullopt;+}++class TestableLLMCompiledModel : public ov::npuw::LLMCompiledModel {+public:+ using ov::npuw::LLMCompiledModel::LLMCompiledModel;++ ov::npuw::LLMCompiledModel::KVCacheDesc& kvcache_desc() {+ return m_kvcache_desc;+ }++ const ov::npuw::LLMCompiledModel::KVCacheDesc& kvcache_desc() const {+ return m_kvcache_desc;+ }++ bool use_chunk_prefill() const {+ return m_use_chunk_prefill;+ }++ uint64_t prefill_chunk_size() const {+ return m_prefill_chunk_size;+ }+};++class TestableLLMInferRequest final : public ov::npuw::LLMInferRequest {+public:+ explicit TestableLLMInferRequest(const std::shared_ptr<TestableLLMCompiledModel>& compiled_model)+ : ov::npuw::LLMInferRequest(compiled_model), m_testable_model(compiled_model) {}++ using ov::npuw::LLMInferRequest::copy_kvcache;+ using ov::npuw::LLMInferRequest::update_kvcache_for;+ using ov::npuw::LLMInferRequest::clear_chunk_prefill_kv_cache;++ const std::vector<std::string>& kvcache_past_names() const {+ return m_kvcache_past_names;+ }++ void prepare_non_chunked_copy() {+ auto& desc = m_testable_model->kvcache_desc();+ ASSERT_FALSE(m_testable_model->use_chunk_prefill());+ ASSERT_GT(desc.max_prompt_size, 0u);+ desc.num_stored_tokens = desc.max_prompt_size;+ }++ std::pair<ov::SoPtr<ov::ITensor>, ov::SoPtr<ov::ITensor>> make_non_chunked_copy_views(+ const std::string& output_name,+ const ov::SoPtr<ov::ITensor>& src_tensor,+ const ov::SoPtr<ov::ITensor>& dst_tensor) const {+ const auto& desc = m_testable_model->kvcache_desc();+ const auto is_value_tensor = output_name.find("value") != std::string::npos;+ const auto kv_dim = [&](bool v_transposed) {+ return (is_value_tensor && v_transposed) ? 3u : desc.dim;+ };++ const auto pre_kv_dim = kv_dim(desc.v_tensors_transposed_pre);+ const auto gen_kv_dim = kv_dim(desc.v_tensors_transposed_gen);++ auto src_view = ov::npuw::util::make_tensor_slice(src_tensor,+ pre_kv_dim,+ desc.max_prompt_size - desc.num_stored_tokens,+ desc.max_prompt_size);+ auto dst_view = ov::npuw::util::make_tensor_slice(dst_tensor, gen_kv_dim, 0u, desc.num_stored_tokens);+ return {src_view, dst_view};+ }++ void prepare_chunked_copy(uint32_t num_stored_tokens, uint64_t tokens_in_present_chunk) {+ auto& desc = m_testable_model->kvcache_desc();+ ASSERT_TRUE(m_testable_model->use_chunk_prefill());+ ASSERT_GT(m_testable_model->prefill_chunk_size(), 0u);+ ASSERT_GT(desc.max_prompt_size, 0u);+ desc.num_stored_tokens = num_stored_tokens;+ m_tokens_in_present_chunk = tokens_in_present_chunk;+ }++ uint64_t prefill_chunk_size() const {+ return m_testable_model->prefill_chunk_size();+ }++ bool past_kv_bound() const {+ return m_past_kv_bound;+ }++ // The unit-test harness has no NPU core, so the temp buffer allocated by the chunked+ // copy_kvcache() backup path (m_past_kv_bound) must live on CPU.+ void use_cpu_pre_alloc() {+ m_pre_alloc_device = "CPU";+ }++ // Returns {pre_kv_dim, gen_kv_dim} used by copy_kvcache() for the given output name.+ std::pair<uint32_t, uint32_t> kv_dims(const std::string& output_name) const {+ const auto& desc = m_testable_model->kvcache_desc();+ const auto is_value_tensor = output_name.find("value") != std::string::npos;+ const auto is_quant_aux_tensor = output_name.find("/scale") != std::string::npos ||+ output_name.find("/zp") != std::string::npos;+ if (is_value_tensor && is_quant_aux_tensor) {+ // Mirror the runtime shape-based detection: embedding is collapsed to 1 by DQ.+ const auto input_name =+ std::regex_replace(output_name, std::regex("present"), "past_key_values");+ auto detect = [&](bool v_trans) -> uint32_t {+ if (m_kvcache_in_ports.count(input_name)) {+ const auto& sh =+ m_kvcache_request->get_tensor(m_kvcache_in_ports.at(input_name))->get_shape();+ if (sh.size() == 4u && sh[3] == 1u && sh[2] > 1u) return 2u;+ if (sh.size() == 4u && sh[2] == 1u && sh[3] > 1u) return 3u;+ }+ return v_trans ? 3u : desc.dim;+ };+ return {detect(desc.v_tensors_transposed_pre), detect(desc.v_tensors_transposed_gen)};+ }+ const auto kv_dim = [&](bool v_transposed) {+ return (is_value_tensor && v_transposed) ? 3u : desc.dim;+ };+ return {kv_dim(desc.v_tensors_transposed_pre), kv_dim(desc.v_tensors_transposed_gen)};+ }++ const ov::npuw::LLMInferBaseRequest::PortsMap& prefill_in_ports() const {+ return m_prefill_in_ports;+ }++ const ov::npuw::LLMInferBaseRequest::PortsMap& prefill_out_ports() const {+ return m_prefill_out_ports;+ }++ const ov::npuw::LLMInferBaseRequest::PortsMap& kvcache_in_ports() const {+ return m_kvcache_in_ports;+ }++ const ov::npuw::LLMInferBaseRequest::PortsMap& kvcache_out_ports() const {+ return m_kvcache_out_ports;+ }++ std::shared_ptr<ov::IAsyncInferRequest> prefill_request() const {+ return m_prefill_request;+ }++ std::shared_ptr<ov::IAsyncInferRequest> kvcache_request() const {+ return m_kvcache_request;+ }++private:+ std::shared_ptr<TestableLLMCompiledModel> m_testable_model;+};++bool is_kv_name(std::string_view name) {+ return ov::npuw::util::isKVCacheName(std::string(name));+}++ov::Tensor slice_to_host(const ov::SoPtr<ov::ITensor>& view) {+ ov::Tensor host(view->get_element_type(), view->get_shape());+ view->copy_to(ov::get_tensor_impl(host)._ptr);+ return host;+}++bool is_aux_kv_name(const std::string& name) {+ return name.find("scale") != std::string::npos || name.find("zp") != std::string::npos;+}+const std::map<ov::element::Type, std::map<std::string, ov::element::Type>>& precision_key_input_matrix() {static const std::map<ov::element::Type, std::map<std::string, ov::element::Type>> matrix = {{ov::element::u8, {{"value", ov::element::u8}, {"scale", ov::element::f32}, {"zero_point", ov::element::u8}}},@@ -76,15 +260,21 @@ ov::AnyMap make_kv_precision_props(const ov::element::Type kv_type) {void expect_kv_cache_input_types(const std::shared_ptr<ov::Model>& model,const ov::element::Type kv_type,- const bool check_quant_aux_ports = true) {- // Key cache: asymmetric quantization -> value tensor + scale (f32) + zero_point.+ const bool ignore_quant_aux_ports = false) {+ // Key cache: asymmetric quantization -> value tensor + scale (f32) + zero_point (same as quant type).// Value cache: symmetric quantization -> value tensor (i4) + scale (f32), no zero_point.const bool is_quantized = is_quantized_kv_type(kv_type);- constexpr std::string_view past_key_scale_name = "/past_key_values/key/scale";- constexpr std::string_view past_key_zp_name = "/past_key_values/key/zp";- constexpr std::string_view past_value_scale_name = "/past_key_values/value/scale";- constexpr std::string_view past_value_zp_name = "/past_key_values/value/zp";+ const std::string past_key_scale_name =+ std::string("/") + ov::npuw::util::constants::past_key_values + "/key/scale";+ const std::string past_key_zp_name =+ std::string("/") + ov::npuw::util::constants::past_key_values + "/key/zp";+ const std::string past_value_scale_name =+ std::string("/") + ov::npuw::util::constants::past_key_values + "/value/scale";+ const std::string past_value_zp_name =+ std::string("/") + ov::npuw::util::constants::past_key_values + "/value/zp";+ const std::string past_key_label = std::string(ov::npuw::util::constants::past_key_values) + ".<N>.key";+ const std::string past_value_label = std::string(ov::npuw::util::constants::past_key_values) + ".<N>.value";bool found_key_cache_input = false;bool found_value_cache_input = false;@@ -94,6 +284,11 @@ void expect_kv_cache_input_types(const std::shared_ptr<ov::Model>& model,bool found_value_zp_input = false;for (const auto& input : model->inputs()) {+ if (ignore_quant_aux_ports &&+ (any_name_contains(input, "/scale") || any_name_contains(input, "/zp"))) {+ continue;+ }+// Check if any name on this input matches past_key_values patternbool is_past_key = false;bool is_past_value = false;@@ -110,48 +305,52 @@ void expect_kv_cache_input_types(const std::shared_ptr<ov::Model>& model,found_key_cache_input = true;const auto expected = is_quantized ? precision_key_input_matrix().at(kv_type).at("value") : kv_type;EXPECT_EQ(input.get_element_type(), expected)- << "past_key_values.<N>.key input must have type " << expected;+ << past_key_label << " input must have type " << expected;}if (is_past_value) {found_value_cache_input = true;const auto expected = is_quantized ? precision_value_matrix().at(kv_type).at("value") : kv_type;EXPECT_EQ(input.get_element_type(), expected)- << "past_key_values.<N>.value input must have type " << expected;+ << past_value_label << " input must have type " << expected;}- if (check_quant_aux_ports && any_name_contains(input, past_key_scale_name)) {+ if (!ignore_quant_aux_ports && any_name_contains(input, past_key_scale_name)) {found_key_scale_input = true;const auto expected = precision_key_input_matrix().at(kv_type).at("scale");EXPECT_EQ(input.get_element_type(), expected) << "past_key scale input must have type " << expected;}- if (check_quant_aux_ports && any_name_contains(input, past_key_zp_name)) {+ if (!ignore_quant_aux_ports && any_name_contains(input, past_key_zp_name)) {found_key_zp_input = true;const auto expected = precision_key_input_matrix().at(kv_type).at("zero_point");EXPECT_EQ(input.get_element_type(), expected) << "past_key zero-point input must have type " << expected;}- if (check_quant_aux_ports && any_name_contains(input, past_value_scale_name)) {+ if (!ignore_quant_aux_ports && any_name_contains(input, past_value_scale_name)) {found_value_scale_input = true;const auto expected = precision_value_matrix().at(kv_type).at("scale");EXPECT_EQ(input.get_element_type(), expected) << "past_value scale input must have type " << expected;}- if (check_quant_aux_ports && any_name_contains(input, past_value_zp_name)) {+ if (!ignore_quant_aux_ports && any_name_contains(input, past_value_zp_name)) {found_value_zp_input = true;}}- EXPECT_TRUE(found_key_cache_input) << "No past_key_values.<N>.key input found in model";- EXPECT_TRUE(found_value_cache_input) << "No past_key_values.<N>.value input found in model";+ EXPECT_TRUE(found_key_cache_input) << "No " << past_key_label << " input found in model";+ EXPECT_TRUE(found_value_cache_input) << "No " << past_value_label << " input found in model";++ if (ignore_quant_aux_ports) {+ return;+ }- if (is_quantized && check_quant_aux_ports) {+ if (is_quantized) {EXPECT_TRUE(found_key_scale_input) << "Asymmetric quantized KV key-cache must expose scale input";EXPECT_TRUE(found_key_zp_input) << "Asymmetric quantized KV key-cache must expose zero-point input";EXPECT_TRUE(found_value_scale_input) << "Symmetric quantized KV value-cache must expose scale input";EXPECT_FALSE(found_value_zp_input) << "Symmetric quantized KV value-cache must not expose zero-point input";- } else if (!is_quantized && check_quant_aux_ports) {+ } else if (!is_quantized) {EXPECT_FALSE(found_key_scale_input) << "Non-quantized KV-cache must not expose key scale input";EXPECT_FALSE(found_key_zp_input) << "Non-quantized KV-cache must not expose key zero-point input";EXPECT_FALSE(found_value_scale_input) << "Non-quantized KV-cache must not expose value scale input";@@ -161,13 +360,19 @@ void expect_kv_cache_input_types(const std::shared_ptr<ov::Model>& model,void expect_kv_cache_present_output_types(const std::shared_ptr<ov::Model>& model,const ov::element::Type kv_type,- const bool check_quant_aux_ports = true) {+ const bool ignore_quant_aux_ports = false) {const bool is_quantized = is_quantized_kv_type(kv_type);- constexpr std::string_view present_key_scale_name = "/present/key/scale";- constexpr std::string_view present_key_zp_name = "/present/key/zp";- constexpr std::string_view present_value_scale_name = "/present/value/scale";- constexpr std::string_view present_value_zp_name = "/present/value/zp";+ const std::string present_key_scale_name =+ std::string("/") + ov::npuw::util::constants::present + "/key/scale";+ const std::string present_key_zp_name =+ std::string("/") + ov::npuw::util::constants::present + "/key/zp";+ const std::string present_value_scale_name =+ std::string("/") + ov::npuw::util::constants::present + "/value/scale";+ const std::string present_value_zp_name =+ std::string("/") + ov::npuw::util::constants::present + "/value/zp";+ const std::string present_key_label = std::string(ov::npuw::util::constants::present) + ".<N>.key";+ const std::string present_value_label = std::string(ov::npuw::util::constants::present) + ".<N>.value";bool found_present_key = false;bool found_present_value = false;@@ -177,6 +382,11 @@ void expect_kv_cache_present_output_types(const std::shared_ptr<ov::Model>& modebool found_present_value_zp = false;for (const auto& output : model->outputs()) {+ if (ignore_quant_aux_ports &&+ (any_name_contains(output, "/scale") || any_name_contains(output, "/zp"))) {+ continue;+ }+// Check if any name on this output matches present patternbool is_present_key = false;bool is_present_value = false;@@ -192,49 +402,55 @@ void expect_kv_cache_present_output_types(const std::shared_ptr<ov::Model>& modeif (is_present_key) {found_present_key = true;const auto expected = is_quantized ? precision_key_output_matrix().at(kv_type).at("value") : kv_type;- EXPECT_EQ(output.get_element_type(), expected) << "present.<N>.key output must have type " << expected;+ EXPECT_EQ(output.get_element_type(), expected)+ << present_key_label << " output must have type " << expected;}if (is_present_value) {found_present_value = true;const auto expected = is_quantized ? precision_value_matrix().at(kv_type).at("value") : kv_type;- EXPECT_EQ(output.get_element_type(), expected) << "present.<N>.value output must have type " << expected;+ EXPECT_EQ(output.get_element_type(), expected)+ << present_value_label << " output must have type " << expected;}- if (check_quant_aux_ports && any_name_contains(output, present_key_scale_name)) {+ if (!ignore_quant_aux_ports && any_name_contains(output, present_key_scale_name)) {found_present_key_scale = true;const auto expected = precision_key_output_matrix().at(kv_type).at("scale");EXPECT_EQ(output.get_element_type(), expected) << "present key scale output must have type " << expected;}- if (check_quant_aux_ports && any_name_contains(output, present_key_zp_name)) {+ if (!ignore_quant_aux_ports && any_name_contains(output, present_key_zp_name)) {found_present_key_zp = true;const auto expected = precision_key_output_matrix().at(kv_type).at("zero_point");EXPECT_EQ(output.get_element_type(), expected)<< "present key zero-point output must have type " << expected;}- if (check_quant_aux_ports && any_name_contains(output, present_value_scale_name)) {+ if (!ignore_quant_aux_ports && any_name_contains(output, present_value_scale_name)) {found_present_value_scale = true;const auto expected = precision_value_matrix().at(kv_type).at("scale");EXPECT_EQ(output.get_element_type(), expected) << "present value scale output must have type " << expected;}- if (check_quant_aux_ports && any_name_contains(output, present_value_zp_name)) {+ if (!ignore_quant_aux_ports && any_name_contains(output, present_value_zp_name)) {found_present_value_zp = true;}}- EXPECT_TRUE(found_present_key) << "No present.<N>.key output found in model";- EXPECT_TRUE(found_present_value) << "No present.<N>.value output found in model";+ EXPECT_TRUE(found_present_key) << "No " << present_key_label << " output found in model";+ EXPECT_TRUE(found_present_value) << "No " << present_value_label << " output found in model";- if (is_quantized && check_quant_aux_ports) {+ if (ignore_quant_aux_ports) {+ return;+ }++ if (is_quantized) {EXPECT_TRUE(found_present_key_scale) << "Asymmetric quantized KV key-cache must expose present scale output";EXPECT_TRUE(found_present_key_zp) << "Asymmetric quantized KV key-cache must expose present zero-point output";EXPECT_TRUE(found_present_value_scale) << "Symmetric quantized KV value-cache must expose present scale output";EXPECT_FALSE(found_present_value_zp)<< "Symmetric quantized KV value-cache must not expose present zero-point output";- } else if (!is_quantized && check_quant_aux_ports) {+ } else if (!is_quantized) {EXPECT_FALSE(found_present_key_scale) << "Non-quantized KV-cache must not expose present key scale output";EXPECT_FALSE(found_present_key_zp) << "Non-quantized KV-cache must not expose present key zero-point output";EXPECT_FALSE(found_present_value_scale) << "Non-quantized KV-cache must not expose present value scale output";@@ -287,6 +503,40 @@ TEST_P(ConvertKVCacheHintPrecisionTest, GenerateModelPresentOutputsHaveExpectedPexpect_kv_cache_present_output_types(generate.model, kv_type);}+// update_kvcache/copy_kvcache map output names to past-key input names. This must+// also work for quantized aux outputs (scale/zero-point) when graph rewrites add+// prefixes (e.g. DynamicDequantize/.../present...).+TEST_P(ConvertKVCacheHintPrecisionTest, GenerateModelKvOutputsResolveToPastInputsForKvUpdate) {+ const auto kv_type = GetParam();+ RecordingFactory recorder;+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;++ ASSERT_NO_THROW(compiled = create_compiled_model(make_kv_precision_props(kv_type), recorder));+ ASSERT_NE(compiled, nullptr);++ const auto& generate = require_sub_model_containing(recorder, "_kv");++ std::unordered_set<std::string> input_names;+ for (const auto& input : generate.model->inputs()) {+ input_names.insert(input.get_any_name());+ }++ bool checked_any_kv_output = false;+ for (const auto& output : generate.model->outputs()) {+ const auto& output_name = output.get_any_name();+ const bool is_kv_output = ov::npuw::util::isKVCacheName(output_name);+ if (!is_kv_output) {+ continue;+ }++ checked_any_kv_output = true;+ const auto resolved_input = resolve_kv_input_name_for_test(output_name, input_names);+ ASSERT_TRUE(resolved_input.has_value())+ << "No matching past-key input for KV output name used by update flow: " << output_name;+ }+ ASSERT_TRUE(checked_any_kv_output) << "No KV-related outputs found in generate model";+}+// present outputs of the prefill model have the requested precision.TEST_P(ConvertKVCacheHintPrecisionTest, PrefillModelPresentOutputsHaveExpectedPrecision) {const auto kv_type = GetParam();@@ -313,7 +563,7 @@ TEST_P(ConvertKVCacheHintPrecisionTest, WhisperKVCacheModelPastKeyInputsHaveExpeASSERT_TRUE(ov::npuw::util::PrepareWhisperKVCacheModel().run_on_model(model));ASSERT_TRUE(ov::npuw::ConvertKVCacheToPrecision(kv_type).run_on_model(model));- expect_kv_cache_input_types(model, kv_type, false);+ expect_kv_cache_input_types(model, kv_type, true);}TEST_P(ConvertKVCacheHintPrecisionTest, WhisperKVCacheModelPresentOutputsHaveExpectedPrecision) {@@ -324,12 +574,22 @@ TEST_P(ConvertKVCacheHintPrecisionTest, WhisperKVCacheModelPresentOutputsHaveExpASSERT_TRUE(ov::npuw::util::PrepareWhisperKVCacheModel().run_on_model(model));ASSERT_TRUE(ov::npuw::ConvertKVCacheToPrecision(kv_type).run_on_model(model));- expect_kv_cache_present_output_types(model, kv_type, false);+ expect_kv_cache_present_output_types(model, kv_type, true);}// --- Non-parametric tests --------------------------------------------------------------------------class ConvertKVCacheToPrecisionPassTest : public ov::test::npuw::LLMPassTestFixture {};+class ConvertKVCacheToPrecisionPassTest : public ov::test::npuw::LLMPassTestFixture {+protected:+ std::shared_ptr<TestableLLMCompiledModel> create_testable_model(const ov::AnyMap& extra_props,+ RecordingFactory& recorder) const {+ auto props = base_props();+ merge_props(props, extra_props);+ std::unique_ptr<TestableLLMCompiledModel> model(new TestableLLMCompiledModel(+ ov::test::npuw::build_llm_test_model(), m_plugin, props, recorder.make_factory()));+ return std::shared_ptr<TestableLLMCompiledModel>(model.release());+ }+};// NPUW_LLM_OPTIMIZE_FP8: model with two consecutive FakeConvert nodes per K/V path.// optimize_kv_cache_storage detects the FakeConvert destination type and sets KV storage to FP8.@@ -406,4 +666,373 @@ TEST_F(ConvertKVCacheToPrecisionPassTest, NonKVInputsAreNotConverted) {<< "input_ids must NOT be f16 -- ConvertKVCacheToPrecision must not touch it";}+TEST_F(ConvertKVCacheToPrecisionPassTest, CopyKvCacheSimpleSmoke) {+ RecordingFactory recorder;+ auto compiled = create_testable_model(make_kv_precision_props(ov::element::i8), recorder);+ ASSERT_NE(compiled, nullptr);+ ASSERT_GT(compiled->kvcache_desc().max_prompt_size, 0u) << "model kvcache_desc not initialized after construction";+ TestableLLMInferRequest request(compiled);+ request.prepare_non_chunked_copy();+ ASSERT_NO_THROW(request.copy_kvcache());+}++TEST_F(ConvertKVCacheToPrecisionPassTest, CopyKvCacheWithPyramidAttentionUsesPyramidKvNames) {+ RecordingFactory recorder;+ auto props = make_kv_precision_props(ov::element::i8);+ props["NPUW_LLM_PREFILL_ATTENTION_HINT"] = "PYRAMID";+ props["NPUW_LLM_GENERATE_ATTENTION_HINT"] = "PYRAMID";+ auto compiled = create_testable_model(props, recorder);+ ASSERT_NE(compiled, nullptr);++ TestableLLMInferRequest request(compiled);+ request.prepare_non_chunked_copy();++ ASSERT_FALSE(request.kvcache_past_names().empty());+ bool found_key_name = false;+ bool found_value_name = false;+ for (const auto& name : request.kvcache_past_names()) {+ EXPECT_TRUE(is_kv_name(name)) << "Unexpected Pyramid KV-cache input name: " << name;+ EXPECT_NE(name.find("past_key_values"), std::string::npos)+ << "Pyramid KV-cache input is missing the past_key_values marker: " << name;+ found_key_name |= name.find(".key") != std::string::npos;+ found_value_name |= name.find(".value") != std::string::npos;+ }+ EXPECT_TRUE(found_key_name) << "Pyramid KV-cache key input name was not discovered";+ EXPECT_TRUE(found_value_name) << "Pyramid KV-cache value input name was not discovered";++ ASSERT_NO_THROW(request.copy_kvcache());+}++// Regression for kv-cache runtime copy path: execute real copy_kvcache() and verify+// that all KV outputs (including quantized aux tensors) are copied to matching past inputs.+TEST_F(ConvertKVCacheToPrecisionPassTest, CopyKvCacheCopiesQuantizedAuxTensorsByNameMapping) {+ RecordingFactory recorder;+ auto compiled = create_testable_model(make_kv_precision_props(ov::element::i8), recorder);+ ASSERT_NE(compiled, nullptr);+ TestableLLMInferRequest request(compiled);+ request.prepare_non_chunked_copy();++ std::unordered_set<std::string> input_names;+ for (const auto& [name, _] : request.kvcache_in_ports()) {+ input_names.insert(name);+ }+ struct CopyPair {+ std::string output_name;+ std::string input_name;+ };+ std::vector<CopyPair> copied_pairs;++ uint8_t pattern_seed = 7u;+ for (const auto& [output_name, _] : request.kvcache_out_ports()) {+ if (!is_kv_name(output_name)) {+ continue;+ }+ const auto resolved_input = resolve_kv_input_name_for_test(output_name, input_names);+ ASSERT_TRUE(resolved_input.has_value())+ << "No past KV input mapped for output: " << output_name;++ const auto& prefill_out_port = request.prefill_out_ports().at(output_name);+ auto src_tensor = request.prefill_request()->get_tensor(prefill_out_port);+ auto dst_tensor = request.kvcache_request()->get_tensor(request.kvcache_in_ports().at(resolved_input.value()));++ if (src_tensor->get_byte_size() == 0 || dst_tensor->get_byte_size() == 0) {+ continue;+ }++ ov::Tensor src_host(src_tensor->get_element_type(), src_tensor->get_shape());+ ov::Tensor dst_host(dst_tensor->get_element_type(), dst_tensor->get_shape());+ std::memset(src_host.data(), pattern_seed, src_host.get_byte_size());+ std::memset(dst_host.data(), static_cast<int>(pattern_seed + 1), dst_host.get_byte_size());+ ov::get_tensor_impl(src_host)->copy_to(src_tensor._ptr);+ ov::get_tensor_impl(dst_host)->copy_to(dst_tensor._ptr);+ pattern_seed = static_cast<uint8_t>(pattern_seed + 13);+ copied_pairs.push_back({output_name, resolved_input.value()});+ }++ ASSERT_FALSE(copied_pairs.empty()) << "No KV output/input pairs found for copy_kvcache test";++ ASSERT_NO_THROW(request.copy_kvcache());++ for (const auto& pair : copied_pairs) {+ auto src_tensor = request.prefill_request()->get_tensor(request.prefill_out_ports().at(pair.output_name));+ auto dst_tensor = request.kvcache_request()->get_tensor(request.kvcache_in_ports().at(pair.input_name));+ auto [src_view, dst_view] = request.make_non_chunked_copy_views(pair.output_name, src_tensor, dst_tensor);++ ASSERT_EQ(src_view->get_byte_size(), dst_view->get_byte_size())+ << "Byte-size mismatch for output/input pair: " << pair.output_name << " -> " << pair.input_name;++ ov::Tensor src_host(src_view->get_element_type(), src_view->get_shape());+ ov::Tensor dst_host(dst_view->get_element_type(), dst_view->get_shape());+ src_view->copy_to(ov::get_tensor_impl(src_host)._ptr);+ dst_view->copy_to(ov::get_tensor_impl(dst_host)._ptr);++ EXPECT_EQ(std::memcmp(src_host.data(), dst_host.data(), src_host.get_byte_size()), 0)+ << "copy_kvcache did not copy bytes for pair: " << pair.output_name << " -> " << pair.input_name;+ }+}++TEST_F(ConvertKVCacheToPrecisionPassTest, CopyKvCacheUsesSequenceDimensionForValueAuxRoi) {+ RecordingFactory recorder;+ auto compiled = create_testable_model(make_kv_precision_props(ov::element::i8), recorder);+ ASSERT_NE(compiled, nullptr);+ TestableLLMInferRequest request(compiled);+ request.prepare_non_chunked_copy();++ bool found_value_aux = false;+ for (const auto& [output_name, output_port] : request.prefill_out_ports()) {+ if (output_name.find("/present/value/scale") == std::string::npos &&+ output_name.find("/present/value/zp") == std::string::npos) {+ continue;+ }++ const auto& tensor = request.prefill_request()->get_tensor(output_port);+ ASSERT_EQ(tensor->get_shape().size(), 4u);+ ASSERT_EQ(tensor->get_shape()[2], 1u);+ ASSERT_GE(tensor->get_shape()[3], compiled->kvcache_desc().max_prompt_size);++ const auto [pre_kv_dim, gen_kv_dim] = request.kv_dims(output_name);+ EXPECT_EQ(pre_kv_dim, 3u);+ EXPECT_EQ(gen_kv_dim, 3u);+ found_value_aux = true;+ break;+ }++ ASSERT_TRUE(found_value_aux) << "No quantized value scale/zp output with [B,H,1,S] layout found";+ ASSERT_NO_THROW(request.copy_kvcache());+}++// Chunked-prefill counterpart of the test above. Exercises the two-part chunked copy_kvcache()+// path (past chunks + last present chunk, incl. the m_past_kv_bound backup) for quantized aux+// tensors (scale/zero-point), verifying that every KV output is mapped to its past input by name.+TEST_F(ConvertKVCacheToPrecisionPassTest, ChunkedCopyKvCacheCopiesQuantizedAuxTensorsByNameMapping) {+ RecordingFactory recorder;+ ov::AnyMap props = make_kv_precision_props(ov::element::i8);+ props["NPUW_LLM_PREFILL_HINT"] = "DYNAMIC";+ props["NPUW_LLM_PREFILL_CHUNK_SIZE"] = "32";+ auto compiled = create_testable_model(props, recorder);+ ASSERT_NE(compiled, nullptr);+ ASSERT_TRUE(compiled->use_chunk_prefill());++ TestableLLMInferRequest request(compiled);+ // No NPU core in the unit-test harness; keep the chunked backup buffer on CPU.+ request.use_cpu_pre_alloc();++ const auto chunk_size = static_cast<uint32_t>(request.prefill_chunk_size());+ ASSERT_GT(chunk_size, 0u);+ const auto max_prompt = compiled->kvcache_desc().max_prompt_size;+ ASSERT_GT(max_prompt, 1u);++ // Model the tail of a chunked prefill: the last chunk holds a single token, and at least+ // one full prior chunk already sits in the past buffer (tokens_in_past > 0 exercises part 1).+ const uint32_t tokens_in_present = 1u;+ const uint32_t tokens_in_past = std::min(chunk_size, max_prompt - tokens_in_present);+ ASSERT_GT(tokens_in_past, 0u);+ const uint32_t num_stored = tokens_in_past + tokens_in_present;+ request.prepare_chunked_copy(num_stored, tokens_in_present);++ std::unordered_set<std::string> input_names;+ for (const auto& [name, _] : request.kvcache_in_ports()) {+ input_names.insert(name);+ }++ auto to_host = [](const ov::SoPtr<ov::ITensor>& view) {+ ov::Tensor host(view->get_element_type(), view->get_shape());+ view->copy_to(ov::get_tensor_impl(host)._ptr);+ return host;+ };++ struct ChunkPair {+ std::string output_name;+ std::string input_name;+ ov::Tensor expected_past; // prefill past [0, tokens_in_past) -> gen past head+ ov::Tensor expected_present; // prefill present [C - M, C) -> gen past tail+ };+ std::vector<ChunkPair> pairs;++ uint8_t pattern_seed = 11u;+ for (const auto& [output_name, _] : request.kvcache_out_ports()) {+ if (!is_kv_name(output_name)) {+ continue;+ }+ const auto resolved_input = resolve_kv_input_name_for_test(output_name, input_names);+ ASSERT_TRUE(resolved_input.has_value()) << "No past KV input mapped for output: " << output_name;+ const auto& input_name = resolved_input.value();+ if (request.prefill_in_ports().find(input_name) == request.prefill_in_ports().end()) {+ continue;+ }++ auto present_tensor = request.prefill_request()->get_tensor(request.prefill_out_ports().at(output_name));+ auto gen_past_tensor = request.kvcache_request()->get_tensor(request.kvcache_in_ports().at(input_name));+ auto prefill_past_tensor = request.prefill_request()->get_tensor(request.prefill_in_ports().at(input_name));+ if (present_tensor->get_byte_size() == 0 || gen_past_tensor->get_byte_size() == 0) {+ continue;+ }++ const auto [pre_kv_dim, gen_kv_dim] = request.kv_dims(output_name);++ // Distinct patterns: A fills gen past (and, when m_past_kv_bound, the aliased prefill past),+ // B fills prefill present, so the part-2 assertion below can't pass by coincidence.+ ov::Tensor gen_fill(gen_past_tensor->get_element_type(), gen_past_tensor->get_shape());+ std::memset(gen_fill.data(), pattern_seed, gen_fill.get_byte_size());+ ov::get_tensor_impl(gen_fill)->copy_to(gen_past_tensor._ptr);++ ov::Tensor present_fill(present_tensor->get_element_type(), present_tensor->get_shape());+ std::memset(present_fill.data(), static_cast<int>(pattern_seed + 5), present_fill.get_byte_size());+ ov::get_tensor_impl(present_fill)->copy_to(present_tensor._ptr);+ pattern_seed = static_cast<uint8_t>(pattern_seed + 13);++ auto past_src = ov::npuw::util::make_tensor_slice(prefill_past_tensor, pre_kv_dim, 0u, tokens_in_past);+ auto present_src =+ ov::npuw::util::make_tensor_slice(present_tensor, pre_kv_dim, chunk_size - tokens_in_present, chunk_size);+ pairs.push_back({output_name, input_name, to_host(past_src), to_host(present_src)});+ }++ ASSERT_FALSE(pairs.empty()) << "No KV output/input pairs found for chunked copy_kvcache test";++ ASSERT_NO_THROW(request.copy_kvcache());++ for (const auto& pair : pairs) {+ auto gen_past_tensor = request.kvcache_request()->get_tensor(request.kvcache_in_ports().at(pair.input_name));+ const auto gen_kv_dim = request.kv_dims(pair.output_name).second;+ auto past_dst = ov::npuw::util::make_tensor_slice(gen_past_tensor, gen_kv_dim, 0u, tokens_in_past);+ auto present_dst =+ ov::npuw::util::make_tensor_slice(gen_past_tensor, gen_kv_dim, tokens_in_past, num_stored);++ ov::Tensor past_host(past_dst->get_element_type(), past_dst->get_shape());+ ov::Tensor present_host(present_dst->get_element_type(), present_dst->get_shape());+ past_dst->copy_to(ov::get_tensor_impl(past_host)._ptr);+ present_dst->copy_to(ov::get_tensor_impl(present_host)._ptr);++ ASSERT_EQ(past_host.get_byte_size(), pair.expected_past.get_byte_size())+ << "Past-chunk byte-size mismatch for pair: " << pair.output_name << " -> " << pair.input_name;+ ASSERT_EQ(present_host.get_byte_size(), pair.expected_present.get_byte_size())+ << "Present-chunk byte-size mismatch for pair: " << pair.output_name << " -> " << pair.input_name;++ EXPECT_EQ(std::memcmp(past_host.data(), pair.expected_past.data(), past_host.get_byte_size()), 0)+ << "chunked copy_kvcache corrupted past chunk for pair: " << pair.output_name << " -> " << pair.input_name;+ EXPECT_EQ(std::memcmp(present_host.data(), pair.expected_present.data(), present_host.get_byte_size()), 0)+ << "chunked copy_kvcache did not copy present chunk for pair: " << pair.output_name << " -> "+ << pair.input_name;+ }+}++// Per generate-step KV update: update_kvcache_for() appends the newly produced token's KV from the+// generate present outputs into the past inputs, including quantized aux (scale/zero-point) tensors.+TEST_F(ConvertKVCacheToPrecisionPassTest, UpdateKvCacheForCopiesQuantizedAuxTensorsByNameMapping) {+ RecordingFactory recorder;+ auto compiled = create_testable_model(make_kv_precision_props(ov::element::i8), recorder);+ ASSERT_NE(compiled, nullptr);+ TestableLLMInferRequest request(compiled);++ auto& desc = compiled->kvcache_desc();+ ASSERT_GT(desc.max_prompt_size, 0u);+ const uint32_t num_tokens = 1u;+ const uint32_t num_stored = desc.max_prompt_size;+ desc.num_stored_tokens = num_stored;++ struct UpdatePair {+ std::string output_name;+ std::string input_name;+ ov::Tensor expected_tail; // generate present [src_seq - num_tokens, src_seq)+ };+ std::vector<UpdatePair> pairs;+ bool saw_aux = false;+ bool saw_dynamic_quantize_aux = false;++ uint8_t seed = 23u;+ for (const auto& input_name : request.kvcache_past_names()) {+ const auto output_name = ov::npuw::util::past_key_values_to_present_name(input_name);+ if (request.kvcache_out_ports().find(output_name) == request.kvcache_out_ports().end() ||+ request.kvcache_in_ports().find(input_name) == request.kvcache_in_ports().end()) {+ continue;+ }+ auto present = request.kvcache_request()->get_tensor(request.kvcache_out_ports().at(output_name));+ auto past = request.kvcache_request()->get_tensor(request.kvcache_in_ports().at(input_name));+ if (present->get_byte_size() == 0 || past->get_byte_size() == 0) {+ continue;+ }+ if (is_aux_kv_name(input_name)) {+ saw_aux = true;+ saw_dynamic_quantize_aux = saw_dynamic_quantize_aux ||+ input_name.rfind("DynamicQuantize/", 0) == 0;+ }++ ov::Tensor present_fill(present->get_element_type(), present->get_shape());+ std::memset(present_fill.data(), seed, present_fill.get_byte_size());+ ov::get_tensor_impl(present_fill)->copy_to(present._ptr);+ ov::Tensor past_fill(past->get_element_type(), past->get_shape());+ std::memset(past_fill.data(), static_cast<int>(seed + 7), past_fill.get_byte_size());+ ov::get_tensor_impl(past_fill)->copy_to(past._ptr);+ seed = static_cast<uint8_t>(seed + 13);++ const auto gen_kv_dim = request.kv_dims(output_name).second;+ const auto src_seq = static_cast<uint32_t>(present->get_shape()[gen_kv_dim]);+ auto present_tail = ov::npuw::util::make_tensor_slice(present, gen_kv_dim, src_seq - num_tokens, src_seq);+ pairs.push_back({output_name, input_name, slice_to_host(present_tail)});+ }+ ASSERT_FALSE(pairs.empty()) << "No KV output/input pairs found for update_kvcache_for test";+ ASSERT_TRUE(saw_aux) << "i8 KV cache must expose scale/zero-point past inputs";+ ASSERT_TRUE(saw_dynamic_quantize_aux)+ << "i8 KV cache update test must exercise DynamicQuantize auxiliary names";++ ASSERT_NO_THROW(request.update_kvcache_for(request.kvcache_request(),+ request.kvcache_in_ports(),+ request.kvcache_out_ports(),+ num_tokens,+ desc.v_tensors_transposed_gen));++ for (const auto& pair : pairs) {+ auto past = request.kvcache_request()->get_tensor(request.kvcache_in_ports().at(pair.input_name));+ const auto gen_kv_dim = request.kv_dims(pair.output_name).second;+ auto dst_tail = ov::npuw::util::make_tensor_slice(past, gen_kv_dim, num_stored - num_tokens, num_stored);+ auto actual = slice_to_host(dst_tail);+ ASSERT_EQ(actual.get_byte_size(), pair.expected_tail.get_byte_size()) << pair.input_name;+ EXPECT_EQ(std::memcmp(actual.data(), pair.expected_tail.data(), actual.get_byte_size()), 0)+ << "update_kvcache_for did not append new-token KV for: " << pair.output_name << " -> " << pair.input_name;+ }+}++// on_reset()/clear_chunk_prefill_kv_cache() zero-fill the prefill past KV inputs; the broadened+// past-name set means quantized aux (scale/zero-point) inputs must be cleared as well.+TEST_F(ConvertKVCacheToPrecisionPassTest, ClearChunkPrefillZeroFillsQuantizedAuxPastTensors) {+ RecordingFactory recorder;+ ov::AnyMap props = make_kv_precision_props(ov::element::i8);+ props["NPUW_LLM_PREFILL_HINT"] = "DYNAMIC";+ props["NPUW_LLM_PREFILL_CHUNK_SIZE"] = "32";+ auto compiled = create_testable_model(props, recorder);+ ASSERT_NE(compiled, nullptr);+ TestableLLMInferRequest request(compiled);++ std::vector<std::string> filled;+ bool saw_aux = false;+ for (const auto& input_name : request.kvcache_past_names()) {+ if (request.prefill_in_ports().find(input_name) == request.prefill_in_ports().end()) {+ continue;+ }+ auto past = request.prefill_request()->get_tensor(request.prefill_in_ports().at(input_name));+ if (past->get_byte_size() == 0) {+ continue;+ }+ saw_aux = saw_aux || is_aux_kv_name(input_name);+ ov::Tensor fill(past->get_element_type(), past->get_shape());+ std::memset(fill.data(), 0xAB, fill.get_byte_size());+ ov::get_tensor_impl(fill)->copy_to(past._ptr);+ filled.push_back(input_name);+ }+ ASSERT_FALSE(filled.empty()) << "No prefill past KV inputs found to clear";+ ASSERT_TRUE(saw_aux) << "i8 KV cache must expose scale/zero-point past inputs";++ ASSERT_NO_THROW(request.clear_chunk_prefill_kv_cache());++ for (const auto& input_name : filled) {+ auto past = request.prefill_request()->get_tensor(request.prefill_in_ports().at(input_name));+ auto host = slice_to_host(past);+ const auto* bytes = static_cast<const uint8_t*>(host.data());+ const bool all_zero = std::all_of(bytes, bytes + host.get_byte_size(), [](uint8_t b) {+ return b == 0u;+ });+ EXPECT_TRUE(all_zero) << "clear_chunk_prefill_kv_cache left non-zero bytes in: " << input_name;+ }+}+} // namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/kv_cache_compression_pass_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/kv_cache_compression_pass_test.cppindex d6eaedb7afe..7bfc27f3f52 100644--- a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/kv_cache_compression_pass_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/kv_cache_compression_pass_test.cpp@@ -42,6 +42,7 @@#include "openvino/op/concat.hpp"#include "openvino/op/matmul.hpp"#include "openvino/op/parameter.hpp"+#include "openvino/op/reduce_min.hpp"#include "openvino/op/result.hpp"#include "openvino/op/shape_of.hpp"#include "openvino/op/softmax.hpp"@@ -233,6 +234,75 @@ TEST_P(KVCacheCompressionPassTest, ModelValidAfterPass) {EXPECT_NO_THROW(model->validate_nodes_and_infer_types());}+TEST(KVCacheCompressionPassRegressionTest, NonTransposedValueAuxUsesTokenAxis) {+ auto model = build_sdpa_model(1);+ ov::npuw::KVCacheCompressionParams params;+ params.key = {QuantizationType::Asymmetric, element::i8};+ params.value = {QuantizationType::Asymmetric, element::i8};++ ASSERT_NO_THROW(ov::npuw::run_kv_cache_dynamic_quantization_passes(model, params));++ bool found_value_scale = false;+ for (const auto& input : model->inputs()) {+ if (input.get_any_name().find("/past_key_values/value/scale") == std::string::npos) {+ continue;+ }+ PartialShape ps{1, 4, 8, 1};+ EXPECT_EQ(input.get_partial_shape(), ps) << "for input: " << input.get_any_name();+ found_value_scale = true;+ }+ EXPECT_TRUE(found_value_scale) << "Value scale parameter was not added";+}++TEST(KVCacheCompressionPassRegressionTest, NonTransposedValueUsesEmbeddingReductionAxis) {+ auto model = build_sdpa_model(1);+ ov::npuw::KVCacheCompressionParams params;+ params.key = {QuantizationType::Asymmetric, element::i8};+ params.value = {QuantizationType::Asymmetric, element::i8};++ ASSERT_NO_THROW(ov::npuw::run_kv_cache_dynamic_quantization_passes(model, params, false));++ const auto expect_shape = [&model](const std::string& name, const PartialShape& expected) {+ for (const auto& input : model->inputs()) {+ if (input.get_any_name().find(name) != std::string::npos) {+ EXPECT_EQ(input.get_partial_shape(), expected) << name;+ return true;+ }+ }+ ADD_FAILURE() << "Missing input: " << name;+ return false;+ };++ expect_shape("/past_key_values/key/scale", PartialShape{1, 4, 8, 1});+ expect_shape("/past_key_values/value/scale", PartialShape{1, 4, 8, 1});+ expect_shape("/past_key_values/key/zp", PartialShape{1, 4, 8, 1});+ expect_shape("/past_key_values/value/zp", PartialShape{1, 4, 8, 1});++ size_t key_reduce_axis_count = 0;+ size_t value_reduce_axis_count = 0;+ for (const auto& node : model->get_ops()) {+ const auto reduce_min = ov::as_type_ptr<ov::op::v1::ReduceMin>(node);+ if (!reduce_min || reduce_min->get_input_size() < 2) {+ continue;+ }+ const auto constant = ov::as_type_ptr<ov::op::v0::Constant>(reduce_min->input_value(1).get_node_shared_ptr());+ if (!constant) {+ continue;+ }+ const auto axes = constant->cast_vector<int64_t>();+ ASSERT_EQ(axes.size(), 1u);+ if (reduce_min->get_friendly_name().find("/key/ReduceMin") != std::string::npos) {+ EXPECT_EQ(axes.front(), 3);+ ++key_reduce_axis_count;+ } else if (reduce_min->get_friendly_name().find("/value/ReduceMin") != std::string::npos) {+ EXPECT_EQ(axes.front(), 3);+ ++value_reduce_axis_count;+ }+ }+ EXPECT_EQ(key_reduce_axis_count, 1u);+ EXPECT_EQ(value_reduce_axis_count, 1u);+}+// The pass must inject exactly (num_sdpa * 2 * added_per_cache) new Parameters// (scale + optionally zp, for both key and value past caches).TEST_P(KVCacheCompressionPassTest, ParameterCountIncreasedCorrectly) {@@ -646,7 +716,7 @@ TEST_P(KVCacheMultiStepDecodeTest, TransformedModelIoTypesMatchQuantConfig) {auto xform_model = build_decode_step_model(WINDOW);xform_model = apply_kv_cache_io_precision_for_test(xform_model, p.key_dt, p.val_dt);ASSERT_NO_THROW(ov::npuw::run_kv_cache_dynamic_quantization_passes(- xform_model, p.to_compression_params()));+ xform_model, p.to_compression_params(), true));ASSERT_NO_THROW(xform_model->validate_nodes_and_infer_types());const bool key_asym = (p.key_quant_type == QuantizationType::Asymmetric);@@ -755,7 +825,7 @@ TEST_P(KVCacheMultiStepDecodeTest, DecodeLoopAccuracy) {auto ref_model = build_decode_step_model(WINDOW);auto xform_model = build_decode_step_model(WINDOW);ASSERT_NO_THROW(ov::npuw::run_kv_cache_dynamic_quantization_passes(- xform_model, p.to_compression_params()));+ xform_model, p.to_compression_params(), true));ASSERT_NO_THROW(xform_model->validate_nodes_and_infer_types());std::mt19937 rng(77);