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][SWA][PR1] Add ShrinkSlidingWindowKVCache transformation for hybrid SWA models (#37782)
Guoliang Shic28370cd20fa
diff --git a/src/plugins/intel_npu/src/plugin/npuw/kv_cache_sliding_window_manager.hpp b/src/plugins/intel_npu/src/plugin/npuw/kv_cache_sliding_window_manager.hppnew file mode 100644index 00000000000..4b06e7457fa--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/kv_cache_sliding_window_manager.hpp@@ -0,0 +1,17 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++namespace ov {+namespace npuw {+namespace util {++// rt_info key stamped on SWA-managed past_key_values Parameters whose seq_len+// axis was shrunk to the SWA window size.+static constexpr const char* NPUW_KV_CACHE_SLIDING_RT_KEY = "npuw_kv_cache_sliding";++} // namespace util+} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hppindex d1e51b17bec..54c14e099ae 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.hpp@@ -27,6 +27,7 @@ public:constexpr const char* kVisualPosMasksParamName = "visual_pos_masks";constexpr const char* kDeepstackVisualEmbedsParamName = "deepstack_visual_embeds";constexpr const char* kTokenTypeIdsParamName = "token_type_ids";+constexpr const char* kSlidingWindowAttentionMaskParamName = "sliding_window_attention_mask";bool has_input(const std::shared_ptr<ov::Model>& model, const std::string& name);diff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/shrink_sliding_window_kv_cache.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/shrink_sliding_window_kv_cache.cppnew file mode 100644index 00000000000..f403e56816d--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/shrink_sliding_window_kv_cache.cpp@@ -0,0 +1,389 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "shrink_sliding_window_kv_cache.hpp"++#include <cstdint>+#include <limits>+#include <memory>+#include <unordered_set>++#include "../kv_cache_sliding_window_manager.hpp"+#include "../llm_compiled_model_utils.hpp"+#include "../logging.hpp"+#include "../util.hpp"+#include "detect_causal_mask.hpp"+#include "openvino/core/validation_util.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/unsqueeze.hpp"++namespace {++using SDPA = ov::op::v13::ScaledDotProductAttention;++// Returns the uniform SWA window size across all SDPA nodes annotated as sliding window,+// or 0 if no sliding window layer is found.+// Throws if sliding layers use different window sizes.+uint32_t detect_swa_window_size(const std::shared_ptr<ov::Model>& model) {+ int64_t detected_window = 0;+ bool has_detected_window = false;++ for (const auto& node : model->get_ordered_ops()) {+ auto sdpa = ov::as_type_ptr<SDPA>(node);+ if (!sdpa) {+ continue;+ }++ const auto& rt_info = sdpa->get_rt_info();+ const auto it = rt_info.find(ov::npuw::NPUW_SDPA_MASK_RT_KEY);+ if (it == rt_info.end()) {+ continue;+ }++ const int64_t encoded = it->second.as<int64_t>();+ if (encoded < 0) {+ continue; // Causal (or unrecognized)+ }++ if (!has_detected_window) {+ detected_window = encoded;+ has_detected_window = true;+ } else {+ OPENVINO_ASSERT(detected_window == encoded,+ "NPUW SWA: inconsistent window sizes across layers (",+ detected_window,+ " vs ",+ encoded,+ ").");+ }+ }++ if (!has_detected_window) {+ LOG_DEBUG("[SWA] No sliding-window layer detected; SWA support disabled.");+ return 0;+ }++ OPENVINO_ASSERT(+ detected_window > 0 && detected_window <= static_cast<int64_t>(std::numeric_limits<uint32_t>::max()),+ "NPUW SWA: invalid window size: ",+ detected_window);++ LOG_INFO("[SWA] Sliding Window Attention is ENABLED: window_size=" << detected_window);+ return static_cast<uint32_t>(detected_window);+}++constexpr size_t kSdpaKeyInputIdx = 1;+constexpr size_t kSdpaValueInputIdx = 2;+constexpr size_t kSdpaMaskInputIdx = 3;+constexpr size_t kShapeInputIdx = 1; // target_shape port of Reshape/Broadcast++// past_kv Parameter feeding a KV Concat, plus the optional Convert in between.+struct PastKVSource {+ std::shared_ptr<ov::op::v0::Parameter> param;+ std::shared_ptr<ov::Node> convert; // nullptr when Parameter -> Concat directly+};++// Classifies an SDPA node as SWA (sliding-window) or not, using attention mask+// classification information attached to the node earlier in the pipeline.+bool is_sliding_sdpa(const std::shared_ptr<SDPA>& sdpa) {+ const auto& rt_info = sdpa->get_rt_info();+ const auto it = rt_info.find(ov::npuw::NPUW_SDPA_MASK_RT_KEY);+ return (it != rt_info.end()) && (it->second.as<int64_t>() >= 0);+}++// Identify the past_kv Parameter feeding a KV Concat. The other Concat input carries the+// freshly computed KV, so elimination is enough; an optional Convert may sit in between.+PastKVSource find_past_kv_source(const std::shared_ptr<ov::op::v0::Concat>& concat) {+ for (size_t i = 0; i < concat->get_input_size(); ++i) {+ auto src = concat->input_value(i).get_node_shared_ptr();+ std::shared_ptr<ov::op::v0::Convert> convert;+ if (auto as_convert = ov::as_type_ptr<ov::op::v0::Convert>(src)) {+ convert = as_convert;+ src = src->input_value(0).get_node_shared_ptr();+ }+ if (auto param = ov::as_type_ptr<ov::op::v0::Parameter>(src)) {+ return {param, convert};+ }+ }+ return {nullptr, nullptr};+}++// Walk back from an SWA SDPA K/V input to the past_kv Concat, patching target-shape+// constants (kvcache_size -> new_kv_total) in place as they are discovered.+//+// Expected backward path (from SDPA port 1/2):+// SDPA(K or V)+// <- Reshape (target_shape)+// <- Broadcast (target_shape)+// <- Unsqueeze+// <- Concat(past_kv, cur_kv) [stop boundary]+//+// The KV sequence dimension is strictly assumed to be the second-last axis of each+// target-shape constant. Supported values on that axis are kvcache_size (patched to+// new_kv_total) and -1 (inferred by Reshape, left unchanged).+std::shared_ptr<ov::op::v0::Concat> scan_kv_path(const std::shared_ptr<SDPA>& sdpa,+ size_t kv_port,+ int64_t kvcache_size,+ int64_t new_kv_total) {+ auto cur = sdpa->input_value(kv_port).get_node_shared_ptr();++ while (cur && !ov::is_type<ov::op::v0::Concat>(cur)) {+ const bool has_target_shape =+ ov::is_type<ov::op::v1::Reshape>(cur) || ov::is_type<ov::op::util::BroadcastBase>(cur);+ OPENVINO_ASSERT(has_target_shape || ov::is_type<ov::op::v0::Unsqueeze>(cur),+ "[SWA] Unexpected op '",+ cur->get_type_name(),+ "' between SDPA and past_kv Concat (only Reshape/Broadcast/Unsqueeze allowed).");++ if (has_target_shape) {+ const auto& src = cur->input_value(kShapeInputIdx);+ auto folded = ov::util::get_constant_from_source(src);+ OPENVINO_ASSERT(folded, "[SWA] ", cur->get_type_name(), " target shape must be constant-foldable.");++ auto vals = folded->cast_vector<int64_t>();+ OPENVINO_ASSERT(vals.size() >= 2, "[SWA] ", cur->get_type_name(), " target shape rank must be >= 2.");++ const size_t kv_axis = vals.size() - 2;+ const int64_t old_val = vals[kv_axis];+ OPENVINO_ASSERT(old_val == kvcache_size || old_val == -1,+ "[SWA] ",+ cur->get_type_name(),+ " target shape kv_axis expected ",+ kvcache_size,+ " or -1, got ",+ old_val,+ ".");++ if (old_val == -1) {+ LOG_DEBUG("[SWA] " << cur->get_type_name() << " '" << cur->get_friendly_name()+ << "' kv_axis=" << kv_axis << " uses inferred extent (-1); keep it unchanged.");+ } else {+ vals[kv_axis] = new_kv_total;+ auto priv =+ std::make_shared<ov::op::v0::Constant>(src.get_element_type(), ov::Shape{vals.size()}, vals);+ priv->set_friendly_name(cur->get_friendly_name() + "/swa_kv_patched");+ cur->input(kShapeInputIdx).replace_source_output(priv);+ LOG_DEBUG("[SWA] Patched " << cur->get_type_name() << " '" << cur->get_friendly_name() << "' kv_axis="+ << kv_axis << ": " << kvcache_size << " -> " << new_kv_total);+ }+ }+ cur = cur->input_value(0).get_node_shared_ptr();+ }++ auto concat = ov::as_type_ptr<ov::op::v0::Concat>(cur);+ OPENVINO_ASSERT(concat, "[SWA] KV path (port ", kv_port, ") did not reach past_kv Concat.");+ return concat;+}++void freeze_shapeof_consumers(const ov::Output<ov::Node>& producer_output,+ const std::shared_ptr<ov::Node>& skip_consumer,+ const std::shared_ptr<ov::op::v0::Concat>& concat,+ const char* via,+ std::unordered_set<const ov::Node*>& seen) {+ for (const auto& target : producer_output.get_target_inputs()) {+ auto consumer = target.get_node()->shared_from_this();+ if (skip_consumer && consumer == skip_consumer) {+ continue;+ }+ if (consumer == concat) {+ continue;+ }++ auto shapeof = ov::as_type_ptr<ov::op::util::ShapeOfBase>(consumer);+ OPENVINO_ASSERT(shapeof,+ "[SWA] past_kv has unsupported consumer '",+ consumer->get_type_name(),+ "' via ",+ via,+ " (only Concat/ShapeOf allowed).");++ if (!seen.insert(shapeof.get()).second) {+ continue;+ }+ auto folded = ov::util::get_constant_from_source(shapeof->output(0));+ OPENVINO_ASSERT(folded, "[SWA] Failed to fold ShapeOf output.");+ auto vals = folded->cast_vector<int64_t>();+ auto frozen =+ std::make_shared<ov::op::v0::Constant>(shapeof->output(0).get_element_type(), ov::Shape{vals.size()}, vals);+ frozen->set_friendly_name(shapeof->get_friendly_name() + "/swa_shapeof_frozen");++ const auto users = shapeof->output(0).get_target_inputs();+ for (const auto& user : users) {+ user.replace_source_output(frozen);+ }+ LOG_DEBUG("[SWA] Froze shared ShapeOf '" << shapeof->get_friendly_name() << "'.");+ }+}++// An SWA past_kv Parameter may only feed its own KV Concat and ShapeOf, optionally via an+// in-between Convert. Freeze each ShapeOf output to a constant before the Parameter is+// resized, so its consumers keep seeing the pre-shrink shape.+//+// Supported consumers of past_kv (Convert is optional):+// Parameter -> [Convert] -> Concat(past_kv, cur_kv) [KV path; left untouched]+// Parameter -> [Convert] -> ShapeOf [frozen to a Constant]+void freeze_shapeofs(const PastKVSource& source,+ const std::shared_ptr<ov::op::v0::Concat>& concat,+ std::unordered_set<const ov::Node*>& seen) {+ freeze_shapeof_consumers(source.param->output(0), source.convert, concat, "Parameter", seen);++ if (source.convert) {+ freeze_shapeof_consumers(source.convert->output(0), nullptr, concat, "Convert", seen);+ }+}++// Scans every SDPA node once, in topological order. For each SWA one found, externalizes+// its mask into one shared Parameter (created on first encounter), patches its K/V shape+// dependencies, and shrinks its past_kv Parameter. Topology violations abort with an error+// as soon as they are found.+void scan_and_patch(const std::shared_ptr<ov::Model>& model,+ int64_t kvcache_size,+ int64_t new_past,+ int64_t new_kv_total,+ size_t seq_len_axis) {+ std::unordered_set<const ov::Node*> seen_shapeof;+ std::unordered_set<const ov::Node*> seen_param;+ std::shared_ptr<ov::op::v0::Parameter> mask_param;+ ov::PartialShape mask_shape;+ ov::element::Type mask_type;+ size_t num_masks_externalized = 0;+ size_t num_params_shrunk = 0;++ for (const auto& node : model->get_ordered_ops()) {+ auto sdpa = ov::as_type_ptr<SDPA>(node);+ if (!sdpa) {+ continue;+ }+ if (!is_sliding_sdpa(sdpa)) {+ continue; // skip non-SWA SDPAs+ }+ LOG_DEBUG("[SWA] Patching SWA SDPA '" << sdpa->get_friendly_name() << "'");++ // Mask: externalize into one shared Parameter, created on first SWA SDPA encountered.+ OPENVINO_ASSERT(sdpa->get_input_size() > kSdpaMaskInputIdx,+ "[SWA] SDPA must have at least ",+ kSdpaMaskInputIdx + 1,+ " inputs (mask required).");+ auto mask_port = sdpa->input(kSdpaMaskInputIdx);+ const ov::PartialShape sdpa_mask_shape = mask_port.get_partial_shape();+ const ov::element::Type sdpa_mask_type = sdpa->input_value(kSdpaMaskInputIdx).get_element_type();+ if (!mask_param) {+ OPENVINO_ASSERT(sdpa_mask_shape.is_static() && sdpa_mask_shape.size() > 0,+ "[SWA] SDPA mask input must be static with non-zero rank.");+ mask_shape = sdpa_mask_shape;+ mask_type = sdpa_mask_type;+ ov::PartialShape param_shape = mask_shape;+ const size_t last_axis = param_shape.size() - 1;+ const int64_t old_mask_width = param_shape[last_axis].get_length();+ param_shape[last_axis] = new_kv_total;++ mask_param = std::make_shared<ov::op::v0::Parameter>(mask_type, param_shape);+ mask_param->set_friendly_name(ov::npuw::util::kSlidingWindowAttentionMaskParamName);+ mask_param->get_output_tensor(0).set_names({ov::npuw::util::kSlidingWindowAttentionMaskParamName});+ model->add_parameters({mask_param});+ LOG_DEBUG("[SWA] Externalized SWA SDPA mask as '" << ov::npuw::util::kSlidingWindowAttentionMaskParamName+ << "'; last axis " << old_mask_width << " -> "+ << new_kv_total << ".");+ } else {+ OPENVINO_ASSERT(sdpa_mask_shape == mask_shape, "[SWA] mask shape mismatch across SWA layers.");+ OPENVINO_ASSERT(sdpa_mask_type == mask_type, "[SWA] mask type mismatch across SWA layers.");+ }+ mask_port.replace_source_output(mask_param->output(0));+ ++num_masks_externalized;++ // K/V: patch shape constants along the way, then shrink the past_kv Parameter (once).+ for (const size_t kv_port : {kSdpaKeyInputIdx, kSdpaValueInputIdx}) {+ auto concat = scan_kv_path(sdpa, kv_port, kvcache_size, new_kv_total);+ const auto source = find_past_kv_source(concat);+ OPENVINO_ASSERT(source.param, "[SWA] KV path (port ", kv_port, ") Concat has no past_kv Parameter input.");+ freeze_shapeofs(source, concat, seen_shapeof);++ if (!seen_param.insert(source.param.get()).second) {+ continue;+ }+ const auto& pshape = source.param->get_partial_shape();+ OPENVINO_ASSERT(+ pshape.rank().is_static() && seq_len_axis < pshape.size() && pshape[seq_len_axis].is_static(),+ "[SWA] Past KV '",+ source.param->get_friendly_name(),+ "' needs static rank and static seq_len axis (",+ seq_len_axis,+ ").");++ ov::PartialShape new_shape = pshape;+ const int64_t old_past = new_shape[seq_len_axis].get_length();+ new_shape[seq_len_axis] = new_past;+ source.param->set_partial_shape(new_shape);+ source.param->get_rt_info()[ov::npuw::util::NPUW_KV_CACHE_SLIDING_RT_KEY] = true;+ ++num_params_shrunk;+ LOG_DEBUG("[SWA] Past KV '" << source.param->get_friendly_name() << "' seq_len " << old_past << " -> "+ << new_past << " (post-concat total=" << new_kv_total << ")");+ }+ }++ LOG_INFO("[SWA] Externalized " << num_masks_externalized << " SWA SDPA mask input(s) as '"+ << ov::npuw::util::kSlidingWindowAttentionMaskParamName << "' and shrunk "+ << num_params_shrunk << " past_key_values parameter(s) in '"+ << model->get_friendly_name() << "'.");++ model->validate_nodes_and_infer_types();+}++} // namespace++namespace ov::npuw {++ShrinkSlidingWindowKVCache::ShrinkSlidingWindowKVCache(uint32_t kvcache_size,+ uint32_t input_size,+ const KVAxesPosition& kv_axes_position)+ : m_kvcache_size(kvcache_size),+ m_input_size(input_size),+ m_kv_axes_position(kv_axes_position) {}++bool ShrinkSlidingWindowKVCache::run_on_model(const std::shared_ptr<ov::Model>& model) {+ const uint32_t window_size = detect_swa_window_size(model);+ if (window_size == 0) {+ LOG_DEBUG("[SWA] Sliding Window Attention is not configured, skipping " << model->get_friendly_name());+ return false;+ }++ OPENVINO_ASSERT(m_input_size <= m_kvcache_size,+ "[SWA] input_size (",+ m_input_size,+ ") exceeds kvcache_size (",+ m_kvcache_size,+ ").");++ // available_past == 0 means prefill consumes the whole KV budget in one shot.+ // Typical cases:+ // 1) chunk prefill is disabled; or+ // 2) prefill_chunk_size == max_prompt_len (for example, both are 1k).+ // Result: there is no past region, so SWA layers keep no past KV.+ const uint32_t available_past = m_kvcache_size - m_input_size;+ OPENVINO_ASSERT(available_past == 0 || window_size <= available_past,+ "[SWA] window_size (",+ window_size,+ ") exceeds available_past (",+ available_past,+ ").");+ const int64_t new_past = available_past == 0 ? 0 : static_cast<int64_t>(window_size);+ const int64_t new_kv_total = static_cast<int64_t>(m_input_size) + new_past;++ LOG_INFO("[SWA] ShrinkSlidingWindowKVCache: model='"+ << model->get_friendly_name() << "' kvcache=" << m_kvcache_size << " input=" << m_input_size+ << " window=" << window_size << " new_past=" << new_past << " new_kv_total=" << new_kv_total);++ const size_t seq_len_axis = static_cast<size_t>(m_kv_axes_position.seq_len);+ scan_and_patch(model, static_cast<int64_t>(m_kvcache_size), new_past, new_kv_total, seq_len_axis);+ return true;+}++} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/shrink_sliding_window_kv_cache.hpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/shrink_sliding_window_kv_cache.hppnew file mode 100644index 00000000000..c3fe2751668--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/shrink_sliding_window_kv_cache.hpp@@ -0,0 +1,44 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstdint>++#include "kv_axes_position.hpp"+#include "openvino/pass/pass.hpp"++namespace ov::npuw {++// Model pass for decoders with sliding-window attention (SWA) layers, whether hybrid+// (mixed SWA and full attention layers) or uniformly SWA.+//+// Responsibilities:+// 1) Externalize the SWA SDPA mask input as one model parameter: "sliding_window_attention_mask".+// 2) Shrink the past_key_values seq_len axis for SWA layers only.+// 3) Shrink the externalized mask width to the same post-concat KV width.+// 4) Privatize and patch KV-length-dependent shape constants (Broadcast/Reshape) to prevent+// cross-layer shared-shape leakage from SWA layers into full attention layers.+//+// SWA contract:+// - new_past = window_size+// - new_kv_total = input_size + window_size+//+// Pass ordering:+// - Run after ReshapeToStatic.+// - Run before DecomposeGQA / V-tensor optimization passes.+//+// Executed once per model variant (prefill and each generate KV-size bucket).+class ShrinkSlidingWindowKVCache : public ov::pass::ModelPass {+ uint32_t m_kvcache_size;+ uint32_t m_input_size;+ KVAxesPosition m_kv_axes_position;++public:+ OPENVINO_MODEL_PASS_RTTI("ov::npuw::ShrinkSlidingWindowKVCache");+ ShrinkSlidingWindowKVCache(uint32_t kvcache_size, uint32_t input_size, const KVAxesPosition& kv_axes_position);+ bool run_on_model(const std::shared_ptr<ov::Model>& model) override;+};++} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmakeindex 686f6c334a6..492f5374867 100644--- a/src/plugins/intel_npu/src/plugin/sources.cmake+++ b/src/plugins/intel_npu/src/plugin/sources.cmake@@ -67,6 +67,7 @@ set(NPUW_SOURCES${CMAKE_CURRENT_SOURCE_DIR}/npuw/just_sync_infer_request.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/kv_cache_block_manager.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/kv_cache_block_manager.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/kv_cache_sliding_window_manager.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/lazy_tensor.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/lazy_tensor.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_block_kvcache_strategy.cpp@@ -135,6 +136,8 @@ set(NPUW_SOURCES${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/lora_stateful_to_stateless.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/optimize_value_tensors.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/optimize_value_tensors.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/shrink_sliding_window_kv_cache.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/shrink_sliding_window_kv_cache.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/patch_sliding_window_mask.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/patch_sliding_window_mask.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/npuw_transformations/remove_token_type_ids.cppdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 6bd20669cb3..18189c24d00 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -113,6 +113,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/untangle_dq_scale.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/lora_stateful_to_stateless.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/optimize_value_tensors.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/shrink_sliding_window_kv_cache.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/patch_sliding_window_mask.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/sliding_window_mask.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/detect_causal_mask.cpp@@ -189,6 +190,7 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/conv_to_matmul_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/patch_sliding_mask_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/detect_causal_mask_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/shrink_sliding_window_kv_cache_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/remove_empty_kv_inputs_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/remove_token_type_ids_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/pipeline_passes/stateful_to_stateless_test.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/shrink_sliding_window_kv_cache_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/shrink_sliding_window_kv_cache_test.cppnew file mode 100644index 00000000000..42c568647dc--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/pipeline_passes/shrink_sliding_window_kv_cache_test.cpp@@ -0,0 +1,347 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Tests for ShrinkSlidingWindowKVCache.+// Focus: sliding-mask externalization and sliding/full layer shape invariants.+//+// The pass is invoked directly rather than through LLMCompiledModel, so the tests+// stay independent of pipeline wiring. run_shrink_pass() reproduces exactly the+// preparation LLMCompiledModel performs right before this pass: annotate per-SDPA+// mask kinds, derive the SWA layout, then reshape to static.++#include "npuw_transformations/shrink_sliding_window_kv_cache.hpp"++#include <gtest/gtest.h>++#include <cstdint>+#include <map>+#include <memory>+#include <string>++#include "kv_cache_sliding_window_manager.hpp"+#include "llm_pass_test_fixture.hpp"+#include "npuw_transformations/add_position_ids_param.hpp"+#include "npuw_transformations/detect_causal_mask.hpp"+#include "npuw_transformations/kv_axes_position.hpp"+#include "npuw_transformations/reshape_to_static.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/scaled_dot_product_attention.hpp"+#include "openvino/pass/stateful_to_stateless.hpp"++namespace {++class ShrinkSlidingWindowKVCacheTest : public ov::test::npuw::LLMPassTestFixture {};++// Maps layer index parsed from "model.layers.N.self_attn" to SDPA node.+std::map<size_t, std::shared_ptr<ov::op::v13::ScaledDotProductAttention>> sdpa_by_layer(+ const std::shared_ptr<ov::Model>& model) {+ std::map<size_t, std::shared_ptr<ov::op::v13::ScaledDotProductAttention>> result;+ const std::string marker = "model.layers.";+ for (const auto& op : model->get_ordered_ops()) {+ auto sdpa = ov::as_type_ptr<ov::op::v13::ScaledDotProductAttention>(op);+ if (!sdpa) {+ continue;+ }+ const auto& name = sdpa->get_friendly_name();+ auto pos = name.find(marker);+ if (pos == std::string::npos) {+ continue;+ }+ result[std::stoul(name.substr(pos + marker.size()))] = sdpa;+ }+ return result;+}++constexpr size_t kWindowSize = 32; // deliberately << kvcache_size (192) to be distinguishable.+constexpr size_t kNumLayers = 4; // layers 0,2 sliding; layers 1,3 full-attention.++// Mirror of the default LLMPassTestFixture properties: max prompt 128, min response 64.+constexpr uint32_t kMaxPromptLen = 128;+constexpr uint32_t kKvCacheSize = 192;+constexpr uint32_t kGenerateInputSize = 1;+const ov::npuw::KVAxesPosition kAxes{0u, 2u};++std::shared_ptr<ov::Model> build_hybrid_model() {+ return ov::test::npuw::build_sliding_window_test_model(kWindowSize, /*sliding_to_full_ratio=*/1, {}, kNumLayers);+}++// GQA variant: num_kv_heads < num_heads makes repeat_kv insert a Broadcast whose target+// shape carries the KV length, which is exactly what the pass has to privatize and patch.+std::shared_ptr<ov::Model> build_hybrid_gqa_model() {+ auto cfg = ov::test::npuw::make_test_model_config();+ cfg.num_layers = kNumLayers;+ cfg.num_kv_heads = 2;+ cfg.sliding_window_size = kWindowSize;+ cfg.sliding_to_full_ratio = 1;+ ov::test::npuw::ModelBuilder mb;+ return mb.build_llm(cfg);+}++// Runs the same preparation sequence LLMCompiledModel applies before the pass under test.+std::shared_ptr<ov::Model> run_shrink_pass(const std::shared_ptr<ov::Model>& model,+ uint32_t input_size,+ uint32_t kvcache_size,+ bool is_prefill) {+ ov::npuw::AddPositionIdsParam().run_on_model(model);+ ov::pass::StatefulToStateless().run_on_model(model);+ ov::npuw::DetectAttentionMask().run_on_model(model);+ ov::npuw::ReshapeToStatic(input_size, kvcache_size, kAxes, /*lora_rank=*/0, /*lhs_seq_size=*/0, is_prefill)+ .run_on_model(model);+ ov::npuw::ShrinkSlidingWindowKVCache(kvcache_size, input_size, kAxes).run_on_model(model);+ return model;+}++std::shared_ptr<ov::Model> make_generate_model(const std::shared_ptr<ov::Model>& model) {+ return run_shrink_pass(model, kGenerateInputSize, kKvCacheSize, /*is_prefill=*/false);+}++std::shared_ptr<ov::Model> make_prefill_model(const std::shared_ptr<ov::Model>& model) {+ return run_shrink_pass(model, kMaxPromptLen, kMaxPromptLen, /*is_prefill=*/true);+}++} // namespace++// Hybrid model invariant: both generate and prefill expose only the sliding-mask input.+TEST_F(ShrinkSlidingWindowKVCacheTest, PrefillAndGenerate_ExternalizeOnlySlidingMask) {+ std::shared_ptr<ov::Model> generate;+ std::shared_ptr<ov::Model> prefill;+ ASSERT_NO_THROW(generate = make_generate_model(build_hybrid_model()));+ ASSERT_NO_THROW(prefill = make_prefill_model(build_hybrid_model()));++ EXPECT_EQ(count_inputs(generate, "sliding_window_attention_mask"), 1u);+ EXPECT_EQ(count_inputs(generate, "global_attention_mask"), 0u);+ EXPECT_EQ(count_inputs(prefill, "sliding_window_attention_mask"), 1u);+ EXPECT_EQ(count_inputs(prefill, "global_attention_mask"), 0u);+}++// Baseline invariant: non-hybrid models must not gain sliding_window_attention_mask.+TEST_F(ShrinkSlidingWindowKVCacheTest, NonHybridModel_NoMaskExternalized) {+ std::shared_ptr<ov::Model> generate;+ // Default build_llm_test_model(), no SWA.+ ASSERT_NO_THROW(generate = make_generate_model(ov::test::npuw::build_llm_test_model()));++ EXPECT_EQ(count_inputs(generate, "sliding_window_attention_mask"), 0u);+ EXPECT_EQ(count_inputs(generate, "global_attention_mask"), 0u);+}++// Layer-selective invariant: only sliding layers shrink the past-KV sequence axis.+TEST_F(ShrinkSlidingWindowKVCacheTest, GenerateModel_OnlySlidingLayersPastKVShrunk) {+ std::shared_ptr<ov::Model> generate;+ ASSERT_NO_THROW(generate = make_generate_model(build_hybrid_model()));++ // kvcache_size=192, generate input_size=1 => full past=191.+ const auto sliding_past = input_shape(generate, "past_key_values.0.key");+ ASSERT_TRUE(sliding_past.has_value()) << "past_key_values.0.key not found in generate model";+ EXPECT_EQ((*sliding_past)[2], kWindowSize);++ const auto full_past = input_shape(generate, "past_key_values.1.key");+ ASSERT_TRUE(full_past.has_value()) << "past_key_values.1.key not found in generate model";+ EXPECT_EQ((*full_past)[2], 191u);+}++// Generate invariant: sliding mask width matches the post-concat KV total width.+TEST_F(ShrinkSlidingWindowKVCacheTest, GenerateModel_SlidingMaskWidthShrunkToNewKvTotal) {+ std::shared_ptr<ov::Model> generate;+ ASSERT_NO_THROW(generate = make_generate_model(build_hybrid_model()));++ const auto mask_shape = input_shape(generate, "sliding_window_attention_mask");+ ASSERT_TRUE(mask_shape.has_value()) << "sliding_window_attention_mask not found in generate model";++ // Generate input_size=1, window=32 => new_kv_total=33.+ EXPECT_EQ(mask_shape->back(), 33u);+}++// Prefill invariant: sliding mask width follows the same post-concat KV width rule.+TEST_F(ShrinkSlidingWindowKVCacheTest, PrefillModel_SlidingMaskWidthShrunkToNewKvTotal) {+ std::shared_ptr<ov::Model> prefill;+ ASSERT_NO_THROW(prefill = make_prefill_model(build_hybrid_model()));++ const auto mask_shape = input_shape(prefill, "sliding_window_attention_mask");+ ASSERT_TRUE(mask_shape.has_value()) << "sliding_window_attention_mask not found in prefill model";+ const auto input_ids_shape = input_shape(prefill, "input_ids");+ ASSERT_TRUE(input_ids_shape.has_value()) << "input_ids not found in prefill model";+ const auto sliding_past = input_shape(prefill, "past_key_values.0.key");++ const size_t expected_width =+ sliding_past.has_value() ? ((*sliding_past)[2] + input_ids_shape->back()) : input_ids_shape->back();++ // Invariant: mask width = post-concat total width.+ EXPECT_EQ(mask_shape->back(), expected_width);+}++// Only sliding-layer past KV parameters get SWA rt_info tag.+TEST_F(ShrinkSlidingWindowKVCacheTest, GenerateModel_OnlySlidingLayersPastKVTaggedWithRtInfo) {+ std::shared_ptr<ov::Model> generate;+ ASSERT_NO_THROW(generate = make_generate_model(build_hybrid_model()));++ const auto sliding_input = find_input(generate, "past_key_values.0.key");+ ASSERT_TRUE(sliding_input.has_value()) << "past_key_values.0.key not found in generate model";+ EXPECT_TRUE(sliding_input->get_node()->get_rt_info().count(ov::npuw::util::NPUW_KV_CACHE_SLIDING_RT_KEY) > 0);++ const auto full_input = find_input(generate, "past_key_values.1.key");+ ASSERT_TRUE(full_input.has_value()) << "past_key_values.1.key not found in generate model";+ EXPECT_EQ(full_input->get_node()->get_rt_info().count(ov::npuw::util::NPUW_KV_CACHE_SLIDING_RT_KEY), 0u);+}++// Input-source invariant: sliding SDPA consumes the externalized mask, full-attention SDPA does not.+TEST_F(ShrinkSlidingWindowKVCacheTest, GenerateModel_SlidingSDPAUsesExternalizedMask_FullSDPADoesNot) {+ std::shared_ptr<ov::Model> generate;+ ASSERT_NO_THROW(generate = make_generate_model(build_hybrid_model()));++ const auto sdpa_map = sdpa_by_layer(generate);+ ASSERT_EQ(sdpa_map.size(), kNumLayers);++ auto is_sliding_mask_param = [](const ov::Node* node) {+ auto param = ov::as_type<const ov::op::v0::Parameter>(node);+ return param != nullptr && param->get_friendly_name() == "sliding_window_attention_mask";+ };++ // Sliding layers (0, 2): mask input IS the externalized Parameter.+ EXPECT_TRUE(is_sliding_mask_param(sdpa_map.at(0)->input_value(3).get_node()));+ EXPECT_TRUE(is_sliding_mask_param(sdpa_map.at(2)->input_value(3).get_node()));++ // Full-attention layers (1, 3): mask input is NOT the externalized Parameter.+ EXPECT_FALSE(is_sliding_mask_param(sdpa_map.at(1)->input_value(3).get_node()));+ EXPECT_FALSE(is_sliding_mask_param(sdpa_map.at(3)->input_value(3).get_node()));+}++// Single-shot prefill (input_size == kvcache_size) leaves no past region at all, unlike+// generate, which keeps a window-sized past.+TEST_F(ShrinkSlidingWindowKVCacheTest, PrefillSingleShot_SlidingPastIsZero_GenerateKeepsWindowSizedPast) {+ std::shared_ptr<ov::Model> generate;+ std::shared_ptr<ov::Model> prefill;+ ASSERT_NO_THROW(generate = make_generate_model(build_hybrid_model()));+ ASSERT_NO_THROW(prefill = make_prefill_model(build_hybrid_model()));++ const auto prefill_sliding_past = input_shape(prefill, "past_key_values.0.key");+ ASSERT_TRUE(prefill_sliding_past.has_value()) << "past_key_values.0.key not found in prefill model";+ EXPECT_EQ((*prefill_sliding_past)[2], 0u);++ const auto generate_sliding_past = input_shape(generate, "past_key_values.0.key");+ ASSERT_TRUE(generate_sliding_past.has_value()) << "past_key_values.0.key not found in generate model";+ EXPECT_EQ((*generate_sliding_past)[2], kWindowSize);+}++// Chunked prefill (input_size < kvcache_size) leaves a nonzero past budget, so sliding+// layers are capped to the window size, same as generate, rather than left at zero.+TEST_F(ShrinkSlidingWindowKVCacheTest, ChunkedPrefill_SlidingLayerKeepsWindowSizedPast) {+ constexpr uint32_t kChunkSize = 64; // < kKvCacheSize (192), so available_past > 0.+ std::shared_ptr<ov::Model> prefill;+ ASSERT_NO_THROW(prefill = run_shrink_pass(build_hybrid_model(), kChunkSize, kKvCacheSize, /*is_prefill=*/true));++ const auto sliding_past = input_shape(prefill, "past_key_values.0.key");+ ASSERT_TRUE(sliding_past.has_value()) << "past_key_values.0.key not found in prefill model";+ EXPECT_EQ((*sliding_past)[2], kWindowSize);+}++// Shape-privatization invariant: KV target-shape constants that carried the full kvcache+// length are replaced by private constants holding the new post-concat KV total.+TEST_F(ShrinkSlidingWindowKVCacheTest, GenerateModel_SlidingKVShapeConstantsPatchedToNewKvTotal) {+ std::shared_ptr<ov::Model> generate;+ ASSERT_NO_THROW(generate = make_generate_model(build_hybrid_gqa_model()));++ // Generate input_size=1, window=32 => new_kv_total=33.+ constexpr int64_t kNewKvTotal = 33;+ std::size_t num_patched = 0;+ for (const auto& op : generate->get_ordered_ops()) {+ auto constant = ov::as_type_ptr<ov::op::v0::Constant>(op);+ if (!constant || constant->get_friendly_name().find("/swa_kv_patched") == std::string::npos) {+ continue;+ }+ const auto vals = constant->cast_vector<int64_t>();+ ASSERT_GE(vals.size(), 2u) << constant->get_friendly_name();+ EXPECT_EQ(vals[vals.size() - 2], kNewKvTotal) << constant->get_friendly_name();+ ++num_patched;+ }++ // Sliding layers (0, 2) only, each patching its K and V repeat_kv Broadcast.+ EXPECT_EQ(num_patched, 4u);+}++// SWA window-size detection is internal to the pass, exercised here indirectly through+// its public run_on_model(). Minimal raw SDPA-only models with no KV-cache/Concat structure+// are enough for these checks, since each returns or throws before the pass would need any+// KV-cache structure to walk.+namespace {++// Builds a minimal SDPA-per-layer model with no KV-cache/Concat structure. Entries absent+// from layer_mask_annotations are left unannotated.+std::shared_ptr<ov::Model> make_annotated_sdpa_model(size_t num_layers,+ const std::map<size_t, int64_t>& layer_mask_annotations) {+ using namespace ov::op;+ ov::ParameterVector params;+ ov::ResultVector results;+ for (size_t layer_idx = 0; layer_idx < num_layers; ++layer_idx) {+ auto q = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, 8});+ auto k = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, 8});+ auto v = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, 8});+ auto sdpa = std::make_shared<v13::ScaledDotProductAttention>(q, k, v, false);+ sdpa->set_friendly_name("model.layers." + std::to_string(layer_idx) + ".self_attn/sdpa");+ const auto it = layer_mask_annotations.find(layer_idx);+ if (it != layer_mask_annotations.end()) {+ sdpa->get_rt_info()[ov::npuw::NPUW_SDPA_MASK_RT_KEY] = it->second;+ }+ params.insert(params.end(), {q, k, v});+ results.push_back(std::make_shared<v0::Result>(sdpa->output(0)));+ }+ return std::make_shared<ov::Model>(results, params);+}++} // namespace++// No annotations at all -> pass is a no-op.+TEST(ShrinkSlidingWindowKVCacheDetectionTest, NoAnnotatedLayers_NoOp) {+ const auto model = make_annotated_sdpa_model(2, {});+ bool applied = true;+ ASSERT_NO_THROW(+ applied = ov::npuw::ShrinkSlidingWindowKVCache(kKvCacheSize, kGenerateInputSize, kAxes).run_on_model(model));+ EXPECT_FALSE(applied);+}++// All causal, no sliding -> pass is a no-op.+TEST(ShrinkSlidingWindowKVCacheDetectionTest, AllLayersCausal_NoOp) {+ const auto model = make_annotated_sdpa_model(3, {{0, -1}, {1, -1}, {2, -1}});+ bool applied = true;+ ASSERT_NO_THROW(+ applied = ov::npuw::ShrinkSlidingWindowKVCache(kKvCacheSize, kGenerateInputSize, kAxes).run_on_model(model));+ EXPECT_FALSE(applied);+}++// Sliding layers must use a single uniform window size.+TEST(ShrinkSlidingWindowKVCacheDetectionTest, InconsistentWindowSizes_Throws) {+ const auto model = make_annotated_sdpa_model(3, {{0, 128}, {1, -1}, {2, 256}});+ EXPECT_THROW(ov::npuw::ShrinkSlidingWindowKVCache(kKvCacheSize, kGenerateInputSize, kAxes).run_on_model(model),+ ov::Exception);+}++// Configuration error: the detected SWA window is larger than the KV budget actually+// available (kvcache_size - input_size).+TEST(ShrinkSlidingWindowKVCacheDetectionTest, WindowSizeExceedsAvailablePast_Throws) {+ const auto model = make_annotated_sdpa_model(1, {{0, 128}});+ constexpr uint32_t kSmallKvCacheSize = 100;+ constexpr uint32_t kSmallInputSize = 50; // available_past = 50 < window_size (128).+ EXPECT_THROW(ov::npuw::ShrinkSlidingWindowKVCache(kSmallKvCacheSize, kSmallInputSize, kAxes).run_on_model(model),+ ov::Exception);+}++// All-sliding (uniform, no full-attention layer) model still gets fully shrunk: the hybrid+// gate only requires at least one sliding layer, not a mix of sliding and full-attention.+TEST_F(ShrinkSlidingWindowKVCacheTest, AllLayersSliding_MaskExternalizedAndPastShrunk) {+ std::shared_ptr<ov::Model> generate;+ ASSERT_NO_THROW(generate = make_generate_model(+ ov::test::npuw::build_sliding_window_test_model(kWindowSize, /*sliding_to_full_ratio=*/0)));++ EXPECT_EQ(count_inputs(generate, "sliding_window_attention_mask"), 1u);++ const auto past0 = input_shape(generate, "past_key_values.0.key");+ ASSERT_TRUE(past0.has_value()) << "past_key_values.0.key not found in generate model";+ EXPECT_EQ((*past0)[2], kWindowSize);++ const auto past1 = input_shape(generate, "past_key_values.1.key");+ ASSERT_TRUE(past1.has_value()) << "past_key_values.1.key not found in generate model";+ EXPECT_EQ((*past1)[2], kWindowSize);+}