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] INT-8 dynamically quantized kv-cache (#34516)
Eugene Smirnoveed5648fed61
diff --git a/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cppindex a7245209190..5ed823a8319 100644--- a/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp@@ -704,7 +704,7 @@ static std::shared_ptr<ov::Node> skip_convert_nodes(const std::shared_ptr<ov::No// ============================================================================static void build_sdpa_param_mapping(HostFlashAttention& hfa,const std::shared_ptr<ov::Model>& model,- const SDPAPatternNodes& pattern_nodes) {+ const ov::npuw::util::SDPAPatternNodes& pattern_nodes) {LOG_INFO("Building SDPA input parameter index mapping...");// Helper lambda to safely extract parameter from node (skipping Convert ops)@@ -884,7 +884,7 @@ std::optional<HostFlashAttention> HostFlashAttention::from(const std::shared_ptr// ========================================================================// Step 1: Validate SDPA pattern and extract key nodes// ========================================================================- auto pattern_nodes = find_sdpa_pattern_nodes(model);+ auto pattern_nodes = ov::npuw::util::find_sdpa_pattern_nodes(model);if (!pattern_nodes.is_valid()) {LOG_WARN("Failed to re-find SDPA pattern nodes");return std::nullopt;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 4dbbe065fec..849a74bdce5 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@@ -625,7 +625,6 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mm_compiled_model_factory(std::move(factory)) {LOG_DEBUG("Creating LLMCompiledModel");LOG_BLOCK();-::intel_npu::registerNPUWLLMOptions(*m_options_desc);ov::AnyMap npuw_llm_props;@@ -636,14 +635,7 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mauto whisper_eos_token = pop_option(other_props, std::string("NPUW_WHISPER_EOS_TOKEN"));auto use_eagle_key = pop_option(other_props, std::string("NPUW_EAGLE"));- auto kv_kache_storage_type = choose_kv_cache_storage_type(model, m_cfg, other_props);-- // Solely used for serialization at the moment- m_non_llm_props = other_props;-- // Remove "NPUW_LLM_PREFILL_CONFIG", "NPUW_LLM_GENERATE_CONFIG" from map,- // to not pass them into ::intel_npu::Config object, as we don't need to- // preserve them somewhere.+ // Remove map-valued section configs before m_cfg.update(any_copy(...)), since Config expects string options.auto prefill_config_opt = pop_option(npuw_llm_props, std::string("NPUW_LLM_PREFILL_CONFIG"));auto generate_config_opt = pop_option(npuw_llm_props, std::string("NPUW_LLM_GENERATE_CONFIG"));auto prefill_config_addition = pop_option(npuw_llm_props, std::string("++NPUW_LLM_PREFILL_CONFIG"));@@ -651,6 +643,15 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m// Also make these maps for third: lm head model, in case it will be created:auto lm_head_config_opt = pop_option(npuw_llm_props, std::string("NPUW_LLM_SHARED_HEAD_CONFIG"));auto lm_head_config_addition = pop_option(npuw_llm_props, std::string("++NPUW_LLM_SHARED_HEAD_CONFIG"));++ m_cfg.update(any_copy(npuw_llm_props));++ // m_cfg should be updated before checking for optimize_fp8, because affect the decision on kv-cache storage type+ auto kv_kache_storage_type = choose_kv_cache_storage_type(model, m_cfg, other_props);++ // Solely used for serialization at the moment+ m_non_llm_props = other_props;+refine_dynamic_props(npuw_llm_props, npudesc);m_cfg.update(any_copy(npuw_llm_props));@@ -891,9 +892,9 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m} else {LOG_DEBUG("Check and apply opt layout --- SKIPPED");}-if (!m_is_embedding) {if (!m_use_chunk_prefill) {+ LOG_DEBUG("Removing EmptyKVInputs");NPUW_ASSERT(ov::npuw::RemoveEmptyKVInputs().run_on_model(prefill_model));} else {LOG_DEBUG("Don't remove input key/values from prefill model.");@@ -906,12 +907,11 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mov::npuw::RedirectNewKvToOutput().run_on_model(generate_model_variants[i]);}}-- LOG_DEBUG("Converting KV-cache in generate model to FP16.");+ 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]);}- LOG_DEBUG("Converting KV-cache in prefill model to FP16.");+ 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);auto prefill_config =@@ -963,7 +963,6 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mif (generate_attn_dyn || generate_attn_pyramid || generate_attn_hfa) {merge_config_with(generate_config, dyn_attn_opts);}-if (is_moe) {// Apply MoE configuration for prefill stageconst auto prefill_moe_hint = m_cfg.get<::intel_npu::NPUW_LLM_PREFILL_MOE_HINT>();@@ -982,7 +981,6 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mLOG_INFO("DEVICE_ROUTED MoE transformations completed");}}-// Note: with dynamic attention in EITHER STAGE, we have to// explicitly disable the run-time fallback to so extra ov::Model// references won't be held by the npuw::CompiledModel, resultingdiff --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 d7c00612b9d..f6afd3ab063 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@@ -215,7 +215,9 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCocontinue;}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);+ // NB: Use fill_tensor_bytes to zero-fill regardless of element type.+ // fill_tensor<ov::float16> would fail with a type mismatch error for i8 kv-cache+ ov::npuw::util::fill_tensor_bytes(kvcache_in_tensor, 0u);}}@@ -614,7 +616,10 @@ void ov::npuw::LLMInferRequest::clear_chunk_prefill_kv_cache() {auto chunk_prefill_kvcache_in_tensor = m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name));- ov::npuw::util::fill_tensor<ov::float16>(chunk_prefill_kvcache_in_tensor, 0);+ // NB: Use fill_tensor_bytes to zero-fill regardless of element type.+ // After KV cache compression, past KV inputs may be i8 precision, and+ // fill_tensor<ov::float16> would fail with a type mismatch error.+ ov::npuw::util::fill_tensor_bytes(chunk_prefill_kvcache_in_tensor, 0u);}}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 d21698635ca..a408c5c0a63 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@@ -5,6 +5,8 @@#include "convert_kvcache_to_precision.hpp"#include "../logging.hpp"+#include "../util.hpp"+#include "kv_cache_compressed.hpp"#include "low_precision/concat.hpp"#include "low_precision/kv_cache_concat.hpp"#include "low_precision/low_precision.hpp"@@ -66,21 +68,52 @@ public:std::shared_ptr<ov::Model> cvt_kvcache_to_low_precision(const std::shared_ptr<ov::Model>& model,const ov::element::Type lptype) {+ // 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;+ auto value_storage_type = lptype;++ const bool use_integer_kv_storage = (lptype == ov::element::i8 || lptype == ov::element::u8);+ if (use_integer_kv_storage) {+ key_storage_type = lptype;+ // TODO: int4 precision for value-cache lead to compilation failure for now+ value_storage_type = ov::element::i8;+ }+ov::preprocess::PrePostProcessor ppp(model);for (const auto& tensor : model->inputs()) {- if (tensor.get_any_name().find("past_key") != std::string::npos) {- ppp.input(tensor.get_any_name()).tensor().set_element_type(lptype);+ const auto& name = tensor.get_any_name();+ if (ov::npuw::util::isPastKeyValuesKey(name).has_value()) {+ ppp.input(name).tensor().set_element_type(key_storage_type);+ } else if (ov::npuw::util::isPastKeyValuesValue(name).has_value()) {+ ppp.input(name).tensor().set_element_type(value_storage_type);}}for (const auto& tensor : model->outputs()) {- if (tensor.get_any_name().find("present") != std::string::npos) {- ppp.output(tensor.get_any_name()).tensor().set_element_type(lptype);+ const auto& name = tensor.get_any_name();+ if (ov::npuw::util::isPresentKeyValuesKey(name).has_value()) {+ ppp.output(name).tensor().set_element_type(key_storage_type);+ } else if (ov::npuw::util::isPresentKeyValuesValue(name).has_value()) {+ ppp.output(name).tensor().set_element_type(value_storage_type);}}+ auto new_model = ppp.build();++ if (use_integer_kv_storage) {+ ov::npuw::KVCacheCompressionParams dq_params;+ dq_params.key.quantization_dt = key_storage_type;+ dq_params.key.quantization_type = ov::npuw::KVCacheCompressionConfig::QuantizationType::Asymmetric;+ dq_params.value.quantization_dt = value_storage_type;+ dq_params.value.quantization_type = ov::npuw::KVCacheCompressionConfig::QuantizationType::Symmetric;++ LOG_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);+ }- return ppp.build();+ return new_model;}} // namespacediff --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.cppnew file mode 100644index 00000000000..f841ec0ff84--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_cache_compressed.cpp@@ -0,0 +1,612 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "kv_cache_compressed.hpp"++#include <limits>++#include "../util.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/clamp.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/maximum.hpp"+#include "openvino/op/minimum.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reduce_max.hpp"+#include "openvino/op/reduce_min.hpp"+#include "openvino/op/round.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/pass/manager.hpp"+#include "openvino/pass/matcher_pass.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "ov_ops/dynamic_quantize.hpp"++namespace opp = ov::pass::pattern;+namespace {+constexpr auto g_key_cache_name = "key";+constexpr auto g_value_cache_name = "value";+constexpr auto g_past_name = "past_key_values";+constexpr auto g_present_name = "present";++bool isKey(const std::string& n) {+ return n.find(g_key_cache_name) != std::string::npos;+}++std::string cacheName(bool is_key) {+ return is_key ? g_key_cache_name : g_value_cache_name;+}++// ── V2 helper functions (ONNX DynamicQuantizeLinear style) ────────────────────++std::shared_ptr<ov::Node> find_min_value(const ov::Output<ov::Node>& input, size_t reduce_axes) {+ const auto& input_min = std::make_shared<ov::op::v1::ReduceMin>(+ input,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {reduce_axes}),+ true);+ const auto& zero_node = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {0});+ return std::make_shared<ov::op::v1::Minimum>(zero_node, input_min);+}++std::shared_ptr<ov::Node> find_max_value(const ov::Output<ov::Node>& input, size_t reduce_axes) {+ const auto& input_max = std::make_shared<ov::op::v1::ReduceMax>(+ input,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {reduce_axes}),+ true);+ const auto& zero_node = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {0});+ return std::make_shared<ov::op::v1::Maximum>(zero_node, input_max);+}++std::shared_ptr<ov::Node> quantize_linear(ov::Output<ov::Node> x,+ ov::Output<ov::Node> x_span,+ ov::Output<ov::Node> quant_range_span,+ ov::Output<ov::Node> y_zero_point) {+ const auto& x_scaled =+ std::make_shared<ov::op::v1::Divide>(std::make_shared<ov::op::v1::Multiply>(x, quant_range_span), x_span);+ const auto& x_rounded = std::make_shared<ov::op::v5::Round>(x_scaled, ov::op::v5::Round::RoundMode::HALF_TO_EVEN);+ const auto& y_zero_point_f32 = std::make_shared<ov::op::v0::Convert>(y_zero_point, ov::element::f32);+ const auto& result_shifted = std::make_shared<ov::op::v1::Add>(x_rounded, y_zero_point_f32);+ const auto& result_clamped = std::make_shared<ov::op::v0::Clamp>(result_shifted, 0, 255);+ return std::make_shared<ov::op::v0::Convert>(result_clamped, ov::element::u8);+}++ov::OutputVector dynamic_quantize_linear(std::shared_ptr<ov::Node> input, size_t reduction_axe) {+ const auto& x = input;+ // quantization range for uint8 is [0, 255] per ONNX DynamicQuantizeLinear spec+ const auto& quant_range_min = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {0});+ const auto& quant_range_max = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {255});+ const auto& quant_range_span = std::make_shared<ov::op::v1::Subtract>(quant_range_max, quant_range_min);++ const auto& x_max = find_max_value(x, reduction_axe);+ const auto& x_min = find_min_value(x, reduction_axe);+ const auto& x_span = std::make_shared<ov::op::v1::Subtract>(x_max, x_min);+ const auto& y_scale = std::make_shared<ov::op::v1::Divide>(x_span, quant_range_span);+ // ONNX spec: intermediate_zero_point = qmin - min(x) / y_scale+ // Note: this is qmin - (x_min / y_scale), NOT (qmin - x_min) / y_scale+ const auto& x_min_div_scale = std::make_shared<ov::op::v1::Divide>(x_min, y_scale);+ const auto& intermediate_zero_point =+ std::make_shared<ov::op::v5::Round>(std::make_shared<ov::op::v1::Subtract>(quant_range_min, x_min_div_scale),+ ov::op::v5::Round::RoundMode::HALF_TO_EVEN);+ const auto& y_zero_point =+ std::make_shared<ov::op::v0::Convert>(std::make_shared<ov::op::v0::Clamp>(intermediate_zero_point, 0, 255),+ ov::element::u8);++ const auto& y = quantize_linear(x, x_span, quant_range_span, y_zero_point);+ return {y, y_scale, y_zero_point};+}++// ── V3 helper function (compiler pattern style) ──────────────────────────────++ov::OutputVector dynamic_quantize_linear_v3(const ov::Output<ov::Node>& input,+ size_t reduction_axis,+ const std::string& name_prefix) {+ auto make_name = [&name_prefix](const std::string& suffix) {+ return name_prefix + "/" + suffix;+ };++ auto reduceAxis = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {reduction_axis});+ auto cst_255 = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {255.0f});+ auto cst_inv255 = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {1.0f / 255.0f});+ auto cst_zero = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {0.0f});++ auto reduceMin = std::make_shared<ov::op::v1::ReduceMin>(input, reduceAxis, true);+ reduceMin->set_friendly_name(make_name("ReduceMin"));++ auto reduceMax = std::make_shared<ov::op::v1::ReduceMax>(input, reduceAxis, true);+ reduceMax->set_friendly_name(make_name("ReduceMax"));++ auto minClamped = std::make_shared<ov::op::v0::Clamp>(reduceMin, std::numeric_limits<float>::lowest(), 0.0);+ minClamped->set_friendly_name(make_name("Clamp_min"));++ auto maxClamped = std::make_shared<ov::op::v0::Clamp>(reduceMax, 0.0, std::numeric_limits<float>::max());+ maxClamped->set_friendly_name(make_name("Clamp_max"));++ auto subtractSpan = std::make_shared<ov::op::v1::Subtract>(maxClamped, minClamped);+ subtractSpan->set_friendly_name(make_name("Subtract_span"));++ auto multiplyScale = std::make_shared<ov::op::v1::Multiply>(subtractSpan, cst_inv255);+ multiplyScale->set_friendly_name(make_name("Multiply_scale"));++ auto multiplyInput = std::make_shared<ov::op::v1::Multiply>(input, cst_255);+ multiplyInput->set_friendly_name(make_name("Multiply_input_255"));++ // ONNX spec: zp = qmin - (minClamped / scale)+ auto cst_qmin = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{1}, {-128.0f});+ auto minDivScale = std::make_shared<ov::op::v1::Divide>(minClamped, multiplyScale);+ minDivScale->set_friendly_name(make_name("Divide_min_by_scale"));++ auto zpFloat = std::make_shared<ov::op::v1::Subtract>(cst_qmin, minDivScale);+ zpFloat->set_friendly_name(make_name("Subtract_zp"));++ auto divideSpan = std::make_shared<ov::op::v1::Divide>(multiplyInput, subtractSpan);+ divideSpan->set_friendly_name(make_name("Divide_span"));++ auto roundZp = std::make_shared<ov::op::v5::Round>(zpFloat, ov::op::v5::Round::RoundMode::HALF_TO_EVEN);+ roundZp->set_friendly_name(make_name("Round_zp"));++ auto roundSpan = std::make_shared<ov::op::v5::Round>(divideSpan, ov::op::v5::Round::RoundMode::HALF_TO_EVEN);+ roundSpan->set_friendly_name(make_name("Round_span"));++ auto clampZp = std::make_shared<ov::op::v0::Clamp>(roundZp, -128.0, 127.0);+ clampZp->set_friendly_name(make_name("Clamp_zp"));++ auto addQuant = std::make_shared<ov::op::v1::Add>(roundSpan, clampZp);+ addQuant->set_friendly_name(make_name("Add_quant"));++ auto clampOutput = std::make_shared<ov::op::v0::Clamp>(addQuant, -128.0, 127.0);+ clampOutput->set_friendly_name(make_name("Clamp_output"));++ auto convertZp = std::make_shared<ov::op::v0::Convert>(clampZp, ov::element::i8);+ convertZp->set_friendly_name(make_name("Convert_zp"));++ auto convertOutput = std::make_shared<ov::op::v0::Convert>(clampOutput, ov::element::i8);+ convertOutput->set_friendly_name(make_name("Convert_output"));++ return {convertOutput->output(0), multiplyScale->output(0), convertZp->output(0)};+}++} // anonymous namespace++// ── V2: ONNX DynamicQuantizeLinear style, u8 [0, 255] ────────────────────────++ov::npuw::DecomposeDynamicQuantize2::DecomposeDynamicQuantize2() {+ 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();+ auto dq_ptr = node_to_output.at(dynamic_quantize).get_node_shared_ptr();++ // This pass only handles asymmetric u8 (ONNX DynamicQuantizeLinear style).+ // Symmetric or non-u8 nodes are handled by other passes.+ auto dq_node = ov::as_type_ptr<ov::op::internal::DynamicQuantize>(dq_ptr);+ const auto& attrs = dq_node->get_attrs();+ if (attrs.quantization_type != ov::op::internal::DynamicQuantize::QuantizationType::Asymmetric ||+ attrs.quantization_dt != ov::element::u8)+ return false;++ 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;++ auto dq_input = dq_ptr->input_value(0);+ auto has_zp = dq_ptr->outputs().size() == 3;++ auto dq_results = dynamic_quantize_linear(dq_input.get_node_shared_ptr(), reduction_axis);++ dq_ptr->output(0).replace(dq_results[0]);+ dq_ptr->output(1).replace(dq_results[1]);+ if (has_zp) {+ dq_ptr->output(2).replace(dq_results[2]);+ }++ return true;+ };++ register_matcher(std::make_shared<opp::Matcher>(dynamic_quantize, "DecomposeDynamicQuantize"), callback);+}++// ── V3: compiler pattern style, i8 [-128, 127] ───────────────────────────────++ov::npuw::DecomposeDynamicQuantize3::DecomposeDynamicQuantize3() {+ 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();+ auto dq_ptr = node_to_output.at(dynamic_quantize).get_node_shared_ptr();++ auto dq_node = ov::as_type_ptr<ov::op::internal::DynamicQuantize>(dq_ptr);++ 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;++ auto dq_input = dq_ptr->input_value(0);+ auto has_zp = dq_ptr->outputs().size() == 3;++ auto dq_results = dynamic_quantize_linear_v3(dq_input, reduction_axis, dq_ptr->get_friendly_name());++ dq_ptr->output(0).replace(dq_results[0]);+ dq_ptr->output(1).replace(dq_results[1]);+ if (has_zp) {+ dq_ptr->output(2).replace(dq_results[2]);+ }++ return true;+ };++ register_matcher(std::make_shared<opp::Matcher>(dynamic_quantize, "DecomposeDynamicQuantize"), callback);+}++// ── V1: handcrafted symmetric-style, i8 [-127, 127] ──────────────────────────++ov::npuw::DecomposeDynamicQuantize::DecomposeDynamicQuantize() {+ 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();+ auto dq_ptr = node_to_output.at(dynamic_quantize).get_node_shared_ptr();++ // DecomposeDynamicQuantize2 (asymmetric u8) runs first in the pass manager.+ // This pass handles whatever remains — dispatch on quantization_dt for the output range.+ auto dq_node = ov::as_type_ptr<ov::op::internal::DynamicQuantize>(dq_ptr);+ const auto& attrs = dq_node->get_attrs();++ const auto quant_dt = attrs.quantization_dt;+ float quant_max, quant_min;+ if (quant_dt == ov::element::i8) {+ quant_max = 127.0f;+ quant_min = -127.0f;+ } else if (quant_dt == ov::element::i4) {+ quant_max = 7.0f;+ quant_min = -7.0f;+ } else {+ LOG_WARN("DecomposeDynamicQuantize: unsupported dtype " << quant_dt);+ return false;+ }++ LOG_DEBUG("Found DynamicQuantize : " << dq_ptr->get_friendly_name() << " decomposing");+ 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;++ //+ auto cst_0 =+ ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {1.0f / quant_max}); // for scale normalization++ auto dq_input = dq_ptr->input_value(0);+ auto has_zp = dq_ptr->outputs().size() == 3;++ auto set_friendly_name = [&dq_ptr](auto node, auto name) {+ node->set_friendly_name(dq_ptr->get_friendly_name() + "/" + name);+ };++ // --- Compute min and max per token using reduction dim ---+ auto reduce_min = std::make_shared<ov::op::v1::ReduceMin>(+ dq_input,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {reduction_axis}), // axis = feature dim D+ true); // keepdims++ set_friendly_name(reduce_min, "ReduceMin");++ auto reduce_max = std::make_shared<ov::op::v1::ReduceMax>(+ dq_input,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {reduction_axis}), // axis = feature dim D+ true);++ set_friendly_name(reduce_max, "ReduceMax");++ // optional clamp+ auto clamped_min = std::make_shared<ov::op::v0::Clamp>(reduce_min, quant_min, quant_max);+ auto clamped_max = std::make_shared<ov::op::v0::Clamp>(reduce_max, quant_min, quant_max);++ set_friendly_name(clamped_min, "clamp_min");+ set_friendly_name(clamped_max, "clamp_max");++ // --- Compute range and scale ---+ auto range = std::make_shared<ov::op::v1::Subtract>(clamped_max, clamped_min); // max - min+ auto scale = std::make_shared<ov::op::v1::Multiply>(range, cst_0); // scale = range / quant_max++ set_friendly_name(range, "subtract_range");+ set_friendly_name(scale, "scale");++ auto scale_converted = std::make_shared<ov::op::v0::Convert>(scale, ov::element::f32);+ set_friendly_name(scale_converted, "scale_converted");++ std::shared_ptr<ov::Node> zp, zp_clamped;+ if (has_zp) {+ // --- Compute zero-point ---+ // zp = round( (-min) / scale ), then clamp to [quant_min, quant_max]+ auto cst_neg_1 = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {-1.0f});+ auto neg_min = std::make_shared<ov::op::v1::Multiply>(clamped_min, cst_neg_1); // negate min+ set_friendly_name(neg_min, "Zp/NegMin");++ auto zp_float = std::make_shared<ov::op::v1::Divide>(neg_min, scale); // (-min) / scale+ set_friendly_name(zp_float, "Zp/Divide");++ auto zp_rounded = std::make_shared<ov::op::v5::Round>(zp_float, ov::op::v5::Round::RoundMode::HALF_TO_EVEN);+ set_friendly_name(zp_rounded, "Zp/Round");++ zp_clamped = std::make_shared<ov::op::v0::Clamp>(zp_rounded, quant_min, quant_max);+ set_friendly_name(zp_clamped, "Zp/Clamp");++ zp = std::make_shared<ov::op::v0::Convert>(zp_clamped, ov::element::i8); // int8 zero-point+ set_friendly_name(zp, "Zp/Convert");+ }++ // --- Quantize input ---+ auto normalized = std::make_shared<ov::op::v1::Divide>(dq_input, scale); // input / scale+ set_friendly_name(normalized, "Divide");++ auto rounded = std::make_shared<ov::op::v5::Round>(normalized, ov::op::v5::Round::RoundMode::HALF_TO_EVEN);+ set_friendly_name(rounded, "Round");++ std::shared_ptr<ov::Node> with_zp = rounded;+ if (has_zp) {+ with_zp = std::make_shared<ov::op::v1::Add>(rounded, zp_clamped); // add zero-point+ set_friendly_name(with_zp, "ZP/Add");+ }+ auto quantized_clamped = std::make_shared<ov::op::v0::Clamp>(with_zp, quant_min, quant_max);+ set_friendly_name(quantized_clamped, "Clamp2");++ // TODO: this convert might be optional???+ auto quantized_output = std::make_shared<ov::op::v0::Convert>(quantized_clamped, quant_dt);+ set_friendly_name(quantized_output, "Convert2");++ // --- Optional: expose outputs ---+ // --- Rewire outputs ---+ dq_ptr->output(0).replace(quantized_output->output(0));+ dq_ptr->output(1).replace(scale_converted->output(0));++ if (has_zp) {+ dq_ptr->output(2).replace(zp->output(0));+ }++ return true;+ };++ register_matcher(std::make_shared<opp::Matcher>(dynamic_quantize, "DecomposeDynamicQuantize"), callback);+}++// inject DynamicQuantize/Dynamic dequantize ops on kv-cache passes before matmuls+void ov::npuw::run_kv_cache_dynamic_quantization_passes(const std::shared_ptr<ov::Model>& model,+ const KVCacheCompressionParams& params) {+ // Validate SDPA patterns and extract key nodes+ auto pattern_nodes_list = ov::npuw::util::find_all_sdpa_pattern_nodes(model);++ if (pattern_nodes_list.empty()) {+ LOG_WARN("Failed to find SDPA pattern nodes in model "+ << model->get_friendly_name()+ << ". 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) {+ 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;++ std::vector<ov::Dimension> new_dims;+ for (int64_t i = 0; i < kv_shape.rank().get_length(); ++i) {+ if (i == embedding_index) { // head_dim axis → set to 1+ new_dims.push_back(1);+ } else {+ new_dims.push_back(kv_shape[i]);+ }+ }+ return new_dims;+ };++ auto create_parameter_with_name = [&model](auto precision, auto dims, auto name) {+ auto new_param = std::make_shared<ov::op::v0::Parameter>(precision, dims);+ new_param->set_friendly_name(name);+ new_param->output(0).get_tensor().set_names({name});+ model->add_parameters({new_param});+ return new_param;+ };++ auto create_result_with_name = [&model](auto result_node, auto name) {+ auto new_res = std::make_shared<ov::op::v0::Result>(result_node);+ new_res->set_friendly_name(name);+ new_res->output(0).get_tensor().set_names({name});+ model->add_results({new_res});+ };++ size_t pattern_index = 0;+ auto make_name = [&pattern_index](auto base_name) {+ return base_name + std::string("/") + std::to_string(pattern_index);+ };++ // Shared lambda: create DynamicQuantize node on a given input, expose scale/zp as Results.+ // Returns the DynamicQuantize node so caller can wire its output(0) as needed.+ auto create_dynamic_quantize =+ [&make_name, &create_result_with_name](+ const ov::Output<ov::Node>& dq_input,+ bool is_key,+ const KVCacheCompressionConfig& cfg) -> std::shared_ptr<ov::op::internal::DynamicQuantize> {+ const std::string kv_name = cacheName(is_key);++ const bool is_asym = cfg.quantization_type == KVCacheCompressionConfig::QuantizationType::Asymmetric;++ auto rank = dq_input.get_partial_shape().size();+ std::vector<uint64_t> shape_group_size(rank, 1);++ ov::op::internal::DynamicQuantize::Attributes dq_config;+ dq_config.quantization_dt = cfg.quantization_dt;+ dq_config.quantization_type = is_asym ? ov::op::internal::DynamicQuantize::QuantizationType::Asymmetric+ : ov::op::internal::DynamicQuantize::QuantizationType::Symmetric;+ dq_config.scale_dt = ov::element::f32;+ dq_config.output_storage_type = ov::op::internal::DynamicQuantize::OutputStorageType::Planar;+ dq_config.group_sizes = shape_group_size;++ if (is_asym) {+ dq_config.zp_dt = cfg.quantization_dt; // zp same type as quantized data+ }++ auto kv_dyn_quant = std::make_shared<ov::op::internal::DynamicQuantize>(dq_input, dq_config);+ kv_dyn_quant->set_friendly_name(make_name("DynamicQuantize") + "/" + kv_name);++ create_result_with_name(kv_dyn_quant->output(1),+ make_name("DynamicQuantize") + "/" + g_present_name + "/" + kv_name + "/scale");++ if (is_asym) {+ create_result_with_name(kv_dyn_quant->output(2),+ make_name("DynamicQuantize") + "/" + g_present_name + "/" + kv_name + "/zp");+ }++ return kv_dyn_quant;+ };++ // helper to recreate dequantization nodes - TODO: probably better to insert Dequantize Node, than decompose it or+ // not.+ auto create_dequant_nodes = [&model, &create_parameter_with_name, &clear_embedding_index, &make_name](+ std::shared_ptr<ov::Node> start_node,+ std::shared_ptr<ov::Node> concat_node,+ bool isKey,+ const KVCacheCompressionConfig& cfg) {+ const std::string node_name = isKey ? g_key_cache_name : g_value_cache_name;++ // TODO: adding back slash here kills partitioning - fix that+ auto make_dq_name = [&make_name, &node_name](auto base_name) {+ return make_name("DynamicQuantize") + node_name + "/" + base_name;+ };+ auto make_dq_param_name = [&make_name, &node_name](auto base_name) {+ return make_name("DynamicQuantize") + "/" + g_past_name + "/" + node_name + "/" + base_name;+ };++ // Take snapshot of the ORIGINAL concat edge BEFORE building new nodes.+ std::vector<ov::Input<ov::Node>> concat_consumers;+ for (auto&& consumer : start_node->output(0).get_target_inputs()) {+ if (consumer.get_node() == concat_node.get()) {+ concat_consumers.push_back(consumer);+ }+ }++ LOG_INFO("Found Dequantize for " << node_name << " insertion point after: " << start_node->get_name()+ << ") shape: " << start_node->get_shape());++ // reconstruct k and v caches intgeres values to matmul using one of Dequantize approach+ // use zp on quant/dequant only in case od assym+ std::shared_ptr<ov::Node> fp_subtracted_zp = start_node;+ if (cfg.quantization_type == KVCacheCompressionConfig::QuantizationType::Asymmetric) {+ // Subtract zero-point - TODO: share this memory with DynamicQuantize/read/assign?+ auto zp = create_parameter_with_name(cfg.quantization_dt,+ clear_embedding_index(start_node, isKey),+ make_dq_param_name("zp"));++ // this probably to be optimized by compiler - but for now we need it to avoid types mismatch+ auto converted_zp = std::make_shared<ov::op::v0::Convert>(zp, ov::element::f32);+ converted_zp->set_friendly_name(make_dq_name("zp_convert"));++ fp_subtracted_zp = std::make_shared<ov::op::v1::Subtract>(start_node, converted_zp);+ fp_subtracted_zp->set_friendly_name(make_dq_name("zp_sub"));+ }++ // Multiply by scale+ auto fp_scale = create_parameter_with_name(ov::element::f32,+ clear_embedding_index(fp_subtracted_zp, isKey),+ make_dq_param_name("scale"));++ auto dequantized = std::make_shared<ov::op::v1::Multiply>(fp_subtracted_zp, fp_scale);+ dequantized->set_friendly_name(make_dq_name("scale"));++ // Rewire only the matched concat input and leave unrelated consumers intact.+ for (auto&& concat_consumer : concat_consumers) {+ concat_consumer.replace_source_output(dequantized);+ }+ };++ for (auto&& pattern_nodes : pattern_nodes_list) {+ if (!pattern_nodes.past_key_concat_node) {+ LOG_INFO("NO k-cache concat node");+ }+ if (!pattern_nodes.past_value_concat_node) {+ LOG_INFO("NO v-cache concat node");+ }+ if (!pattern_nodes.past_value_concat_node || !pattern_nodes.past_key_concat_node) {+ LOG_INFO("skipping Dequantization for this pattern:");+ continue;+ }++ create_dequant_nodes(pattern_nodes.past_key_concat_node->input_value(0).get_node_shared_ptr(),+ pattern_nodes.past_key_concat_node,+ true,+ params.key);+ create_dequant_nodes(pattern_nodes.past_value_concat_node->input_value(0).get_node_shared_ptr(),+ pattern_nodes.past_value_concat_node,+ false,+ params.value);++ pattern_index++;+ }++ model->validate_nodes_and_infer_types();++ // For DynamicQuantize we need just to iterate over present.key/values results and insert DynQuante ops+ auto original_results = model->get_results();+ for (const auto& result : original_results) {+ auto result_name = result->get_friendly_name();+ LOG_BLOCK();+ LOG_DEBUG("Probing result for DynamicQuantize: " << result_name);++ auto is_key = ov::npuw::util::isPresentKeyValuesKey(result_name);+ auto is_value = ov::npuw::util::isPresentKeyValuesValue(result_name);++ if (!is_key && !is_value) {+ LOG_DEBUG("Not a key and not a value - SKIP");+ continue;+ }++ if (is_key && is_value) {+ LOG_WARN("Invalid result name for DynamicQuantize: " << result_name);+ continue;+ }++ auto kv_result = result;+ pattern_index = is_key ? is_key.value() : is_value.value();+ auto kv_name = cacheName(is_key.has_value());++ LOG_DEBUG("is a " << kv_name << ": with index=" << pattern_index << ", shape=" << result->get_input_shape(0));++ auto dq_input_value = kv_result->input_value(0);+ auto dq_input_node = dq_input_value.get_node_shared_ptr();++ // might be a convert layer - that substitute, if no just insert before it+ if (ov::is_type<ov::op::v0::Convert>(dq_input_node) && dq_input_node->get_users().size() == 1) {+ LOG_DEBUG("Bypassing PPP-inserted Convert: " << dq_input_node->get_friendly_name() << " ("+ << dq_input_node->input_value(0).get_element_type() << " -> "+ << dq_input_node->get_element_type() << ")");+ dq_input_value = dq_input_node->input_value(0);+ }++ const auto& cfg = is_key.has_value() ? params.key : params.value;+ auto kv_dyn_quant = create_dynamic_quantize(dq_input_value, is_key.has_value(), cfg);++ kv_result->input(0).replace_source_output(kv_dyn_quant->output(0));++ LOG_DEBUG("Done");+ }+ model->validate_nodes_and_infer_types();++ // TODO: for now internal op DynamicQuantize not easily gets converted into IE so run decompose here+ ov::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.run_passes(model);++ model->validate_nodes_and_infer_types();++ LOG_INFO("DynamicQuantize passes complete");+}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.hppnew file mode 100644index 00000000000..5bb4611c7b6--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_cache_compressed.hpp@@ -0,0 +1,63 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/openvino.hpp"+#include "openvino/pass/matcher_pass.hpp"++namespace ov::npuw {++/// Compression configuration for a single KV cache tensor (key or value).+struct KVCacheCompressionConfig {+ enum class QuantizationType { Symmetric, Asymmetric };++ QuantizationType quantization_type = QuantizationType::Asymmetric;+ ov::element::Type quantization_dt = ov::element::u8;+};++/// Independent compression parameters for key and value caches.+struct KVCacheCompressionParams {+ KVCacheCompressionConfig key;+ KVCacheCompressionConfig value;+};++// The compression passes will look for SDPA patterns,+// insert ov::op::internal::DynamicQuantize nodes on the concat outputs, redirected to result+// and Dequantize nodes for past.key.values+// Then decompose those DynamicQuantize nodes into+// subgraphs that expose quantization parameters as Results.+// The added extra results like scale/zeropoints coefficients will be named+// "DynamicQuantize/{kv_index}/present/{key|value}/scale"+// "DynamicQuantize/{kv_index}/present/{key|value}/zp"+// 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);++/// Decomposition passes for ov::op::internal::DynamicQuantize.++/// V1: handcrafted symmetric-style, i8 [-127, 127]+class DecomposeDynamicQuantize : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::DecomposeDynamicQuantize");+ DecomposeDynamicQuantize();+};++/// V2: ONNX DynamicQuantizeLinear style, u8 [0, 255]+class DecomposeDynamicQuantize2 : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::DecomposeDynamicQuantize2");+ DecomposeDynamicQuantize2();+};++/// V3: compiler pattern style, i8 [-128, 127]+class DecomposeDynamicQuantize3 : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("npuw::patterns::DecomposeDynamicQuantize3");+ DecomposeDynamicQuantize3();+};++// NOLINTNEXTLINE(readability/namespace)+} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cppindex a7c71e9002e..1c176be27ef 100644--- a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp@@ -8,20 +8,10 @@#include <utility>#include "openvino/core/validation_util.hpp"-#include "openvino/op/add.hpp"-#include "openvino/op/broadcast.hpp"#include "openvino/op/concat.hpp"-#include "openvino/op/matmul.hpp"-#include "openvino/op/reshape.hpp"-#include "openvino/op/softmax.hpp"-#include "openvino/opsets/opset13.hpp"-#include "openvino/pass/graph_rewrite.hpp"-#include "openvino/pass/matcher_pass.hpp"-#include "openvino/pass/pattern/op/or.hpp"-#include "openvino/pass/pattern/op/wrap_type.hpp"-#include "openvino/pass/validate.hpp"--namespace opp = ov::pass::pattern;+#include "openvino/op/parameter.hpp"+#include "openvino/op/util/op_types.hpp"+#include "util.hpp"namespace ov {namespace npuw {@@ -57,7 +47,7 @@ std::optional<ov::npuw::function::Attention> create_attention_from_model(const std::map<std::string, size_t>& past_key_sequence_dims,const std::map<std::string, size_t>& past_value_sequence_dims) {// Find SDPA pattern nodes in the model- auto pattern_nodes = find_sdpa_pattern_nodes(model);+ auto pattern_nodes = ov::npuw::util::find_sdpa_pattern_nodes(model);if (!pattern_nodes.is_valid()) {LOG_WARN("Could not find SDPA pattern in model");return std::nullopt;@@ -228,7 +218,7 @@ std::optional<PyramidModelResult> process_pyramid_model(const std::shared_ptr<ov// Helper function to validate model and extract necessary information for pyramid attentionstd::optional<PyramidValidationResult> validate_and_setup_pyramid_attention(const std::shared_ptr<ov::Model>& model) {// Find SDPA pattern nodes using the extracted function- auto pattern_nodes = find_sdpa_pattern_nodes(model);+ auto pattern_nodes = ov::npuw::util::find_sdpa_pattern_nodes(model);if (!pattern_nodes.is_valid()) {LOG_WARN("Could not find valid SDPA pattern in model");return std::nullopt;@@ -287,8 +277,8 @@ std::optional<PyramidValidationResult> validate_and_setup_pyramid_attention(consconst auto& original_params = model->get_parameters();for (const auto& param : original_params) {const std::string param_name = param->get_friendly_name();- bool is_target_param = is_key ? ov::npuw::util::isPastKeyValuesKey(param_name)- : ov::npuw::util::isPastKeyValuesValue(param_name);+ bool is_target_param = is_key ? ov::npuw::util::isPastKeyValuesKey(param_name).has_value()+ : ov::npuw::util::isPastKeyValuesValue(param_name).has_value();if (is_target_param) {sequence_dims[param_name] = concat_axis;@@ -325,99 +315,6 @@ std::optional<PyramidValidationResult> validate_and_setup_pyramid_attention(conspast_value_sequence_dims};}-SDPAPatternNodes find_sdpa_pattern_nodes(const std::shared_ptr<ov::Model>& model) {- // Find decomposed SDPA pattern components- SDPAPatternNodes pattern_nodes;-- // Find past key and value parameter nodes- for (auto input : model->inputs()) {- auto input_node = input.get_node();- auto input_name = input_node->get_friendly_name();- if (ov::npuw::util::isPastKeyValuesKey(input_name)) {- pattern_nodes.past_key_param_node = input_node->shared_from_this();- } else if (ov::npuw::util::isPastKeyValuesValue(input_name)) {- pattern_nodes.past_value_param_node = input_node->shared_from_this();- }- }-- // Helper lambda to trace from MatMul to find Concat node- auto find_concat_from_matmul = [](const std::shared_ptr<ov::Node>& matmul_node,- size_t input_idx) -> std::shared_ptr<ov::Node> {- if (!matmul_node)- return nullptr;-- auto current_node = matmul_node->input(input_idx).get_source_output().get_node_shared_ptr();-- // Traverse backwards through reshape/transpose operations to find Concat- while (current_node) {- if (ov::is_type<ov::op::v0::Concat>(current_node)) {- return current_node;- }-- // Allow traversing through Reshape and Transpose- if (ov::is_type<ov::op::v1::Reshape>(current_node) || ov::is_type<ov::op::v3::Broadcast>(current_node) ||- ov::is_type<ov::op::v0::Unsqueeze>(current_node)) {- if (current_node->get_input_size() > 0) {- current_node = current_node->input(0).get_source_output().get_node_shared_ptr();- } else {- break;- }- } else {- // Stop at other operations- break;- }- }-- return nullptr;- };-- // Search for the pattern: MatMul -> Add -> Softmax -> MatMul- auto ops = model->get_ordered_ops();- for (auto&& node : ops) {- if (ov::is_type<ov::op::v8::Softmax>(node)) {- pattern_nodes.softmax_node = node;-- // Check if softmax is fed by Add- auto softmax_input = node->input(0).get_source_output().get_node_shared_ptr();- if (ov::is_type<ov::op::v1::Add>(softmax_input)) {- pattern_nodes.add_node = softmax_input;-- // Check if add is fed by MatMul (first MatMul)- auto add_input0 = pattern_nodes.add_node->input(0).get_source_output().get_node_shared_ptr();- if (ov::is_type<ov::op::v0::MatMul>(add_input0)) {- pattern_nodes.matmul1_node = add_input0;-- // Find Concat node for past key (input 1 of MatMul1)- pattern_nodes.past_key_concat_node = find_concat_from_matmul(pattern_nodes.matmul1_node, 1);- }- }-- // Check if softmax feeds into MatMul (second MatMul)- for (auto&& output : node->outputs()) {- for (auto&& target_input : output.get_target_inputs()) {- auto target_node = target_input.get_node()->shared_from_this();- if (ov::is_type<ov::op::v0::MatMul>(target_node)) {- pattern_nodes.matmul2_node = target_node;-- // Find Concat node for past value (input 1 of MatMul2)- pattern_nodes.past_value_concat_node = find_concat_from_matmul(pattern_nodes.matmul2_node, 1);- break;- }- }- if (pattern_nodes.matmul2_node)- break;- }-- if (pattern_nodes.is_valid()) {- pattern_nodes.log_pattern();- break; // Found complete pattern- }- }- }-- return pattern_nodes;-}-std::optional<PyramidAttention> PyramidAttention::from(const std::shared_ptr<ov::Model>& model) {// Validate and setup pyramid attentionauto validation_result = validate_and_setup_pyramid_attention(model);diff --git a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.hpp b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.hppindex 697c6aff7c1..4899df76989 100644--- a/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.hpp@@ -1,5 +1,6 @@// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0+//#pragma once@@ -59,38 +60,6 @@ std::optional<PyramidModelResult> process_pyramid_model(const std::shared_ptr<ov// Helper function to validate model and extract necessary information for pyramid attentionstd::optional<PyramidValidationResult> validate_and_setup_pyramid_attention(const std::shared_ptr<ov::Model>& model);-// Structure to hold SDPA pattern nodes-struct SDPAPatternNodes {- std::shared_ptr<ov::Node> matmul1_node = nullptr;- std::shared_ptr<ov::Node> matmul2_node = nullptr;- std::shared_ptr<ov::Node> softmax_node = nullptr;- std::shared_ptr<ov::Node> add_node = nullptr;- std::shared_ptr<ov::Node> past_key_param_node = nullptr;- std::shared_ptr<ov::Node> past_value_param_node = nullptr;- std::shared_ptr<ov::Node> past_key_concat_node = nullptr;- std::shared_ptr<ov::Node> past_value_concat_node = nullptr;-- bool is_valid() const {- return matmul1_node && matmul2_node && softmax_node && add_node && past_key_param_node &&- past_value_param_node && past_key_concat_node && past_value_concat_node;- }-- // Log pattern information for debugging- void log_pattern() const {- LOG_DEBUG("SDPA Pattern nodes:");- LOG_DEBUG(" MatMul1: " << (matmul1_node ? matmul1_node->get_friendly_name() : "null"));- LOG_DEBUG(" Add: " << (add_node ? add_node->get_friendly_name() : "null"));- LOG_DEBUG(" Softmax: " << (softmax_node ? softmax_node->get_friendly_name() : "null"));- LOG_DEBUG(" MatMul2: " << (matmul2_node ? matmul2_node->get_friendly_name() : "null"));- LOG_DEBUG(" Key Concat: " << (past_key_concat_node ? past_key_concat_node->get_friendly_name() : "null"));- LOG_DEBUG(- " Value Concat: " << (past_value_concat_node ? past_value_concat_node->get_friendly_name() : "null"));- }-};--// Function to find SDPA pattern nodes in the model-SDPAPatternNodes find_sdpa_pattern_nodes(const std::shared_ptr<ov::Model>& model);-// Function to find mask parameter by traversing from Add nodestd::shared_ptr<ov::op::v0::Parameter> find_mask_parameter(const std::shared_ptr<ov::Node>& add_node);diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cppindex 6013a7f4733..188c969f6af 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp@@ -15,7 +15,14 @@#include "llm_lora_states.hpp"#include "logging.hpp"-#include "openvino/op/transpose.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/softmax.hpp"+#include "openvino/op/unsqueeze.hpp"#include "openvino/op/util/op_types.hpp"#include "openvino/runtime/make_tensor.hpp" // get_tensor_impl#include "util_xarch.hpp"@@ -912,12 +919,166 @@ void ov::npuw::util::fill_tensor_bytes(ov::SoPtr<ov::ITensor> tensor, uint8_t fistd::memset(tensor_data, fill_val, byte_size);}-bool ov::npuw::util::isPastKeyValuesKey(const std::string& str) {- std::regex pattern(R"(past_key_values\.\d+\.key)");- return std::regex_match(str, pattern);+std::optional<int> ov::npuw::util::isPastKeyValuesKey(const std::string& str) {+ // Capture the number in parentheses+ std::regex pattern(R"(past_key_values\.(\d+)\.key)");+ std::smatch match;+ if (std::regex_match(str, match, pattern)) {+ // match[1] contains the number+ int index = std::stoi(match[1].str());+ return index;+ }+ return std::nullopt;+}++std::optional<int> ov::npuw::util::isPastKeyValuesValue(const std::string& str) {+ // Capture the number in parentheses+ std::regex pattern(R"(past_key_values\.(\d+)\.value)");+ std::smatch match;+ if (std::regex_match(str, match, pattern)) {+ // match[1] contains the number+ int index = std::stoi(match[1].str());+ return index;+ }+ return std::nullopt;}-bool ov::npuw::util::isPastKeyValuesValue(const std::string& str) {- std::regex pattern(R"(past_key_values\.\d+\.value)");- return std::regex_match(str, pattern);+std::optional<int> ov::npuw::util::isPresentKeyValuesKey(const std::string& str) {+ // Capture the number in parentheses+ std::regex pattern(R"(present\.(\d+)\.key)");+ std::smatch match;+ if (std::regex_match(str, match, pattern)) {+ // match[1] contains the number+ int index = std::stoi(match[1].str());+ return index;+ }+ return std::nullopt;}++std::optional<int> ov::npuw::util::isPresentKeyValuesValue(const std::string& str) {+ // Capture the number in parentheses+ std::regex pattern(R"(present\.(\d+)\.value)");+ std::smatch match;+ if (std::regex_match(str, match, pattern)) {+ // match[1] contains the number+ int index = std::stoi(match[1].str());+ return index;+ }+ return std::nullopt;+}++namespace {++std::vector<ov::npuw::util::SDPAPatternNodes> find_sdpa_pattern_nodes_internal(const std::shared_ptr<ov::Model>& model,+ bool findAll) {+ // Find decomposed SDPA pattern components+ std::vector<ov::npuw::util::SDPAPatternNodes> pattern_nodes;++ // Helper lambda to trace from MatMul to find Concat node+ auto find_concat_from_matmul = [](const std::shared_ptr<ov::Node>& matmul_node,+ size_t input_idx) -> std::shared_ptr<ov::Node> {+ if (!matmul_node)+ return nullptr;++ auto current_node = matmul_node->input(input_idx).get_source_output().get_node_shared_ptr();++ // Traverse backwards through reshape/transpose operations to find Concat+ while (current_node) {+ if (ov::is_type<ov::op::v0::Concat>(current_node)) {+ return current_node;+ }++ // Allow traversing through Reshape and Transpose+ if (ov::is_type<ov::op::v1::Reshape>(current_node) || ov::is_type<ov::op::v3::Broadcast>(current_node) ||+ ov::is_type<ov::op::v0::Unsqueeze>(current_node)) {+ if (current_node->get_input_size() > 0) {+ current_node = current_node->input(0).get_source_output().get_node_shared_ptr();+ } else {+ break;+ }+ } else {+ // Stop at other operations+ break;+ }+ }++ return nullptr;+ };++ LOG_DEBUG("Entering find_sdpa_pattern_nodes_internal");+ LOG_BLOCK();+ // Search for the pattern: MatMul -> Add -> Softmax -> MatMul+ auto ops = model->get_ordered_ops();+ for (auto&& node : ops) {+ if (!ov::is_type<ov::op::v8::Softmax>(node))+ continue;+ LOG_DEBUG("Examining node: " << node->get_friendly_name() << " (" << node->get_type_name() << ")");++ ov::npuw::util::SDPAPatternNodes candidate;+ auto& current_node = candidate;+ current_node.softmax_node = node;++ // Check if softmax is fed by Add - TODO: how optional is add?+ auto softmax_input = node->input(0).get_source_output().get_node_shared_ptr();+ if (!ov::is_type<ov::op::v1::Add>(softmax_input)) {+ LOG_DEBUG("Softmax input is not Add(" << softmax_input->get_friendly_name() << "), skipping pattern check");+ continue;+ }+ current_node.add_node = softmax_input;++ // Check if add is fed by MatMul (first MatMul)+ auto add_input0 = current_node.add_node->input(0).get_source_output().get_node_shared_ptr();+ if (!ov::is_type<ov::op::v0::MatMul>(add_input0)) {+ LOG_DEBUG("Add input is not MatMul(" << add_input0->get_friendly_name() << "), skipping pattern check");+ continue;+ }+ current_node.matmul1_node = add_input0;++ // Find Concat node for past key (input 1 of MatMul1)+ current_node.past_key_concat_node = find_concat_from_matmul(current_node.matmul1_node, 1);++ // Check if softmax feeds into MatMul (second MatMul)+ for (auto&& output : node->outputs()) {+ for (auto&& target_input : output.get_target_inputs()) {+ auto target_node = target_input.get_node()->shared_from_this();+ if (ov::is_type<ov::op::v0::MatMul>(target_node)) {+ current_node.matmul2_node = target_node;++ // Find Concat node for past value (input 1 of MatMul2)+ current_node.past_value_concat_node = find_concat_from_matmul(current_node.matmul2_node, 1);+ break;+ }+ }+ if (current_node.matmul2_node)+ break;+ }+ if (!current_node.matmul2_node) {+ LOG_DEBUG("Softmax does not feed into MatMul, skipping pattern check");+ continue;+ }++ // pattern might be not full, say missed concats for example+ current_node.log_pattern(std::to_string(pattern_nodes.size()));++ pattern_nodes.push_back(candidate);+ if (!findAll) {+ break;+ }+ }++ return pattern_nodes;+}+} // namespace++std::vector<ov::npuw::util::SDPAPatternNodes> ov::npuw::util::find_all_sdpa_pattern_nodes(+ const std::shared_ptr<ov::Model>& model) {+ return find_sdpa_pattern_nodes_internal(model, true);+}++ov::npuw::util::SDPAPatternNodes ov::npuw::util::find_sdpa_pattern_nodes(const std::shared_ptr<ov::Model>& model) {+ auto internal_nodes = find_sdpa_pattern_nodes_internal(model, false);+ if (internal_nodes.size() != 1) {+ return {};+ }+ return internal_nodes.front();+}\ No newline at end of filediff --git a/src/plugins/intel_npu/src/plugin/npuw/util.hpp b/src/plugins/intel_npu/src/plugin/npuw/util.hppindex d6e783a8a4b..b800a14d477 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.hpp@@ -5,6 +5,7 @@#pragma once#include <future>+#include <optional>#include <random>#include <string>@@ -189,6 +190,37 @@ bool matchLoRAMatMulBString(const std::string& input);bool matchLoRAMatMulAlphaString(const std::string& input);+// Structure to hold SDPA pattern nodes+struct SDPAPatternNodes {+ std::shared_ptr<ov::Node> matmul1_node = nullptr;+ std::shared_ptr<ov::Node> matmul2_node = nullptr;+ std::shared_ptr<ov::Node> softmax_node = nullptr;+ std::shared_ptr<ov::Node> add_node = nullptr;+ std::shared_ptr<ov::Node> past_key_concat_node = nullptr;+ std::shared_ptr<ov::Node> past_value_concat_node = nullptr;++ bool is_valid() const {+ return matmul1_node && matmul2_node && softmax_node && add_node && past_key_concat_node &&+ past_value_concat_node;+ }++ // Log pattern information for debugging+ void log_pattern(const std::string& prefix) const {+ LOG_DEBUG("SDPA Pattern " << prefix << " nodes:");+ LOG_DEBUG(" MatMul1: " << (matmul1_node ? matmul1_node->get_friendly_name() : "null"));+ LOG_DEBUG(" Add: " << (add_node ? add_node->get_friendly_name() : "null"));+ LOG_DEBUG(" Softmax: " << (softmax_node ? softmax_node->get_friendly_name() : "null"));+ LOG_DEBUG(" MatMul2: " << (matmul2_node ? matmul2_node->get_friendly_name() : "null"));+ LOG_DEBUG(" Key Concat: " << (past_key_concat_node ? past_key_concat_node->get_friendly_name() : "null"));+ LOG_DEBUG(+ " Value Concat: " << (past_value_concat_node ? past_value_concat_node->get_friendly_name() : "null"));+ }+};++// Function to find SDPA pattern nodes in the model+SDPAPatternNodes find_sdpa_pattern_nodes(const std::shared_ptr<ov::Model>& model);+std::vector<SDPAPatternNodes> find_all_sdpa_pattern_nodes(const std::shared_ptr<ov::Model>& model);+template <typename T>void fill_tensor(ov::SoPtr<ov::ITensor> tensor, T fill_val, size_t offset = 0u) {T* tensor_data = tensor->data<T>();@@ -243,9 +275,10 @@ private:mutable bool done = false;};-bool isPastKeyValuesKey(const std::string& str);--bool isPastKeyValuesValue(const std::string& str);+std::optional<int> isPastKeyValuesKey(const std::string& str);+std::optional<int> isPastKeyValuesValue(const std::string& str);+std::optional<int> isPresentKeyValuesKey(const std::string& str);+std::optional<int> isPresentKeyValuesValue(const std::string& str);} // namespace util} // namespace npuwdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 95c5228ea7e..9989274e349 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -68,6 +68,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/attention.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/kv_cache_compressed.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/perf.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/spatial.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/weights_bank.cpp@@ -121,4 +122,6 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_compiled_model_graph_options_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/partitioning_options_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_options_smoke_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/sdpa_pattern_nodes_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/remove_empty_kv_inputs_test.cpp)diff --git a/src/plugins/intel_npu/tests/unit/npuw/dynamic_quantize_accuracy_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/dynamic_quantize_accuracy_test.cppnew file mode 100644index 00000000000..8df3e8de40c--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/dynamic_quantize_accuracy_test.cpp@@ -0,0 +1,882 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Unit tests for DynamicQuantize decomposition accuracy.+//+// All models use fp16 input/output — this is the native precision of the+// KV-cache compression subgraphs we want to test.+//+// The test builds models that mirror the real KV-cache compression pipeline,+// which in production consists of TWO separate compiled models:+//+// 1. Quantize model (applied to each new token being stored):+// Parameter(f16) -> Convert(f32) -> DynamicQuantize -> [q, scale, zp] Results+//+// 2. Dequantize model (applied when reading cached tokens for attention):+// Parameters(q_i8, scale_f32, zp_i8) -> dequant chain -> Result(f16)+//+// Test cases:+// RoundtripAccuracy - single fused roundtrip model via evaluate()+// SplitModelRoundtripAccuracy - separate quantize + dequantize models via+// evaluate(), validates that each model works+// independently and that the roundtrip through+// both produces acceptable accuracy+// DeviceRoundtripAccuracy - opt-in device test (OV_DQ_TEST_DEVICE env var)+// using the split model approach; catches+// compilation failures for quantize-only models+//+// The dequantize chain matches the actual product code in create_dequant_nodes():+// deq = (convert(q, f32) - convert(zp, f32)) * scale_f32++#include <gtest/gtest.h>++#include <array>+#include <cctype>+#include <cmath>+#include <cstdlib>+#include <iomanip>+#include <limits>+#include <numeric>+#include <random>+#include <sstream>+#include <string>+#include <vector>++#include "npuw_transformations/kv_cache_compressed.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/openvino.hpp"+#include "openvino/pass/manager.hpp"+#include "openvino/runtime/intel_npu/properties.hpp"+#include "ov_ops/dynamic_quantize.hpp"++namespace {++using namespace ov;++// ============================================================================+// Accuracy metrics+// ============================================================================+struct AccuracyMetrics {+ double l2_norm;+ double rel_l2_norm;+ double max_abs_error;+ double mean_abs_error;+};++AccuracyMetrics compute_metrics(const float* original, const float* reconstructed, size_t count) {+ double sum_sq_err = 0.0;+ double sum_abs_err = 0.0;+ double max_abs = 0.0;+ double sum_sq_orig = 0.0;++ for (size_t i = 0; i < count; ++i) {+ double diff = static_cast<double>(original[i]) - static_cast<double>(reconstructed[i]);+ sum_sq_err += diff * diff;+ double abs_diff = std::abs(diff);+ sum_abs_err += abs_diff;+ if (abs_diff > max_abs) max_abs = abs_diff;+ sum_sq_orig += static_cast<double>(original[i]) * static_cast<double>(original[i]);+ }++ AccuracyMetrics m;+ m.l2_norm = std::sqrt(sum_sq_err);+ m.rel_l2_norm = (sum_sq_orig > 0.0) ? m.l2_norm / std::sqrt(sum_sq_orig) : 0.0;+ m.max_abs_error = max_abs;+ m.mean_abs_error = (count > 0) ? sum_abs_err / static_cast<double>(count) : 0.0;+ return m;+}++// ============================================================================+// Test parameter definition+// ============================================================================+enum class DistributionKind { Uniform, GenGaussian };++struct DQTestParams {+ int decompose_version;+ Shape shape;+ unsigned seed;+ DistributionKind dist_kind;+ float uniform_min;+ float uniform_max;+ float ggd_mu;+ float ggd_alpha;+ float ggd_beta;+ // Quantization config overrides.+ // quant_dt == element::dynamic → infer from decompose_version (u8 for v2, i8 otherwise)+ element::Type quant_dt = element::dynamic;+ bool is_symmetric = false; // true = symmetric (no ZP, 2 DQ outputs)+ double threshold = 0.02; // rel-L2 pass threshold+};++static element::Type resolve_quant_dt(const DQTestParams& p) {+ return (p.quant_dt != element::dynamic)+ ? p.quant_dt+ : (p.decompose_version == 2 ? element::u8 : element::i8);+}++static std::string dist_to_token(DistributionKind kind) {+ return kind == DistributionKind::Uniform ? "Uniform" : "GGD";+}++static std::string type_to_token(const element::Type& t) {+ if (t == element::u8)+ return "u8";+ if (t == element::i8)+ return "i8";+ if (t == element::i4)+ return "i4";+ return "dyn";+}++static std::string float_to_token(float v) {+ std::ostringstream ss;+ ss << std::fixed << std::setprecision(3) << v;+ auto token = ss.str();+ while (!token.empty() && token.back() == '0') {+ token.pop_back();+ }+ if (!token.empty() && token.back() == '.') {+ token.pop_back();+ }+ for (auto& ch : token) {+ if (ch == '-') {+ ch = 'm';+ } else if (ch == '.') {+ ch = 'p';+ }+ }+ return token;+}++static std::string sanitize_gtest_name(std::string name) {+ for (auto& ch : name) {+ if (!std::isalnum(static_cast<unsigned char>(ch))) {+ ch = '_';+ }+ }+ return name;+}++static std::string make_test_case_name(const DQTestParams& p) {+ std::ostringstream os;+ os << "V" << p.decompose_version+ << "_" << dist_to_token(p.dist_kind)+ << "_" << (p.is_symmetric ? "Sym" : "Asym")+ << "_" << type_to_token(resolve_quant_dt(p));++ if (p.dist_kind == DistributionKind::Uniform) {+ os << "_R" << float_to_token(p.uniform_min) << "_" << float_to_token(p.uniform_max);+ } else {+ os << "_Mu" << float_to_token(p.ggd_mu)+ << "_A" << float_to_token(p.ggd_alpha)+ << "_B" << float_to_token(p.ggd_beta);+ }++ os << "_S";+ for (size_t i = 0; i < p.shape.size(); ++i) {+ if (i > 0) {+ os << "x";+ }+ os << p.shape[i];+ }+ os << "_Seed" << p.seed;+ return sanitize_gtest_name(os.str());+}++std::ostream& operator<<(std::ostream& os, const DQTestParams& p) {+ return os << make_test_case_name(p);+}+++// ============================================================================+// Shared helpers for DQ config and decompose pass+// ============================================================================+op::internal::DynamicQuantize::Attributes make_dq_config(const Shape& shape,+ const DQTestParams& p) {+ using QT = op::internal::DynamicQuantize::QuantizationType;++ // Resolve effective quantization dtype: explicit override beats version default.+ const element::Type quant_dt = resolve_quant_dt(p);++ op::internal::DynamicQuantize::Attributes config;+ config.scale_dt = element::f32;+ config.quantization_dt = quant_dt;+ config.group_sizes = std::vector<uint64_t>(shape.size(), 1);++ if (p.is_symmetric) {+ config.quantization_type = QT::Symmetric;+ config.zp_dt = element::dynamic; // no zero-point+ } else {+ config.quantization_type = QT::Asymmetric;+ config.zp_dt = quant_dt;+ }+ return config;+}++void run_decompose_pass(const std::shared_ptr<Model>& model, int decompose_version) {+ pass::Manager manager("decompose_dq");+ switch (decompose_version) {+ case 1:+ manager.register_pass<ov::npuw::DecomposeDynamicQuantize>();+ break;+ case 2:+ manager.register_pass<ov::npuw::DecomposeDynamicQuantize2>();+ break;+ case 3:+ manager.register_pass<ov::npuw::DecomposeDynamicQuantize3>();+ break;+ default:+ OPENVINO_THROW("Unknown decompose version: ", decompose_version);+ }+ manager.run_passes(model);+ model->validate_nodes_and_infer_types();+}++// ============================================================================+// Build a single fused roundtrip model:+// Parameter(f16) -> Convert(f32) -> [DQ + dequant in f32] -> Convert(f16) -> Result(f16)+//+// The DynamicQuantize node is named with "key" so the decomposition pass+// selects reduction_axis=3 (the key-cache embedding dimension).+// ============================================================================+std::shared_ptr<Model> build_roundtrip_model(const Shape& shape,+ const DQTestParams& p) {+ auto input = std::make_shared<op::v0::Parameter>(element::f16, shape);+ input->set_friendly_name("input");++ auto dq_input = std::make_shared<op::v0::Convert>(input, element::f32);+ dq_input->set_friendly_name("input_cvt_f32");++ auto config = make_dq_config(shape, p);++ auto dq = std::make_shared<op::internal::DynamicQuantize>(dq_input, config);+ dq->set_friendly_name("DynamicQuantize/0/key");++ // Dequant chain depends on symmetry:+ // Symmetric: q * scale+ // Asymmetric: (q - zp) * scale+ auto q_f32 = std::make_shared<op::v0::Convert>(dq->output(0), element::f32);+ std::shared_ptr<Node> dequant_input;+ if (p.is_symmetric) {+ dequant_input = q_f32;+ } else {+ auto zp_f32 = std::make_shared<op::v0::Convert>(dq->output(2), element::f32);+ dequant_input = std::make_shared<op::v1::Subtract>(q_f32, zp_f32);+ }+ auto reconstructed = std::make_shared<op::v1::Multiply>(dequant_input, dq->output(1));++ auto output_cvt = std::make_shared<op::v0::Convert>(reconstructed, element::f16);+ output_cvt->set_friendly_name("output_cvt_f16");++ auto result = std::make_shared<op::v0::Result>(output_cvt);+ result->set_friendly_name("result_reconstructed");++ auto model = std::make_shared<Model>(+ ResultVector{result},+ ParameterVector{input},+ "roundtrip_fp16_v" + std::to_string(p.decompose_version));++ model->validate_nodes_and_infer_types();+ run_decompose_pass(model, p.decompose_version);+ return model;+}++// ============================================================================+// Build a quantize-only model (matches the real "store new token" path):+// Parameter(f16) -> Convert(f32) -> DynamicQuantize -> Results(q, scale, zp)+//+// In production this is compiled as a separate subgraph. A compilation+// failure here (which has been observed) would go unnoticed with a single+// fused roundtrip model.+// ============================================================================+std::shared_ptr<Model> build_quantize_model(const Shape& shape,+ const DQTestParams& p) {+ auto input = std::make_shared<op::v0::Parameter>(element::f16, shape);+ input->set_friendly_name("input");++ auto cvt_f32 = std::make_shared<op::v0::Convert>(input, element::f32);+ cvt_f32->set_friendly_name("input_cvt_f32");++ auto config = make_dq_config(shape, p);++ auto dq = std::make_shared<op::internal::DynamicQuantize>(cvt_f32, config);+ dq->set_friendly_name("DynamicQuantize/0/key");++ auto result_q = std::make_shared<op::v0::Result>(dq->output(0));+ result_q->set_friendly_name("result_quantized");++ auto result_scale = std::make_shared<op::v0::Result>(dq->output(1));+ result_scale->set_friendly_name("result_scale");++ ResultVector results{result_q, result_scale};+ if (!p.is_symmetric) {+ auto result_zp = std::make_shared<op::v0::Result>(dq->output(2));+ result_zp->set_friendly_name("result_zp");+ results.push_back(result_zp);+ }++ auto model = std::make_shared<Model>(+ results,+ ParameterVector{input},+ "quantize_fp16_v" + std::to_string(p.decompose_version));++ model->validate_nodes_and_infer_types();+ run_decompose_pass(model, p.decompose_version);+ return model;+}++// ============================================================================+// Build a dequantize-only model (matches the real "read cached tokens" path):+// Parameters(q, scale, zp) -> (convert(q,f32) - convert(zp,f32)) * scale+// -> Convert(f16) -> Result+//+// This mirrors create_dequant_nodes() in the production code.+// No decompose pass needed -- the dequant chain is plain arithmetic.+// ============================================================================+std::shared_ptr<Model> build_dequantize_model(const Shape& shape,+ const DQTestParams& p) {+ auto config = make_dq_config(shape, p);++ auto param_q = std::make_shared<op::v0::Parameter>(config.quantization_dt, shape);+ param_q->set_friendly_name("quantized_data");++ // Scale/ZP shape: same as data but with embedding dim (last) collapsed to 1+ Shape scale_shape = shape;+ scale_shape.back() = 1;++ auto param_scale = std::make_shared<op::v0::Parameter>(element::f32, scale_shape);+ param_scale->set_friendly_name("scale");++ // Dequant chain depends on symmetry:+ // Symmetric: convert(q, f32) * scale+ // Asymmetric: (convert(q, f32) - convert(zp, f32)) * scale+ auto q_f32 = std::make_shared<op::v0::Convert>(param_q, element::f32);+ q_f32->set_friendly_name("q_cvt_f32");++ std::shared_ptr<Node> dequant_input;+ ParameterVector params{param_q, param_scale};++ if (p.is_symmetric) {+ dequant_input = q_f32;+ } else {+ auto param_zp = std::make_shared<op::v0::Parameter>(config.zp_dt, scale_shape);+ param_zp->set_friendly_name("zero_point");+ params.push_back(param_zp);++ auto zp_f32 = std::make_shared<op::v0::Convert>(param_zp, element::f32);+ zp_f32->set_friendly_name("zp_cvt_f32");+ auto sub_zp = std::make_shared<op::v1::Subtract>(q_f32, zp_f32);+ sub_zp->set_friendly_name("sub_zp");+ dequant_input = sub_zp;+ }++ auto dequantized = std::make_shared<op::v1::Multiply>(dequant_input, param_scale);+ dequantized->set_friendly_name("dequantized");++ auto output_cvt = std::make_shared<op::v0::Convert>(dequantized, element::f16);+ output_cvt->set_friendly_name("output_cvt_f16");++ auto result = std::make_shared<op::v0::Result>(output_cvt);+ result->set_friendly_name("result_dequantized");++ auto model = std::make_shared<Model>(+ ResultVector{result},+ params,+ "dequantize_fp16_v" + std::to_string(p.decompose_version));++ model->validate_nodes_and_infer_types();+ return model;+}++// ============================================================================+// Data generation helpers+// Generated values are rounded to fp16 so the source distribution is exactly+// representable -- no f32->f16 conversion artifacts in error measurements.+// ============================================================================++static float to_fp16(float v) {+ return static_cast<float>(ov::float16(v));+}++std::vector<float> generate_uniform_data(size_t count, float min_val, float max_val, unsigned seed) {+ std::mt19937 gen(seed);+ std::uniform_real_distribution<float> dist(min_val, max_val);+ std::vector<float> data(count);+ for (auto& v : data) {+ v = to_fp16(dist(gen));+ }+ return data;+}++std::vector<float> generate_gen_gaussian_data(size_t count, float mu, float alpha, float beta, unsigned seed) {+ std::mt19937 gen(seed);+ std::gamma_distribution<double> gamma_dist(1.0 / static_cast<double>(beta), 1.0);+ std::bernoulli_distribution sign_dist(0.5);++ std::vector<float> data(count);+ for (size_t i = 0; i < count; ++i) {+ double g = gamma_dist(gen);+ double abs_x = static_cast<double>(alpha) * std::pow(g, 1.0 / static_cast<double>(beta));+ double sign = sign_dist(gen) ? 1.0 : -1.0;+ data[i] = to_fp16(static_cast<float>(static_cast<double>(mu) + sign * abs_x));+ }+ return data;+}++// ============================================================================+// Helper: evaluate a roundtrip model via the reference interpreter.+// ============================================================================+AccuracyMetrics evaluate_roundtrip(const std::shared_ptr<Model>& model,+ const float* input_data,+ size_t element_count) {+ auto input_tensor = Tensor(element::f16, model->get_parameters()[0]->get_shape());+ auto* dst = input_tensor.data<ov::float16>();+ for (size_t i = 0; i < element_count; ++i) {+ dst[i] = ov::float16(input_data[i]);+ }++ auto output_tensor = Tensor(element::f16, model->get_results()[0]->get_shape());++ TensorVector inputs{input_tensor};+ TensorVector outputs{output_tensor};++ bool ok = model->evaluate(outputs, inputs);+ EXPECT_TRUE(ok) << "Model evaluation failed for " << model->get_friendly_name();++ std::vector<float> output_f32(element_count);+ const auto* src = outputs[0].data<ov::float16>();+ for (size_t i = 0; i < element_count; ++i) {+ output_f32[i] = static_cast<float>(src[i]);+ }++ return compute_metrics(input_data, output_f32.data(), element_count);+}++// ============================================================================+// Helper: run split quantize -> dequantize pipeline via the reference+// interpreter. Executes two separate model->evaluate() calls, passing+// intermediate tensors (q, scale, zp) from the quantize model to the+// dequantize model -- exactly as the real NPU pipeline does.+// ============================================================================+AccuracyMetrics evaluate_split_roundtrip(const std::shared_ptr<Model>& quant_model,+ const std::shared_ptr<Model>& dequant_model,+ const float* input_data,+ size_t element_count) {+ // Step 1: run quantize model+ auto quant_input = Tensor(element::f16, quant_model->get_parameters()[0]->get_shape());+ auto* q_dst = quant_input.data<ov::float16>();+ for (size_t i = 0; i < element_count; ++i) {+ q_dst[i] = ov::float16(input_data[i]);+ }++ TensorVector quant_outputs;+ for (size_t i = 0; i < quant_model->get_results().size(); ++i) {+ const auto& res = quant_model->get_results()[i];+ quant_outputs.emplace_back(res->get_output_element_type(0), res->get_output_shape(0));+ }++ TensorVector quant_inputs{quant_input};+ bool ok = quant_model->evaluate(quant_outputs, quant_inputs);+ EXPECT_TRUE(ok) << "Quantize model evaluation failed";++ // Step 2: run dequantize model+ // Pass all quantize outputs as dequantize inputs (2 for symmetric, 3 for asymmetric).+ TensorVector dequant_inputs(quant_outputs.begin(), quant_outputs.end());++ auto dequant_output = Tensor(element::f16, dequant_model->get_results()[0]->get_output_shape(0));+ TensorVector dequant_outputs{dequant_output};++ ok = dequant_model->evaluate(dequant_outputs, dequant_inputs);+ EXPECT_TRUE(ok) << "Dequantize model evaluation failed";++ std::vector<float> output_f32(element_count);+ const auto* src = dequant_outputs[0].data<ov::float16>();+ for (size_t i = 0; i < element_count; ++i) {+ output_f32[i] = static_cast<float>(src[i]);+ }++ return compute_metrics(input_data, output_f32.data(), element_count);+}++// ============================================================================+// Helper: run split quantize -> dequantize pipeline on a real device.+// Compiles and infers each model separately, passing intermediate tensors.+// ============================================================================+AccuracyMetrics evaluate_split_roundtrip_on_device(const std::shared_ptr<Model>& quant_model,+ const std::shared_ptr<Model>& dequant_model,+ const std::string& device_name,+ const float* input_data,+ size_t element_count) {+ Core core;+ ov::AnyMap device_config;+ if (device_name == "NPU") {+ device_config[ov::intel_npu::compiler_type.name()] = ov::intel_npu::CompilerType::PLUGIN;+ }++ // Step 1: compile and run quantize model+ auto compiled_quant = core.compile_model(quant_model, device_name, device_config);+ auto quant_request = compiled_quant.create_infer_request();++ auto quant_input = Tensor(element::f16, quant_model->get_parameters()[0]->get_shape());+ auto* q_dst = quant_input.data<ov::float16>();+ for (size_t i = 0; i < element_count; ++i) {+ q_dst[i] = ov::float16(input_data[i]);+ }+ quant_request.set_input_tensor(quant_input);+ quant_request.infer();++ auto tensor_q = quant_request.get_output_tensor(0);+ auto tensor_scale = quant_request.get_output_tensor(1);++ // Step 2: compile and run dequantize model+ auto compiled_dequant = core.compile_model(dequant_model, device_name, device_config);+ auto dequant_request = compiled_dequant.create_infer_request();++ dequant_request.set_input_tensor(0, tensor_q);+ dequant_request.set_input_tensor(1, tensor_scale);+ // For asymmetric quantization a ZP tensor exists as the 3rd output/input.+ const bool has_zp = (quant_model->get_results().size() == 3);+ if (has_zp) {+ auto tensor_zp = quant_request.get_output_tensor(2);+ dequant_request.set_input_tensor(2, tensor_zp);+ }+ dequant_request.infer();++ auto output_tensor = dequant_request.get_output_tensor();++ std::vector<float> output_f32(element_count);+ const auto* src = output_tensor.data<ov::float16>();+ for (size_t i = 0; i < element_count; ++i) {+ output_f32[i] = static_cast<float>(src[i]);+ }++ return compute_metrics(input_data, output_f32.data(), element_count);+}+++// ============================================================================+// Helper: get the target device from the environment, empty if not set+// ============================================================================+std::string get_test_device() {+ const char* env = std::getenv("OV_DQ_TEST_DEVICE");+ return env ? std::string(env) : std::string{};+}+++// ============================================================================+// Parameterized test fixture+// ============================================================================+class DynamicQuantizeAccuracyTest : public ::testing::TestWithParam<DQTestParams> {+protected:+ static std::string format_metrics(const AccuracyMetrics& m) {+ std::ostringstream os;+ os << "L2=" << m.l2_norm+ << ", relL2=" << m.rel_l2_norm+ << ", maxAbs=" << m.max_abs_error+ << ", meanAbs=" << m.mean_abs_error;+ return os.str();+ }++ std::vector<float> generate_data(const DQTestParams& p, size_t count) {+ switch (p.dist_kind) {+ case DistributionKind::Uniform:+ return generate_uniform_data(count, p.uniform_min, p.uniform_max, p.seed);+ case DistributionKind::GenGaussian:+ return generate_gen_gaussian_data(count, p.ggd_mu, p.ggd_alpha, p.ggd_beta, p.seed);+ default:+ return {};+ }+ }++ size_t compute_element_count(const Shape& shape) {+ size_t n = 1;+ for (auto d : shape) {+ n *= d;+ }+ return n;+ }++ // Setup for the single fused roundtrip model+ struct TestContext {+ std::shared_ptr<Model> model;+ std::vector<float> data;+ size_t element_count;+ };++ TestContext setup_test() {+ const auto& p = GetParam();+ size_t element_count = compute_element_count(p.shape);+ auto data = generate_data(p, element_count);+ EXPECT_EQ(data.size(), element_count);++ auto model = build_roundtrip_model(p.shape, p);+ model->validate_nodes_and_infer_types();++ return {model, std::move(data), element_count};+ }++ // Setup for the split quantize + dequantize models+ struct SplitTestContext {+ std::shared_ptr<Model> quant_model;+ std::shared_ptr<Model> dequant_model;+ std::vector<float> data;+ size_t element_count;+ };++ SplitTestContext setup_split_test() {+ const auto& p = GetParam();+ size_t element_count = compute_element_count(p.shape);+ auto data = generate_data(p, element_count);+ EXPECT_EQ(data.size(), element_count);++ auto quant_model = build_quantize_model(p.shape, p);+ auto dequant_model = build_dequantize_model(p.shape, p);++ return {quant_model, dequant_model, std::move(data), element_count};+ }+};++// -- Reference interpreter test -- single fused roundtrip (always runs) -------++TEST_P(DynamicQuantizeAccuracyTest, RoundtripAccuracy) {+ auto [model, data, element_count] = setup_test();+ const auto& p = GetParam();++ auto metrics = evaluate_roundtrip(model, data.data(), element_count);++ SCOPED_TRACE("roundtrip metrics: " + format_metrics(metrics));+ EXPECT_LT(metrics.rel_l2_norm, p.threshold)+ << "V" << p.decompose_version << " relative L2 too high";+}++// -- Reference interpreter test -- split quantize + dequantize models ---------+// This matches the real pipeline: two separate models with intermediate+// tensors passed between them.++TEST_P(DynamicQuantizeAccuracyTest, SplitModelRoundtripAccuracy) {+ auto [quant_model, dequant_model, data, element_count] = setup_split_test();+ const auto& p = GetParam();++ auto metrics = evaluate_split_roundtrip(quant_model, dequant_model,+ data.data(), element_count);++ SCOPED_TRACE("split roundtrip metrics: " + format_metrics(metrics));+ EXPECT_LT(metrics.rel_l2_norm, p.threshold)+ << "V" << p.decompose_version << " split model relative L2 too high";+}++// -- Device-based inference test -- split models (opt-in via OV_DQ_TEST_DEVICE)+// Compiles quantize and dequantize models SEPARATELY on the device.+// This catches compilation failures for quantize-only models (which have+// been observed in practice) and measures real device error accumulation.+//+// Run with: OV_DQ_TEST_DEVICE=CPU ./ov_npu_unit_tests --gtest_filter=*DeviceRoundtripAccuracy*+// OV_DQ_TEST_DEVICE=NPU ./ov_npu_unit_tests --gtest_filter=*DeviceRoundtripAccuracy*++TEST_P(DynamicQuantizeAccuracyTest, DeviceRoundtripAccuracy) {+ const std::string device = get_test_device();+ if (device.empty()) {+ GTEST_SKIP() << "OV_DQ_TEST_DEVICE not set -- skipping device inference test";+ }++ auto [quant_model, dequant_model, data, element_count] = setup_split_test();+ const auto& p = GetParam();++ // Reference: interpreter on the split models+ auto ref_metrics = evaluate_split_roundtrip(quant_model, dequant_model,+ data.data(), element_count);++ AccuracyMetrics dev_metrics;+ try {+ dev_metrics = evaluate_split_roundtrip_on_device(quant_model, dequant_model,+ device, data.data(), element_count);+ } catch (const std::exception& e) {+ GTEST_SKIP() << "Device '" << device << "' is not available: " << e.what();+ }++ SCOPED_TRACE("reference metrics: " + format_metrics(ref_metrics));+ SCOPED_TRACE("device metrics: " + format_metrics(dev_metrics));++ EXPECT_LT(dev_metrics.rel_l2_norm, p.threshold)+ << "V" << p.decompose_version << " on " << device << ": relative L2 too high";++ if (ref_metrics.rel_l2_norm > 1e-9) {+ double ratio = dev_metrics.rel_l2_norm / ref_metrics.rel_l2_norm;+ EXPECT_LT(ratio, 4.0)+ << "V" << p.decompose_version << " on " << device+ << ": device accuracy is " << ratio << "x worse than interpreter";+ }+}++// ============================================================================+// Helper functions for concise param construction+// ============================================================================+static std::string get_test_case_name(const ::testing::TestParamInfo<DQTestParams>& info) {+ return make_test_case_name(info.param);+}++// clang-format off+static DQTestParams make_uniform(int version, Shape shape,+ float lo, float hi, unsigned seed) {+ return {version, shape, seed, DistributionKind::Uniform,+ lo, hi, 0.0f, 0.0f, 0.0f};+}++static DQTestParams make_ggd(int version, Shape shape,+ float mu, float alpha, float beta, unsigned seed) {+ return {version, shape, seed, DistributionKind::GenGaussian,+ 0.0f, 0.0f, mu, alpha, beta};+}++// Symmetric i4 factories: decompose_version=1 (V1 now handles i4 via dtype dispatch),+// is_symmetric=true (2 DQ outputs, no ZP), higher threshold (coarser 4-bit grid).+static DQTestParams make_sym_i4_uniform(Shape shape,+ float lo, float hi, unsigned seed) {+ DQTestParams p = make_uniform(1, shape, lo, hi, seed);+ p.quant_dt = element::i4;+ p.is_symmetric = true;+ p.threshold = 0.15; // i4: ±7 levels → higher quantisation error+ return p;+}++static DQTestParams make_sym_i4_ggd(Shape shape,+ float mu, float alpha, float beta, unsigned seed) {+ DQTestParams p = make_ggd(1, shape, mu, alpha, beta, seed);+ p.quant_dt = element::i4;+ p.is_symmetric = true;+ // GGD heavy-tail distributions produce outliers that compress the i4 scale,+ // causing higher quantisation error than uniform data (~0.25 observed).+ p.threshold = 0.40;+ return p;+}+// clang-format on++static std::vector<DQTestParams> make_uniform_cases(int version) {+ return {+ make_uniform(version, {1, 8, 64, 128}, -1.0f, 1.0f, 42),+ make_uniform(version, {1, 8, 64, 128}, -10.0f, 10.0f, 77),+ make_uniform(version, {1, 8, 64, 128}, 0.0f, 5.0f, 999),+ make_uniform(version, {1, 8, 1024, 128}, -3.0f, 3.0f, 314),+ };+}++static std::vector<DQTestParams> make_ggd_cases(int version) {+ return {+ make_ggd(version, {1, 8, 1024, 128}, 0.018f, 1.121f, 0.923f, 42),+ make_ggd(version, {1, 8, 1024, 128}, 0.032f, 1.388f, 1.016f, 77),+ make_ggd(version, {1, 8, 1024, 128}, -0.027f, 1.830f, 1.271f, 123),+ };+}++static std::vector<DQTestParams> make_sym_i4_uniform_cases() {+ return {+ make_sym_i4_uniform({1, 8, 64, 128}, -1.0f, 1.0f, 42),+ make_sym_i4_uniform({1, 8, 64, 128}, -10.0f, 10.0f, 77),+ make_sym_i4_uniform({1, 8, 64, 128}, 0.0f, 5.0f, 999),+ make_sym_i4_uniform({1, 8, 1024, 128}, -3.0f, 3.0f, 314),+ };+}++static std::vector<DQTestParams> make_sym_i4_ggd_cases() {+ return {+ make_sym_i4_ggd({1, 8, 1024, 128}, 0.018f, 1.121f, 0.923f, 42),+ make_sym_i4_ggd({1, 8, 1024, 128}, 0.032f, 1.388f, 1.016f, 77),+ make_sym_i4_ggd({1, 8, 1024, 128}, -0.027f, 1.830f, 1.271f, 123),+ };+}++// ============================================================================+// Test instantiation -- V1: handcrafted symmetric i8 [-127, 127]+// ============================================================================+INSTANTIATE_TEST_SUITE_P(+ V1_Uniform,+ DynamicQuantizeAccuracyTest,+ ::testing::ValuesIn(make_uniform_cases(1)),+ get_test_case_name);++INSTANTIATE_TEST_SUITE_P(+ V1_GenGaussian,+ DynamicQuantizeAccuracyTest,+ ::testing::ValuesIn(make_ggd_cases(1)),+ get_test_case_name);++// ============================================================================+// Test instantiation -- V2: ONNX DynamicQuantizeLinear u8 [0, 255]+// ============================================================================+INSTANTIATE_TEST_SUITE_P(+ V2_Uniform,+ DynamicQuantizeAccuracyTest,+ ::testing::ValuesIn(make_uniform_cases(2)),+ get_test_case_name);++INSTANTIATE_TEST_SUITE_P(+ V2_GenGaussian,+ DynamicQuantizeAccuracyTest,+ ::testing::ValuesIn(make_ggd_cases(2)),+ get_test_case_name);++// ============================================================================+// Test instantiation -- V3: compiler pattern style i8 [-128, 127]+// ============================================================================+INSTANTIATE_TEST_SUITE_P(+ V3_Uniform,+ DynamicQuantizeAccuracyTest,+ ::testing::ValuesIn(make_uniform_cases(3)),+ get_test_case_name);++INSTANTIATE_TEST_SUITE_P(+ V3_GenGaussian,+ DynamicQuantizeAccuracyTest,+ ::testing::ValuesIn(make_ggd_cases(3)),+ get_test_case_name);++// ============================================================================+// Test instantiation -- V1 symmetric i4: handcrafted symmetric i4 [-7, 7]+// ============================================================================+INSTANTIATE_TEST_SUITE_P(+ V1_Symmetric_i4_Uniform,+ DynamicQuantizeAccuracyTest,+ ::testing::ValuesIn(make_sym_i4_uniform_cases()),+ get_test_case_name);++INSTANTIATE_TEST_SUITE_P(+ V1_Symmetric_i4_GenGaussian,+ DynamicQuantizeAccuracyTest,+ ::testing::ValuesIn(make_sym_i4_ggd_cases()),+ get_test_case_name);++// ============================================================================+// Test instantiation -- asymmetric i8 offset distributions for all versions.+//+// V1 coverage additionally exposes the known bug in zero-point computation:+// zp = 0 / scale (always zero)+// which causes clipping for shifted distributions (min/max away from zero).+// This can fail until V1 formula is corrected to use -min/scale.+// ============================================================================+static std::vector<DQTestParams> make_asym_i8_offset_cases() {+ static constexpr std::array<int, 3> versions = {1, 2, 3};++ std::vector<DQTestParams> cases;+ cases.reserve(versions.size() * 3u);++ for (const int version : versions) {+ cases.push_back(make_uniform(version, {1, 8, 64, 128}, 0.5f, 5.0f, 42));+ cases.push_back(make_uniform(version, {1, 8, 64, 128}, 1.0f, 5.0f, 77));+ cases.push_back(make_uniform(version, {1, 8, 64, 128}, -5.0f, -0.5f, 99));+ }++ return cases;+}++INSTANTIATE_TEST_SUITE_P(+ Asymmetric_i8_OffsetCoverage,+ DynamicQuantizeAccuracyTest,+ ::testing::ValuesIn(make_asym_i8_offset_cases()),+ get_test_case_name);++} // namespacediff --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 b2b8179ae12..f949403b981 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@@ -13,6 +13,8 @@#include "compiled_model.hpp"#include "llm_compiled_model.hpp"#include "model_builder.hpp"+#include "openvino/op/fake_convert.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"#include "openvino/runtime/iplugin.hpp"#include "serialization.hpp"#include "weights_bank.hpp"@@ -36,6 +38,34 @@ inline std::shared_ptr<ov::Model> build_llm_test_model() {return mb.build_llm(make_test_model_config());}+inline std::shared_ptr<ov::Model> build_llm_test_model_with_kv_fake_convert(const ov::element::Type fake_convert_type) {+ auto model = build_llm_test_model();+ auto scale = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {1.0f});++ for (const auto& op : model->get_ordered_ops()) {+ auto sdpa = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(op);+ if (!sdpa) {+ continue;+ }++ auto inject_fake_convert = [&](size_t input_idx, const std::string& suffix) {+ auto fake_convert_1 =+ std::make_shared<ov::op::v13::FakeConvert>(sdpa->input_value(input_idx), scale, fake_convert_type);+ auto fake_convert_2 =+ std::make_shared<ov::op::v13::FakeConvert>(fake_convert_1, scale, fake_convert_type);+ fake_convert_1->set_friendly_name(sdpa->get_friendly_name() + "/" + suffix + "_1");+ fake_convert_2->set_friendly_name(sdpa->get_friendly_name() + "/" + suffix + "_2");+ sdpa->input(input_idx).replace_source_output(fake_convert_2);+ };++ inject_fake_convert(1, "key_fake_convert");+ inject_fake_convert(2, "value_fake_convert");+ }++ model->validate_nodes_and_infer_types();+ return model;+}+inline std::shared_ptr<ov::Model> build_whisper_decoder_test_model() {ModelBuilder mb;return mb.build_whisper_decoder(make_test_model_config<WhisperConfig>());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 1b7855db99e..b894dac24b9 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@@ -4,10 +4,12 @@#include <gtest/gtest.h>+#include <map>#include <sstream>#include <string>#include "llm_pass_test_fixture.hpp"+#include "../util.hpp"#include "openvino/runtime/properties.hpp"// --- Design note -------------------------------------------------------------------------@@ -22,8 +24,231 @@ namespace {using ov::test::npuw::RecordingFactory;+bool any_name_contains(const ov::Output<const ov::Node>& port, std::string_view needle) {+ for (const auto& name : port.get_names()) {+ if (name.find(needle) != std::string::npos) {+ return true;+ }+ }+ return false;+}++const std::map<ov::element::Type, std::map<std::string, ov::element::Type>>& precision_key_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}}},+ {ov::element::i8, {{"value", ov::element::i8}, {"scale", ov::element::f32}, {"zero_point", ov::element::i8}}}+ };+ return matrix;+}++const std::map<ov::element::Type, std::map<std::string, ov::element::Type>>& precision_value_matrix() {+ static const std::map<ov::element::Type, std::map<std::string, ov::element::Type>> matrix = {+ {ov::element::u8, {{"value", ov::element::i8}, {"scale", ov::element::f32}}},+ {ov::element::i8, {{"value", ov::element::i8}, {"scale", ov::element::f32}}}+ };+ return matrix;+}++bool is_quantized_kv_type(const ov::element::Type kv_type) {+ return precision_key_matrix().count(kv_type) > 0;+}++bool is_fp8_kv_type(const ov::element::Type kv_type) {+ return kv_type == ov::element::f8e4m3 || kv_type == ov::element::f8e5m2 || kv_type == ov::element::f8e8m0;+}++ov::AnyMap make_kv_precision_props(const ov::element::Type kv_type) {+ ov::AnyMap props = {{ov::hint::kv_cache_precision.name(), kv_type}};+ if (is_fp8_kv_type(kv_type)) {+ props["NPUW_LLM_OPTIMIZE_FP8"] = "YES";+ }+ return props;+}++void expect_kv_cache_input_types(const std::shared_ptr<ov::Model>& model, const ov::element::Type kv_type) {+ // 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";++ bool found_key_cache_input = false;+ bool found_value_cache_input = false;+ bool found_key_scale_input = false;+ bool found_key_zp_input = false;+ bool found_value_scale_input = false;+ bool found_value_zp_input = false;++ for (const auto& input : model->inputs()) {+ // Check if any name on this input matches past_key_values pattern+ bool is_past_key = false;+ bool is_past_value = false;+ for (const auto& name : input.get_names()) {+ if (!is_past_key && ov::npuw::util::isPastKeyValuesKey(name).has_value()) {+ is_past_key = true;+ }+ if (!is_past_value && ov::npuw::util::isPastKeyValuesValue(name).has_value()) {+ is_past_value = true;+ }+ }++ if (is_past_key) {+ found_key_cache_input = true;+ const auto expected = is_quantized ? precision_key_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;+ }++ 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;+ }++ if (any_name_contains(input, past_key_scale_name)) {+ found_key_scale_input = true;+ const auto expected = precision_key_matrix().at(kv_type).at("scale");+ EXPECT_EQ(input.get_element_type(), expected)+ << "past_key scale input must have type " << expected;+ }++ if (any_name_contains(input, past_key_zp_name)) {+ found_key_zp_input = true;+ const auto expected = precision_key_matrix().at(kv_type).at("zero_point");+ EXPECT_EQ(input.get_element_type(), expected)+ << "past_key zero-point input must have type " << expected;+ }++ if (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 (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";++ 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 {+ 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";+ EXPECT_FALSE(found_value_zp_input) << "Non-quantized KV-cache must not expose value zero-point input";+ }+}++void expect_kv_cache_present_output_types(const std::shared_ptr<ov::Model>& model, const ov::element::Type kv_type) {+ 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";++ bool found_present_key = false;+ bool found_present_value = false;+ bool found_present_key_scale = false;+ bool found_present_key_zp = false;+ bool found_present_value_scale = false;+ bool found_present_value_zp = false;++ for (const auto& output : model->outputs()) {+ // Check if any name on this output matches present pattern+ bool is_present_key = false;+ bool is_present_value = false;+ for (const auto& name : output.get_names()) {+ if (!is_present_key && ov::npuw::util::isPresentKeyValuesKey(name).has_value()) {+ is_present_key = true;+ }+ if (!is_present_value && ov::npuw::util::isPresentKeyValuesValue(name).has_value()) {+ is_present_value = true;+ }+ }++ if (is_present_key) {+ found_present_key = true;+ const auto expected = is_quantized ? precision_key_matrix().at(kv_type).at("value") : kv_type;+ EXPECT_EQ(output.get_element_type(), expected)+ << "present.<N>.key 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;+ }++ if (any_name_contains(output, present_key_scale_name)) {+ found_present_key_scale = true;+ const auto expected = precision_key_matrix().at(kv_type).at("scale");+ EXPECT_EQ(output.get_element_type(), expected)+ << "present key scale output must have type " << expected;+ }++ if (any_name_contains(output, present_key_zp_name)) {+ found_present_key_zp = true;+ const auto expected = precision_key_matrix().at(kv_type).at("zero_point");+ EXPECT_EQ(output.get_element_type(), expected)+ << "present key zero-point output must have type " << expected;+ }++ if (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 (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";++ 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 {+ 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";+ EXPECT_FALSE(found_present_value_zp)+ << "Non-quantized KV-cache must not expose present value zero-point output";+ }+}+// --- Parametrized fixture --------------------------------------------------------------------------// Parametrized over ov::element::Type so that f16, f8e4m3, and f8e5m2 are each+// Parametrized over ov::element::Type so that f16, f8e4m3, f8e5m2, i8, and u8 are each// exercised in exactly the same test bodies.class ConvertKVCacheHintPrecisionTest : public ov::test::npuw::LLMPassTestFixture,@@ -32,7 +257,11 @@ class ConvertKVCacheHintPrecisionTest : public ov::test::npuw::LLMPassTestFixturINSTANTIATE_TEST_SUITE_P(KVCachePrecisions,ConvertKVCacheHintPrecisionTest,- ::testing::Values(ov::element::f16, ov::element::f8e4m3, ov::element::f8e5m2),+ ::testing::Values(ov::element::f16,+ ov::element::f8e4m3,+ ov::element::f8e5m2,+ ov::element::i8,+ ov::element::u8),[](const ::testing::TestParamInfo<ov::element::Type>& info) -> std::string {std::ostringstream ss;ss << info.param;@@ -45,14 +274,11 @@ TEST_P(ConvertKVCacheHintPrecisionTest, GenerateModelPastKeyInputsHaveExpectedPrRecordingFactory recorder;std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;- ASSERT_NO_THROW(compiled = create_compiled_model(- {{ov::hint::kv_cache_precision.name(), kv_type}}, recorder));+ 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");- EXPECT_TRUE(all_inputs_with_name_have_type(generate.model, "past_key", kv_type))- << "past_key inputs must have type " << kv_type;+ expect_kv_cache_input_types(generate.model, kv_type);}// present outputs of the generate model have the requested precision.@@ -61,14 +287,12 @@ TEST_P(ConvertKVCacheHintPrecisionTest, GenerateModelPresentOutputsHaveExpectedPRecordingFactory recorder;std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;- ASSERT_NO_THROW(compiled = create_compiled_model(- {{ov::hint::kv_cache_precision.name(), kv_type}}, recorder));+ 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");- EXPECT_TRUE(all_outputs_with_name_have_type(generate.model, "present", kv_type))- << "present outputs must have type " << kv_type;+ expect_kv_cache_present_output_types(generate.model, kv_type);}// present outputs of the prefill model have the requested precision.@@ -77,20 +301,65 @@ TEST_P(ConvertKVCacheHintPrecisionTest, PrefillModelPresentOutputsHaveExpectedPrRecordingFactory recorder;std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;- ASSERT_NO_THROW(compiled = create_compiled_model(- {{ov::hint::kv_cache_precision.name(), kv_type}}, recorder));+ ASSERT_NO_THROW(compiled = create_compiled_model(make_kv_precision_props(kv_type), recorder));ASSERT_NE(compiled, nullptr);const auto& prefill = require_sub_model(recorder, "_prefill");- EXPECT_TRUE(all_outputs_with_name_have_type(prefill.model, "present", kv_type))- << "present outputs in the prefill model must have type " << kv_type;+ expect_kv_cache_present_output_types(prefill.model, kv_type);}+// --- Non-parametric tests -------------------------------------------------------------------------class ConvertKVCacheToPrecisionPassTest : public ov::test::npuw::LLMPassTestFixture {};+// 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.+// Uses non chunked prefill so the pipeline also tests the RedirectNewKvToOutput path (no down-up-proj needed).+TEST_F(ConvertKVCacheToPrecisionPassTest, OptimizeFp8ConsecutiveFakeConvertsKvCacheToFp8) {+ for (const auto fp8_type : {ov::element::f8e4m3, ov::element::f8e5m2}) {+ SCOPED_TRACE(std::string("optimize_fp8 type=") + fp8_type.get_type_name());++ RecordingFactory recorder;+ auto model = ov::test::npuw::build_llm_test_model_with_kv_fake_convert(fp8_type);+ std::unique_ptr<ov::npuw::LLMCompiledModel> compiled;+ try {+ compiled = create_compiled_model(model,+ {{"NPUW_LLM_OPTIMIZE_FP8", "YES"},+ {"NPUW_LLM_PREFILL_HINT", "DYNAMIC"},+ {"NPUW_LLM_PREFILL_CHUNK_SIZE", "32"}},+ recorder);+ } catch (const std::exception& ex) {+ FAIL() << "create_compiled_model failed with exception: " << ex.what();+ } catch (...) {+ FAIL() << "create_compiled_model failed with a non-std exception";+ }+ ASSERT_NE(compiled, nullptr);++ const auto& generate = require_sub_model_containing(recorder, "_kv");+ const auto& prefill = require_sub_model(recorder, "_prefill");++ expect_kv_cache_input_types(generate.model, fp8_type);+ expect_kv_cache_present_output_types(generate.model, fp8_type);+ expect_kv_cache_present_output_types(prefill.model, fp8_type);+ }+}++// NPUW_LLM_OPTIMIZE_FP8 should leave KV cache in f16 when the model has no suitable FakeConvert pattern.+TEST_F(ConvertKVCacheToPrecisionPassTest, OptimizeFp8WithPlainModelKeepsF16KvCache) {+ RecordingFactory recorder;+ ASSERT_NO_THROW(create_compiled_model({{"NPUW_LLM_OPTIMIZE_FP8", "YES"}}, recorder));++ const auto& generate = require_sub_model_containing(recorder, "_kv");+ const auto& prefill = require_sub_model(recorder, "_prefill");++ expect_kv_cache_input_types(generate.model, ov::element::f16);+ expect_kv_cache_present_output_types(generate.model, ov::element::f16);+ expect_kv_cache_present_output_types(prefill.model, ov::element::f16);+}++// Chunked-prefill: past_key inputs of the prefill model are converted to f16.TEST_F(ConvertKVCacheToPrecisionPassTest, ChunkedPrefillModelPastKeyInputsAreF16) {RecordingFactory recorder;diff --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.cppnew file mode 100644index 00000000000..db390969039--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/kv_cache_compression_pass_test.cpp@@ -0,0 +1,926 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Unit tests for run_kv_cache_dynamic_quantization_passes().+//+// Each test builds a synthetic SDPA model, runs the compression pass, and+// verifies the structural outcome (param/result counts, absence of internal+// DynamicQuantize ops after decomposition). Parametrized over:+// - num_sdpa: 1 (single head) or 3 (multi-head)+// - quant_type: Asymmetric (adds scale + zp) or Symmetric (scale only)+// - quant_dt: u8 / i8+//+// Model structure per SDPA block N:+//+// Parameters:+// past_key_values.N.key [1,H,Spast,D] ---++// new_key.N [1,H,1,D] +-- Concat(axis=2) --> MatMul1(Q, K^T)+// |+// query.N [1,H,1,D] -----------------------------|+// mask.N [1,1,1,Spast+1] --> Add --> Softmax --> MatMul2+// |+// past_key_values.N.value [1,H,D,Spast] ---+ |+// new_value.N [1,H,D,1] +-- Concat(axis=3) -------|+//+// Results:+// present.N.key = concat_key (DynamicQuantize inserted here)+// present.N.value = concat_value (DynamicQuantize inserted here)+// attn_out.N = MatMul2 output++#include <gtest/gtest.h>++#include <cmath>+#include <random>+#include <regex>+#include <unordered_map>++#include "npuw_transformations/kv_cache_compressed.hpp"+#include "openvino/core/preprocess/pre_post_process.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/softmax.hpp"+#include "openvino/openvino.hpp"+#include "ov_ops/dynamic_quantize.hpp"++namespace {++using namespace ov;++std::shared_ptr<Model> apply_kv_cache_io_precision_for_test(const std::shared_ptr<Model>& model,+ const element::Type key_type,+ const element::Type value_type) {+ ov::preprocess::PrePostProcessor ppp(model);+ const std::regex past_key_re(R"(past_key_values\.\d+\.key)");+ const std::regex past_value_re(R"(past_key_values\.\d+\.value)");+ const std::regex present_key_re(R"(present\.\d+\.key)");+ const std::regex present_value_re(R"(present\.\d+\.value)");++ for (const auto& tensor : model->inputs()) {+ const auto& name = tensor.get_any_name();+ if (std::regex_match(name, past_key_re)) {+ ppp.input(name).tensor().set_element_type(key_type);+ } else if (std::regex_match(name, past_value_re)) {+ ppp.input(name).tensor().set_element_type(value_type);+ }+ }++ for (const auto& tensor : model->outputs()) {+ const auto& name = tensor.get_any_name();+ if (std::regex_match(name, present_key_re)) {+ ppp.output(name).tensor().set_element_type(key_type);+ } else if (std::regex_match(name, present_value_re)) {+ ppp.output(name).tensor().set_element_type(value_type);+ }+ }++ return ppp.build();+}++// ============================================================================+// Model builder+// ============================================================================++std::shared_ptr<Model> build_sdpa_model(size_t num_sdpa) {+ // [batch, heads, seq_past, head_dim]+ const Shape past_shape = {1, 4, 8, 64};+ const Shape new_token_shape = {1, 4, 1, 64};+ const Shape mask_shape = {1, 1, 1, 9}; // broadcastable over [1,4,1,9]++ ParameterVector params;+ ResultVector results;++ for (size_t n = 0; n < num_sdpa; ++n) {+ const std::string idx = std::to_string(n);++ auto make_param = [&](const std::string& name, const Shape& shape) {+ auto p = std::make_shared<op::v0::Parameter>(element::f32, shape);+ p->set_friendly_name(name);+ p->output(0).get_tensor().set_names({name});+ params.push_back(p);+ return p;+ };++ auto past_key = make_param("past_key_values." + idx + ".key", past_shape);+ auto past_val = make_param("past_key_values." + idx + ".value", past_shape);+ auto query = make_param("query." + idx, new_token_shape);+ auto new_key = make_param("new_key." + idx, new_token_shape);+ auto new_val = make_param("new_value." + idx, new_token_shape);+ auto mask = make_param("mask." + idx, mask_shape);++ // Build SDPA: Q @ K^T -> Add(mask) -> Softmax -> @ V+ auto concat_key = std::make_shared<op::v0::Concat>(OutputVector{past_key, new_key}, 2);+ auto concat_val = std::make_shared<op::v0::Concat>(OutputVector{past_val, new_val}, 2);++ auto qk = std::make_shared<op::v0::MatMul>(query, concat_key, false, true);+ auto add = std::make_shared<op::v1::Add>(qk->output(0), mask->output(0));+ auto softmax = std::make_shared<op::v8::Softmax>(add->output(0), 3);+ auto attn_out = std::make_shared<op::v0::MatMul>(softmax->output(0), concat_val->output(0));++ auto make_result = [&](Output<Node> out, const std::string& name) {+ auto r = std::make_shared<op::v0::Result>(out);+ r->set_friendly_name(name);+ r->output(0).get_tensor().set_names({name});+ results.push_back(r);+ };++ make_result(concat_key->output(0), "present." + idx + ".key");+ make_result(concat_val->output(0), "present." + idx + ".value");+ make_result(attn_out->output(0), "attn_out." + idx);+ }++ auto model = std::make_shared<Model>(results, params, "sdpa_test_" + std::to_string(num_sdpa));+ model->validate_nodes_and_infer_types();+ return model;+}++std::shared_ptr<Model> build_sdpa_model_with_hanging_past_consumers() {+ // [batch, heads, seq_past, head_dim]+ const Shape past_shape = {1, 4, 8, 64};+ const Shape new_token_shape = {1, 4, 1, 64};+ const Shape mask_shape = {1, 1, 1, 9};++ ParameterVector params;+ ResultVector results;++ auto make_param = [&](const std::string& name, const Shape& shape) {+ auto p = std::make_shared<op::v0::Parameter>(element::f32, shape);+ p->set_friendly_name(name);+ p->output(0).get_tensor().set_names({name});+ params.push_back(p);+ return p;+ };++ auto make_result = [&](Output<Node> out, const std::string& name) {+ auto r = std::make_shared<op::v0::Result>(out);+ r->set_friendly_name(name);+ r->output(0).get_tensor().set_names({name});+ results.push_back(r);+ };++ auto past_key = make_param("past_key_values.0.key", past_shape);+ auto past_val = make_param("past_key_values.0.value", past_shape);+ auto query = make_param("query.0", new_token_shape);+ auto new_key = make_param("new_key.0", new_token_shape);+ auto new_val = make_param("new_value.0", new_token_shape);+ auto mask = make_param("mask.0", mask_shape);++ auto concat_key = std::make_shared<op::v0::Concat>(OutputVector{past_key, new_key}, 2);+ auto concat_val = std::make_shared<op::v0::Concat>(OutputVector{past_val, new_val}, 2);++ auto qk = std::make_shared<op::v0::MatMul>(query, concat_key, false, true);+ auto add = std::make_shared<op::v1::Add>(qk->output(0), mask->output(0));+ auto softmax = std::make_shared<op::v8::Softmax>(add->output(0), 3);+ auto attn_out = std::make_shared<op::v0::MatMul>(softmax->output(0), concat_val->output(0));++ // Extra non-concat consumers that must keep reading from original past cache params.+ auto key_shapeof = std::make_shared<op::v3::ShapeOf>(past_key);+ key_shapeof->set_friendly_name("past_key_values.0.key.shapeof");+ auto val_shapeof = std::make_shared<op::v3::ShapeOf>(past_val);+ val_shapeof->set_friendly_name("past_key_values.0.value.shapeof");++ make_result(concat_key->output(0), "present.0.key");+ make_result(concat_val->output(0), "present.0.value");+ make_result(attn_out->output(0), "attn_out.0");+ make_result(key_shapeof->output(0), "past_key_shapeof.0");+ make_result(val_shapeof->output(0), "past_value_shapeof.0");++ auto model = std::make_shared<Model>(results, params, "sdpa_hanging_consumers_test");+ model->validate_nodes_and_infer_types();+ return model;+}++bool has_dynamic_quantize_ops(const std::shared_ptr<Model>& model) {+ for (const auto& op : model->get_ordered_ops()) {+ if (ov::is_type<ov::op::internal::DynamicQuantize>(op)) {+ return true;+ }+ }+ return false;+}++// ============================================================================+// Test parameters+// ============================================================================++using QuantizationType = ov::npuw::KVCacheCompressionConfig::QuantizationType;++struct CompressionPassParams {+ std::string name;+ size_t num_sdpa;+ QuantizationType quant_type;+ element::Type quant_dt;+ // Expected newly-added params/results per single cache tensor (key or value):+ // Asymmetric: scale + zp = 2+ // Symmetric: scale = 1+ size_t added_per_cache;+};++std::ostream& operator<<(std::ostream& os, const CompressionPassParams& p) {+ return os << p.name;+}++class KVCacheCompressionPassTest : public ::testing::TestWithParam<CompressionPassParams> {+protected:+ ov::npuw::KVCacheCompressionParams make_compression_params(const CompressionPassParams& p) const {+ ov::npuw::KVCacheCompressionParams cp;+ cp.key = {p.quant_type, p.quant_dt};+ cp.value = {p.quant_type, p.quant_dt};+ return cp;+ }+};++// ============================================================================+// Tests+// ============================================================================++// The model must still pass type-inference after the pass.+TEST_P(KVCacheCompressionPassTest, ModelValidAfterPass) {+ const auto& p = GetParam();+ auto model = build_sdpa_model(p.num_sdpa);++ ASSERT_NO_THROW(ov::npuw::run_kv_cache_dynamic_quantization_passes(model, make_compression_params(p)));+ EXPECT_NO_THROW(model->validate_nodes_and_infer_types());+}++// 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) {+ const auto& p = GetParam();+ auto model = build_sdpa_model(p.num_sdpa);+ const size_t params_before = model->get_parameters().size();+ // 2 caches (key + value) per SDPA, each getting added_per_cache new params+ const size_t expected_new = p.num_sdpa * 2 * p.added_per_cache;++ ASSERT_NO_THROW(ov::npuw::run_kv_cache_dynamic_quantization_passes(model, make_compression_params(p)));+ EXPECT_EQ(model->get_parameters().size(), params_before + expected_new);+}++// The pass must add exactly (num_sdpa * 2 * added_per_cache) new Results+// (scale + optionally zp, for both key and value present outputs).+TEST_P(KVCacheCompressionPassTest, ResultCountIncreasedCorrectly) {+ const auto& p = GetParam();+ auto model = build_sdpa_model(p.num_sdpa);+ const size_t results_before = model->get_results().size();+ const size_t expected_new = p.num_sdpa * 2 * p.added_per_cache;++ ASSERT_NO_THROW(ov::npuw::run_kv_cache_dynamic_quantization_passes(model, make_compression_params(p)));+ EXPECT_EQ(model->get_results().size(), results_before + expected_new);+}++// All DynamicQuantize internal ops must be decomposed away by the end of the pass.+TEST_P(KVCacheCompressionPassTest, NoDynamicQuantizeOpsInDecomposedModel) {+ const auto& p = GetParam();+ auto model = build_sdpa_model(p.num_sdpa);++ ASSERT_NO_THROW(ov::npuw::run_kv_cache_dynamic_quantization_passes(model, make_compression_params(p)));+ EXPECT_FALSE(has_dynamic_quantize_ops(model));+}++// The present.N.key and present.N.value results must produce a quantized+// (non-floating-point) element type after the pass.+TEST_P(KVCacheCompressionPassTest, PresentCacheOutputIsQuantizedType) {+ const auto& p = GetParam();+ auto model = build_sdpa_model(p.num_sdpa);++ ASSERT_NO_THROW(ov::npuw::run_kv_cache_dynamic_quantization_passes(model, make_compression_params(p)));+ ASSERT_NO_THROW(model->validate_nodes_and_infer_types());++ for (const auto& result : model->get_results()) {+ const auto& name = result->get_friendly_name();+ // Only check the main quantized cache outputs; skip scale/zp results+ const bool is_main_cache = (name.find("present.") != std::string::npos) &&+ (name.find("/scale") == std::string::npos) &&+ (name.find("/zp") == std::string::npos);+ if (!is_main_cache) continue;++ const auto type = result->get_input_element_type(0);+ EXPECT_TRUE(type.is_integral())+ << "Present cache result '" << name << "' should be an integer (quantized) type, got "+ << type;+ }+}++// With identity dequant parameters (scale=1, zp=0) the transformed model's+// attn_out must match the reference model's attn_out to within floating-point+// rounding tolerance.+TEST_P(KVCacheCompressionPassTest, AttnOutputMatchesWithIdentityDequant) {+ const auto& p = GetParam();++ auto ref_model = build_sdpa_model(p.num_sdpa);+ auto xform_model = build_sdpa_model(p.num_sdpa);++ ASSERT_NO_THROW(ov::npuw::run_kv_cache_dynamic_quantization_passes(+ xform_model, make_compression_params(p)));+ ASSERT_NO_THROW(xform_model->validate_nodes_and_infer_types());++ std::mt19937 rng(42);+ std::uniform_real_distribution<float> dist(-1.0f, 1.0f);++ std::unordered_map<std::string, Tensor> orig_inputs;+ for (const auto& param : ref_model->get_parameters()) {+ Tensor t(element::f32, param->get_shape());+ auto* d = t.data<float>();+ for (size_t i = 0; i < t.get_size(); ++i) d[i] = dist(rng);+ orig_inputs[param->get_friendly_name()] = t;+ }++ TensorVector ref_inputs;+ for (const auto& param : ref_model->get_parameters()) {+ ref_inputs.push_back(orig_inputs.at(param->get_friendly_name()));+ }++ TensorVector xform_inputs;+ for (const auto& param : xform_model->get_parameters()) {+ auto it = orig_inputs.find(param->get_friendly_name());+ if (it != orig_inputs.end()) {+ xform_inputs.push_back(it->second);+ } else {+ // New scale/zp params: scale=1, zp=0 -> identity dequant+ Tensor t(param->get_element_type(), param->get_shape());+ if (param->get_element_type() == element::f32)+ std::fill_n(t.data<float>(), t.get_size(), 1.0f);+ else+ std::fill_n(t.data<uint8_t>(), t.get_size(), uint8_t(0));+ xform_inputs.push_back(t);+ }+ }++ auto make_output_tensors = [](const std::shared_ptr<Model>& m) {+ TensorVector outs;+ for (const auto& res : m->get_results())+ outs.emplace_back(res->get_output_element_type(0), res->get_output_shape(0));+ return outs;+ };++ auto ref_outputs = make_output_tensors(ref_model);+ auto xform_outputs = make_output_tensors(xform_model);++ ASSERT_TRUE(ref_model->evaluate(ref_outputs, ref_inputs));+ ASSERT_TRUE(xform_model->evaluate(xform_outputs, xform_inputs));++ auto index_outputs = [](const std::shared_ptr<Model>& m, const TensorVector& outs) {+ std::unordered_map<std::string, const Tensor*> map;+ for (size_t i = 0; i < m->get_results().size(); ++i)+ map[m->get_results()[i]->get_friendly_name()] = &outs[i];+ return map;+ };++ auto ref_map = index_outputs(ref_model, ref_outputs);+ auto xform_map = index_outputs(xform_model, xform_outputs);++ for (size_t n = 0; n < p.num_sdpa; ++n) {+ const std::string name = "attn_out." + std::to_string(n);+ ASSERT_TRUE(ref_map.count(name)) << "Missing ref result: " << name;+ ASSERT_TRUE(xform_map.count(name)) << "Missing xform result: " << name;++ const auto& ref_t = *ref_map.at(name);+ const auto& xform_t = *xform_map.at(name);+ ASSERT_EQ(ref_t.get_shape(), xform_t.get_shape());+ ASSERT_EQ(ref_t.get_element_type(), element::f32);++ const float* ref_data = ref_t.data<float>();+ const float* xform_data = xform_t.data<float>();+ const size_t count = ref_t.get_size();++ double sum_sq_err = 0.0, sum_sq_orig = 0.0;+ for (size_t i = 0; i < count; ++i) {+ double diff = static_cast<double>(ref_data[i]) - static_cast<double>(xform_data[i]);+ sum_sq_err += diff * diff;+ sum_sq_orig += static_cast<double>(ref_data[i]) * static_cast<double>(ref_data[i]);+ }+ const double rel_l2 = (sum_sq_orig > 1e-12)+ ? std::sqrt(sum_sq_err / sum_sq_orig)+ : std::sqrt(sum_sq_err);+ EXPECT_LT(rel_l2, 1e-5)+ << "attn_out." << n << " diverges with identity dequant (rel L2=" << rel_l2 << ")";+ }+}++TEST(KVCacheCompressionPassRegressionTest, KeepsNonConcatConsumersOnOriginalPastCacheEdges) {+ auto model = build_sdpa_model_with_hanging_past_consumers();++ ov::npuw::KVCacheCompressionParams params;+ params.key = {QuantizationType::Asymmetric, element::u8};+ params.value = {QuantizationType::Asymmetric, element::u8};+ ASSERT_NO_THROW(ov::npuw::run_kv_cache_dynamic_quantization_passes(model, params));+ ASSERT_NO_THROW(model->validate_nodes_and_infer_types());++ auto get_result_by_name = [&model](const std::string& name) -> std::shared_ptr<op::v0::Result> {+ for (const auto& result : model->get_results()) {+ if (result->get_friendly_name() == name) {+ return result;+ }+ }+ return nullptr;+ };++ auto key_shape_res = get_result_by_name("past_key_shapeof.0");+ auto val_shape_res = get_result_by_name("past_value_shapeof.0");+ ASSERT_NE(key_shape_res, nullptr);+ ASSERT_NE(val_shape_res, nullptr);++ auto key_shapeof = ov::as_type_ptr<op::v3::ShapeOf>(key_shape_res->input_value(0).get_node_shared_ptr());+ auto val_shapeof = ov::as_type_ptr<op::v3::ShapeOf>(val_shape_res->input_value(0).get_node_shared_ptr());+ ASSERT_NE(key_shapeof, nullptr) << "past_key_shapeof.0 must be produced by ShapeOf";+ ASSERT_NE(val_shapeof, nullptr) << "past_value_shapeof.0 must be produced by ShapeOf";++ auto key_src = key_shapeof->input_value(0).get_node_shared_ptr();+ auto val_src = val_shapeof->input_value(0).get_node_shared_ptr();++ auto key_param = ov::as_type_ptr<op::v0::Parameter>(key_src);+ auto val_param = ov::as_type_ptr<op::v0::Parameter>(val_src);++ const std::string key_src_name = key_src ? key_src->get_friendly_name() : std::string("<null>");+ const std::string val_src_name = val_src ? val_src->get_friendly_name() : std::string("<null>");++ ASSERT_TRUE(key_param != nullptr)+ << "ShapeOf(past_key) must stay connected to original past_key parameter, got node '"+ << key_src_name << "'";+ ASSERT_TRUE(val_param != nullptr)+ << "ShapeOf(past_value) must stay connected to original past_value parameter, got node '"+ << val_src_name << "'";++ EXPECT_EQ(key_param->get_friendly_name(), "past_key_values.0.key");+ EXPECT_EQ(val_param->get_friendly_name(), "past_key_values.0.value");+}++// ============================================================================+// Instantiation+// ============================================================================++INSTANTIATE_TEST_SUITE_P(+ SingleSdpa,+ KVCacheCompressionPassTest,+ ::testing::Values(+ CompressionPassParams{"SingleSdpa_Asymmetric_u8",+ 1, QuantizationType::Asymmetric, element::u8, 2},+ CompressionPassParams{"SingleSdpa_Symmetric_i8",+ 1, QuantizationType::Symmetric, element::i8, 1},+ CompressionPassParams{"SingleSdpa_Symmetric_i4",+ 1, QuantizationType::Symmetric, element::i4, 1}+ ),+ [](const ::testing::TestParamInfo<CompressionPassParams>& info) { return info.param.name; }+);++INSTANTIATE_TEST_SUITE_P(+ MultiSdpa,+ KVCacheCompressionPassTest,+ ::testing::Values(+ CompressionPassParams{"ThreeSdpa_Asymmetric_u8",+ 3, QuantizationType::Asymmetric, element::u8, 2},+ CompressionPassParams{"ThreeSdpa_Symmetric_i8",+ 3, QuantizationType::Symmetric, element::i8, 1},+ CompressionPassParams{"ThreeSdpa_Symmetric_i4",+ 3, QuantizationType::Symmetric, element::i4, 1}+ ),+ [](const ::testing::TestParamInfo<CompressionPassParams>& info) { return info.param.name; }+);++// ============================================================================+// Multi-step decode simulation+// ============================================================================++// Single-head SDPA model (H=1) with a fixed past window of `window` tokens.+// H=1 keeps each token's data contiguous in memory, enabling simple slicing.+//+// Key layout: {1, 1, seq, D} -- tokens on axis 2, concat on axis 2+// Value layout: {1, 1, D, seq} -- tokens on axis 3, concat on axis 3+// This mirrors the real model where V is transposed for MatMul(attn, V^T).+std::shared_ptr<Model> build_decode_step_model(size_t window) {+ constexpr size_t D = 64;+ const Shape past_key_shape = {1, 1, window, D};+ const Shape past_val_shape = {1, 1, D, window};+ const Shape new_key_shape = {1, 1, 1, D};+ const Shape new_value_shape = {1, 1, D, 1};+ const Shape mask_shape = {1, 1, 1, window + 1};++ ParameterVector params;+ ResultVector results;++ auto make_param = [&](const std::string& n, const Shape& s) {+ auto p = std::make_shared<op::v0::Parameter>(element::f32, s);+ p->set_friendly_name(n);+ p->output(0).get_tensor().set_names({n});+ params.push_back(p);+ return p;+ };+ auto make_result = [&](Output<Node> out, const std::string& n) {+ auto r = std::make_shared<op::v0::Result>(out);+ r->set_friendly_name(n);+ r->output(0).get_tensor().set_names({n});+ results.push_back(r);+ };++ auto past_key = make_param("past_key_values.0.key", past_key_shape);+ auto past_val = make_param("past_key_values.0.value", past_val_shape);+ auto query = make_param("query.0", new_key_shape);+ auto new_key = make_param("new_key.0", new_key_shape);+ auto new_val = make_param("new_value.0", new_value_shape);+ auto mask = make_param("mask.0", mask_shape);++ auto concat_key = std::make_shared<op::v0::Concat>(OutputVector{past_key, new_key}, 2);+ auto concat_val = std::make_shared<op::v0::Concat>(OutputVector{past_val, new_val}, 3);+ auto qk = std::make_shared<op::v0::MatMul>(query, concat_key, false, true);+ auto add_node = std::make_shared<op::v1::Add>(qk->output(0), mask->output(0));+ auto softmax = std::make_shared<op::v8::Softmax>(add_node->output(0), -1);+ auto attn_out = std::make_shared<op::v0::MatMul>(softmax->output(0), concat_val->output(0), false, true);++ make_result(concat_key->output(0), "present.0.key");+ make_result(concat_val->output(0), "present.0.value");+ make_result(attn_out->output(0), "attn_out.0");++ auto m = std::make_shared<Model>(results, params, "decode_step");+ m->validate_nodes_and_infer_types();+ return m;+}++// Cast every element of a quantised tensor to float (integer value preserved).+Tensor cast_quant_to_f32(const Tensor& src) {+ Tensor dst(element::f32, src.get_shape());+ float* d = dst.data<float>();+ const size_t n = src.get_size();+ const auto et = src.get_element_type();+ if (et == element::u8) {+ const uint8_t* s = src.data<uint8_t>();+ for (size_t i = 0; i < n; ++i) d[i] = float(s[i]);+ } else if (et == element::i8) {+ const int8_t* s = src.data<int8_t>();+ for (size_t i = 0; i < n; ++i) d[i] = float(s[i]);+ } else if (et == element::i4) {+ const uint8_t* s = static_cast<const uint8_t*>(src.data());+ for (size_t i = 0; i < n; ++i) {+ const uint8_t byte = s[i / 2];+ int val = (i % 2 == 0) ? (byte & 0x0F) : ((byte >> 4) & 0x0F);+ if (val > 7) val -= 16;+ d[i] = float(val);+ }+ } else {+ ADD_FAILURE() << "cast_quant_to_f32: unsupported element type " << et;+ throw std::runtime_error("Unsupported element type");+ }+ return dst;+}++// ---------------------------------------------------------------------------+// Key slicing helpers (key layout: {1, 1, seq, D}, tokens on axis 2)+// ---------------------------------------------------------------------------++// Slice last `keep` tokens (rows) from [1, 1, total, D] -- contiguous tail.+template<typename T>+Tensor slice_last_tokens_h1(const Tensor& src, size_t keep) {+ const size_t total = src.get_shape()[2];+ const size_t D = src.get_shape()[3];+ const size_t off = (total - keep) * D;+ Tensor dst(src.get_element_type(), Shape{1, 1, keep, D});+ const T* sd = src.data<T>();+ std::copy(sd + off, sd + off + keep * D, dst.data<T>());+ return dst;+}++// Slice last `keep` per-token scales from [1, 1, total, 1] f32 tensor.+Tensor slice_last_scales_h1(const Tensor& src, size_t keep) {+ const size_t off = src.get_shape()[2] - keep;+ Tensor dst(element::f32, Shape{1, 1, keep, 1});+ const float* sd = src.data<float>();+ std::copy(sd + off, sd + off + keep, dst.data<float>());+ return dst;+}++// Slice last `keep` per-token zero-points from [1, 1, total, 1] u8 tensor.+Tensor slice_last_zp_h1(const Tensor& src, size_t keep) {+ const size_t off = src.get_shape()[2] - keep;+ Tensor dst(src.get_element_type(), Shape{1, 1, keep, 1});+ const uint8_t* sd = src.data<uint8_t>();+ std::copy(sd + off, sd + off + keep, dst.data<uint8_t>());+ return dst;+}++// ---------------------------------------------------------------------------+// Value slicing helpers (value layout: {1, 1, D, seq}, tokens on axis 3)+// ---------------------------------------------------------------------------++// Slice last `keep` columns from [1, 1, rows, total] -- strided: pick the+// last `keep` elements from each of `rows` rows.+template<typename T>+Tensor slice_last_cols_h1(const Tensor& src, size_t keep) {+ const size_t rows = src.get_shape()[2]; // D+ const size_t total = src.get_shape()[3]; // seq+ const size_t col_off = total - keep;+ Tensor dst(src.get_element_type(), Shape{1, 1, rows, keep});+ const T* sd = src.data<T>();+ T* dd = dst.data<T>();+ for (size_t r = 0; r < rows; ++r) {+ std::copy(sd + r * total + col_off,+ sd + r * total + col_off + keep,+ dd + r * keep);+ }+ return dst;+}++// Slice last `keep` per-channel scales from [1, 1, 1, total] f32 tensor.+Tensor slice_last_scales_col(const Tensor& src, size_t keep) {+ const size_t total = src.get_shape()[3];+ const size_t off = total - keep;+ Tensor dst(element::f32, Shape{1, 1, 1, keep});+ const float* sd = src.data<float>();+ std::copy(sd + off, sd + off + keep, dst.data<float>());+ return dst;+}++// Slice last `keep` per-channel zero-points from [1, 1, 1, total] u8 tensor.+Tensor slice_last_zp_col(const Tensor& src, size_t keep) {+ const size_t total = src.get_shape()[3];+ const size_t off = total - keep;+ Tensor dst(src.get_element_type(), Shape{1, 1, 1, keep});+ const uint8_t* sd = src.data<uint8_t>();+ std::copy(sd + off, sd + off + keep, dst.data<uint8_t>());+ return dst;+}++// Independent key/value quantisation configuration for the decode-loop test.+struct DecodeLoopParams {+ std::string name;+ QuantizationType key_quant_type;+ element::Type key_dt;+ QuantizationType val_quant_type;+ element::Type val_dt;++ ov::npuw::KVCacheCompressionParams to_compression_params() const {+ ov::npuw::KVCacheCompressionParams p;+ p.key = {key_quant_type, key_dt};+ p.value = {val_quant_type, val_dt};+ return p;+ }+};++class KVCacheMultiStepDecodeTest : public ::testing::TestWithParam<DecodeLoopParams> {};++TEST_P(KVCacheMultiStepDecodeTest, TransformedModelIoTypesMatchQuantConfig) {+ const auto& p = GetParam();++ constexpr size_t WINDOW = 2;+ 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()));+ ASSERT_NO_THROW(xform_model->validate_nodes_and_infer_types());++ const bool key_asym = (p.key_quant_type == QuantizationType::Asymmetric);+ const bool val_asym = (p.val_quant_type == QuantizationType::Asymmetric);++ auto expect_param_type = [&](const std::string& name, const element::Type expected) {+ const auto it = std::find_if(xform_model->get_parameters().begin(),+ xform_model->get_parameters().end(),+ [&](const auto& prm) {+ return prm->get_friendly_name() == name;+ });+ ASSERT_NE(it, xform_model->get_parameters().end()) << "Missing parameter: " << name;+ EXPECT_EQ((*it)->get_element_type(), expected)+ << "Parameter '" << name << "' has unexpected type";+ };++ auto expect_param_absent = [&](const std::string& name) {+ const auto it = std::find_if(xform_model->get_parameters().begin(),+ xform_model->get_parameters().end(),+ [&](const auto& prm) {+ return prm->get_friendly_name() == name;+ });+ EXPECT_EQ(it, xform_model->get_parameters().end()) << "Unexpected parameter: " << name;+ };++ auto expect_result_type = [&](const std::string& name, const element::Type expected) {+ const auto it = std::find_if(xform_model->get_results().begin(),+ xform_model->get_results().end(),+ [&](const auto& res) {+ return res->get_friendly_name() == name;+ });+ ASSERT_NE(it, xform_model->get_results().end()) << "Missing result: " << name;+ EXPECT_EQ((*it)->get_input_element_type(0), expected)+ << "Result '" << name << "' has unexpected type";+ };++ auto expect_result_absent = [&](const std::string& name) {+ const auto it = std::find_if(xform_model->get_results().begin(),+ xform_model->get_results().end(),+ [&](const auto& res) {+ return res->get_friendly_name() == name;+ });+ EXPECT_EQ(it, xform_model->get_results().end()) << "Unexpected result: " << name;+ };++ expect_param_type("past_key_values.0.key", p.key_dt);+ expect_param_type("past_key_values.0.value", p.val_dt);+ expect_param_type("DynamicQuantize/0/past_key_values/key/scale", element::f32);+ expect_param_type("DynamicQuantize/0/past_key_values/value/scale", element::f32);++ if (key_asym) {+ expect_param_type("DynamicQuantize/0/past_key_values/key/zp", p.key_dt);+ } else {+ expect_param_absent("DynamicQuantize/0/past_key_values/key/zp");+ }+ if (val_asym) {+ expect_param_type("DynamicQuantize/0/past_key_values/value/zp", p.val_dt);+ } else {+ expect_param_absent("DynamicQuantize/0/past_key_values/value/zp");+ }++ expect_result_type("present.0.key", p.key_dt);+ expect_result_type("present.0.value", p.val_dt);+ expect_result_type("DynamicQuantize/0/present/key/scale", element::f32);+ expect_result_type("DynamicQuantize/0/present/value/scale", element::f32);++ if (key_asym) {+ expect_result_type("DynamicQuantize/0/present/key/zp", p.key_dt);+ } else {+ expect_result_absent("DynamicQuantize/0/present/key/zp");+ }+ if (val_asym) {+ expect_result_type("DynamicQuantize/0/present/value/zp", p.val_dt);+ } else {+ expect_result_absent("DynamicQuantize/0/present/value/zp");+ }+}++TEST_P(KVCacheMultiStepDecodeTest, DecodeLoopAccuracy) {+ const auto& p = GetParam();++ constexpr size_t WINDOW = 2;+ constexpr size_t N_STEPS = 3;+ constexpr size_t D = 64;++ const bool key_asym = (p.key_quant_type == QuantizationType::Asymmetric);+ const bool val_asym = (p.val_quant_type == QuantizationType::Asymmetric);++ 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()));+ ASSERT_NO_THROW(xform_model->validate_nodes_and_infer_types());++ std::mt19937 rng(77);+ std::uniform_real_distribution<float> dist(-1.0f, 1.0f);++ auto zero_f32 = [](Shape sh) {+ Tensor t(element::f32, sh); std::fill_n(t.data<float>(), t.get_size(), 0.0f); return t; };+ auto ones_f32 = [](Shape sh) {+ Tensor t(element::f32, sh); std::fill_n(t.data<float>(), t.get_size(), 1.0f); return t; };+ auto zero_u8 = [](Shape sh) {+ Tensor t(element::u8, sh); std::memset(t.data(), 0, t.get_byte_size()); return t; };++ // Key: {1,1,WINDOW,D}, Value: {1,1,D,WINDOW}+ Tensor ref_past_key = zero_f32({1, 1, WINDOW, D});+ Tensor ref_past_val = zero_f32({1, 1, D, WINDOW});++ // Key scale: per-token {1,1,W,1} (reduce axis 3 = D)+ // Value scale: per-channel {1,1,1,W} (reduce axis 2 = D in transposed layout)+ Tensor xf_past_key = zero_f32({1, 1, WINDOW, D});+ Tensor xf_key_scale = ones_f32({1, 1, WINDOW, 1});+ Tensor xf_key_zp = zero_u8({1, 1, WINDOW, 1});+ Tensor xf_past_val = zero_f32({1, 1, D, WINDOW});+ Tensor xf_val_scale = ones_f32({1, 1, 1, WINDOW});+ Tensor xf_val_zp = zero_u8({1, 1, 1, WINDOW});++ // Key: tokens on axis 2 -> slice_last_tokens_h1+ auto slice_and_cast_key = [&](const Tensor& src) -> Tensor {+ const auto et = src.get_element_type();+ if (et == element::u8) return cast_quant_to_f32(slice_last_tokens_h1<uint8_t>(src, WINDOW));+ if (et == element::i8) return cast_quant_to_f32(slice_last_tokens_h1<int8_t> (src, WINDOW));+ return slice_last_tokens_h1<float>(cast_quant_to_f32(src), WINDOW);+ };++ // Value: tokens on axis 3 -> slice_last_cols_h1+ auto slice_and_cast_val = [&](const Tensor& src) -> Tensor {+ const auto et = src.get_element_type();+ if (et == element::u8) return cast_quant_to_f32(slice_last_cols_h1<uint8_t>(src, WINDOW));+ if (et == element::i8) return cast_quant_to_f32(slice_last_cols_h1<int8_t> (src, WINDOW));+ return slice_last_cols_h1<float>(cast_quant_to_f32(src), WINDOW);+ };++ const double tol = (p.key_dt == element::i4 || p.val_dt == element::i4) ? 0.5 : 0.05;++ for (size_t step = 0; step < N_STEPS; ++step) {+ Tensor t_query(element::f32, Shape{1, 1, 1, D});+ Tensor t_new_key(element::f32, Shape{1, 1, 1, D});+ Tensor t_new_val(element::f32, Shape{1, 1, D, 1});+ Tensor t_mask(element::f32, Shape{1, 1, 1, WINDOW + 1});+ for (auto* t : {&t_query, &t_new_key, &t_new_val})+ for (size_t i = 0; i < t->get_size(); ++i) t->data<float>()[i] = dist(rng);+ std::fill_n(t_mask.data<float>(), t_mask.get_size(), 0.0f);++ // -- Reference inference --+ TensorVector ref_inputs;+ for (const auto& param : ref_model->get_parameters()) {+ const std::string& n = param->get_friendly_name();+ if (n == "past_key_values.0.key") ref_inputs.push_back(ref_past_key);+ else if (n == "past_key_values.0.value") ref_inputs.push_back(ref_past_val);+ else if (n == "query.0") ref_inputs.push_back(t_query);+ else if (n == "new_key.0") ref_inputs.push_back(t_new_key);+ else if (n == "new_value.0") ref_inputs.push_back(t_new_val);+ else if (n == "mask.0") ref_inputs.push_back(t_mask);+ else FAIL() << "Unexpected ref param: " << n;+ }+ TensorVector ref_outputs;+ for (const auto& res : ref_model->get_results())+ ref_outputs.emplace_back(res->get_output_element_type(0), res->get_output_shape(0));+ ASSERT_TRUE(ref_model->evaluate(ref_outputs, ref_inputs))+ << "step " << step << ": ref evaluate() failed";++ std::unordered_map<std::string, Tensor> rout;+ for (size_t i = 0; i < ref_model->get_results().size(); ++i)+ rout[ref_model->get_results()[i]->get_friendly_name()] = ref_outputs[i];++ // Key present {1,1,W+1,D} -> slice last W rows (axis 2)+ ref_past_key = slice_last_tokens_h1<float>(rout.at("present.0.key"), WINDOW);+ // Value present {1,1,D,W+1} -> slice last W columns (axis 3)+ ref_past_val = slice_last_cols_h1<float>(rout.at("present.0.value"), WINDOW);++ // -- Compressed inference --+ TensorVector xform_inputs;+ for (const auto& param : xform_model->get_parameters()) {+ const std::string& n = param->get_friendly_name();+ if (n == "past_key_values.0.key") xform_inputs.push_back(xf_past_key);+ else if (n == "DynamicQuantize/0/past_key_values/key/scale") xform_inputs.push_back(xf_key_scale);+ else if (n == "DynamicQuantize/0/past_key_values/key/zp") xform_inputs.push_back(xf_key_zp);+ else if (n == "past_key_values.0.value") xform_inputs.push_back(xf_past_val);+ else if (n == "DynamicQuantize/0/past_key_values/value/scale") xform_inputs.push_back(xf_val_scale);+ else if (n == "DynamicQuantize/0/past_key_values/value/zp") xform_inputs.push_back(xf_val_zp);+ else if (n == "query.0") xform_inputs.push_back(t_query);+ else if (n == "new_key.0") xform_inputs.push_back(t_new_key);+ else if (n == "new_value.0") xform_inputs.push_back(t_new_val);+ else if (n == "mask.0") xform_inputs.push_back(t_mask);+ else FAIL() << "Unexpected compressed param: " << n;+ }+ TensorVector xform_outputs;+ for (const auto& res : xform_model->get_results())+ xform_outputs.emplace_back(res->get_output_element_type(0), res->get_output_shape(0));+ ASSERT_TRUE(xform_model->evaluate(xform_outputs, xform_inputs))+ << "step " << step << ": compressed evaluate() failed";++ std::unordered_map<std::string, Tensor> xout;+ for (size_t i = 0; i < xform_model->get_results().size(); ++i)+ xout[xform_model->get_results()[i]->get_friendly_name()] = xform_outputs[i];++ // -- Compare attn_out.0 --+ {+ const Tensor& xt = xout.at("attn_out.0");+ const Tensor& rt = rout.at("attn_out.0");+ ASSERT_EQ(xt.get_shape(), rt.get_shape());+ const float* xd = xt.data<float>(), *rd = rt.data<float>();+ const size_t cnt = xt.get_size();+ double ss_err = 0, ss_ref = 0;+ for (size_t i = 0; i < cnt; ++i) {+ double e = double(xd[i]) - double(rd[i]);+ ss_err += e * e;+ ss_ref += double(rd[i]) * double(rd[i]);+ }+ const double rel = (ss_ref > 1e-12) ? std::sqrt(ss_err / ss_ref) : std::sqrt(ss_err);+ EXPECT_LT(rel, tol)+ << "Step " << step << ": attn_out.0 rel-L2 = " << rel;+ }++ // -- Advance compressed past state --+ // Key: {1,1,W+1,D} -> cast + slice rows (axis 2)+ xf_past_key = slice_and_cast_key(xout.at("present.0.key"));+ // Value: {1,1,D,W+1} -> cast + slice cols (axis 3)+ xf_past_val = slice_and_cast_val(xout.at("present.0.value"));+ // Key scale {1,1,W+1,1} -> slice rows (axis 2)+ xf_key_scale = slice_last_scales_h1(xout.at("DynamicQuantize/0/present/key/scale"), WINDOW);+ if (key_asym) xf_key_zp = slice_last_zp_h1(xout.at("DynamicQuantize/0/present/key/zp"), WINDOW);+ // Value scale {1,1,1,W+1} -> slice cols (axis 3)+ xf_val_scale = slice_last_scales_col(xout.at("DynamicQuantize/0/present/value/scale"), WINDOW);+ if (val_asym) xf_val_zp = slice_last_zp_col(xout.at("DynamicQuantize/0/present/value/zp"), WINDOW);+ }+}++INSTANTIATE_TEST_SUITE_P(+ DecodeLoop,+ KVCacheMultiStepDecodeTest,+ ::testing::Values(+ DecodeLoopParams{"Key_Asym_u8__Val_Asym_u8",+ QuantizationType::Asymmetric, element::u8,+ QuantizationType::Asymmetric, element::u8},+ DecodeLoopParams{"Key_Sym_i8__Val_Sym_i8",+ QuantizationType::Symmetric, element::i8,+ QuantizationType::Symmetric, element::i8},+ DecodeLoopParams{"Key_Sym_i4__Val_Sym_i4",+ QuantizationType::Symmetric, element::i4,+ QuantizationType::Symmetric, element::i4},+ DecodeLoopParams{"Key_Asym_u8__Val_Sym_i8",+ QuantizationType::Asymmetric, element::u8,+ QuantizationType::Symmetric, element::i8},+ DecodeLoopParams{"Key_Sym_i4__Val_Asym_u8",+ QuantizationType::Symmetric, element::i4,+ QuantizationType::Asymmetric, element::u8},+ DecodeLoopParams{"Key_Asym_u8__Val_Sym_i4",+ QuantizationType::Asymmetric, element::u8,+ QuantizationType::Symmetric, element::i4}+ ),+ [](const ::testing::TestParamInfo<DecodeLoopParams>& info) { return info.param.name; }+);++} // namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/llm_pass_test_fixture.hpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/llm_pass_test_fixture.hppindex 8d7e38e59c3..59669f335b7 100644--- a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/llm_pass_test_fixture.hpp+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/llm_pass_test_fixture.hpp@@ -34,6 +34,7 @@#include <algorithm>#include <memory>#include <optional>+#include <sstream>#include <stdexcept>#include <string>#include <string_view>@@ -73,6 +74,15 @@ protected:build_llm_test_model(), m_plugin, props, recorder.make_factory());}+ std::unique_ptr<ov::npuw::LLMCompiledModel> create_compiled_model(const std::shared_ptr<ov::Model>& model,+ const ov::AnyMap& extra_props,+ RecordingFactory& recorder) const {+ auto props = base_props();+ merge_props(props, extra_props);+ return std::make_unique<ov::npuw::LLMCompiledModel>(+ model, m_plugin, props, recorder.make_factory());+ }+std::unique_ptr<ov::npuw::LLMCompiledModel> create_whisper_compiled_model(const ov::AnyMap& extra_props,RecordingFactory& recorder) const {auto props = base_props();@@ -146,42 +156,83 @@ protected:return ps.to_shape();}- // Returns true iff every input whose name contains `needle` has `expected_type`.- // Throws std::runtime_error if no input matching `needle` is found.- static bool all_inputs_with_name_have_type(const std::shared_ptr<ov::Model>& model,- std::string_view needle,- ov::element::Type expected_type) {+ // Helper to format a port's type and names for error messages.+ template <class Port>+ static void append_port_info(std::ostringstream& ss, const Port& port) {+ ss << "\n - type=" << port.get_element_type() << ", names={";+ bool first = true;+ for (const auto& name : port.get_names()) {+ if (!first) ss << ", ";+ ss << name;+ first = false;+ }+ if (first) ss << "<none>";+ ss << "}";+ }++ // Generic helper: check ports against a predicate. Throws if no match found.+ // Predicate returns false if a port fails the check (causes mismatch).+ template <class PortRange, class Predicate>+ static bool check_ports_with_name(const std::shared_ptr<ov::Model>& model,+ const PortRange& ports,+ std::string_view needle,+ std::string_view port_kind,+ const Predicate& predicate,+ std::string_view failure_msg_verb) {bool found_any = false;- for (const auto& input : model->inputs()) {- if (port_has_name(input, needle)) {+ std::ostringstream mismatch;+ bool has_mismatch = false;++ for (const auto& port : ports) {+ if (port_has_name(port, needle)) {found_any = true;- if (input.get_element_type() != expected_type)- return false;+ if (!predicate(port)) {+ has_mismatch = true;+ append_port_info(mismatch, port);+ }}}- if (!found_any)- throw std::runtime_error(std::string("No input matching needle '") + std::string(needle) +- "' found in model '" + model->get_friendly_name() + "'");++ if (!found_any) {+ std::ostringstream ss;+ ss << "No " << port_kind << " matching needle '" << needle << "' found in model '"+ << model->get_friendly_name() << "'. Available " << port_kind << "s:";+ for (const auto& port : ports) {+ append_port_info(ss, port);+ }+ throw std::runtime_error(ss.str());+ }++ if (has_mismatch) {+ ADD_FAILURE() << port_kind << "s matching needle '" << needle << "' in model '"+ << model->get_friendly_name() << "' " << failure_msg_verb << "."+ << " Mismatched " << port_kind << "s:" << mismatch.str();+ return false;+ }+return true;}+ // Returns true iff every input whose name contains `needle` has `expected_type`.+ // Throws std::runtime_error if no input matching `needle` is found.+ static bool all_inputs_with_name_have_type(const std::shared_ptr<ov::Model>& model,+ std::string_view needle,+ ov::element::Type expected_type) {+ return check_ports_with_name(+ model, model->inputs(), needle, "input",+ [expected_type](const auto& port) { return port.get_element_type() == expected_type; },+ "do not all have expected type " + std::string(ov::element::Type(expected_type).to_string()));+ }+// Returns true iff every output whose name contains `needle` has `expected_type`.// Throws std::runtime_error if no output matching `needle` is found.static bool all_outputs_with_name_have_type(const std::shared_ptr<ov::Model>& model,std::string_view needle,ov::element::Type expected_type) {- bool found_any = false;- for (const auto& output : model->outputs()) {- if (port_has_name(output, needle)) {- found_any = true;- if (output.get_element_type() != expected_type)- return false;- }- }- if (!found_any)- throw std::runtime_error(std::string("No output matching needle '") + std::string(needle) +- "' found in model '" + model->get_friendly_name() + "'");- return true;+ return check_ports_with_name(+ model, model->outputs(), needle, "output",+ [expected_type](const auto& port) { return port.get_element_type() == expected_type; },+ "do not all have expected type " + std::string(ov::element::Type(expected_type).to_string()));}// Returns true iff no input whose name contains `needle` has `excluded_type`.@@ -189,18 +240,10 @@ protected:static bool no_inputs_with_name_have_type(const std::shared_ptr<ov::Model>& model,std::string_view needle,ov::element::Type excluded_type) {- bool found_any = false;- for (const auto& input : model->inputs()) {- if (port_has_name(input, needle)) {- found_any = true;- if (input.get_element_type() == excluded_type)- return false;- }- }- if (!found_any)- throw std::runtime_error(std::string("No input matching needle '") + std::string(needle) +- "' found in model '" + model->get_friendly_name() + "'");- return true;+ return check_ports_with_name(+ model, model->inputs(), needle, "input",+ [excluded_type](const auto& port) { return port.get_element_type() != excluded_type; },+ "should not have type " + std::string(ov::element::Type(excluded_type).to_string()));}// -- Sub-model lookup ----------------------------------------------------------diff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/remove_empty_kv_inputs_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/remove_empty_kv_inputs_test.cppnew file mode 100644index 00000000000..bfb2e132675--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/remove_empty_kv_inputs_test.cpp@@ -0,0 +1,60 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include "embedding/remove_empty_kv_inputs.hpp"+#include "llm_pass_test_fixture.hpp"+#include "openvino/opsets/opset13.hpp"++namespace {++class RemoveEmptyKVInputsPassTest : public ov::test::npuw::LLMPassTestFixture {};++// Direct unit test for RemoveEmptyKVInputs: only the minimal past/current KV concat subgraph+// is needed. This avoids relying on LLMCompiledModel orchestration to validate the matcher.+TEST_F(RemoveEmptyKVInputsPassTest, HandlesDownUpProjSubgraph) {+ using namespace ov::opset13;++ auto past_k = std::make_shared<Parameter>(ov::element::f8e4m3, ov::Shape{1, 4, 0, 16});+ past_k->set_friendly_name("past_key_values.0.key");+ past_k->output(0).set_names({"past_key_values.0.key"});++ auto current_k = std::make_shared<Parameter>(ov::element::f8e4m3, ov::Shape{1, 4, 1, 16});+ current_k->set_friendly_name("current_key_values.0.key");+ current_k->output(0).set_names({"current_key_values.0.key"});++ auto upconvert = std::make_shared<Convert>(past_k, ov::element::f32);+ auto upscale = Constant::create(ov::element::f32, ov::Shape{}, {1.0f});+ auto upmul = std::make_shared<Multiply>(upconvert, upscale);+ auto downscale = Constant::create(ov::element::f32, ov::Shape{}, {1.0f});+ auto downmul = std::make_shared<Multiply>(upmul, downscale);+ auto downconvert = std::make_shared<Convert>(downmul, ov::element::f8e4m3);++ auto concat = std::make_shared<Concat>(ov::OutputVector{downconvert, current_k}, 2);+ concat->set_friendly_name("past_key_values.0.keypresent.0.key_concat");++ // ShapeOf on the original parameter exercises the replacement-to-constant path.+ auto shapeof = std::make_shared<ShapeOf>(past_k, ov::element::i64);+ auto concat_result = std::make_shared<Result>(concat);+ concat_result->output(0).set_names({"present.0.key"});+ auto shape_result = std::make_shared<Result>(shapeof);+ auto model = std::make_shared<ov::Model>(ov::ResultVector{concat_result, shape_result},+ ov::ParameterVector{past_k, current_k},+ "remove_empty_kv_inputs_test");++ ov::npuw::RemoveEmptyKVInputs pass;+ EXPECT_TRUE(pass.run_on_model(model));++ EXPECT_EQ(model->get_parameters().size(), 1u);+ EXPECT_EQ(model->get_parameters().front()->get_friendly_name(), "current_key_values.0.key");+ EXPECT_EQ(count_ops<ov::op::v0::Concat>(model), 0u);+ EXPECT_EQ(count_ops<ov::op::v3::ShapeOf>(model), 0u);++ const auto outputs = model->outputs();+ ASSERT_EQ(outputs.size(), 2u);+ EXPECT_EQ(outputs[0].get_partial_shape(), ov::PartialShape({1, 4, 1, 16}));+}++} // namespacediff --git a/src/plugins/intel_npu/tests/unit/npuw/sdpa_pattern_nodes_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/sdpa_pattern_nodes_test.cppnew file mode 100644index 00000000000..d923b09f7d3--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/sdpa_pattern_nodes_test.cpp@@ -0,0 +1,669 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <algorithm>+#include <string>+#include <vector>+#include <limits>++#include "openvino/op/add.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/softmax.hpp"+#include "openvino/openvino.hpp"+#include "util.hpp"++namespace {++using ExpectedNodes = ov::npuw::util::SDPAPatternNodes;++struct ModelBuildResult {+ std::shared_ptr<ov::Model> model;+ std::vector<ExpectedNodes> expected;+};++ModelBuildResult build_sdpa_model(size_t num_sdpa, bool miss_key_concat = false, bool miss_past_key_param = false) {+ using namespace ov;++ const Shape past_shape = {1, 4, 8, 64};+ const Shape new_token_shape = {1, 4, 1, 64};+ const Shape mask_shape = {1, 1, 1, 9};++ ParameterVector params;+ ResultVector results;+ std::vector<ExpectedNodes> expected;+ expected.reserve(num_sdpa);++ std::shared_ptr<ov::Node> prev_attn_out; // Track output of previous SDPA to chain them++ for (size_t n = 0; n < num_sdpa; ++n) {+ const std::string idx = std::to_string(n);++ auto make_param = [&](const std::string& name, const Shape& shape) {+ auto p = std::make_shared<op::v0::Parameter>(element::f32, shape);+ p->set_friendly_name(name);+ p->output(0).get_tensor().set_names({name});+ params.push_back(p);+ return p;+ };++ auto past_value = make_param("past_key_values." + idx + ".value", past_shape);+ std::shared_ptr<op::v0::Parameter> past_key;+ std::shared_ptr<op::v0::Parameter> fallback_key;+ if (miss_past_key_param) {+ fallback_key = make_param("fallback_key." + idx, past_shape);+ } else {+ past_key = make_param("past_key_values." + idx + ".key", past_shape);+ }++ // Use output from previous SDPA as query for current SDPA (chain layers)+ std::shared_ptr<ov::Node> query;+ if (n == 0) {+ query = make_param("query." + idx, new_token_shape);+ } else {+ // Reshape previous attention output to query shape and use as input+ auto reshape_shape = op::v0::Constant::create(element::i64, Shape{4},+ {1, 4, 1, 64});+ query = std::make_shared<op::v1::Reshape>(prev_attn_out, reshape_shape, false);+ query->set_friendly_name("query_from_prev." + idx);+ }++ auto new_key = make_param("new_key." + idx, new_token_shape);+ auto new_value = make_param("new_value." + idx, new_token_shape);+ auto mask = make_param("mask." + idx, mask_shape);++ std::shared_ptr<ov::Node> key_path;+ std::shared_ptr<ov::Node> key_concat;+ if (miss_key_concat) {+ key_path = new_key;+ } else {+ key_concat = std::make_shared<op::v0::Concat>(OutputVector{(miss_past_key_param ? fallback_key : past_key), new_key}, 2);+ key_concat->set_friendly_name("concat_key." + idx);+ key_path = key_concat;+ }++ auto value_concat = std::make_shared<op::v0::Concat>(OutputVector{past_value, new_value}, 2);+ value_concat->set_friendly_name("concat_value." + idx);++ auto qk = std::make_shared<op::v0::MatMul>(query, key_path, false, true);+ qk->set_friendly_name("matmul1." + idx);+ auto add = std::make_shared<op::v1::Add>(qk->output(0), mask->output(0));+ add->set_friendly_name("add." + idx);+ auto softmax = std::make_shared<op::v8::Softmax>(add->output(0), 3);+ softmax->set_friendly_name("softmax." + idx);+ auto matmul2 = std::make_shared<op::v0::MatMul>(softmax->output(0), value_concat->output(0));+ matmul2->set_friendly_name("matmul2." + idx);++ auto make_result = [&](const ov::Output<ov::Node>& out, const std::string& name) {+ auto r = std::make_shared<op::v0::Result>(out);+ r->set_friendly_name(name);+ r->output(0).get_tensor().set_names({name});+ results.push_back(r);+ };++ make_result(key_path->output(0), "present." + idx + ".key");+ make_result(value_concat->output(0), "present." + idx + ".value");+ make_result(matmul2->output(0), "attn_out." + idx);++ prev_attn_out = matmul2; // Store output for next iteration++ expected.push_back(ExpectedNodes{qk,+ matmul2,+ softmax,+ add,+ key_concat,+ value_concat});+ }++ auto model = std::make_shared<Model>(results, params, "sdpa_pattern_nodes_test_model");+ model->validate_nodes_and_infer_types();+ //ov::save_model(model, "sdpa_pattern_nodes_test_model.xml");+ return {model, expected};+}++void expect_nodes_equal(const ov::npuw::util::SDPAPatternNodes& actual, const ExpectedNodes& expected) {+ EXPECT_EQ(actual.matmul1_node, expected.matmul1_node);+ EXPECT_EQ(actual.matmul2_node, expected.matmul2_node);+ EXPECT_EQ(actual.softmax_node, expected.softmax_node);+ EXPECT_EQ(actual.add_node, expected.add_node);+ // EXPECT_EQ(actual.past_key_param_node, expected.past_key_param_node);+ // EXPECT_EQ(actual.past_value_param_node, expected.past_value_param_node);+ EXPECT_EQ(actual.past_key_concat_node, expected.past_key_concat_node);+ EXPECT_EQ(actual.past_value_concat_node, expected.past_value_concat_node);+}++std::string sort_key(const ExpectedNodes& nodes) {+ return nodes.matmul1_node->get_friendly_name();+}++struct PoisonBuildResult {+ std::shared_ptr<ov::Node> chain_out;+};++PoisonBuildResult make_poisoned_sdpa(const std::string& idx,+ size_t poison_type,+ const std::shared_ptr<ov::Node>& query_in,+ ov::ParameterVector& params,+ ov::ResultVector& results) {+ using namespace ov;++ const Shape q_shape = {1, 4, 1, 64};+ const Shape k_shape = {1, 4, 9, 64};+ const Shape v_shape = {1, 4, 9, 64};+ const Shape score_shape = {1, 4, 1, 9};+ const Shape score_bias_shape = {1, 1, 1, 9};++ auto make_param = [&](const std::string& name, const Shape& shape) {+ auto p = std::make_shared<op::v0::Parameter>(element::f32, shape);+ p->set_friendly_name(name);+ p->output(0).get_tensor().set_names({name});+ params.push_back(p);+ return p;+ };++ auto q = query_in;+ if (!q) {+ q = make_param("poison_query." + idx, q_shape);+ }++ auto k = make_param("poison_key." + idx, k_shape);+ auto v = make_param("poison_value." + idx, v_shape);++ std::shared_ptr<ov::Node> poison_out;+ std::shared_ptr<ov::Node> chain_out;+ switch (poison_type % 4) {+ case 0: {+ // Missing Add: MatMul -> Softmax -> MatMul+ auto mm1 = std::make_shared<op::v0::MatMul>(q, k, false, true);+ mm1->set_friendly_name("poison_matmul1." + idx);+ auto sm = std::make_shared<op::v8::Softmax>(mm1, 3);+ sm->set_friendly_name("poison_softmax." + idx);+ auto mm2 = std::make_shared<op::v0::MatMul>(sm, v);+ mm2->set_friendly_name("poison_matmul2." + idx);+ poison_out = mm2;+ chain_out = mm2;+ break;+ }+ case 1: {+ // Missing second MatMul: MatMul -> Add -> Softmax+ auto mm1 = std::make_shared<op::v0::MatMul>(q, k, false, true);+ mm1->set_friendly_name("poison_matmul1." + idx);+ auto mask = make_param("poison_mask." + idx, score_bias_shape);+ auto add = std::make_shared<op::v1::Add>(mm1, mask);+ add->set_friendly_name("poison_add." + idx);+ auto sm = std::make_shared<op::v8::Softmax>(add, 3);+ sm->set_friendly_name("poison_softmax." + idx);+ poison_out = sm;+ // Keep the global chain shape stable for next attention block.+ chain_out = q;+ break;+ }+ case 2: {+ // Missing first MatMul: Add -> Softmax -> MatMul+ auto score = make_param("poison_score." + idx, score_shape);+ auto mask = make_param("poison_mask." + idx, score_bias_shape);+ auto add = std::make_shared<op::v1::Add>(score, mask);+ add->set_friendly_name("poison_add." + idx);+ auto sm = std::make_shared<op::v8::Softmax>(add, 3);+ sm->set_friendly_name("poison_softmax." + idx);+ auto mm2 = std::make_shared<op::v0::MatMul>(sm, v);+ mm2->set_friendly_name("poison_matmul2." + idx);+ poison_out = mm2;+ chain_out = mm2;+ break;+ }+ default: {+ // Missing Softmax: MatMul -> Add -> MatMul+ auto mm1 = std::make_shared<op::v0::MatMul>(q, k, false, true);+ mm1->set_friendly_name("poison_matmul1." + idx);+ auto mask = make_param("poison_mask." + idx, score_bias_shape);+ auto add = std::make_shared<op::v1::Add>(mm1, mask);+ add->set_friendly_name("poison_add." + idx);+ auto mm2 = std::make_shared<op::v0::MatMul>(add, v);+ mm2->set_friendly_name("poison_matmul2." + idx);+ poison_out = mm2;+ chain_out = mm2;+ break;+ }+ }++ auto r = std::make_shared<op::v0::Result>(poison_out);+ r->set_friendly_name("poison_out." + idx);+ r->output(0).get_tensor().set_names({"poison_out." + idx});+ results.push_back(r);++ return {chain_out};+}++ModelBuildResult build_noisy_sdpa_model(size_t num_sdpa, size_t broken_idx, size_t poison_count) {+ using namespace ov;++ const Shape past_shape = {1, 4, 8, 64};+ const Shape new_token_shape = {1, 4, 1, 64};+ const Shape context_shape = {1, 4, 9, 64};+ const Shape mask_shape = {1, 1, 1, 9};++ ParameterVector params;+ ResultVector results;+ std::vector<ExpectedNodes> expected;+ expected.reserve(num_sdpa);++ std::shared_ptr<ov::Node> prev_attn_out;+ size_t emitted_poison = 0;++ auto maybe_add_poison = [&]() {+ if (emitted_poison >= poison_count) {+ return;+ }+ const std::string poison_idx = std::to_string(emitted_poison);+ auto poison = make_poisoned_sdpa(poison_idx, emitted_poison, prev_attn_out, params, results);+ prev_attn_out = poison.chain_out;+ emitted_poison++;+ };++ for (size_t n = 0; n < num_sdpa; ++n) {+ const std::string idx = std::to_string(n);+ const bool is_broken = (n == broken_idx);++ auto make_param = [&](const std::string& name, const Shape& shape) {+ auto p = std::make_shared<op::v0::Parameter>(element::f32, shape);+ p->set_friendly_name(name);+ p->output(0).get_tensor().set_names({name});+ params.push_back(p);+ return p;+ };++ std::shared_ptr<op::v0::Parameter> past_key;+ std::shared_ptr<op::v0::Parameter> past_value;++ if (!is_broken) {+ past_key = make_param("past_key_values." + idx + ".key", past_shape);+ past_value = make_param("past_key_values." + idx + ".value", past_shape);+ }++ std::shared_ptr<ov::Node> query;+ if (!prev_attn_out) {+ query = make_param("query." + idx, new_token_shape);+ } else {+ query = prev_attn_out;+ }+ auto new_key = make_param("new_key." + idx, new_token_shape);+ auto new_value = make_param("new_value." + idx, new_token_shape);+ auto mask = make_param("mask." + idx, mask_shape);++ std::shared_ptr<ov::Node> key_path;+ std::shared_ptr<ov::Node> value_path;+ std::shared_ptr<ov::Node> key_concat;+ std::shared_ptr<ov::Node> value_concat;++ if (is_broken) {+ // No-concat SDPA: direct cache parameters without KV-cache concat, pattern is invalid.+ key_path = make_param("cache_key." + idx, context_shape);+ value_path = make_param("cache_value." + idx, context_shape);+ } else {+ key_concat = std::make_shared<op::v0::Concat>(OutputVector{past_key, new_key}, 2);+ key_concat->set_friendly_name("concat_key." + idx);+ key_path = key_concat;++ value_concat = std::make_shared<op::v0::Concat>(OutputVector{past_value, new_value}, 2);+ value_concat->set_friendly_name("concat_value." + idx);+ value_path = value_concat;+ }++ auto qk = std::make_shared<op::v0::MatMul>(query, key_path, false, true);+ qk->set_friendly_name("matmul1." + idx);+ auto add = std::make_shared<op::v1::Add>(qk->output(0), mask->output(0));+ add->set_friendly_name("add." + idx);+ auto softmax = std::make_shared<op::v8::Softmax>(add->output(0), 3);+ softmax->set_friendly_name("softmax." + idx);+ auto matmul2 = std::make_shared<op::v0::MatMul>(softmax->output(0), value_path->output(0));+ matmul2->set_friendly_name("matmul2." + idx);++ auto make_result = [&](const ov::Output<ov::Node>& out, const std::string& name) {+ auto r = std::make_shared<op::v0::Result>(out);+ r->set_friendly_name(name);+ r->output(0).get_tensor().set_names({name});+ results.push_back(r);+ };++ make_result(key_path->output(0), "present." + idx + ".key");+ make_result(value_path->output(0), "present." + idx + ".value");+ make_result(matmul2->output(0), "attn_out." + idx);++ prev_attn_out = matmul2;++ expected.push_back(ExpectedNodes{qk,+ matmul2,+ softmax,+ add,+ key_concat,+ value_concat});++ maybe_add_poison();+ }++ while (emitted_poison < poison_count) {+ maybe_add_poison();+ }++ auto model = std::make_shared<Model>(results, params, "sdpa_pattern_nodes_noisy_test_model");+ model->validate_nodes_and_infer_types();+ return {model, expected};+}++ModelBuildResult build_sdpa_model_with_wrapped_concats(size_t num_sdpa) {+ using namespace ov;++ const Shape past_shape = {1, 4, 8, 64};+ const Shape new_token_shape = {1, 4, 1, 64};+ const Shape cache_shape = {1, 4, 9, 64};+ const Shape mask_shape = {1, 1, 1, 9};++ ParameterVector params;+ ResultVector results;+ std::vector<ExpectedNodes> expected;+ expected.reserve(num_sdpa);++ for (size_t n = 0; n < num_sdpa; ++n) {+ const std::string idx = std::to_string(n);++ auto make_param = [&](const std::string& name, const Shape& shape) {+ auto p = std::make_shared<op::v0::Parameter>(element::f32, shape);+ p->set_friendly_name(name);+ p->output(0).get_tensor().set_names({name});+ params.push_back(p);+ return p;+ };++ auto past_key = make_param("past_key_values." + idx + ".key", past_shape);+ auto past_value = make_param("past_key_values." + idx + ".value", past_shape);+ auto query = make_param("query_wrapped." + idx, new_token_shape);+ auto new_key = make_param("new_key_wrapped." + idx, new_token_shape);+ auto new_value = make_param("new_value_wrapped." + idx, new_token_shape);+ auto mask = make_param("mask_wrapped." + idx, mask_shape);++ auto key_concat = std::make_shared<op::v0::Concat>(OutputVector{past_key, new_key}, 2);+ key_concat->set_friendly_name("concat_key_wrapped." + idx);+ auto value_concat = std::make_shared<op::v0::Concat>(OutputVector{past_value, new_value}, 2);+ value_concat->set_friendly_name("concat_value_wrapped." + idx);++ auto shape_c = op::v0::Constant::create(element::i64, Shape{4},+ {static_cast<int64_t>(cache_shape[0]),+ static_cast<int64_t>(cache_shape[1]),+ static_cast<int64_t>(cache_shape[2]),+ static_cast<int64_t>(cache_shape[3])});++ auto key_reshape = std::make_shared<op::v1::Reshape>(key_concat, shape_c, false);+ key_reshape->set_friendly_name("reshape_key_wrapped." + idx);+ auto value_reshape = std::make_shared<op::v1::Reshape>(value_concat, shape_c, false);+ value_reshape->set_friendly_name("reshape_value_wrapped." + idx);++ auto qk = std::make_shared<op::v0::MatMul>(query, key_reshape, false, true);+ qk->set_friendly_name("matmul1_wrapped." + idx);+ auto add = std::make_shared<op::v1::Add>(qk->output(0), mask->output(0));+ add->set_friendly_name("add_wrapped." + idx);+ auto softmax = std::make_shared<op::v8::Softmax>(add->output(0), 3);+ softmax->set_friendly_name("softmax_wrapped." + idx);+ auto matmul2 = std::make_shared<op::v0::MatMul>(softmax->output(0), value_reshape->output(0));+ matmul2->set_friendly_name("matmul2_wrapped." + idx);++ auto make_result = [&](const ov::Output<ov::Node>& out, const std::string& name) {+ auto r = std::make_shared<op::v0::Result>(out);+ r->set_friendly_name(name);+ r->output(0).get_tensor().set_names({name});+ results.push_back(r);+ };++ make_result(key_reshape->output(0), "present." + idx + ".key");+ make_result(value_reshape->output(0), "present." + idx + ".value");+ make_result(matmul2->output(0), "attn_out_wrapped." + idx);++ expected.push_back(ExpectedNodes{qk,+ matmul2,+ softmax,+ add,+ key_concat,+ value_concat});+ }++ auto model = std::make_shared<Model>(results, params, "sdpa_pattern_nodes_wrapped_concat_model");+ model->validate_nodes_and_infer_types();+ return {model, expected};+}+++ModelBuildResult build_sdpa_model_without_concats(size_t num_sdpa) {+ using namespace ov;++ const Shape cache_shape = {1, 4, 9, 64};+ const Shape query_shape = {1, 4, 1, 64};+ const Shape mask_shape = {1, 1, 1, 9};++ ParameterVector params;+ ResultVector results;+ std::vector<ExpectedNodes> expected;+ expected.reserve(num_sdpa);++ for (size_t n = 0; n < num_sdpa; ++n) {+ const std::string idx = std::to_string(n);++ auto make_param = [&](const std::string& name, const Shape& shape) {+ auto p = std::make_shared<op::v0::Parameter>(element::f32, shape);+ p->set_friendly_name(name);+ p->output(0).get_tensor().set_names({name});+ params.push_back(p);+ return p;+ };++ auto query = make_param("query_noconcat." + idx, query_shape);+ auto key_context = make_param("cache_key_noconcat." + idx, cache_shape);+ auto value_context = make_param("cache_value_noconcat." + idx, cache_shape);+ auto mask = make_param("mask_noconcat." + idx, mask_shape);++ auto qk = std::make_shared<op::v0::MatMul>(query, key_context, false, true);+ qk->set_friendly_name("matmul1_noconcat." + idx);+ auto add = std::make_shared<op::v1::Add>(qk->output(0), mask->output(0));+ add->set_friendly_name("add_noconcat." + idx);+ auto softmax = std::make_shared<op::v8::Softmax>(add->output(0), 3);+ softmax->set_friendly_name("softmax_noconcat." + idx);+ auto matmul2 = std::make_shared<op::v0::MatMul>(softmax->output(0), value_context->output(0));+ matmul2->set_friendly_name("matmul2_noconcat." + idx);++ auto out = std::make_shared<op::v0::Result>(matmul2);+ out->set_friendly_name("attn_out_noconcat." + idx);+ out->output(0).get_tensor().set_names({"attn_out_noconcat." + idx});+ results.push_back(out);++ expected.push_back(ExpectedNodes{qk, matmul2, softmax, add, nullptr, nullptr});+ }++ auto model = std::make_shared<Model>(results, params, "sdpa_pattern_nodes_no_concat_model");+ model->validate_nodes_and_infer_types();+ return {model, expected};+}++TEST(SdpaPatternNodesTest, MissingConcatKeepsSearchStableAndReturnsInvalidPattern) {+ const auto built = build_sdpa_model(/*num_sdpa=*/1, /*miss_key_concat=*/true, /*miss_past_key_param=*/false);++ auto pattern = ov::npuw::util::find_sdpa_pattern_nodes(built.model);+ const auto& expected = built.expected.front();++ EXPECT_FALSE(pattern.is_valid());+ EXPECT_EQ(pattern.matmul1_node, expected.matmul1_node);+ EXPECT_EQ(pattern.matmul2_node, expected.matmul2_node);+ EXPECT_EQ(pattern.softmax_node, expected.softmax_node);+ EXPECT_EQ(pattern.add_node, expected.add_node);+ // EXPECT_EQ(pattern.past_key_param_node, expected.past_key_param_node);+ // EXPECT_EQ(pattern.past_value_param_node, expected.past_value_param_node);+ EXPECT_EQ(pattern.past_key_concat_node, nullptr);+ EXPECT_EQ(pattern.past_value_concat_node, expected.past_value_concat_node);+}++TEST(SdpaPatternNodesTest, SingleBrokenSdpaWithoutAnyConcatReturnsInvalidPattern) {+ const auto built = build_noisy_sdpa_model(/*num_sdpa=*/1, /*broken_idx=*/0, /*poison_count=*/0);++ auto pattern = ov::npuw::util::find_sdpa_pattern_nodes(built.model);+ const auto& expected = built.expected.front();++ EXPECT_FALSE(pattern.is_valid());+ EXPECT_EQ(pattern.matmul1_node, expected.matmul1_node);+ EXPECT_EQ(pattern.matmul2_node, expected.matmul2_node);+ EXPECT_EQ(pattern.softmax_node, expected.softmax_node);+ EXPECT_EQ(pattern.add_node, expected.add_node);+ // EXPECT_EQ(pattern.past_key_param_node, expected.past_key_param_node);+ // EXPECT_EQ(pattern.past_value_param_node, expected.past_value_param_node);+ EXPECT_EQ(pattern.past_key_concat_node, nullptr);+ EXPECT_EQ(pattern.past_value_concat_node, nullptr);+}++TEST(SdpaPatternNodesTest, SingleCompletedSdpaReturnsExpectedNodeSet) {+ const auto built = build_sdpa_model(/*num_sdpa=*/1, /*miss_key_concat=*/false, /*miss_past_key_param=*/false);++ auto pattern = ov::npuw::util::find_sdpa_pattern_nodes(built.model);++ ASSERT_TRUE(pattern.is_valid());+ expect_nodes_equal(pattern, built.expected.front());+}++TEST(SdpaPatternNodesTest, SingleModeReturnsFirstPatternWhenMultipleSdpasExist) {+ const auto built = build_sdpa_model(/*num_sdpa=*/2, /*miss_key_concat=*/false, /*miss_past_key_param=*/false);++ auto pattern = ov::npuw::util::find_sdpa_pattern_nodes(built.model);++ ASSERT_TRUE(pattern.is_valid());+ expect_nodes_equal(pattern, built.expected.front());+}+++TEST(SdpaPatternNodesTest, FindAllReturnsAllSdpaPatternsWithExactNodes) {+ const auto built = build_sdpa_model(/*num_sdpa=*/2, /*miss_key_concat=*/false, /*miss_past_key_param=*/false);++ auto patterns = ov::npuw::util::find_all_sdpa_pattern_nodes(built.model);+ auto expected = built.expected;++ ASSERT_EQ(patterns.size(), built.expected.size());+ ASSERT_EQ(patterns.size(), 2u);++ std::sort(patterns.begin(), patterns.end(), [](const auto& lhs, const auto& rhs) {+ return sort_key(lhs) < sort_key(rhs);+ });+ std::sort(expected.begin(), expected.end(), [](const auto& lhs, const auto& rhs) {+ return sort_key(lhs) < sort_key(rhs);+ });++ for (size_t i = 0; i < patterns.size(); ++i) {+ ASSERT_TRUE(patterns[i].is_valid()) << "Pattern at index " << i << " must be valid";+ expect_nodes_equal(patterns[i], expected[i]);+ }+}++TEST(SdpaPatternNodesTest, FindAllIgnoresPoisonSubgraphsInLargePrefillLikeModel) {+ const auto built = build_noisy_sdpa_model(/*num_sdpa=*/10, /*broken_idx=*/std::numeric_limits<size_t>::max(),+ /*poison_count=*/7);++ auto patterns = ov::npuw::util::find_all_sdpa_pattern_nodes(built.model);+ auto expected = built.expected;++ ASSERT_EQ(patterns.size(), expected.size());+ ASSERT_EQ(patterns.size(), 10u);++ std::sort(patterns.begin(), patterns.end(), [](const auto& lhs, const auto& rhs) {+ return sort_key(lhs) < sort_key(rhs);+ });+ std::sort(expected.begin(), expected.end(), [](const auto& lhs, const auto& rhs) {+ return sort_key(lhs) < sort_key(rhs);+ });++ for (size_t i = 0; i < patterns.size(); ++i) {+ ASSERT_TRUE(patterns[i].is_valid()) << "Pattern at index " << i << " must be valid";+ expect_nodes_equal(patterns[i], expected[i]);+ }+}++TEST(SdpaPatternNodesTest, FindAllSkipsBrokenSdpaAndFindsRemainingInLargePrefillLikeModel) {+ const auto built = build_noisy_sdpa_model(/*num_sdpa=*/10, /*broken_idx=*/4, /*poison_count=*/7);++ auto patterns = ov::npuw::util::find_all_sdpa_pattern_nodes(built.model);+ auto expected = built.expected;+ expected.erase(std::remove_if(expected.begin(), expected.end(), [](const auto& nodes) {+ return !nodes.is_valid();+ }),+ expected.end());++ ASSERT_EQ(patterns.size(), 10u);++ auto valid_patterns = patterns;+ valid_patterns.erase(std::remove_if(valid_patterns.begin(), valid_patterns.end(), [](const auto& nodes) {+ return !nodes.is_valid();+ }),+ valid_patterns.end());+++ ASSERT_EQ(valid_patterns.size(), 9u);++ std::sort(valid_patterns.begin(), valid_patterns.end(), [](const auto& lhs, const auto& rhs) {+ return sort_key(lhs) < sort_key(rhs);+ });+ std::sort(expected.begin(), expected.end(), [](const auto& lhs, const auto& rhs) {+ return sort_key(lhs) < sort_key(rhs);+ });++ for (size_t i = 0; i < valid_patterns.size(); ++i) {+ ASSERT_TRUE(valid_patterns[i].is_valid()) << "Pattern at index " << i << " must be valid";+ expect_nodes_equal(valid_patterns[i], expected[i]);+ }+}++TEST(SdpaPatternNodesTest, FindAllHandlesConcatWrappedByReshape) {+ const auto built = build_sdpa_model_with_wrapped_concats(/*num_sdpa=*/3);++ auto patterns = ov::npuw::util::find_all_sdpa_pattern_nodes(built.model);+ auto expected = built.expected;++ ASSERT_EQ(patterns.size(), expected.size());+ ASSERT_EQ(patterns.size(), 3u);++ std::sort(patterns.begin(), patterns.end(), [](const auto& lhs, const auto& rhs) {+ return sort_key(lhs) < sort_key(rhs);+ });+ std::sort(expected.begin(), expected.end(), [](const auto& lhs, const auto& rhs) {+ return sort_key(lhs) < sort_key(rhs);+ });++ for (size_t i = 0; i < patterns.size(); ++i) {+ ASSERT_TRUE(patterns[i].is_valid()) << "Pattern at index " << i << " must be valid";+ expect_nodes_equal(patterns[i], expected[i]);+ }+}+++TEST(SdpaPatternNodesTest, FindAllReturnsAllSdpaWhenNoConcatIsPresent) {+ const auto built = build_sdpa_model_without_concats(/*num_sdpa=*/4);++ auto patterns = ov::npuw::util::find_all_sdpa_pattern_nodes(built.model);+ auto expected = built.expected;++ ASSERT_EQ(patterns.size(), expected.size());+ ASSERT_EQ(patterns.size(), 4u);++ std::sort(patterns.begin(), patterns.end(), [](const auto& lhs, const auto& rhs) {+ return sort_key(lhs) < sort_key(rhs);+ });+ std::sort(expected.begin(), expected.end(), [](const auto& lhs, const auto& rhs) {+ return sort_key(lhs) < sort_key(rhs);+ });++ for (size_t i = 0; i < patterns.size(); ++i) {+ ASSERT_FALSE(patterns[i].is_valid()) << "Pattern at index " << i << " is expected to be invalid without concats";+ expect_nodes_equal(patterns[i], expected[i]);+ }+}++} // namespace