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][PR3] Integrate Sliding Window Attention Module and Enable Pipeline (#38041)
Guoliang Shib416a27b0974
diff --git a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.incindex e844d18cd39..a6d9c4e7481 100644--- a/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc+++ b/src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc@@ -75,6 +75,7 @@ INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_PREFIX_CACHING_MAX_NUM_BLOCKS, uint64_t, 128,INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_ENABLE_CONTINUOUS_PREFILL, bool, false, ov::intel_npu::npuw::llm, enable_continuous_prefill, "NPUW_LLM_ENABLE_CONTINUOUS_PREFILL", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_CACHE_ROPE, bool, true, ov::intel_npu::npuw::llm, cache_rope, "NPUW_LLM_CACHE_ROPE", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE, bool, false, ov::intel_npu::npuw::llm, enable_block_based_kv_cache, "NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE", LLM, EXPOSED, CACHED, ALL)+INTEL_NPU_NPUW_SIMPLE_OPT(NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK, bool, false, ov::intel_npu::npuw::llm, enable_swa_kv_cache_shrink, "NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_STRING_ENUM_OPT(NPUW_LLM_PREFILL_MOE_HINT, ::intel_npu::npuw::llm::MoEHint, MoEHintOptionTraits, ov::intel_npu::npuw::llm, prefill_moe_hint, "NPUW_LLM_PREFILL_MOE_HINT", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_STRING_ENUM_OPT(NPUW_LLM_GENERATE_MOE_HINT, ::intel_npu::npuw::llm::MoEHint, MoEHintOptionTraits, ov::intel_npu::npuw::llm, generate_moe_hint, "NPUW_LLM_GENERATE_MOE_HINT", LLM, EXPOSED, CACHED, ALL)INTEL_NPU_NPUW_STRING_ENUM_OPT(NPUW_LLM_PREFILL_HINT, ::intel_npu::npuw::llm::PrefillHint, PrefillHintOptionTraits, ov::intel_npu::npuw::llm, prefill_hint, "NPUW_LLM_PREFILL_HINT", LLM, EXPOSED, CACHED, ALL)diff --git a/src/plugins/intel_npu/src/plugin/npuw/kv_cache_sliding_window_manager.cpp b/src/plugins/intel_npu/src/plugin/npuw/kv_cache_sliding_window_manager.cppindex 3c20476c47f..b528a7f953d 100644--- a/src/plugins/intel_npu/src/plugin/npuw/kv_cache_sliding_window_manager.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/kv_cache_sliding_window_manager.cpp@@ -78,14 +78,14 @@ namespace {template <typename T>void fill_causal_sliding_window_mask_typed(const MaskView& mask_view,uint32_t num_stored_tokens,- uint32_t window_size) {+ uint32_t window_size,+ bool past_is_circular) {const uint32_t stored_tokens = num_stored_tokens;const uint32_t past_width = mask_view.past_width;const uint32_t row_dim = mask_view.row_dim;const uint32_t row_pad = mask_view.row_pad;const bool has_past_region = past_width > 0u;const bool is_past_saturated = has_past_region && stored_tokens >= past_width;- const uint32_t wrap_slot = is_past_saturated ? (stored_tokens % past_width) : 0u;const int64_t stored_tokens_i64 = static_cast<int64_t>(stored_tokens);const int64_t past_width_i64 = static_cast<int64_t>(past_width);const int64_t window_i64 = static_cast<int64_t>(window_size);@@ -94,15 +94,20 @@ void fill_causal_sliding_window_mask_typed(const MaskView& mask_view,const T kAttend = T(0.0f);const T kMasked = T(std::numeric_limits<ov::float16>::lowest());- // Row columns = [past circular slots][current-chunk columns]+ // Row columns = [past slots][current-chunk columns]// = [0 .. past_width-1] [past_width .. past_width+row_dim-1].// past_width == 0 degenerates to current-chunk-only masking.//- // Past slot -> absolute token index:- // unsaturated (stored_tokens < past_width): abs == slot, for slot < stored_tokens.- // saturated (stored_tokens >= past_width), wrap_slot = stored_tokens % past_width:- // [0, wrap_slot): abs = (stored_tokens - wrap_slot) + slot- // [wrap_slot, past_width): abs = (stored_tokens - wrap_slot) + slot - past_width+ // Past slot -> absolute token index depends on the past buffer's physical layout, which+ // must match past_is_circular:+ // unsaturated (stored_tokens < past_width), either layout: abs == slot, for slot < stored_tokens.+ // saturated (stored_tokens >= past_width):+ // circular layout, wrap_slot = stored_tokens % past_width:+ // [0, wrap_slot): abs = (stored_tokens - wrap_slot) + slot+ // [wrap_slot, past_width): abs = (stored_tokens - wrap_slot) + slot - past_width+ // chronologically packed layout: shifting (not wrapping) keeps the buffer in order,+ // so there is no split -- a single range:+ // [0, past_width): abs = (stored_tokens - past_width) + slot//// Visibility: attend(abs) iff abs in [row_abs_pos - window_size + 1, row_abs_pos] (causal +// window). Current-chunk equivalent: local_c in [max(row_pad, row-window_size+1), row].@@ -142,15 +147,27 @@ void fill_causal_sliding_window_mask_typed(const MaskView& mask_view,};// Visible slot ranges in the past region for one row. A saturated ring wraps into at most- // two contiguous ranges (returned as a fixed-size array to avoid a per-row allocation).+ // two contiguous ranges; a saturated chronologically-packed buffer never wraps (returned+ // as a fixed-size array either way to avoid a per-row allocation).auto compute_visible_past_slots = [&](int64_t min_visible_abs_pos,int64_t max_visible_abs_pos) -> std::array<VisibleRange, 2> {if (!has_past_region) {return {kEmptyRange, kEmptyRange};}+ if (is_past_saturated && !past_is_circular) {+ // Chronologically packed buffer: shifting keeps it in order, so the whole past+ // region is one contiguous range: abs = (stored_tokens - past_width) + slot.+ const int64_t base_abs = stored_tokens_i64 - past_width_i64;+ return {compute_visible_range(min_visible_abs_pos - base_abs,+ max_visible_abs_pos - base_abs,+ 0,+ past_width_i64 - 1),+ kEmptyRange};+ }if (is_past_saturated) {// Saturated ring: at most two contiguous slot ranges can be visible,// one in [wrap_slot, past_width) and one in [0, wrap_slot).+ const uint32_t wrap_slot = stored_tokens % past_width;const int64_t ring_base_abs = stored_tokens_i64 - static_cast<int64_t>(wrap_slot);const int64_t older_segment_bias = ring_base_abs - past_width_i64; // abs = older_segment_bias + slot@@ -216,16 +233,17 @@ void fill_causal_sliding_window_mask_typed(const MaskView& mask_view,void ov::npuw::util::fill_causal_sliding_window_mask(ov::SoPtr<ov::ITensor> mask_tensor,uint32_t num_stored_tokens,uint32_t num_new_tokens,- uint32_t window_size) {+ uint32_t window_size,+ bool past_is_circular) {const auto mask_view = get_mask_view(mask_tensor, num_new_tokens, "fill_causal_sliding_window_mask");OPENVINO_ASSERT(window_size > 0, "fill_causal_sliding_window_mask: window_size must be > 0");switch (mask_view.element_type) {case ov::element::f32:- fill_causal_sliding_window_mask_typed<float>(mask_view, num_stored_tokens, window_size);+ fill_causal_sliding_window_mask_typed<float>(mask_view, num_stored_tokens, window_size, past_is_circular);break;case ov::element::f16:- fill_causal_sliding_window_mask_typed<ov::float16>(mask_view, num_stored_tokens, window_size);+ fill_causal_sliding_window_mask_typed<ov::float16>(mask_view, num_stored_tokens, window_size, past_is_circular);break;default:OPENVINO_THROW("fill_causal_sliding_window_mask: unsupported mask element type ", mask_view.element_type);@@ -325,13 +343,14 @@ void ov::npuw::util::fill_sliding_window_attention_mask(const std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,uint32_t num_stored_tokens,uint32_t num_new_tokens,- uint32_t window_size) {+ uint32_t window_size,+ bool past_is_circular) {const auto mask_it = in_ports.find(ov::npuw::util::kSlidingWindowAttentionMaskParamName);if (mask_it == in_ports.end()) {return;}auto mask_tensor = request->get_tensor(mask_it->second);- fill_causal_sliding_window_mask(mask_tensor, num_stored_tokens, num_new_tokens, window_size);+ fill_causal_sliding_window_mask(mask_tensor, num_stored_tokens, num_new_tokens, window_size, past_is_circular);const auto token_type_ids_it = in_ports.find(ov::npuw::util::kTokenTypeIdsParamName);if (token_type_ids_it != in_ports.end()) {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.hppindex aa905a9b45e..4eb476299b6 100644--- 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.hpp@@ -21,16 +21,16 @@ 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";-// Fills additive causal sliding-window attention mask tensor in-place:// 0.0f for visible positions, -inf for masked ones.+//+// past_is_circular must match the past-KV buffer's physical layout: true for a ring buffer,+// false for one kept in chronological order.void fill_causal_sliding_window_mask(ov::SoPtr<ov::ITensor> mask_tensor,uint32_t num_stored_tokens,uint32_t num_new_tokens,- uint32_t window_size);+ uint32_t window_size,+ bool past_is_circular);// Overlays bidirectional visibility for same image vision tokens.// token_type_ids is per-call right-aligned token metadata (0 = text, 1 = vision)@@ -44,7 +44,8 @@ void fill_sliding_window_attention_mask(const std::shared_ptr<ov::IAsyncInferReqconst std::unordered_map<std::string, ov::Output<const ov::Node>>& in_ports,uint32_t num_stored_tokens,uint32_t num_new_tokens,- uint32_t window_size);+ uint32_t window_size,+ bool past_is_circular);// Writes SWA KV deltas into a left-aligned past buffer, shifting the// surviving tail to the front first when the window is saturated.diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cppindex cae6e95c9c7..5d3d02c72a2 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp@@ -23,7 +23,7 @@ std::string make_numbered_block_input_name(const std::string& kv_type, const std// Classify a port name into its KV block role.// Returns Key/Value for numbered blocks, Tail for block_tail ports,-// and Skip for contiguous KV params or unrelated ports.+// and Skip for contiguous KV params, SWA managed ports, or unrelated ports.ov::npuw::BlockParamKind classify_block_param(const std::string& name) {using ov::npuw::BlockParamKind;namespace uu = ov::npuw::util;@@ -35,6 +35,9 @@ ov::npuw::BlockParamKind classify_block_param(const std::string& name) {if (uu::isPastKeyValuesKeyContiguous(name).has_value() || uu::isPastKeyValuesValueContiguous(name).has_value()) {return ov::npuw::BlockParamKind::Skip;}+ if (uu::is_swa_kv_cache_name(name)) {+ return ov::npuw::BlockParamKind::Skip;+ }if (name.find("block_tail") != std::string::npos) {return ov::npuw::BlockParamKind::TailBlock;}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 7f0332ad940..09d7d887b81 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@@ -28,6 +28,7 @@#include "npuw_transformations/reshape_sliced_head_to_static.hpp"#include "npuw_transformations/reshape_to_static.hpp"#include "npuw_transformations/right_align_mask_slice_for_conv.hpp"+#include "npuw_transformations/shrink_sliding_window_kv_cache.hpp"#include "npuw_transformations/slice_out_embeds.hpp"#include "npuw_transformations/split_kvcache_into_blocks.hpp"#include "openvino/op/convert.hpp"@@ -700,6 +701,24 @@ std::vector<std::shared_ptr<ov::Model>> ov::npuw::LLMCompiledModel::create_generov::npuw::ReshapeToStatic(max_generation_token_len, kv_size, axes, m_max_lora_rank, whisper_lhs_seq_size).run_on_model(generate_variant);+ if (m_cfg.get<::intel_npu::NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK>()) {+ // Must run after ReshapeToStatic, before OptimizeValueTensors (V-tensor optimization).+ // No-op (returns false) for models without sliding-window attention layers.+ ov::npuw::ShrinkSlidingWindowKVCache swa_pass(kv_size, max_generation_token_len, axes);+ if (swa_pass.run_on_model(generate_variant)) {+ // m_swa_window_size was already set from the prefill model earlier in the+ // constructor; here we only verify every generate variant agrees with it.+ OPENVINO_ASSERT(m_swa_window_size == swa_pass.window_size(),+ "SWA window size mismatch: ",+ m_swa_window_size,+ " vs ",+ swa_pass.window_size());+ LOG_INFO("ShrinkSlidingWindowKVCache applied to generate variant (kv_size="+ << kv_size << ", max_generation_token_len=" << max_generation_token_len+ << ", window_size=" << m_swa_window_size << ")");+ }+ }+// Set unique name for this variantgenerate_variant->set_friendly_name(generate_model->get_friendly_name() + "_kv" + std::to_string(kv_size));generate_model_variants.push_back(generate_variant);@@ -965,7 +984,12 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& mov::npuw::DetectAttentionMask().run_on_model(kvcache_model);ov::npuw::log_detected_masks(kvcache_model);- if (!m_is_whisper) {+ // Two mutually-exclusive ways to handle sliding-window attention (SWA) layers:+ // - PatchSlidingWindowMask (default): only fixes up the attention mask for correctness;+ // the KV cache still keeps the full context (no memory/perf savings).+ // - ShrinkSlidingWindowKVCache: shrinks the KV cache to the window size and+ // manages it as a sliding buffer at runtime for better memory/perf.+ if (!m_is_whisper && !m_cfg.get<::intel_npu::NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK>()) {LOG_DEBUG("Try patch sliding window attention mask (Phi-3, Gemma-2, Gemma-3, Gemma-4), if it exists.");ov::npuw::PatchSlidingWindowMask().run_on_model(kvcache_model);}@@ -1032,6 +1056,24 @@ ov::npuw::LLMCompiledModel::LLMCompiledModel(const std::shared_ptr<ov::Model>& m}LOG_DEBUG("Make kvcache model with static shapes");+ if (m_cfg.get<::intel_npu::NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK>()) {+ // Must run after ReshapeToStatic, before OptimizeValueTensors (V-tensor optimization).+ // No-op (returns false) for models without sliding-window attention layers.+ const uint32_t prefill_input_size =+ m_use_chunk_prefill ? static_cast<uint32_t>(m_prefill_chunk_size) : m_kvcache_desc.max_prompt_size;+ ov::npuw::ShrinkSlidingWindowKVCache swa_pass(m_kvcache_desc.max_prompt_size, prefill_input_size, axes);+ if (swa_pass.run_on_model(prefill_model)) {+ m_swa_window_size = swa_pass.window_size();+ LOG_INFO("ShrinkSlidingWindowKVCache applied to prefill model (max_prompt_size="+ << m_kvcache_desc.max_prompt_size << ", prefill_input_size=" << prefill_input_size+ << ", window_size=" << m_swa_window_size << ")");+ OPENVINO_ASSERT(!m_enable_prefix_caching,+ "NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK and NPUW_LLM_ENABLE_PREFIX_CACHING cannot be enabled "+ "simultaneously: the prefix cache restores KV blocks at offsets sized against "+ "the full prompt capacity, which does not fit the window-shrunk SWA KV tensors.");+ }+ }+// In case of Gemma3, we should remove `token_type_ids` from generate version of the model,// as it leads to inaccurate output otherwise.// NOTE: It is important to preserve `token_type_ids` in prefill model, however, as `token_type_ids`@@ -1538,7 +1580,7 @@ void ov::npuw::LLMCompiledModel::serialize(std::ostream& raw_stream, const ov::nm_kvcache_desc.v_tensors_transposed_gen & m_prefill_chunk_size & m_use_chunk_prefill & m_max_lora_rank &m_enable_prefix_caching & m_prefix_caching_block_size & m_prefix_caching_max_num_blocks &m_longrope_context_limit & m_is_whisper & m_eos_token_id & m_decomposed_sdpa_size & m_is_eagle &- m_is_embedding & m_is_block_kv_cache & m_is_encoder_embedding;+ m_is_embedding & m_is_block_kv_cache & m_is_encoder_embedding & m_swa_window_size;// LongRoPE cos/sin tables: the transformed graphs have npuw_lr_cos/npuw_lr_sin// inputs the host must fill every call, but deserialization imports already-@@ -1772,7 +1814,7 @@ std::shared_ptr<ov::npuw::LLMCompiledModel> ov::npuw::LLMCompiledModel::deserialcompiled->m_prefix_caching_block_size & compiled->m_prefix_caching_max_num_blocks &compiled->m_longrope_context_limit & compiled->m_is_whisper & compiled->m_eos_token_id &compiled->m_decomposed_sdpa_size & compiled->m_is_eagle & compiled->m_is_embedding &- compiled->m_is_block_kv_cache & compiled->m_is_encoder_embedding;+ compiled->m_is_block_kv_cache & compiled->m_is_encoder_embedding & compiled->m_swa_window_size;// LongRoPE cos/sin tables - see the matching comment in serialize()stream & compiled->m_longrope_tables;@@ -1855,6 +1897,9 @@ bool ov::npuw::LLMCompiledModel::compute_continuous_prefill_supported() const {if (m_longrope_context_limit > 0u) {return false; // LongRoPE threshold can be crossed mid-generation}+ if (m_swa_window_size > 0u) {+ return false;+ }OPENVINO_ASSERT(m_prefill_compiled, "Continuous prefill probe requires a compiled prefill model.");const auto& prefill_inputs = m_prefill_compiled->inputs();for (const auto& input : prefill_inputs) {@@ -1971,6 +2016,7 @@ void ov::npuw::LLMCompiledModel::implement_properties() {BIND(npuw::llm::optimize_fp8, NPUW_LLM_OPTIMIZE_FP8, get),BIND(npuw::llm::cache_rope, NPUW_LLM_CACHE_ROPE, get),BIND(npuw::llm::enable_block_based_kv_cache, NPUW_LLM_ENABLE_BLOCK_BASED_KV_CACHE, get),+ BIND(npuw::llm::enable_swa_kv_cache_shrink, NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK, get),BIND(npuw::llm::enable_continuous_prefill, NPUW_LLM_ENABLE_CONTINUOUS_PREFILL, get),BIND(npuw::llm::prefill_moe_hint, NPUW_LLM_PREFILL_MOE_HINT, get),BIND(npuw::llm::generate_moe_hint, NPUW_LLM_GENERATE_MOE_HINT, get),diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hppindex de1709078a4..653ad387a48 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.hpp@@ -16,6 +16,7 @@ namespace npuw {struct LLMVariantSwitchTestAccess;struct LLMTrimKVCacheTestAccess;struct LLMContinuedPrefillTestAccess;+struct LLMSwaCacheTestAccess;} // namespace npuw} // namespace test} // namespace ov@@ -91,9 +92,11 @@ private:friend class EmbeddingInferRequest;friend class LLMBlockKVCacheStrategy;friend class LLMContinuousKVCacheStrategy;+ friend class SwaKVCacheHelper;friend struct ov::test::npuw::LLMVariantSwitchTestAccess;friend struct ov::test::npuw::LLMTrimKVCacheTestAccess;friend struct ov::test::npuw::LLMContinuedPrefillTestAccess;+ friend struct ov::test::npuw::LLMSwaCacheTestAccess;friend class EncoderEmbeddingInferRequest;std::shared_ptr<ov::ISyncInferRequest> create_llm_infer_request();@@ -168,6 +171,9 @@ private:// routed to the dedicated KV/RoPE-free encoder embedding path.bool m_is_encoder_embedding = false;+ // SWA (sliding-window attention) window size, 0 if none.+ uint32_t m_swa_window_size = 0;+// Create generate model variants with different sizesstd::vector<std::shared_ptr<ov::Model>> create_generate_model_variants(const std::shared_ptr<ov::Model>& generate_model,diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cppindex ace56c24b2a..a357aa2a85c 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@@ -9,6 +9,7 @@#include <regex>#include "infer_request_utils.hpp"+#include "kv_cache_sliding_window_manager.hpp"#include "llm_block_kvcache_strategy.hpp"#include "llm_compiled_model.hpp"#include "llm_continuous_kvcache_strategy.hpp"@@ -347,19 +348,9 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCo}}- for (const auto& input_port : m_kvcache_request->get_compiled_model()->inputs()) {- const auto& all_names = input_port.get_names();- for (const auto& name : all_names) {- if (ov::npuw::util::starts_with(name, layer_names::past_key_values)) {- m_kvcache_past_names.push_back(name);- break;- }- if (ov::npuw::util::starts_with_past_lincache(name)) {- m_lincache_past_names.push_back(name);- break;- }- }- }+ init_past_name_lists();++ m_swa_cache = std::make_unique<SwaKVCacheHelper>(*this, m_npuw_llm_compiled_model->m_swa_window_size);m_pre_alloc_device = init_pre_alloc_device();m_stored_tokens_state = std::make_shared<ov::npuw::StoredTokensState>();@@ -386,9 +377,10 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCom_kvcache_strategy = std::make_unique<LLMContinuousKVCacheStrategy>(*this);}m_kvcache_strategy->on_initialize();- // Lincache shape is kvcache_size-independent, so the same tensor can be shared across all+ // Lincache/SWA shape is kvcache_size-independent, so the same tensor can be shared across all// generate variants.share_lincache_across_generate_variants();+ m_swa_cache->share_across_generate_variants();if (m_npuw_llm_compiled_model->m_enable_prefix_caching) {const size_t prefix_cache_count = m_npuw_llm_compiled_model->m_longrope_context_limit > 0u ? 2u : 1u;@@ -437,16 +429,17 @@ ov::npuw::LLMInferRequest::LLMInferRequest(const std::shared_ptr<ov::npuw::LLMCo// Apply CPU workaround only for the largest variant since all variants share its past KV tensorsauto& largest_kvcache_req = m_generate_requests.back();const auto& variant_in_ports = m_generate_variant_in_ports.at(largest_kvcache_req);- for (const auto& kv_past_name : m_kvcache_past_names) {- auto kvcache_in_tensor = largest_kvcache_req->get_tensor(variant_in_ports.at(kv_past_name));- // 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);- }- for (const auto& lincache_past_name : m_lincache_past_names) {- auto lincache_in_tensor = largest_kvcache_req->get_tensor(variant_in_ports.at(lincache_past_name));- ov::npuw::util::fill_tensor_bytes(lincache_in_tensor, 0u);- }+ // 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+ auto zero_fill_past_tensors = [&](const std::vector<std::string>& past_names) {+ for (const auto& past_name : past_names) {+ auto past_tensor = largest_kvcache_req->get_tensor(variant_in_ports.at(past_name));+ ov::npuw::util::fill_tensor_bytes(past_tensor, 0u);+ }+ };+ zero_fill_past_tensors(m_kvcache_past_names);+ zero_fill_past_tensors(m_lincache_past_names);+ zero_fill_past_tensors(m_swa_past_names);}m_generate_initialized = false;@@ -488,6 +481,39 @@ std::string ov::npuw::LLMInferRequest::init_pre_alloc_device() {return pre_alloc_on_npu ? "NPU" : "CPU";}+void ov::npuw::LLMInferRequest::init_past_name_lists() {+ m_kvcache_past_names.clear();+ m_lincache_past_names.clear();+ m_swa_past_names.clear();++ for (const auto& input_port : m_kvcache_request->get_compiled_model()->inputs()) {+ const auto& all_names = input_port.get_names();+ for (const auto& name : all_names) {+ if (ov::npuw::util::starts_with_past_lincache(name)) {+ m_lincache_past_names.push_back(name);+ break;+ }+ if (ov::npuw::util::is_swa_kv_cache_name(name)) {+ m_swa_past_names.push_back(name);+ break;+ }+ if (ov::npuw::util::starts_with(name, layer_names::past_key_values)) {+ m_kvcache_past_names.push_back(name);+ break;+ }+ }+ }+}++void ov::npuw::LLMInferRequest::zero_prefill_past_tensors(const std::vector<std::string>& past_names) {+ namespace uu = ov::npuw::util;+ for (const auto& input_name : past_names) {+ if (m_prefill_in_ports.find(input_name) != m_prefill_in_ports.end()) {+ uu::fill_tensor_bytes(m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name)), 0u);+ }+ }+}+void ov::npuw::LLMInferRequest::bind_past_kv() {auto& kvcache_desc = m_npuw_llm_compiled_model->m_kvcache_desc;if (kvcache_desc.v_tensors_transposed_pre != kvcache_desc.v_tensors_transposed_gen) {@@ -675,8 +701,6 @@ void ov::npuw::LLMInferRequest::bind_generate_variant(int64_t prompt_length) {}void ov::npuw::LLMInferRequest::prepare_for_new_conversation(int64_t prompt_length) {- namespace uu = ov::npuw::util;-// A continued prefill that failed mid-way may leave its delta base behind;// a full prefill always addresses the caller tensors from zero.m_continued_prefill_base = 0u;@@ -685,11 +709,8 @@ void ov::npuw::LLMInferRequest::prepare_for_new_conversation(int64_t prompt_lengm_kvcache_strategy->on_reset(prompt_length > 0 ? static_cast<uint32_t>(prompt_length) : 0u);- for (const auto& input_name : m_lincache_past_names) {- if (m_prefill_in_ports.find(input_name) != m_prefill_in_ports.end()) {- uu::fill_tensor_bytes(m_prefill_request->get_tensor(m_prefill_in_ports.at(input_name)), 0u);- }- }+ zero_prefill_past_tensors(m_lincache_past_names);+ m_swa_cache->zero_prefill_tensors();m_npuw_llm_compiled_model->m_kvcache_desc.num_stored_tokens = 0u;@@ -1145,6 +1166,12 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inptoken_type_ids_in_tensor->data<int64_t>() + total_len - current_prompts_len);}+ // Fill the SWA attention mask for this chunk (prefill's past-KV buffer is not a ring).+ m_swa_cache->fill_attention_masks(m_prefill_request,+ m_prefill_in_ports,+ static_cast<uint32_t>(current_prompts_len),+ /*use_circular_layout=*/false);+// Prepare KV blocks or bind memory for this chunk via strategy.m_kvcache_strategy->on_prefill_chunk_begin(static_cast<uint32_t>(current_prompts_len));});@@ -1180,6 +1207,7 @@ void ov::npuw::LLMInferRequest::infer_chunked_prefill(ov::SoPtr<ov::ITensor> inpif (!is_last_chunk) {// Attention mask and lincache update for intermediate chunks.copy_lincache(m_prefill_request, m_prefill_request, m_prefill_out_ports, m_prefill_in_ports);+ m_swa_cache->update_prefill(static_cast<uint32_t>(current_prompts_len));std::copy_n(attn_mask_in_tensor->data<int64_t>() + attn_mask_in_tensor->get_size() - current_prompts_len,@@ -1255,6 +1283,12 @@ void ov::npuw::LLMInferRequest::infer_whole_prefill(ov::SoPtr<ov::ITensor> inputauto dst = m_prefill_request->get_tensor(m_prefill_in_ports.at(layer_names::per_layer_inputs));ov::npuw::util::copy_to_right(per_layer_inputs, dst);}++ m_swa_cache->fill_attention_masks(+ m_prefill_request,+ m_prefill_in_ports,+ static_cast<uint32_t>(input_ids->get_shape()[layer_ids::INPUT_IDS_SEQ_LEN_DIM]),+ /*use_circular_layout=*/false);});m_llm_profile["1/prefill:3b.infer"].record([&]() {@@ -1479,6 +1513,7 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,if (kvcache_desc.num_stored_tokens > 0) {m_kvcache_strategy->on_generate_kv_init();copy_lincache(m_prefill_request, m_kvcache_request, m_prefill_out_ports, m_kvcache_in_ports);+ m_swa_cache->copy_prefill_to_generate();}LOG_DEBUG("Prepare inputs.");@@ -1549,6 +1584,11 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,auto dst = m_kvcache_request->get_tensor(m_kvcache_in_ports.at(layer_names::per_layer_inputs));ov::npuw::util::copy_to_right(per_layer_inputs, dst);}++ m_swa_cache->fill_attention_masks(m_kvcache_request,+ m_kvcache_in_ports,+ input_tokens_len,+ /*use_circular_layout=*/true);});m_llm_profile["N/generate:2.infer"].record([&]() {@@ -1561,6 +1601,7 @@ void ov::npuw::LLMInferRequest::infer_generate(ov::SoPtr<ov::ITensor> input_ids,m_llm_profile["N/generate:3.update_kvcache"].record([&]() {if (kvcache_desc.num_stored_tokens < kvcache_desc.total_size) {m_kvcache_strategy->on_generate_step_done(input_tokens_len);+ m_swa_cache->update_generate(input_tokens_len);}});};diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hppindex c374acabecb..64b97bc8a9e 100644--- a/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.hpp@@ -15,6 +15,7 @@#include "llm_lora_states.hpp"#include "llm_prefix_caching.hpp"#include "llm_stored_tokens_state.hpp"+#include "llm_swa_cache.hpp"#include "openvino/core/descriptor/output.hpp"#include "perf.hpp"@@ -25,6 +26,7 @@ struct LLMVariantSwitchTestAccess;struct LLMTrimKVCacheTestAccess;struct LLMPortNameRegistrationTestAccess;struct LLMContinuedPrefillTestAccess;+struct LLMSwaCacheTestAccess;} // namespace npuw} // namespace test} // namespace ov@@ -60,6 +62,12 @@ protected:// that a variant switch requires no explicit lincache migration. Called once after// m_kvcache_strategy->on_initialize() and is strategy-independent.void share_lincache_across_generate_variants();++ // Classifies each generate model input into m_kvcache_past_names / m_lincache_past_names /+ // m_swa_past_names.+ void init_past_name_lists();+ // Zeroes the prefill model's inputs named in `past_names` on a new conversation.+ void zero_prefill_past_tensors(const std::vector<std::string>& past_names);// Select appropriate generate request variant based on prompt length// Internally calculates expected total tokens (prompt + min_response_len) to ensure// sufficient capacity for both input prompt and minimum response generation@@ -164,6 +172,7 @@ protected:std::vector<std::string> m_kvcache_past_names;std::vector<std::string> m_lincache_past_names;+ std::vector<std::string> m_swa_past_names;// NB: It can be either input_ids(LLM) or inputs_embeds(VLM)std::string m_input_ids_name;@@ -208,6 +217,9 @@ protected:// Support prefix cachingstd::vector<std::unique_ptr<PrefixCachingHelper>> m_prefix_caching_helpers;+ // Support Sliding Window Attention+ std::unique_ptr<SwaKVCacheHelper> m_swa_cache;+// LLM-level profiling for 1st token generation analysisusing MS = ov::npuw::perf::metric<ov::npuw::perf::MSec>;ov::npuw::perf::Profile<MS> m_llm_profile;@@ -215,14 +227,17 @@ protected:// KV cache management strategy (set once in the constructor, valid for the object's lifetime)std::unique_ptr<LLMKVCacheStrategy> m_kvcache_strategy;- // Friend declarations: strategies and PrefixCachingHelper need access to protected members+ // Friend declarations: strategies, PrefixCachingHelper and SwaKVCacheHelper need access to+ // protected membersfriend class LLMContinuousKVCacheStrategy;friend class LLMBlockKVCacheStrategy;friend class PrefixCachingHelper;+ friend class SwaKVCacheHelper;friend struct ov::test::npuw::LLMVariantSwitchTestAccess;friend struct ov::test::npuw::LLMTrimKVCacheTestAccess;friend struct ov::test::npuw::LLMPortNameRegistrationTestAccess;friend struct ov::test::npuw::LLMContinuedPrefillTestAccess;+ friend struct ov::test::npuw::LLMSwaCacheTestAccess;};} // namespace npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_swa_cache.cpp b/src/plugins/intel_npu/src/plugin/npuw/llm_swa_cache.cppnew file mode 100644index 00000000000..2ce68c3b7bf--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_swa_cache.cpp@@ -0,0 +1,244 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "llm_swa_cache.hpp"++#include <algorithm>+#include <regex>++#include "infer_request_utils.hpp"+#include "kv_cache_sliding_window_manager.hpp"+#include "llm_infer_request.hpp"+#include "logging.hpp"+#include "openvino/core/parallel.hpp"+#include "openvino/runtime/iasync_infer_request.hpp"+#include "util.hpp"++ov::npuw::SwaKVCacheHelper::SwaKVCacheHelper(LLMInferRequest& request, uint32_t window_size)+ : m_request(request),+ m_window_size(window_size) {}++void ov::npuw::SwaKVCacheHelper::share_across_generate_variants() {+ if (m_request.m_swa_past_names.empty()) {+ return;+ }+ auto& generate_requests = m_request.m_generate_requests;+ if (generate_requests.size() <= 1) {+ return;+ }+ const auto& largest_req = generate_requests.back();+ const auto& largest_ports = m_request.m_generate_variant_in_ports.at(largest_req);+ std::unordered_map<std::string, ov::SoPtr<ov::ITensor>> swa_tensors;+ for (const auto& name : m_request.m_swa_past_names) {+ swa_tensors[name] = largest_req->get_tensor(largest_ports.at(name));+ }+ for (size_t i = 0; i < generate_requests.size() - 1; ++i) {+ const auto& variant_ports = m_request.m_generate_variant_in_ports.at(generate_requests[i]);+ for (const auto& name : m_request.m_swa_past_names) {+ const auto& shared_tensor = swa_tensors.at(name);+ auto variant_tensor = generate_requests[i]->get_tensor(variant_ports.at(name));+ OPENVINO_ASSERT(variant_tensor->get_shape() == shared_tensor->get_shape() &&+ variant_tensor->get_element_type() == shared_tensor->get_element_type(),+ "SWA past tensor ",+ name,+ " shape/type mismatch across generate variants — sliding-window capacity is expected "+ "to be independent of the total kv-cache size.");+ generate_requests[i]->set_tensor(variant_ports.at(name), shared_tensor);+ }+ }+ LOG_INFO("Shared " << m_request.m_swa_past_names.size() << " SWA tensors across " << generate_requests.size()+ << " generate variants");+}++void ov::npuw::SwaKVCacheHelper::zero_prefill_tensors() {+ m_request.zero_prefill_past_tensors(m_request.m_swa_past_names);+}++void ov::npuw::SwaKVCacheHelper::copy_prefill_to_generate() {+ if (m_request.m_swa_past_names.empty()) {+ return;+ }+ namespace uu = ov::npuw::util;+ LOG_DEBUG("Copying SWA kv-cache from prefill to generate model.");+ LOG_BLOCK();+ auto& kvcache_desc = m_request.m_npuw_llm_compiled_model->m_kvcache_desc;+ const auto prefill_chunk_size = m_request.m_npuw_llm_compiled_model->m_prefill_chunk_size;+ const bool use_chunk_prefill = m_request.m_npuw_llm_compiled_model->m_use_chunk_prefill;+ const uint32_t last_chunk_tokens =+ use_chunk_prefill ? static_cast<uint32_t>(m_request.m_tokens_in_present_chunk) : 0u;+ OPENVINO_ASSERT(!use_chunk_prefill || kvcache_desc.num_stored_tokens >= last_chunk_tokens,+ "SWA copy: num_stored_tokens is smaller than last chunk size.");+ const uint32_t tokens_in_past_chunks =+ use_chunk_prefill ? (kvcache_desc.num_stored_tokens - last_chunk_tokens) : 0u;+ const bool chunk_equals_window = use_chunk_prefill && (prefill_chunk_size == m_window_size);++ ov::parallel_for(m_request.m_swa_past_names.size(), [&](size_t out_idx) {+ const auto& input_name = m_request.m_swa_past_names[out_idx];+ auto kvcache_in_tensor = m_request.m_kvcache_request->get_tensor(m_request.m_kvcache_in_ports.at(input_name));++ const auto& output_name =+ std::regex_replace(input_name, std::regex(LLMInferBaseRequest::layer_names::past_key_values), "present");+ OPENVINO_ASSERT(m_request.m_prefill_out_ports.find(output_name) != m_request.m_prefill_out_ports.end(),+ "Incosistent input/output naming for KV cache: ",+ output_name,+ " not found in prefill model outputs.");+ auto prefill_out_tensor =+ m_request.m_prefill_request->get_tensor(m_request.m_prefill_out_ports.at(output_name));++ const auto is_value_tensor = output_name.find("value") != std::string::npos;+ const auto kv_dim = [&](bool v_trans) -> uint32_t {+ return (is_value_tensor && v_trans) ? 3u : kvcache_desc.dim;+ };++ const auto& pre_kv_dim = kv_dim(kvcache_desc.v_tensors_transposed_pre);+ const auto& gen_kv_dim = kv_dim(kvcache_desc.v_tensors_transposed_gen);++ auto append_to_generate_swa = [&](ov::SoPtr<ov::ITensor> src_tensor,+ uint32_t src_kv_dim,+ uint32_t num_stored_tokens_before,+ uint32_t num_new_tokens) {+ if (num_new_tokens == 0u) {+ return;+ }+ uu::write_swa_kv_slice_circular(kvcache_in_tensor,+ src_tensor,+ gen_kv_dim,+ src_kv_dim,+ num_stored_tokens_before,+ num_new_tokens);+ };++ if (!use_chunk_prefill) {+ // Non-chunk prefill has a single present source; keep the newest num_stored tokens.+ append_to_generate_swa(prefill_out_tensor, pre_kv_dim, 0u, kvcache_desc.num_stored_tokens);+ return;+ }++ // If the last prefill chunk fully spans the SWA window, seeding can be done+ // directly from this chunk's present output.+ if (chunk_equals_window && last_chunk_tokens == prefill_chunk_size) {+ auto prefill_present_kv_chunk =+ uu::make_tensor_slice(prefill_out_tensor, pre_kv_dim, 0u, static_cast<uint32_t>(prefill_chunk_size));+ append_to_generate_swa(prefill_present_kv_chunk, pre_kv_dim, tokens_in_past_chunks, last_chunk_tokens);+ return;+ }++ // Chunk prefill has two logical source segments:+ // 1) persisted past prefix from previous chunks (left-aligned),+ // 2) tail of this loop's present output from the final chunk.++ if (tokens_in_past_chunks > 0u) {+ auto prefill_past_kv = m_request.m_prefill_request->get_tensor(m_request.m_prefill_in_ports.at(input_name));++ // ShrinkSlidingWindowKVCache may shrink SWA past capacity to window size, so+ // read only the valid left-aligned prefix.+ const auto pre_capacity = static_cast<uint32_t>(prefill_past_kv->get_shape()[pre_kv_dim]);+ const uint32_t valid_past_chunks = std::min(tokens_in_past_chunks, pre_capacity);++ if (valid_past_chunks > 0u) {+ ov::SoPtr<ov::ITensor> prefill_past_kv_chunks;+ if (m_request.m_past_kv_bound) {+ // When prefill/generate past are bound to shared backing, snapshot first+ // to avoid aliasing while we seed generate SWA.+ auto tmp_dense_kv_tensor =+ ov::npuw::util::allocMem(prefill_past_kv->get_element_type(),+ prefill_past_kv->get_shape(),+ m_request.m_pre_alloc_device,+ m_request.m_npuw_llm_compiled_model->get_plugin());+ NPUW_ASSERT(tmp_dense_kv_tensor._ptr &&+ "KV cache buffer allocation failed — check device availability and memory constraints");+ prefill_past_kv->copy_to(tmp_dense_kv_tensor._ptr);+ prefill_past_kv_chunks =+ uu::make_tensor_slice(tmp_dense_kv_tensor, pre_kv_dim, 0u, valid_past_chunks);+ } else {+ prefill_past_kv_chunks = uu::make_tensor_slice(prefill_past_kv, pre_kv_dim, 0u, valid_past_chunks);+ }+ append_to_generate_swa(prefill_past_kv_chunks, pre_kv_dim, 0u, tokens_in_past_chunks);+ }+ }++ if (last_chunk_tokens > 0u) {+ auto prefill_present_kv_chunk =+ uu::make_tensor_slice(prefill_out_tensor,+ pre_kv_dim,+ static_cast<uint32_t>(prefill_chunk_size - last_chunk_tokens),+ static_cast<uint32_t>(prefill_chunk_size));+ append_to_generate_swa(prefill_present_kv_chunk, pre_kv_dim, tokens_in_past_chunks, last_chunk_tokens);+ }+ });+ LOG_DEBUG("Done.");+}++void ov::npuw::SwaKVCacheHelper::update_cache(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ const PortsMap& out_ports,+ uint32_t num_tokens,+ bool v_transposed,+ bool use_circular_layout) {+ if (m_request.m_swa_past_names.empty()) {+ return;+ }+ namespace uu = ov::npuw::util;+ auto& kvcache_desc = m_request.m_npuw_llm_compiled_model->m_kvcache_desc;++ ov::parallel_for(m_request.m_swa_past_names.size(), [&](size_t i) {+ const auto& input_name = m_request.m_swa_past_names[i];+ OPENVINO_ASSERT(in_ports.find(input_name) != in_ports.end(),+ "There is no ",+ input_name,+ " in input ports map, while it is expected!");+ const auto& output_name =+ std::regex_replace(input_name, std::regex(LLMInferBaseRequest::layer_names::past_key_values), "present");+ OPENVINO_ASSERT(out_ports.find(output_name) != out_ports.end(),+ "There is no ",+ output_name,+ " in output ports map, while it is expected!");++ auto dst_tensor = request->get_tensor(in_ports.at(input_name));+ const auto& kv_dim = (output_name.find("value") != std::string::npos && v_transposed) ? 3u : kvcache_desc.dim;+ auto src_tensor = request->get_tensor(out_ports.at(output_name));++ // num_stored_tokens was already advanced by the caller past the tokens written here.+ const uint32_t num_stored_before = kvcache_desc.num_stored_tokens - num_tokens;+ if (use_circular_layout) {+ uu::write_swa_kv_slice_circular(dst_tensor, src_tensor, kv_dim, kv_dim, num_stored_before, num_tokens);+ } else {+ uu::write_swa_kv_slice_left_aligned(dst_tensor, src_tensor, kv_dim, kv_dim, num_stored_before, num_tokens);+ }+ });+}++void ov::npuw::SwaKVCacheHelper::update_prefill(uint32_t num_tokens) {+ auto& kvcache_desc = m_request.m_npuw_llm_compiled_model->m_kvcache_desc;+ update_cache(m_request.m_prefill_request,+ m_request.m_prefill_in_ports,+ m_request.m_prefill_out_ports,+ num_tokens,+ kvcache_desc.v_tensors_transposed_pre,+ /*use_circular_layout=*/false);+}++void ov::npuw::SwaKVCacheHelper::update_generate(uint32_t num_tokens) {+ auto& kvcache_desc = m_request.m_npuw_llm_compiled_model->m_kvcache_desc;+ update_cache(m_request.m_kvcache_request,+ m_request.m_kvcache_in_ports,+ m_request.m_kvcache_out_ports,+ num_tokens,+ kvcache_desc.v_tensors_transposed_gen,+ /*use_circular_layout=*/true);+}++void ov::npuw::SwaKVCacheHelper::fill_attention_masks(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ uint32_t num_new_tokens,+ bool use_circular_layout) const {+ auto& kvcache_desc = m_request.m_npuw_llm_compiled_model->m_kvcache_desc;+ const uint32_t num_stored_before = kvcache_desc.num_stored_tokens;+ ov::npuw::util::fill_sliding_window_attention_mask(request,+ in_ports,+ num_stored_before,+ num_new_tokens,+ m_window_size,+ use_circular_layout);+}diff --git a/src/plugins/intel_npu/src/plugin/npuw/llm_swa_cache.hpp b/src/plugins/intel_npu/src/plugin/npuw/llm_swa_cache.hppnew file mode 100644index 00000000000..070ef571cff--- /dev/null+++ b/src/plugins/intel_npu/src/plugin/npuw/llm_swa_cache.hpp@@ -0,0 +1,80 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstdint>+#include <memory>+#include <string>+#include <vector>++#include "llm_infer_base_request.hpp"+#include "openvino/runtime/iasync_infer_request.hpp"++namespace ov {+namespace npuw {++class LLMInferRequest; // forward declaration — helper always outlived by its owning request++/**+ * @brief Owns the SWA window size and all cache-management logic (prefill/generate+ * updates, prefill->generate handover, cross-variant sharing, attention-mask population)+ * for Sliding Window Attention (SWA) KV cache inputs. The SWA input names themselves live+ * on LLMInferRequest::m_swa_past_names; this helper reads them via m_request.+ *+ * Lifecycle call sequence (all called unconditionally from LLMInferRequest):+ * 1. share_across_generate_variants() — once, right after m_kvcache_strategy->on_initialize()+ * 2. zero_prefill_tensors() — each conversation reset+ * 3. Per prefill chunk, after m_kvcache_strategy->on_prefill_chunk_done() (intermediate+ * chunks only): update_prefill(num_tokens)+ * 4. First generate step, after m_kvcache_strategy->on_generate_kv_init():+ * copy_prefill_to_generate()+ * 5. Per generate step, after m_kvcache_strategy->on_generate_step_done():+ * update_generate(num_tokens)+ * 6. Before every prefill/generate infer(): fill_attention_masks(...)+ */+class SwaKVCacheHelper {+public:+ using PortsMap = LLMInferBaseRequest::PortsMap;++ // window_size == 0 means the model has no SWA layers.+ SwaKVCacheHelper(LLMInferRequest& request, uint32_t window_size);++ // Shares SWA tensors from the largest generate variant to avoid migration on promotion.+ void share_across_generate_variants();++ // Zeroes the prefill model's SWA past-KV inputs on a new conversation.+ void zero_prefill_tensors();++ // Copies SWA past KV from the prefill model's present output into the generate model's+ // circular past input, once at prefill->generate switchover.+ void copy_prefill_to_generate();++ // Left-aligned SWA past KV update for the prefill model.+ void update_prefill(uint32_t num_tokens);++ // Circular SWA past KV update for the generate model.+ void update_generate(uint32_t num_tokens);++ // Fills the externalized sliding-window attention mask input for `request`, and, if+ // present, overlays the vision-bidirectional mask from token type ids.+ void fill_attention_masks(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ uint32_t num_new_tokens,+ bool use_circular_layout) const;++private:+ void update_cache(const std::shared_ptr<ov::IAsyncInferRequest>& request,+ const PortsMap& in_ports,+ const PortsMap& out_ports,+ uint32_t num_tokens,+ bool v_transposed,+ bool use_circular_layout);++ LLMInferRequest& m_request;+ uint32_t m_window_size;+};++} // namespace npuw+} // namespace ovdiff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/duplicate_shared_kv_concat.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/duplicate_shared_kv_concat.cppindex 389e9eef309..e69fd101d8a 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/duplicate_shared_kv_concat.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/duplicate_shared_kv_concat.cpp@@ -28,8 +28,8 @@ namespace pass {namespace {-// Returns true when the parameter name is a past-KV param (contiguous or-// block-split), using the canonical NPUW naming utilities.+// Returns true when the parameter name is a past-KV param (contiguous, block-split,+// or SWA-managed), using the canonical NPUW naming utilities.bool is_past_kv_param(const std::shared_ptr<ov::op::v0::Parameter>& param) {const auto& name = param->get_friendly_name();return ov::npuw::util::isPastKeyParam(name) || ov::npuw::util::isPastValueParam(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.cppindex 5326dcae00c..3d440e10f7e 100644--- 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.cpp@@ -7,9 +7,9 @@#include <cstdint>#include <limits>#include <memory>+#include <regex>#include <unordered_set>-#include "../kv_cache_sliding_window_manager.hpp"#include "../llm_compiled_model_utils.hpp"#include "../logging.hpp"#include "../util.hpp"@@ -84,6 +84,7 @@ 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+constexpr int64_t kKvAlignment = 16; // NPU HW-preferred KV length granularity// past_kv Parameter feeding a KV Concat, plus the optional Convert in between.struct PastKVSource {@@ -248,6 +249,35 @@ void freeze_shapeofs(const PastKVSource& source,}}+// Renames an SWA past_kv Parameter (and its matching present.N.key/value output) by marking+// them as SWA-managed, so SWA-managed KV cache entries can be identified by name downstream.+void rename_swa_past_kv_and_present(const std::shared_ptr<ov::Model>& model,+ const std::shared_ptr<ov::op::v0::Parameter>& param) {+ const std::string old_name = param->get_friendly_name();++ // Mark the name as SWA-managed by inserting an extra "swa" segment before the final+ // key/value segment, e.g. "past_key_values.0.key" -> "past_key_values.0.swa.key".+ const auto pos = old_name.find_last_of('.');+ OPENVINO_ASSERT(pos != std::string::npos, "[SWA] Cannot mark unqualified name '", old_name, "' as SWA-managed.");+ const std::string new_name = old_name.substr(0, pos) + ".swa" + old_name.substr(pos);++ param->set_friendly_name(new_name);+ param->get_output_tensor(0).set_names({new_name});++ static const std::regex past_kv_regex("past_key_values");+ const std::string old_present_name = std::regex_replace(old_name, past_kv_regex, "present");+ const std::string new_present_name = std::regex_replace(new_name, past_kv_regex, "present");+ for (const auto& output : model->outputs()) {+ if (output.get_names().count(old_present_name) == 0) {+ continue;+ }+ output.get_tensor().set_names({new_present_name});+ LOG_DEBUG("[SWA] Renamed present output '" << old_present_name << "' -> '" << new_present_name << "'.");+ return;+ }+ OPENVINO_ASSERT(false, "[SWA] No present output found matching past_kv Parameter '", old_name, "'.");+}+// 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@@ -330,10 +360,12 @@ void scan_and_patch(const std::shared_ptr<ov::Model>& model,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;+ const std::string old_kv_name = source.param->get_friendly_name();+ rename_swa_past_kv_and_present(model, source.param);++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_DEBUG("[SWA] Past KV '" << old_kv_name << "' seq_len " << old_past << " -> " << new_past+ << " (post-concat total=" << new_kv_total << "), renamed to '"+ << source.param->get_friendly_name() << "'");}}@@ -357,8 +389,8 @@ ShrinkSlidingWindowKVCache::ShrinkSlidingWindowKVCache(uint32_t kvcache_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) {+ m_window_size = detect_swa_window_size(model);+ if (m_window_size == 0) {LOG_DEBUG("[SWA] Sliding Window Attention is not configured, skipping " << model->get_friendly_name());return false;}@@ -376,18 +408,28 @@ bool ShrinkSlidingWindowKVCache::run_on_model(const std::shared_ptr<ov::Model>&// 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);++ // Sliding layers keep only the last window_size past tokens. Grow that past region so+ // past + present lands on a kKvAlignment boundary.+ // e.g. window=512, present=1: unaligned total=513 -> aligned to 528 -> past=527.+ int64_t new_past = 0;+ if (available_past > 0) {+ const int64_t input_size = static_cast<int64_t>(m_input_size);+ const int64_t unaligned_total = input_size + static_cast<int64_t>(m_window_size);+ const int64_t aligned_total = (unaligned_total + kKvAlignment - 1) / kKvAlignment * kKvAlignment;+ new_past = aligned_total - input_size;+ OPENVINO_ASSERT(new_past <= static_cast<int64_t>(available_past),+ "[SWA] window_size (",+ m_window_size,+ ") exceeds available_past (",+ available_past,+ ")");+ }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);+ << " window=" << m_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);diff --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.hppindex c3fe2751668..c7b78e673ef 100644--- 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.hpp@@ -20,10 +20,13 @@ namespace ov::npuw {// 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.+// 5) Prefix SWA past_key_values.N.key/value Parameter and present.N.key/value output names,+// so SWA-managed KV cache entries can be identified by name alone downstream.//// SWA contract:-// - new_past = window_size-// - new_kv_total = input_size + window_size+// - new_past = window_size, rounded up so that input_size + new_past is a multiple of 16+// (NPU HW prefers 16-aligned KV lengths).+// - new_kv_total = input_size + new_past.//// Pass ordering:// - Run after ReshapeToStatic.@@ -34,11 +37,17 @@ class ShrinkSlidingWindowKVCache : public ov::pass::ModelPass {uint32_t m_kvcache_size;uint32_t m_input_size;KVAxesPosition m_kv_axes_position;+ uint32_t m_window_size = 0;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;++ // SWA window size detected by the last run_on_model() call, 0 if none.+ uint32_t window_size() const {+ return m_window_size;+ }};} // namespace ov::npuwdiff --git a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/split_kvcache_into_blocks.cpp b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/split_kvcache_into_blocks.cppindex ba0b2228b27..d44cdb85d8b 100644--- a/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/split_kvcache_into_blocks.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/split_kvcache_into_blocks.cpp@@ -83,6 +83,10 @@ bool SplitKVCacheIntoBlocks::run_on_model(const std::shared_ptr<ov::Model>& modefor (const auto& param : model->get_parameters()) {const std::string& name = param->get_friendly_name();+ if (ov::npuw::util::is_swa_kv_cache_name(name)) {+ continue;+ }+const bool is_key = ov::npuw::util::isPastKeyValuesKeyContiguous(name).has_value();const bool is_value = ov::npuw::util::isPastKeyValuesValueContiguous(name).has_value();if (!is_key && !is_value) {diff --git a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp b/src/plugins/intel_npu/src/plugin/npuw/serialization.hppindex 3b675f804e1..137a643d5e7 100644--- a/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/serialization.hpp@@ -52,7 +52,7 @@ const constexpr ov::npuw::s11n::IndicatorType NPUW_GQA_COMPILED_MODEL_INDICATORconst constexpr ov::npuw::s11n::IndicatorType NPUW_FLUX2_COMPILED_MODEL_INDICATOR ={char{0x46}, char{0x4c}, char{0x32}, char{0x43}, char{0x4d}, char{0x4f}};-const constexpr char* NPUW_SERIALIZATION_VERSION = "0.32";+const constexpr char* NPUW_SERIALIZATION_VERSION = "0.33";// Forward declarationnamespace intel_npu {diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.cpp b/src/plugins/intel_npu/src/plugin/npuw/util.cppindex 9533d48a912..0dae485d7f5 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.cpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.cpp@@ -965,6 +965,11 @@ bool ov::npuw::util::starts_with_past_lincache(const std::string& input_name) {ov::npuw::util::starts_with(input_name, past_lin_ssm_cache);}+bool ov::npuw::util::is_swa_kv_cache_name(const std::string& input_name) {+ // SWA-managed names carry an extra "swa" segment, e.g. "past_key_values.0.swa.key".+ return input_name.find(".swa.") != std::string::npos;+}+bool ov::npuw::util::is_pa_kv_cache_name(const std::string& input_name) {return ov::npuw::util::starts_with(input_name, "key_cache.") ||ov::npuw::util::starts_with(input_name, "value_cache.");@@ -976,14 +981,20 @@ void ov::npuw::util::fill_tensor_bytes(ov::SoPtr<ov::ITensor> tensor, uint8_t fi}bool ov::npuw::util::isPastKeyParam(const std::string& str) {- // Match any past key param: contiguous or block-split (e.g. key_block_3, key_block_tail).- static const std::regex pattern(R"(past_key_values\.\d+\.key(_block_(\d+|tail))?)");+ // Match any past key param:+ // - contiguous, e.g. past_key_values.0.key+ // - block-split, e.g. past_key_values.0.key_block_3, past_key_values.0.key_block_tail+ // - SWA-managed, e.g. past_key_values.0.swa.key+ static const std::regex pattern(R"(past_key_values\.\d+(?:\.[^.]+)*\.key(_block_(\d+|tail))?)");return std::regex_match(str, pattern);}bool ov::npuw::util::isPastValueParam(const std::string& str) {- // Match any past value param: contiguous or block-split.- static const std::regex pattern(R"(past_key_values\.\d+\.value(_block_(\d+|tail))?)");+ // Match any past value param:+ // - contiguous, e.g. past_key_values.0.value+ // - block-split, e.g. past_key_values.0.value_block_3, past_key_values.0.value_block_tail+ // - SWA-managed, e.g. past_key_values.0.swa.value+ static const std::regex pattern(R"(past_key_values\.\d+(?:\.[^.]+)*\.value(_block_(\d+|tail))?)");return std::regex_match(str, pattern);}diff --git a/src/plugins/intel_npu/src/plugin/npuw/util.hpp b/src/plugins/intel_npu/src/plugin/npuw/util.hppindex 2dadc693b44..e75950bca08 100644--- a/src/plugins/intel_npu/src/plugin/npuw/util.hpp+++ b/src/plugins/intel_npu/src/plugin/npuw/util.hpp@@ -232,6 +232,10 @@ bool matchLinCacheString(const std::string& input, const std::string& past_or_prbool starts_with_past_lincache(const std::string& input_name);+// Matches past_key_values.N.key/value Parameter (and present.N.key/value output) names of+// layers managed by sliding window attention.+bool is_swa_kv_cache_name(const std::string& input_name);+// Matches the paged KV cache inputs of the PagedAttention model deployed by// the GenAI continuous-batching pipeline (key_cache.N / value_cache.N, named// by the SDPAToPagedAttention transformation).diff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmakeindex a03591fb98c..118c8e2f78c 100644--- a/src/plugins/intel_npu/src/plugin/sources.cmake+++ b/src/plugins/intel_npu/src/plugin/sources.cmake@@ -91,6 +91,8 @@ set(NPUW_SOURCES${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_prefix_caching.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_prefix_caching.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_stored_tokens_state.hpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_swa_cache.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_swa_cache.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/logging.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/logging.hpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/moe/moe_config.hppdiff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txtindex 9ec0a556096..929086315ad 100644--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt@@ -55,6 +55,7 @@ ov_add_test_target(${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_compiled_model_utils.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_infer_request.cpp+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_swa_cache.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_block_kvcache_strategy.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_continuous_kvcache_strategy.cpp${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/llm_infer_base_request.cpp@@ -176,6 +177,7 @@ target_sources(${TARGET_NAME} PRIVATE${CMAKE_CURRENT_SOURCE_DIR}/npuw/gather_sub128_matcher_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_continuation_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_continued_prefill_test.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_swa_cache_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/stored_tokens_state_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_infer_request_variant_switch_test.cpp${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_infer_request_port_names_test.cppdiff --git a/src/plugins/intel_npu/tests/unit/npuw/llm_swa_cache_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/llm_swa_cache_test.cppnew file mode 100644index 00000000000..5fdd04c83de--- /dev/null+++ b/src/plugins/intel_npu/tests/unit/npuw/llm_swa_cache_test.cpp@@ -0,0 +1,354 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++// Request-level regression tests for SwaKVCacheHelper: classifying SWA-managed+// KV names, sharing SWA tensors across generate variants, and handing SWA past+// KV off between prefill and generate. Submodels are compiled through a factory+// that returns fake sub-requests whose infer() stamps every "present" output+// with a call-local, increasing byte value ("color") and zeroes everything+// else, so every byte observed in an SWA KV tensor was moved there by the+// plugin's own SWA plumbing, not the fake compute.+//+// The low-level write algorithms are already covered by+// sliding_window_manager_update_kv_cache_test.cpp; these tests stay within the+// SWA window to exercise the wiring only, not that math.++#include <gtest/gtest.h>++#include <cstdint>+#include <cstring>+#include <memory>+#include <string>+#include <unordered_map>+#include <vector>++#include "executor.hpp"+#include "infer_request_utils.hpp"+#include "llm_compiled_model.hpp"+#include "llm_infer_request.hpp"+#include "llm_test_helpers.hpp"+#include "openvino/openvino.hpp"+#include "util.hpp"++namespace ov::test::npuw {++struct LLMSwaCacheTestAccess {+ using Request = ov::npuw::LLMInferRequest;++ static const ov::npuw::LLMCompiledModel::KVCacheDesc& desc(Request& req) {+ return req.m_npuw_llm_compiled_model->m_kvcache_desc;+ }++ static const std::vector<std::string>& swa_past_names(const Request& req) {+ return req.m_swa_past_names;+ }++ static const std::vector<std::string>& kvcache_past_names(const Request& req) {+ return req.m_kvcache_past_names;+ }++ static ov::SoPtr<ov::ITensor> prefill_past(Request& req, const std::string& name) {+ return req.m_prefill_request->get_tensor(req.m_prefill_in_ports.at(name));+ }++ static ov::SoPtr<ov::ITensor> generate_past(Request& req, const std::string& name) {+ return req.m_kvcache_request->get_tensor(req.m_kvcache_in_ports.at(name));+ }++ static std::size_t generate_variant_count(const std::shared_ptr<ov::npuw::LLMCompiledModel>& compiled) {+ return compiled->m_generate_compiled_variants.size();+ }++ static ov::SoPtr<ov::ITensor> generate_variant_past(Request& req,+ std::size_t variant_idx,+ const std::string& name) {+ const auto& request = req.m_generate_requests.at(variant_idx);+ const auto& ports = req.m_generate_variant_in_ports.at(request);+ return request->get_tensor(ports.at(name));+ }++ static uint32_t kv_dim(const Request& req, const std::string& name, bool v_transposed) {+ const auto& desc = req.m_npuw_llm_compiled_model->m_kvcache_desc;+ return (ov::npuw::util::isPastValueParam(name) && v_transposed) ? 3u : desc.dim;+ }+};++} // namespace ov::test::npuw++namespace {++using ov::test::npuw::build_sliding_window_test_model;+using ov::test::npuw::LLMSwaCacheTestAccess;+using ov::test::npuw::NullPlugin;+class FakeSubCompiledModel;++// Stamps "present" outputs with a per-instance call counter ("color") on each+// infer(); everything else is zeroed.+class FakeSubInferRequest final : public ov::ISyncInferRequest {+public:+ explicit FakeSubInferRequest(std::shared_ptr<const FakeSubCompiledModel> compiled_model);++ void infer() override;+ ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override {+ return ov::ISyncInferRequest::get_tensor(port);+ }+ void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override {+ ov::ISyncInferRequest::set_tensor(port, tensor);+ }+ void check_tensors() const override {}+ std::vector<ov::SoPtr<ov::IVariableState>> query_state() const override {+ return {};+ }+ std::vector<ov::ProfilingInfo> get_profiling_info() const override {+ return {};+ }++private:+ uint8_t m_calls = 0u;+};++class FakeSubCompiledModel final : public ov::npuw::ICompiledModel_v0 {+public:+ FakeSubCompiledModel(const std::shared_ptr<ov::Model>& model,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ const ov::AnyMap&)+ : ov::npuw::ICompiledModel_v0(model, plugin),+ m_model(model) {}++ void export_model(std::ostream&) const override {}+ std::shared_ptr<const ov::Model> get_runtime_model() const override {+ return m_model;+ }+ void set_property(const ov::AnyMap&) override {}+ ov::Any get_property(const std::string&) const override {+ return {};+ }+ std::shared_ptr<ov::ISyncInferRequest> create_sync_infer_request() const override {+ auto self = std::static_pointer_cast<const FakeSubCompiledModel>(shared_from_this());+ return std::make_shared<FakeSubInferRequest>(std::move(self));+ }+ std::shared_ptr<ov::npuw::IBaseInferRequest> create_base_infer_request() const override {+ return {};+ }+ std::shared_ptr<ov::IAsyncInferRequest> wrap_async_infer_request(+ std::shared_ptr<ov::npuw::IBaseInferRequest>) const override {+ return std::make_shared<ov::IAsyncInferRequest>(create_sync_infer_request(),+ intel_npu::make_executor("swa_cache_task", 1),+ intel_npu::make_executor("swa_cache_callback", 1));+ }+ std::string submodel_device(std::size_t) const override {+ return "CPU";+ }+ std::size_t num_submodels() const override {+ return 1; // keeps init_pre_alloc_device() on CPU staging, not NPU remote tensors+ }+ std::shared_ptr<ov::npuw::weights::Bank> get_weights_bank() const override {+ return {};+ }+ void set_weights_bank(std::shared_ptr<ov::npuw::weights::Bank>) override {}+ void finalize_weights_bank() override {}+ void reconstruct_closure() override {}+ void serialize(std::ostream&, const ov::npuw::s11n::CompiledContext&) const override {}++private:+ std::shared_ptr<ov::Model> m_model;+};++FakeSubInferRequest::FakeSubInferRequest(std::shared_ptr<const FakeSubCompiledModel> compiled_model)+ : ov::ISyncInferRequest(std::move(compiled_model)) {+ for (const auto& input : get_compiled_model()->inputs()) {+ ov::ISyncInferRequest::set_tensor(input,+ ov::get_tensor_impl(ov::Tensor(input.get_element_type(), input.get_shape())));+ }+ for (const auto& output : get_compiled_model()->outputs()) {+ ov::ISyncInferRequest::set_tensor(+ output,+ ov::get_tensor_impl(ov::Tensor(output.get_element_type(), output.get_shape())));+ }+}++void FakeSubInferRequest::infer() {+ ++m_calls;+ for (const auto& output : get_compiled_model()->outputs()) {+ auto tensor = ov::ISyncInferRequest::get_tensor(output);+ const auto& name = output.get_any_name();+ const uint8_t value = (name.find("present") != std::string::npos) ? m_calls : 0u;+ std::memset(tensor->data(), value, tensor->get_byte_size());+ }+}++class SwaCacheFactory {+public:+ ov::npuw::LLMCompiledModel::CompiledModelFactory make_factory() {+ return [](const std::shared_ptr<ov::Model>& model,+ const std::shared_ptr<const ov::IPlugin>& plugin,+ const ov::AnyMap& props) -> std::shared_ptr<ov::npuw::ICompiledModel_v0> {+ return std::make_shared<FakeSubCompiledModel>(model, plugin, props);+ };+ }+};++std::vector<uint8_t> materialize_bytes(const ov::SoPtr<ov::ITensor>& tensor) {+ ov::Tensor copy(tensor->get_element_type(), tensor->get_shape());+ tensor->copy_to(ov::get_tensor_impl(copy)._ptr);+ auto* data = static_cast<uint8_t*>(copy.data());+ return std::vector<uint8_t>(data, data + copy.get_byte_size());+}++ov::Tensor make_i64(std::initializer_list<size_t> shape, int64_t fill_value) {+ ov::Tensor tensor(ov::element::i64, ov::Shape(shape));+ std::fill_n(tensor.data<int64_t>(), tensor.get_size(), fill_value);+ return tensor;+}++constexpr size_t kWindowSize = 32; // << kv_cache_size (192), so shrinkage is visible+constexpr size_t kNumLayers = 4; // layers 0,2 sliding; layers 1,3 full-attention+constexpr size_t kChunkSize = 8;++class LLMSwaCacheTest : public ::testing::Test {+protected:+ void SetUp() override {+ m_plugin = std::make_shared<NullPlugin>();+ }++ void init(const ov::AnyMap& extra_props) {+ SwaCacheFactory factory;+ ov::AnyMap props{{"NPUW_LLM", "YES"},+ {"NPUW_DEVICES", "CPU"},+ {"NPUW_LLM_MAX_PROMPT_LEN", "128"},+ {"NPUW_LLM_MIN_RESPONSE_LEN", "64"},+ {"NPUW_LLM_ENABLE_SWA_KV_CACHE_SHRINK", "YES"}};+ for (const auto& [key, value] : extra_props) {+ props[key] = value;+ }+ auto model = build_sliding_window_test_model(kWindowSize, /*sliding_to_full_ratio=*/1, {}, kNumLayers);+ m_compiled = std::make_shared<ov::npuw::LLMCompiledModel>(model, m_plugin, props, factory.make_factory());+ ASSERT_NE(m_compiled, nullptr);+ m_request = std::make_unique<ov::npuw::LLMInferRequest>(m_compiled);+ }++ void set_inputs(const ov::Tensor& input_ids, const ov::Tensor& attention_mask, const ov::Tensor& position_ids) {+ const auto& inputs = m_request->get_inputs();+ m_request->set_tensor(ov::npuw::util::find_port_by_name(inputs, "input_ids").value(),+ ov::get_tensor_impl(input_ids));+ m_request->set_tensor(ov::npuw::util::find_port_by_name(inputs, "attention_mask").value(),+ ov::get_tensor_impl(attention_mask));+ m_request->set_tensor(ov::npuw::util::find_port_by_name(inputs, "position_ids").value(),+ ov::get_tensor_impl(position_ids));+ }++ void run_prefill(size_t prompt_len) {+ set_inputs(make_i64({1, prompt_len}, 1), make_i64({1, prompt_len}, 1), make_i64({1, prompt_len}, 0));+ m_request->infer();+ }++ void run_generate_step(size_t live_tokens) {+ set_inputs(make_i64({1, 1}, 1),+ make_i64({1, live_tokens + 1}, 1),+ make_i64({1, 1}, static_cast<int64_t>(live_tokens)));+ m_request->infer();+ }++ std::shared_ptr<ov::IPlugin> m_plugin;+ std::shared_ptr<ov::npuw::LLMCompiledModel> m_compiled;+ std::unique_ptr<ov::npuw::LLMInferRequest> m_request;+};++// Only the sliding layers (0, 2) should be classified as SWA-managed; the+// full-attention layers (1, 3) must stay on the regular contiguous-KV path.+TEST_F(LLMSwaCacheTest, OnlySlidingLayersAreClassifiedAsSwaManaged) {+ init({});+ const auto& swa_names = LLMSwaCacheTestAccess::swa_past_names(*m_request);+ const auto& kv_names = LLMSwaCacheTestAccess::kvcache_past_names(*m_request);++ ASSERT_EQ(swa_names.size(), 4u); // 2 sliding layers * (key + value)+ for (const auto& name : swa_names) {+ EXPECT_TRUE(ov::npuw::util::is_swa_kv_cache_name(name)) << name;+ }+ for (const auto& name : kv_names) {+ EXPECT_FALSE(ov::npuw::util::is_swa_kv_cache_name(name)) << name;+ }+ for (const auto& name : swa_names) {+ EXPECT_EQ(std::find(kv_names.begin(), kv_names.end(), name), kv_names.end()) << name;+ }+}++// Two-chunk prefill (16 tokens, well inside the 32-token window) followed by+// one generate step: checks that every byte lands where the prefill<->generate+// handoff claims (update_prefill(), copy_prefill_to_generate(), update_generate()).+TEST_F(LLMSwaCacheTest, ChunkedPrefillUpdatesWindowAndHandsOffToGenerate) {+ init({{"NPUW_LLM_PREFILL_HINT", "DYNAMIC"}, {"NPUW_LLM_PREFILL_CHUNK_SIZE", std::to_string(kChunkSize)}});+ const auto& swa_names = LLMSwaCacheTestAccess::swa_past_names(*m_request);+ ASSERT_FALSE(swa_names.empty());++ // Chunk 1 (intermediate) is merged into the prefill past tensor (color 1);+ // chunk 2 (final) is left unmerged until the generate handoff.+ run_prefill(2 * kChunkSize);++ const auto& desc = LLMSwaCacheTestAccess::desc(*m_request);+ for (const auto& name : swa_names) {+ const auto dim = LLMSwaCacheTestAccess::kv_dim(*m_request, name, desc.v_tensors_transposed_pre);+ auto past = LLMSwaCacheTestAccess::prefill_past(*m_request, name);++ auto chunk0 = ov::npuw::util::make_tensor_slice(past, dim, 0u, static_cast<uint32_t>(kChunkSize));+ auto expected0 = std::vector<uint8_t>(chunk0->get_byte_size(), 1u);+ EXPECT_EQ(materialize_bytes(chunk0), expected0) << name << " (chunk 1, merged via update_prefill)";++ auto chunk1 = ov::npuw::util::make_tensor_slice(past,+ dim,+ static_cast<uint32_t>(kChunkSize),+ static_cast<uint32_t>(2 * kChunkSize));+ auto expected_zero = std::vector<uint8_t>(chunk1->get_byte_size(), 0u);+ EXPECT_EQ(materialize_bytes(chunk1), expected_zero) << name << " (chunk 2, not yet merged)";+ }++ run_generate_step(2 * kChunkSize);++ for (const auto& name : swa_names) {+ const auto dim = LLMSwaCacheTestAccess::kv_dim(*m_request, name, desc.v_tensors_transposed_gen);+ auto generate_past = LLMSwaCacheTestAccess::generate_past(*m_request, name);++ auto history = ov::npuw::util::make_tensor_slice(generate_past, dim, 0u, static_cast<uint32_t>(kChunkSize));+ auto expected_chunk0 = std::vector<uint8_t>(history->get_byte_size(), 1u);+ EXPECT_EQ(materialize_bytes(history), expected_chunk0) << name << " (handed off chunk 1)";++ auto tail = ov::npuw::util::make_tensor_slice(generate_past,+ dim,+ static_cast<uint32_t>(kChunkSize),+ static_cast<uint32_t>(2 * kChunkSize));+ auto expected_chunk1 = std::vector<uint8_t>(tail->get_byte_size(), 2u);+ EXPECT_EQ(materialize_bytes(tail), expected_chunk1) << name+ << " (handed off chunk 2, color from its own "+ "present output)";++ auto new_token = ov::npuw::util::make_tensor_slice(generate_past,+ dim,+ static_cast<uint32_t>(2 * kChunkSize),+ static_cast<uint32_t>(2 * kChunkSize + 1));+ auto expected_new_token = std::vector<uint8_t>(new_token->get_byte_size(), 1u);+ EXPECT_EQ(materialize_bytes(new_token), expected_new_token)+ << name << " (appended by update_generate from the generate model's own first call)";+ }+}++// share_across_generate_variants() should alias every SWA past tensor from the+// largest generate variant onto the smaller ones, not just shape-match them.+TEST_F(LLMSwaCacheTest, SharesSwaPastTensorsAcrossGenerateVariants) {+ init({{"NPUW_LLM_GENERATE_PYRAMID", "YES"}, {"NPUW_LLM_MAX_PROMPT_LEN", "2048"}});+ ASSERT_GE(LLMSwaCacheTestAccess::generate_variant_count(m_compiled), 2u);++ const auto& swa_names = LLMSwaCacheTestAccess::swa_past_names(*m_request);+ ASSERT_FALSE(swa_names.empty());++ const auto last_variant = LLMSwaCacheTestAccess::generate_variant_count(m_compiled) - 1u;+ for (const auto& name : swa_names) {+ auto largest = LLMSwaCacheTestAccess::generate_variant_past(*m_request, last_variant, name);+ for (std::size_t i = 0; i < last_variant; ++i) {+ auto smaller = LLMSwaCacheTestAccess::generate_variant_past(*m_request, i, name);+ EXPECT_EQ(smaller->data(), largest->data()) << name << " variant " << i;+ }+ }+}++} // namespacediff --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.cppindex 0aa097cc148..71107414d80 100644--- 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.cpp@@ -68,6 +68,21 @@ constexpr uint32_t kKvCacheSize = 192;constexpr uint32_t kGenerateInputSize = 1;const ov::npuw::KVAxesPosition kAxes{0u, 2u};+// Mirrors ShrinkSlidingWindowKVCache's own 16-alignment: when there is a nonzero past+// region, past is grown so that past + present is a multiple of 16 (NPU HW preference).+constexpr uint32_t kKvAlignment = 16;+uint32_t aligned_kv_total(uint32_t window_size, uint32_t input_size) {+ const uint32_t unaligned_total = input_size + window_size;+ return ((unaligned_total + kKvAlignment - 1) / kKvAlignment) * kKvAlignment;+}+uint32_t aligned_past(uint32_t window_size, uint32_t input_size) {+ return aligned_kv_total(window_size, input_size) - input_size;+}++// window=32, generate input_size=1: unaligned total=33 -> aligned to 48, so past=47.+const uint32_t kGenerateAlignedPast = aligned_past(kWindowSize, kGenerateInputSize);+const uint32_t kGenerateAlignedKvTotal = aligned_kv_total(kWindowSize, kGenerateInputSize);+std::shared_ptr<ov::Model> build_hybrid_model() {return ov::test::npuw::build_sliding_window_test_model(kWindowSize, /*sliding_to_full_ratio=*/1, {}, kNumLayers);}@@ -137,9 +152,10 @@ TEST_F(ShrinkSlidingWindowKVCacheTest, GenerateModel_OnlySlidingLayersPastKVShruASSERT_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 sliding_past = input_shape(generate, "past_key_values.0.swa.key");+ ASSERT_TRUE(sliding_past.has_value()) << "past_key_values.0.swa.key not found in generate model";+ // window=32 is grown to kGenerateAlignedPast (47) so past+present is 16-aligned.+ EXPECT_EQ((*sliding_past)[2], kGenerateAlignedPast);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";@@ -154,8 +170,8 @@ TEST_F(ShrinkSlidingWindowKVCacheTest, GenerateModel_SlidingMaskWidthShrunkToNewconst 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);+ // Generate input_size=1, window=32 => unaligned new_kv_total=33, 16-aligned to 48.+ EXPECT_EQ(mask_shape->back(), kGenerateAlignedKvTotal);}// Prefill invariant: sliding mask width follows the same post-concat KV width rule.@@ -176,18 +192,23 @@ TEST_F(ShrinkSlidingWindowKVCacheTest, PrefillModel_SlidingMaskWidthShrunkToNewKEXPECT_EQ(mask_shape->back(), expected_width);}-// Only sliding-layer past KV parameters get SWA rt_info tag.-TEST_F(ShrinkSlidingWindowKVCacheTest, GenerateModel_OnlySlidingLayersPastKVTaggedWithRtInfo) {+// Only sliding-layer past KV parameters (and their matching present outputs) get renamed+// with the SWA "swa" marker segment; full-attention layers keep their original names untouched.+TEST_F(ShrinkSlidingWindowKVCacheTest, GenerateModel_OnlySlidingLayersPastKVRenamedWithSwaPrefix) {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 sliding_input = find_input(generate, "past_key_values.0.swa.key");+ ASSERT_TRUE(sliding_input.has_value()) << "past_key_values.0.swa.key not found in generate model";+ const auto sliding_present = find_output(generate, "present.0.swa.key");+ ASSERT_TRUE(sliding_present.has_value()) << "present.0.swa.key not found in generate model outputs";+ EXPECT_TRUE(ov::npuw::util::is_swa_kv_cache_name(sliding_input->get_node()->get_friendly_name()));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);+ EXPECT_FALSE(ov::npuw::util::is_swa_kv_cache_name(full_input->get_node()->get_friendly_name()));+ const auto full_present = find_output(generate, "present.1.key");+ ASSERT_TRUE(full_present.has_value()) << "present.1.key not found in generate model outputs";}// Input-source invariant: sliding SDPA consumes the externalized mask, full-attention SDPA does not.@@ -220,13 +241,13 @@ TEST_F(ShrinkSlidingWindowKVCacheTest, PrefillSingleShot_SlidingPastIsZero_GenerASSERT_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";+ const auto prefill_sliding_past = input_shape(prefill, "past_key_values.0.swa.key");+ ASSERT_TRUE(prefill_sliding_past.has_value()) << "past_key_values.0.swa.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);+ const auto generate_sliding_past = input_shape(generate, "past_key_values.0.swa.key");+ ASSERT_TRUE(generate_sliding_past.has_value()) << "past_key_values.0.swa.key not found in generate model";+ EXPECT_EQ((*generate_sliding_past)[2], kGenerateAlignedPast);}// Chunked prefill (input_size < kvcache_size) leaves a nonzero past budget, so sliding@@ -236,8 +257,8 @@ TEST_F(ShrinkSlidingWindowKVCacheTest, ChunkedPrefill_SlidingLayerKeepsWindowSizstd::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";+ const auto sliding_past = input_shape(prefill, "past_key_values.0.swa.key");+ ASSERT_TRUE(sliding_past.has_value()) << "past_key_values.0.swa.key not found in prefill model";EXPECT_EQ((*sliding_past)[2], kWindowSize);}@@ -247,8 +268,8 @@ TEST_F(ShrinkSlidingWindowKVCacheTest, GenerateModel_SlidingKVShapeConstantsPatcstd::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;+ // Generate input_size=1, window=32 => unaligned new_kv_total=33, 16-aligned to 48.+ const int64_t kNewKvTotal = static_cast<int64_t>(kGenerateAlignedKvTotal);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);@@ -391,11 +412,11 @@ TEST_F(ShrinkSlidingWindowKVCacheTest, AllLayersSliding_MaskExternalizedAndPastSEXPECT_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 past0 = input_shape(generate, "past_key_values.0.swa.key");+ ASSERT_TRUE(past0.has_value()) << "past_key_values.0.swa.key not found in generate model";+ EXPECT_EQ((*past0)[2], kGenerateAlignedPast);- 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);+ const auto past1 = input_shape(generate, "past_key_values.1.swa.key");+ ASSERT_TRUE(past1.has_value()) << "past_key_values.1.swa.key not found in generate model";+ EXPECT_EQ((*past1)[2], kGenerateAlignedPast);}diff --git a/src/plugins/intel_npu/tests/unit/npuw/sliding_window_manager_generate_mask_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/sliding_window_manager_generate_mask_test.cppindex eba67974868..f7870a9f436 100644--- a/src/plugins/intel_npu/tests/unit/npuw/sliding_window_manager_generate_mask_test.cpp+++ b/src/plugins/intel_npu/tests/unit/npuw/sliding_window_manager_generate_mask_test.cpp@@ -88,7 +88,8 @@ TEST_F(FillCausalSlidingWindowMaskTest, UnsaturatedPastBuildsExpectedMask) {uu::fill_causal_sliding_window_mask(mask,/*num_stored_tokens=*/2u,/*num_new_tokens=*/2u,- /*window_size=*/3u);+ /*window_size=*/3u,+ /*past_is_circular=*/true);// row=2: q=2, past abs=[0,1] visible; only diagonal local key is visible.EXPECT_FLOAT_EQ(mask_at(mask, 2u, 0u), 0.f);@@ -112,7 +113,8 @@ TEST_F(FillCausalSlidingWindowMaskTest, SaturatedPastUsesCircularSlotMapping) {uu::fill_causal_sliding_window_mask(mask,/*num_stored_tokens=*/6u,/*num_new_tokens=*/2u,- /*window_size=*/3u);+ /*window_size=*/3u,+ /*past_is_circular=*/true);// past_width=4, r=2 => slot->abs=[4,5,2,3]; row=0(q=6): 4/5 visible, 2/3 masked.EXPECT_FLOAT_EQ(mask_at(mask, 0u, 0u), 0.f);@@ -129,6 +131,37 @@ TEST_F(FillCausalSlidingWindowMaskTest, SaturatedPastUsesCircularSlotMapping) {EXPECT_FLOAT_EQ(mask_at(mask, 1u, 5u), 0.f);}+TEST_F(FillCausalSlidingWindowMaskTest, SaturatedPastUsesLeftAlignedSlotMapping) {+ // Same inputs as the circular-layout test above, but past_is_circular=false: once+ // saturated, a non-wrapping buffer maps slots to one contiguous range instead of a+ // two-segment ring, producing a different mask from identical inputs.+ auto mask = make_mask_tensor(/*rows=*/2u, /*cols=*/6u, /*init_value=*/777.f);+ const float kMasked = static_cast<float>(std::numeric_limits<ov::float16>::lowest());++ uu::fill_causal_sliding_window_mask(mask,+ /*num_stored_tokens=*/6u,+ /*num_new_tokens=*/2u,+ /*window_size=*/3u,+ /*past_is_circular=*/false);++ // past_width=4, chronologically-packed layout => slot->abs=[2,3,4,5] (contiguous, no wrap).+ // row=0(abs=6): visible abs range [4,6] -> past slots 2,3 (abs 4,5) visible, slots 0,1 masked.+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 0u), kMasked);+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 1u), kMasked);+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 2u), 0.f);+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 3u), 0.f);+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 4u), 0.f);+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 5u), kMasked);++ // row=1(abs=7): visible abs range [5,7] -> only past slot 3 (abs 5) visible.+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 0u), kMasked);+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 1u), kMasked);+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 2u), kMasked);+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 3u), 0.f);+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 4u), 0.f);+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 5u), 0.f);+}+TEST_F(FillCausalSlidingWindowMaskTest, ZeroPastWidthFallsBackToCurrentChunkSlidingWindowCausalMask) {// rows == cols => past_width == 0, so mask must be built from current chunk only.auto mask = make_mask_tensor(/*rows=*/4u, /*cols=*/4u, /*init_value=*/777.f);@@ -137,7 +170,8 @@ TEST_F(FillCausalSlidingWindowMaskTest, ZeroPastWidthFallsBackToCurrentChunkSliduu::fill_causal_sliding_window_mask(mask,/*num_stored_tokens=*/0u,/*num_new_tokens=*/4u,- /*window_size=*/2u);+ /*window_size=*/2u,+ /*past_is_circular=*/true);// Expected visible local columns per row for window=2:// row0 -> [0]@@ -170,7 +204,8 @@ TEST_F(FillCausalSlidingWindowMaskTest, UnsaturatedPastBuildsExpectedMaskF16) {uu::fill_causal_sliding_window_mask(mask,/*num_stored_tokens=*/2u,/*num_new_tokens=*/2u,- /*window_size=*/3u);+ /*window_size=*/3u,+ /*past_is_circular=*/true);EXPECT_FLOAT_EQ(mask_at(mask, 2u, 0u), 0.f);EXPECT_FLOAT_EQ(mask_at(mask, 2u, 1u), 0.f);@@ -193,7 +228,8 @@ TEST_F(FillCausalSlidingWindowMaskTest, RowPadRowsDoNotAffectRealRowVisibility)uu::fill_causal_sliding_window_mask(mask,/*num_stored_tokens=*/3u,/*num_new_tokens=*/2u,- /*window_size=*/3u);+ /*window_size=*/3u,+ /*past_is_circular=*/true);// row=2 is the real row 0: abs=3, visible past slots [1,2], present local_c=2 (col 6).EXPECT_FLOAT_EQ(mask_at(mask, 2u, 0u), kMasked);@@ -222,7 +258,8 @@ TEST_F(FillCausalSlidingWindowMaskTest, SaturatedPastWithExactWrapUsesSingleSegmuu::fill_causal_sliding_window_mask(mask,/*num_stored_tokens=*/8u,/*num_new_tokens=*/2u,- /*window_size=*/3u);+ /*window_size=*/3u,+ /*past_is_circular=*/true);// row=0(abs=8): visible past slots [2,3] -> cols 2,3; present local_c=0 -> col 4.EXPECT_FLOAT_EQ(mask_at(mask, 0u, 0u), kMasked);@@ -306,7 +343,8 @@ TEST_F(FillSlidingWindowAttentionMaskTest, MaskPortMissingIsNoOp) {in_ports,/*num_stored_tokens=*/3u,/*num_new_tokens=*/3u,- /*window_size=*/4u));+ /*window_size=*/4u,+ /*past_is_circular=*/true));}TEST_F(FillSlidingWindowAttentionMaskTest, TokenTypeIdsPortMissingSkipsOverlay) {@@ -327,7 +365,8 @@ TEST_F(FillSlidingWindowAttentionMaskTest, TokenTypeIdsPortMissingSkipsOverlay)in_ports,/*num_stored_tokens=*/3u,/*num_new_tokens=*/3u,- /*window_size=*/4u);+ /*window_size=*/4u,+ /*past_is_circular=*/true);EXPECT_FLOAT_EQ(mask_at(mask, 0u, 0u), 0.f);EXPECT_FLOAT_EQ(mask_at(mask, 0u, 4u), 0.f);@@ -359,7 +398,8 @@ TEST_F(FillSlidingWindowAttentionMaskTest, CombinesCausalMaskAndVisionOverlay) {in_ports,/*num_stored_tokens=*/3u,/*num_new_tokens=*/3u,- /*window_size=*/4u);+ /*window_size=*/4u,+ /*past_is_circular=*/true);// row 0: vision overlay forces col 5 to attend on top of the causal mask.EXPECT_FLOAT_EQ(mask_at(mask, 0u, 0u), 0.f);@@ -396,7 +436,8 @@ TEST_F(FillSlidingWindowAttentionMaskTest, TokenTypeIdsSizeMismatchThrows) {in_ports,/*num_stored_tokens=*/3u,/*num_new_tokens=*/3u,- /*window_size=*/4u),+ /*window_size=*/4u,+ /*past_is_circular=*/true),ov::Exception);}