Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[NPUW][SWA][PR2] Attention mask generation and KV slice writes (#37788)

Guoliang Shi7ba126441931
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.cpp
new file mode 100644
index 00000000000..3c20476c47f
--- /dev/null
+++ b/src/plugins/intel_npu/src/plugin/npuw/kv_cache_sliding_window_manager.cpp
@@ -0,0 +1,509 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "kv_cache_sliding_window_manager.hpp"
+
+#include <algorithm>
+#include <array>
+#include <cstdint>
+#include <limits>
+
+#include "infer_request_utils.hpp"
+#include "llm_compiled_model_utils.hpp"
+#include "logging.hpp"
+#include "openvino/runtime/iasync_infer_request.hpp"
+#include "openvino/runtime/itensor.hpp"
+#include "util.hpp"
+
+namespace {
+
+struct MaskView {
+ uint32_t row_dim = 0; // Query axis length
+ uint32_t col_dim = 0; // Key axis length
+ uint32_t past_width = 0; // Past-region column count: col_dim - row_dim
+ uint32_t row_pad = 0; // Unused leading rows in this call's chunk: row_dim - num_new_tokens
+ ov::element::Type element_type; // Actual mask tensor element type: f32 or f16
+ void* data = nullptr; // Base pointer to the mask tensor's data
+};
+
+MaskView get_mask_view(const ov::SoPtr<ov::ITensor>& mask_tensor, uint32_t num_new_tokens, const char* caller_name) {
+ const auto element_type = mask_tensor->get_element_type();
+ OPENVINO_ASSERT(element_type == ov::element::f32 || element_type == ov::element::f16,
+ caller_name,
+ ": Attention mask tensor is expected to be f32 or f16, got: ",
+ element_type);
+ const auto& shape = mask_tensor->get_shape();
+ OPENVINO_ASSERT(shape.size() >= 2, caller_name, ": Attention mask tensor rank must be >= 2, got shape: ", shape);
+
+ const uint32_t row_dim = static_cast<uint32_t>(shape[shape.size() - 2]);
+ const uint32_t col_dim = static_cast<uint32_t>(shape[shape.size() - 1]);
+ OPENVINO_ASSERT(std::all_of(shape.begin(),
+ shape.end() - 2,
+ [](size_t dim) {
+ return dim == 1;
+ }),
+ caller_name,
+ ": attention mask leading dimensions must be singleton, got shape: ",
+ shape);
+ OPENVINO_ASSERT(col_dim >= row_dim,
+ caller_name,
+ ": attention mask key axis (",
+ col_dim,
+ ") must be >= query axis (",
+ row_dim,
+ ")");
+ OPENVINO_ASSERT(num_new_tokens <= row_dim,
+ caller_name,
+ ": num_new_tokens (",
+ num_new_tokens,
+ ") exceeds query axis (",
+ row_dim,
+ ")");
+
+ MaskView mv;
+ mv.row_dim = row_dim;
+ mv.col_dim = col_dim;
+ mv.past_width = col_dim - row_dim;
+ mv.row_pad = row_dim - num_new_tokens;
+ mv.element_type = element_type;
+ mv.data = mask_tensor->data();
+ return mv;
+}
+
+} // namespace
+
+namespace {
+
+template <typename T>
+void fill_causal_sliding_window_mask_typed(const MaskView& mask_view,
+ uint32_t num_stored_tokens,
+ uint32_t window_size) {
+ 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);
+ const int64_t row_pad_i64 = static_cast<int64_t>(row_pad);
+
+ const T kAttend = T(0.0f);
+ const T kMasked = T(std::numeric_limits<ov::float16>::lowest());
+
+ // Row columns = [past circular 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
+ //
+ // 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].
+ //
+ // Example (past_width=4, row_dim=3, row_pad=0, stored_tokens=3, window_size=4):
+ // Past slots hold real tokens for abs 0,1,2 (slot 3 unwritten: stored_tokens < past_width).
+ // Row q's absolute position is stored_tokens + q.
+ //
+ // cols -> 0 1 2 3 | 4 5 6
+ // row 0(q=0,abs=3): A A A . | A . .
+ // row 1(q=1,abs=4): . A A . | A A .
+ // row 2(q=2,abs=5): . . A . | A A A
+ //
+ // A = attend (0.0f), . = masked (-inf). The past A-run slides one slot right per row
+ // (window_size=4 tokens total, incl. the causal diagonal); slot 3 stays masked because
+ // stored_tokens=3 hasn't written it yet. row_pad > 0 just adds unused rows above row 0.
+
+ // Inclusive [begin, end] slot interval; begin > end means "empty".
+ struct VisibleRange {
+ int64_t begin;
+ int64_t end;
+ };
+ constexpr VisibleRange kEmptyRange{1, 0};
+
+ // Step 1 helper: pure range arithmetic, no memory access. Clamps the visibility window
+ // [range_begin, range_end] against a region's own domain [domain_begin, domain_end].
+ auto compute_visible_range =
+ [](int64_t range_begin, int64_t range_end, int64_t domain_begin, int64_t domain_end) -> VisibleRange {
+ return {std::max(range_begin, domain_begin), std::min(range_end, domain_end)};
+ };
+
+ // Step 2 helper: pure memory write, no range math. Fills an already-clamped range.
+ auto fill_visible_range = [](T* ptr, VisibleRange range, T fill_value) {
+ if (range.begin <= range.end) {
+ std::fill_n(ptr + range.begin, static_cast<size_t>(range.end - range.begin + 1), fill_value);
+ }
+ };
+
+ // 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).
+ 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) {
+ // Saturated ring: at most two contiguous slot ranges can be visible,
+ // one in [wrap_slot, past_width) and one in [0, wrap_slot).
+ 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
+
+ // Segment 1: c in [wrap_slot, past_width-1].
+ const VisibleRange segment1 = compute_visible_range(min_visible_abs_pos - older_segment_bias,
+ max_visible_abs_pos - older_segment_bias,
+ static_cast<int64_t>(wrap_slot),
+ past_width_i64 - 1);
+ // Segment 2: c in [0, wrap_slot-1], only when the ring actually wrapped.
+ const VisibleRange segment2 = (wrap_slot > 0u) ? compute_visible_range(min_visible_abs_pos - ring_base_abs,
+ max_visible_abs_pos - ring_base_abs,
+ 0,
+ static_cast<int64_t>(wrap_slot) - 1)
+ : kEmptyRange;
+ return {segment1, segment2};
+ }
+ if (stored_tokens > 0u) {
+ // Unsaturated prefix: slot index equals absolute position for valid slots.
+ return {compute_visible_range(min_visible_abs_pos, max_visible_abs_pos, 0, stored_tokens_i64 - 1),
+ kEmptyRange};
+ }
+ return {kEmptyRange, kEmptyRange};
+ };
+
+ T* base = static_cast<T*>(mask_view.data);
+ for (uint32_t row = 0; row < row_dim; ++row) {
+ T* row_ptr = base + static_cast<size_t>(row) * mask_view.col_dim;
+
+ const int64_t row_i64 = static_cast<int64_t>(row);
+ const int64_t row_abs_pos = stored_tokens_i64 + (row_i64 - row_pad_i64);
+ const int64_t min_visible_abs_pos = row_abs_pos - window_i64 + 1;
+ const int64_t max_visible_abs_pos = row_abs_pos;
+
+ // Step 1: compute which slots are visible in this row. Pure arithmetic only --
+ // nothing is written to the mask buffer yet.
+ const std::array<VisibleRange, 2> past_slots =
+ compute_visible_past_slots(min_visible_abs_pos, max_visible_abs_pos);
+
+ // Current chunk ("present") diagonal region [past_width, past_width + row_dim).
+ // local_c must satisfy all constraints below:
+ // 1) valid key in right-aligned chunk: local_c >= row_pad
+ // 2) causal: local_c <= row
+ // 3) window: row - local_c < window_size
+ // => local_c in [max(row_pad, row-window+1), row].
+ const VisibleRange present_segment = compute_visible_range(std::max(row_pad_i64, row_i64 - window_i64 + 1),
+ row_i64,
+ 0,
+ static_cast<int64_t>(row_dim) - 1);
+
+ // Step 2: populate masked and attended values.
+ // 2.1 init row: all masked.
+ std::fill_n(row_ptr, mask_view.col_dim, kMasked);
+ // 2.2 attend past in ranges (from step 1).
+ fill_visible_range(row_ptr, past_slots[0], kAttend);
+ fill_visible_range(row_ptr, past_slots[1], kAttend);
+ // 2.3 attend present.
+ fill_visible_range(row_ptr + past_width, present_segment, kAttend);
+ }
+}
+
+} // namespace
+
+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) {
+ 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);
+ break;
+ case ov::element::f16:
+ fill_causal_sliding_window_mask_typed<ov::float16>(mask_view, num_stored_tokens, window_size);
+ break;
+ default:
+ OPENVINO_THROW("fill_causal_sliding_window_mask: unsupported mask element type ", mask_view.element_type);
+ }
+}
+
+namespace {
+
+template <typename T>
+void overlay_vision_bidirectional_mask_typed(const MaskView& mask_view,
+ const int64_t* token_type_ids,
+ uint32_t num_new_tokens) {
+ const T kAttend = T(0.0f);
+ constexpr int64_t kVisionTokenTypeId = 1;
+
+ // This function makes vision-token runs bidirectional inside the current chunk.
+ // We scan token_type_ids and find contiguous runs where token_type_id == 1.
+ // For each run [run_start, run_end), we unmask a square block in the current-chunk
+ // submatrix: rows run_start..run_end-1 and cols run_start..run_end-1.
+ //
+ // Example (current chunk only, V=vision, T=text):
+ // token_type_ids: [T, V, V, V, T, V, V]
+ // runs: [1,4), [5,7)
+ //
+ // local cols -> 0 1 2 3 4 5 6
+ // local rows
+ // 0(T): . . . . . . .
+ // 1(V): . A A A . . .
+ // 2(V): . A A A . . .
+ // 3(V): . A A A . . .
+ // 4(T): . . . . . . .
+ // 5(V): . . . . . B B
+ // 6(V): . . . . . B B
+ // A/B: cells forced to attend (0.0f) by this overlay.
+ T* base = static_cast<T*>(mask_view.data);
+ auto apply_vision_run = [&](uint32_t run_start, uint32_t run_end_exclusive) {
+ const uint32_t run_length = run_end_exclusive - run_start;
+ const uint32_t run_col_start = mask_view.past_width + mask_view.row_pad + run_start;
+ for (uint32_t row_index = run_start; row_index < run_end_exclusive; ++row_index) {
+ T* row_ptr = base + static_cast<size_t>(mask_view.row_pad + row_index) * mask_view.col_dim;
+ std::fill_n(row_ptr + run_col_start, run_length, kAttend);
+ }
+ };
+
+ uint32_t token_index = 0;
+ while (token_index < num_new_tokens) {
+ if (token_type_ids[token_index] != kVisionTokenTypeId) {
+ ++token_index;
+ continue;
+ }
+ const uint32_t run_start = token_index;
+ while (token_index < num_new_tokens && token_type_ids[token_index] == kVisionTokenTypeId) {
+ ++token_index;
+ }
+ apply_vision_run(run_start, token_index);
+ }
+}
+
+} // namespace
+
+void ov::npuw::util::overlay_vision_bidirectional_mask(ov::SoPtr<ov::ITensor> mask_tensor,
+ const int64_t* token_type_ids,
+ uint32_t num_new_tokens) {
+ if (num_new_tokens == 0) {
+ return;
+ }
+ OPENVINO_ASSERT(token_type_ids != nullptr, "overlay_vision_bidirectional_mask: token_type_ids must not be null");
+
+ const auto mask_view = get_mask_view(mask_tensor, num_new_tokens, "overlay_vision_bidirectional_mask");
+
+ switch (mask_view.element_type) {
+ case ov::element::f32:
+ overlay_vision_bidirectional_mask_typed<float>(mask_view, token_type_ids, num_new_tokens);
+ break;
+ case ov::element::f16:
+ overlay_vision_bidirectional_mask_typed<ov::float16>(mask_view, token_type_ids, num_new_tokens);
+ break;
+ default:
+ OPENVINO_THROW("overlay_vision_bidirectional_mask: unsupported mask element type ", mask_view.element_type);
+ }
+}
+
+// Orchestrates the two mask passes above: causal sliding-window mask, then the
+// vision-bidirectional overlay on top (only adds attention, never removes).
+//
+// Example (past_width=4, row_dim=3, row_pad=0, stored_tokens=3, window_size=4,
+// token_type_ids=[V,V,T] -> vision run over local rows/cols [0,2)):
+//
+// causal only: causal + vision overlay:
+// cols -> 0 1 2 3 | 4 5 6 cols -> 0 1 2 3 | 4 5 6
+// row 0(abs=3): A A A . | A . . row 0(abs=3): A A A . | A B .
+// row 1(abs=4): . A A . | A A . row 1(abs=4): . A A . | A A .
+// row 2(abs=5): . . A . | A A A row 2(abs=5): . . A . | A A A
+//
+void ov::npuw::util::fill_sliding_window_attention_mask(
+ const std::shared_ptr<ov::IAsyncInferRequest>& request,
+ 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) {
+ 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);
+
+ const auto token_type_ids_it = in_ports.find(ov::npuw::util::kTokenTypeIdsParamName);
+ if (token_type_ids_it != in_ports.end()) {
+ auto token_type_ids_tensor = request->get_tensor(token_type_ids_it->second);
+ const size_t total_len = token_type_ids_tensor->get_size();
+ OPENVINO_ASSERT(num_new_tokens <= total_len,
+ "fill_sliding_window_attention_mask: num_new_tokens (",
+ num_new_tokens,
+ ") exceeds token_type_ids size (",
+ total_len,
+ ")");
+ const int64_t* token_type_ids = token_type_ids_tensor->data<int64_t>() + total_len - num_new_tokens;
+ overlay_vision_bidirectional_mask(mask_tensor, token_type_ids, num_new_tokens);
+ }
+}
+
+void ov::npuw::util::write_swa_kv_slice_left_aligned(ov::SoPtr<ov::ITensor> dst_tensor,
+ ov::SoPtr<ov::ITensor> src_new_kv,
+ uint32_t dst_kv_dim,
+ uint32_t src_kv_dim,
+ uint32_t num_stored_tokens,
+ uint32_t num_new_tokens) {
+ // Used in the prefill stage to write a chunk of num_new_tokens tokens into a fixed-
+ // capacity (window_size) left-aligned buffer: valid tokens stay packed at the front
+ // as [surviving old tail | newest tokens], truncated to capacity. Three cases:
+ //
+ // A) chunk == capacity: the new chunk alone fills the whole window -> single
+ // full-buffer overwrite, all old tokens discarded (capacity=6):
+ // before: o1 o2 o3 o4 _ _ after: n1 n2 n3 n4 n5 n6
+ //
+ // B) chunk < capacity: no old data is discarded until the buffer would overflow.
+ // B1) not yet full -> plain append, no shift (capacity=6):
+ // before: o1 o2 _ _ _ _ after: o1 o2 n1 n2 n3 _
+ // B2) already full -> shift the surviving old tail to the front, then append
+ // (capacity=6, oldest tokens o1-o3 evicted):
+ // before: o1 o2 o3 o4 o5 o6 after: o4 o5 o6 n1 n2 n3
+ //
+ // C) chunk > capacity: even an empty buffer can't hold the whole chunk -> slice
+ // off just the newest `capacity` tokens of the input and overwrite everything;
+ // old data is discarded and the chunk's own oldest tokens (n1,n2) never get
+ // written (chunk = n1..n8, capacity=6):
+ // before: o1 o2 _ _ _ _ after: n3 n4 n5 n6 n7 n8
+ const uint32_t capacity = static_cast<uint32_t>(dst_tensor->get_shape()[dst_kv_dim]);
+ const uint32_t old_total = num_stored_tokens;
+ const uint32_t new_total = old_total + num_new_tokens;
+ const uint32_t old_valid = std::min(old_total, capacity);
+ const uint32_t new_valid = std::min(new_total, capacity);
+
+ // Clamp against source length too. Some source tensors can hold fewer tokens
+ // than num_new_tokens when they were capacity-limited earlier.
+ const uint32_t src_len = static_cast<uint32_t>(src_new_kv->get_shape()[src_kv_dim]);
+ const uint32_t tokens_to_write = std::min({num_new_tokens, new_valid, src_len});
+
+ // keep: number of old tokens that remain visible after appending the new chunk.
+ // If keep < old_valid, the window is saturated and we must shift surviving old
+ // tokens to the front before appending new ones.
+ const uint32_t keep = new_valid - tokens_to_write;
+ const bool needs_shift = (keep > 0 && keep < old_valid);
+
+ if (needs_shift && dst_kv_dim == 3u) {
+ // Transposed-V (dim=3) partial-slice shifts degrade into many small remote
+ // transfers. Use a full-buffer round-trip to keep transfer count low:
+ // 1) copy full dst -> CPU tmp,
+ // 2) rearrange entirely on CPU,
+ // 3) copy full CPU tmp -> dst.
+ // This avoids many fine-grained remote transactions in the shift phase.
+ LOG_DEBUG("[SWA] Bulk-shifting KV buffer (dim=3): keeping last " << keep << " of " << old_valid
+ << " old token(s), capacity=" << capacity);
+ auto whole_tmp =
+ ov::npuw::util::allocMem(dst_tensor->get_element_type(), dst_tensor->get_shape(), "CPU", nullptr);
+ dst_tensor->copy_to(whole_tmp._ptr); // single bulk contiguous transfer
+
+ auto old_tail_cpu = ov::npuw::util::make_tensor_slice(whole_tmp, dst_kv_dim, old_valid - keep, old_valid);
+ auto shift_tmp =
+ ov::npuw::util::allocMem(dst_tensor->get_element_type(), old_tail_cpu->get_shape(), "CPU", nullptr);
+ old_tail_cpu->copy_to(shift_tmp._ptr); // isolate surviving tail before front overwrite
+ auto dst_front_cpu = ov::npuw::util::make_tensor_slice(whole_tmp, dst_kv_dim, 0u, keep);
+ ov::npuw::util::copy_tensor_by_dim(shift_tmp, dst_front_cpu, dst_kv_dim, dst_kv_dim);
+
+ if (tokens_to_write > 0) {
+ auto src_slice =
+ (src_len > tokens_to_write)
+ ? ov::npuw::util::make_tensor_slice(src_new_kv, src_kv_dim, src_len - tokens_to_write, src_len)
+ : src_new_kv;
+ auto dst_back_cpu = ov::npuw::util::make_tensor_slice(whole_tmp, dst_kv_dim, keep, keep + tokens_to_write);
+ ov::npuw::util::copy_tensor_by_dim(src_slice, dst_back_cpu, src_kv_dim, dst_kv_dim);
+ }
+
+ whole_tmp->copy_to(dst_tensor._ptr); // single bulk contiguous transfer back
+ return;
+ }
+
+ if (needs_shift) {
+ // Window saturated: move the surviving old tail to the front.
+ // Use a temporary buffer to avoid overlapping in-place copy.
+ LOG_DEBUG("[SWA] Shifting KV buffer: keeping last "
+ << keep << " of " << old_valid << " old token(s), dim=" << dst_kv_dim << ", capacity=" << capacity);
+ auto old_tail = ov::npuw::util::make_tensor_slice(dst_tensor, dst_kv_dim, old_valid - keep, old_valid);
+ auto tmp = ov::npuw::util::allocMem(dst_tensor->get_element_type(), old_tail->get_shape(), "CPU", nullptr);
+ old_tail->copy_to(tmp._ptr);
+ auto dst_front = ov::npuw::util::make_tensor_slice(dst_tensor, dst_kv_dim, 0u, keep);
+ ov::npuw::util::copy_tensor_by_dim(tmp, dst_front, dst_kv_dim, dst_kv_dim);
+ }
+
+ if (tokens_to_write == 0) {
+ return;
+ }
+ // Append newest source tail right after the preserved prefix.
+ auto src_slice = (src_len > tokens_to_write)
+ ? ov::npuw::util::make_tensor_slice(src_new_kv, src_kv_dim, src_len - tokens_to_write, src_len)
+ : src_new_kv;
+ auto dst_back = ov::npuw::util::make_tensor_slice(dst_tensor, dst_kv_dim, keep, keep + tokens_to_write);
+ ov::npuw::util::copy_tensor_by_dim(src_slice, dst_back, src_kv_dim, dst_kv_dim);
+}
+
+void ov::npuw::util::write_swa_kv_slice_circular(ov::SoPtr<ov::ITensor> dst_tensor,
+ ov::SoPtr<ov::ITensor> src_new_kv,
+ uint32_t dst_kv_dim,
+ uint32_t src_kv_dim,
+ uint32_t num_stored_tokens,
+ uint32_t num_new_tokens) {
+ // Used in the generate stage to append newly produced token(s) (usually num_new_tokens
+ // == 1) into a fixed-capacity ring buffer: token at absolute position p always lives at
+ // slot (p % capacity), and once full, appending overwrites the oldest slot in place --
+ // nothing shifts.
+ //
+ // Example A - single leg (capacity=6, num_stored_tokens=8, num_new_tokens=2):
+ // dst_start = 8 % 6 = 2, and 2+2 <= 6 -> one contiguous write.
+ //
+ // slot: 0 1 2 3 4 5
+ // before: a6 a7 a2 a3 a4 a5
+ // after: a6 a7 [a8] [a9] a4 a5
+ //
+ // Example B - wraps (capacity=6, num_stored_tokens=10, num_new_tokens=3):
+ // dst_start = 10 % 6 = 4, and 4+3 > 6 -> splits into [4,6) then [0,1).
+ //
+ // slot: 0 1 2 3 4 5
+ // before: a6 a7 a8 a9 a4 a5
+ // after: [a12] a7 a8 a9 [a10] [a11]
+ const uint32_t capacity = static_cast<uint32_t>(dst_tensor->get_shape()[dst_kv_dim]);
+ const uint32_t old_total = num_stored_tokens;
+ const uint32_t new_total = old_total + num_new_tokens;
+ const uint32_t new_valid = std::min(new_total, capacity);
+
+ // Clamp by source length as well: source may already be capacity-limited.
+ const uint32_t src_len = static_cast<uint32_t>(src_new_kv->get_shape()[src_kv_dim]);
+ const uint32_t tokens_to_write = std::min({num_new_tokens, new_valid, src_len});
+
+ if (tokens_to_write == 0) {
+ return;
+ }
+ const uint32_t first_new_abs_pos = num_stored_tokens + (num_new_tokens - tokens_to_write);
+ const uint32_t dst_start = first_new_abs_pos % capacity;
+
+ auto src_slice = (src_len > tokens_to_write)
+ ? ov::npuw::util::make_tensor_slice(src_new_kv, src_kv_dim, src_len - tokens_to_write, src_len)
+ : src_new_kv;
+
+ if (dst_start + tokens_to_write <= capacity) {
+ auto dst_slice =
+ ov::npuw::util::make_tensor_slice(dst_tensor, dst_kv_dim, dst_start, dst_start + tokens_to_write);
+ ov::npuw::util::copy_tensor_by_dim(src_slice, dst_slice, src_kv_dim, dst_kv_dim);
+ } else {
+ const uint32_t first_leg_len = capacity - dst_start;
+ const uint32_t second_leg_len = tokens_to_write - first_leg_len;
+
+ auto src_first_leg = ov::npuw::util::make_tensor_slice(src_slice, src_kv_dim, 0u, first_leg_len);
+ auto dst_first_leg = ov::npuw::util::make_tensor_slice(dst_tensor, dst_kv_dim, dst_start, capacity);
+ ov::npuw::util::copy_tensor_by_dim(src_first_leg, dst_first_leg, src_kv_dim, dst_kv_dim);
+
+ auto src_second_leg = ov::npuw::util::make_tensor_slice(src_slice, src_kv_dim, first_leg_len, tokens_to_write);
+ auto dst_second_leg = ov::npuw::util::make_tensor_slice(dst_tensor, dst_kv_dim, 0u, second_leg_len);
+ ov::npuw::util::copy_tensor_by_dim(src_second_leg, dst_second_leg, src_kv_dim, dst_kv_dim);
+ }
+}
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.hpp
index 4b06e7457fa..aa905a9b45e 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
@@ -4,6 +4,19 @@
#pragma once
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <unordered_map>
+
+#include "openvino/core/node_output.hpp"
+#include "openvino/runtime/so_ptr.hpp"
+
+namespace ov {
+class IAsyncInferRequest;
+class ITensor;
+} // namespace ov
+
namespace ov {
namespace npuw {
namespace util {
@@ -12,6 +25,44 @@ namespace util {
// 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.
+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);
+
+// Overlays bidirectional visibility for same image vision tokens.
+// token_type_ids is per-call right-aligned token metadata (0 = text, 1 = vision)
+void overlay_vision_bidirectional_mask(ov::SoPtr<ov::ITensor> mask_tensor,
+ const int64_t* token_type_ids,
+ uint32_t num_new_tokens);
+
+// Fills sliding_window_attention_mask input when present.
+// No-op for non-SWA models that do not expose this input.
+void fill_sliding_window_attention_mask(const std::shared_ptr<ov::IAsyncInferRequest>& request,
+ 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);
+
+// Writes SWA KV deltas into a left-aligned past buffer, shifting the
+// surviving tail to the front first when the window is saturated.
+void write_swa_kv_slice_left_aligned(ov::SoPtr<ov::ITensor> dst_tensor,
+ ov::SoPtr<ov::ITensor> src_new_kv,
+ uint32_t dst_kv_dim,
+ uint32_t src_kv_dim,
+ uint32_t num_stored_tokens,
+ uint32_t num_new_tokens);
+
+// Writes SWA KV deltas into a circular past buffer
+void write_swa_kv_slice_circular(ov::SoPtr<ov::ITensor> dst_tensor,
+ ov::SoPtr<ov::ITensor> src_new_kv,
+ uint32_t dst_kv_dim,
+ uint32_t src_kv_dim,
+ uint32_t num_stored_tokens,
+ uint32_t num_new_tokens);
+
} // namespace util
} // namespace npuw
} // namespace ov
diff --git a/src/plugins/intel_npu/src/plugin/sources.cmake b/src/plugins/intel_npu/src/plugin/sources.cmake
index 492f5374867..d9f79bb3637 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.cpp
${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
diff --git a/src/plugins/intel_npu/tests/unit/CMakeLists.txt b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
index 18189c24d00..344fa256975 100644
--- a/src/plugins/intel_npu/tests/unit/CMakeLists.txt
+++ b/src/plugins/intel_npu/tests/unit/CMakeLists.txt
@@ -83,6 +83,7 @@ ov_add_test_target(
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/insert_vocab_sub128.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/npuw_transformations/duplicate_shared_kv_concat.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/kv_cache_block_manager.cpp
+ ${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/kv_cache_sliding_window_manager.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/attention.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/pyramid_attention.cpp
${OpenVINO_SOURCE_DIR}/src/plugins/intel_npu/src/plugin/npuw/host_flash_attention.cpp
@@ -171,6 +172,8 @@ target_sources(${TARGET_NAME} PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_infer_request_variant_switch_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_infer_request_port_names_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/llm_trim_kvcache_test.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/sliding_window_manager_update_kv_cache_test.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/npuw/sliding_window_manager_generate_mask_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/lincache_utils_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/model_builder_lora_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/npuw/partitioning_options_test.cpp
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.cpp
new file mode 100644
index 00000000000..eba67974868
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/sliding_window_manager_generate_mask_test.cpp
@@ -0,0 +1,403 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+
+#include <cstdint>
+#include <limits>
+#include <unordered_map>
+#include <vector>
+
+#include "kv_cache_sliding_window_manager.hpp"
+#include "llm_compiled_model_utils.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/openvino.hpp"
+#include "openvino/runtime/iasync_infer_request.hpp"
+#include "openvino/runtime/make_tensor.hpp"
+
+namespace ov::test::npuw {
+
+namespace {
+
+namespace uu = ov::npuw::util;
+
+ov::SoPtr<ov::ITensor> make_mask_tensor(uint32_t rows,
+ uint32_t cols,
+ float init_value,
+ const ov::element::Type& element_type = ov::element::f32) {
+ auto mask = ov::get_tensor_impl(ov::Tensor(element_type, ov::Shape{1u, rows, cols}));
+ if (element_type == ov::element::f16) {
+ std::fill(mask->data<ov::float16>(), mask->data<ov::float16>() + mask->get_size(), ov::float16(init_value));
+ } else {
+ std::fill(mask->data<float>(), mask->data<float>() + mask->get_size(), init_value);
+ }
+ return mask;
+}
+
+float mask_at(const ov::SoPtr<ov::ITensor>& mask, uint32_t row, uint32_t col) {
+ const auto& shape = mask->get_shape();
+ const auto rows = static_cast<uint32_t>(shape[shape.size() - 2]);
+ const auto cols = static_cast<uint32_t>(shape[shape.size() - 1]);
+ OPENVINO_ASSERT(row < rows && col < cols, "mask_at index out of range");
+ const size_t index = static_cast<size_t>(row) * cols + col;
+ if (mask->get_element_type() == ov::element::f16) {
+ return static_cast<float>(mask->data<ov::float16>()[index]);
+ }
+ return mask->data<float>()[index];
+}
+
+// Builds a standalone Parameter port. The returned Output keeps the Parameter node alive
+// (Output owns a shared_ptr to its node), so no separate storage is needed by callers.
+ov::Output<const ov::Node> make_param_port(const ov::element::Type& type, const ov::Shape& shape) {
+ return std::make_shared<ov::op::v0::Parameter>(type, shape)->output(0);
+}
+
+// Minimal fake IAsyncInferRequest for testing fill_sliding_window_attention_mask, which only
+// calls request->get_tensor(port). Tensors are bound to ports ahead of time via bind().
+class FakeAsyncInferRequest final : public ov::IAsyncInferRequest {
+public:
+ FakeAsyncInferRequest() : ov::IAsyncInferRequest(nullptr, nullptr, nullptr) {}
+
+ void bind(const ov::Output<const ov::Node>& port, ov::SoPtr<ov::ITensor> tensor) {
+ m_tensors[port.get_node()] = std::move(tensor);
+ }
+
+ ov::SoPtr<ov::ITensor> get_tensor(const ov::Output<const ov::Node>& port) const override {
+ const auto it = m_tensors.find(port.get_node());
+ OPENVINO_ASSERT(it != m_tensors.end(), "FakeAsyncInferRequest: no tensor bound for the requested port");
+ return it->second;
+ }
+
+ void set_tensor(const ov::Output<const ov::Node>& port, const ov::SoPtr<ov::ITensor>& tensor) override {
+ m_tensors[port.get_node()] = tensor;
+ }
+
+private:
+ std::unordered_map<const ov::Node*, ov::SoPtr<ov::ITensor>> m_tensors;
+};
+
+} // namespace
+
+class FillCausalSlidingWindowMaskTest : public ::testing::Test {};
+
+TEST_F(FillCausalSlidingWindowMaskTest, UnsaturatedPastBuildsExpectedMask) {
+ auto mask = make_mask_tensor(/*rows=*/4u, /*cols=*/8u, /*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=*/2u,
+ /*num_new_tokens=*/2u,
+ /*window_size=*/3u);
+
+ // 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);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 1u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 2u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 3u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 6u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 7u), kMasked);
+
+ // row=3: abs=0 is out-of-window, abs=1 is still visible.
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 0u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 1u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 6u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 7u), 0.f);
+}
+
+TEST_F(FillCausalSlidingWindowMaskTest, SaturatedPastUsesCircularSlotMapping) {
+ 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_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);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 1u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 2u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 3u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 4u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 5u), kMasked);
+
+ // row=1(q=7): abs 5 visible, abs 4 masked.
+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 0u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 1u), 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);
+ const float kMasked = static_cast<float>(std::numeric_limits<ov::float16>::lowest());
+
+ uu::fill_causal_sliding_window_mask(mask,
+ /*num_stored_tokens=*/0u,
+ /*num_new_tokens=*/4u,
+ /*window_size=*/2u);
+
+ // Expected visible local columns per row for window=2:
+ // row0 -> [0]
+ // row1 -> [0,1]
+ // row2 -> [1,2]
+ // row3 -> [2,3]
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 0u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 1u), kMasked);
+
+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 0u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 1u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 2u), kMasked);
+
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 0u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 1u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 2u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 3u), kMasked);
+
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 1u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 2u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 3u), 0.f);
+}
+
+TEST_F(FillCausalSlidingWindowMaskTest, UnsaturatedPastBuildsExpectedMaskF16) {
+ // Same scenario as UnsaturatedPastBuildsExpectedMask, but on an f16 mask tensor to cover
+ // the fill_causal_sliding_window_mask_typed<ov::float16> instantiation.
+ auto mask = make_mask_tensor(/*rows=*/4u, /*cols=*/8u, /*init_value=*/777.f, ov::element::f16);
+ const float kMasked = static_cast<float>(std::numeric_limits<ov::float16>::lowest());
+
+ uu::fill_causal_sliding_window_mask(mask,
+ /*num_stored_tokens=*/2u,
+ /*num_new_tokens=*/2u,
+ /*window_size=*/3u);
+
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 0u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 1u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 2u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 6u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 7u), kMasked);
+
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 0u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 1u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 6u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 7u), 0.f);
+}
+
+TEST_F(FillCausalSlidingWindowMaskTest, RowPadRowsDoNotAffectRealRowVisibility) {
+ // num_new_tokens(2) < row_dim(4) => row_pad=2: the first 2 rows are padding and the real
+ // chunk occupies rows [2,4). past_width=4, stored_tokens=3 (unsaturated).
+ auto mask = make_mask_tensor(/*rows=*/4u, /*cols=*/8u, /*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=*/3u,
+ /*num_new_tokens=*/2u,
+ /*window_size=*/3u);
+
+ // 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);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 1u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 2u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 3u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 6u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 4u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 5u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 7u), kMasked);
+
+ // row=3 is the real row 1: abs=4, visible past slot [2], present local_c in [2,3] (cols 6,7).
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 2u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 0u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 1u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 6u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 7u), 0.f);
+}
+
+TEST_F(FillCausalSlidingWindowMaskTest, SaturatedPastWithExactWrapUsesSingleSegment) {
+ // stored_tokens(8) is an exact multiple of past_width(4) => wrap_slot=0, so the saturated
+ // ring resolves to a single contiguous segment (segment2 stays empty).
+ 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=*/8u,
+ /*num_new_tokens=*/2u,
+ /*window_size=*/3u);
+
+ // 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);
+ 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=9): visible past slot [3] -> col 3; present local_c in [0,1] -> cols 4,5.
+ 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);
+}
+
+class OverlayVisionBidirectionalMaskTest : public ::testing::Test {};
+
+TEST_F(OverlayVisionBidirectionalMaskTest, SingleVisionRunUnmasksRunBlock) {
+ auto mask = make_mask_tensor(/*rows=*/4u, /*cols=*/8u, /*init_value=*/-7.f);
+ const std::vector<int64_t> token_types = {0, 1, 1, 0};
+
+ uu::overlay_vision_bidirectional_mask(mask, token_types.data(), static_cast<uint32_t>(token_types.size()));
+
+ // run [1,3): rows 1..2 and cols 5..6 are unmasked.
+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 5u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 6u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 5u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 6u), 0.f);
+
+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 4u), -7.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 5u), -7.f);
+}
+
+TEST_F(OverlayVisionBidirectionalMaskTest, DisjointVisionRunsAreHandledSeparately) {
+ auto mask = make_mask_tensor(/*rows=*/4u, /*cols=*/8u, /*init_value=*/-9.f);
+ const std::vector<int64_t> token_types = {1, 1, 0, 1};
+
+ uu::overlay_vision_bidirectional_mask(mask, token_types.data(), static_cast<uint32_t>(token_types.size()));
+
+ // run [0,2): rows 0..1 and cols 4..5.
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 4u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 5u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 4u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 5u), 0.f);
+
+ // run [3,4): row 3 and col 7.
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 7u), 0.f);
+
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 7u), -9.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 3u, 6u), -9.f);
+}
+
+TEST_F(OverlayVisionBidirectionalMaskTest, ZeroNewTokensIsNoOp) {
+ auto mask = make_mask_tensor(/*rows=*/4u, /*cols=*/8u, /*init_value=*/-3.f);
+ const std::vector<int64_t> token_types = {1, 1, 0};
+
+ uu::overlay_vision_bidirectional_mask(mask, token_types.data(), /*num_new_tokens=*/0u);
+
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 0u), -3.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 1u, 4u), -3.f);
+}
+
+TEST_F(OverlayVisionBidirectionalMaskTest, NullTokenTypeIdsThrows) {
+ auto mask = make_mask_tensor(/*rows=*/4u, /*cols=*/8u, /*init_value=*/-3.f);
+
+ EXPECT_THROW(uu::overlay_vision_bidirectional_mask(mask, nullptr, /*num_new_tokens=*/2u), ov::Exception);
+}
+
+class FillSlidingWindowAttentionMaskTest : public ::testing::Test {};
+
+TEST_F(FillSlidingWindowAttentionMaskTest, MaskPortMissingIsNoOp) {
+ // Non-SWA models don't expose the sliding_window_attention_mask input: the function must
+ // return without touching the (empty) request at all.
+ auto fake_request = std::make_shared<FakeAsyncInferRequest>();
+ std::unordered_map<std::string, ov::Output<const ov::Node>> in_ports;
+
+ EXPECT_NO_THROW(uu::fill_sliding_window_attention_mask(fake_request,
+ in_ports,
+ /*num_stored_tokens=*/3u,
+ /*num_new_tokens=*/3u,
+ /*window_size=*/4u));
+}
+
+TEST_F(FillSlidingWindowAttentionMaskTest, TokenTypeIdsPortMissingSkipsOverlay) {
+ // Same numbers as the causal half of the combined-mask example documented on
+ // fill_sliding_window_attention_mask, but without a token_type_ids port: only the causal
+ // mask must be filled, no vision overlay applied.
+ auto mask = make_mask_tensor(/*rows=*/3u, /*cols=*/7u, /*init_value=*/777.f);
+ const float kMasked = static_cast<float>(std::numeric_limits<ov::float16>::lowest());
+
+ auto fake_request = std::make_shared<FakeAsyncInferRequest>();
+ auto mask_port = make_param_port(ov::element::f32, ov::Shape{1u, 3u, 7u});
+ fake_request->bind(mask_port, mask);
+
+ std::unordered_map<std::string, ov::Output<const ov::Node>> in_ports;
+ in_ports[uu::kSlidingWindowAttentionMaskParamName] = mask_port;
+
+ uu::fill_sliding_window_attention_mask(fake_request,
+ in_ports,
+ /*num_stored_tokens=*/3u,
+ /*num_new_tokens=*/3u,
+ /*window_size=*/4u);
+
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 0u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 4u), 0.f);
+ // Would be unmasked by the vision overlay if a token_type_ids port had been provided.
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 5u), kMasked);
+}
+
+TEST_F(FillSlidingWindowAttentionMaskTest, CombinesCausalMaskAndVisionOverlay) {
+ // Reproduces the worked example from fill_sliding_window_attention_mask's doc comment:
+ // past_width=4, row_dim=3, stored_tokens=3, window_size=4, token_type_ids=[V,V,T].
+ auto mask = make_mask_tensor(/*rows=*/3u, /*cols=*/7u, /*init_value=*/777.f);
+ const float kMasked = static_cast<float>(std::numeric_limits<ov::float16>::lowest());
+
+ auto fake_request = std::make_shared<FakeAsyncInferRequest>();
+ auto mask_port = make_param_port(ov::element::f32, ov::Shape{1u, 3u, 7u});
+ fake_request->bind(mask_port, mask);
+
+ const std::vector<int64_t> token_types = {1, 1, 0}; // V, V, T
+ auto token_type_ids = ov::get_tensor_impl(ov::Tensor(ov::element::i64, ov::Shape{token_types.size()}));
+ std::copy(token_types.begin(), token_types.end(), token_type_ids->data<int64_t>());
+ auto token_type_ids_port = make_param_port(ov::element::i64, ov::Shape{token_types.size()});
+ fake_request->bind(token_type_ids_port, token_type_ids);
+
+ std::unordered_map<std::string, ov::Output<const ov::Node>> in_ports;
+ in_ports[uu::kSlidingWindowAttentionMaskParamName] = mask_port;
+ in_ports[uu::kTokenTypeIdsParamName] = token_type_ids_port;
+
+ uu::fill_sliding_window_attention_mask(fake_request,
+ in_ports,
+ /*num_stored_tokens=*/3u,
+ /*num_new_tokens=*/3u,
+ /*window_size=*/4u);
+
+ // 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);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 1u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 2u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 3u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 4u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 5u), 0.f);
+ EXPECT_FLOAT_EQ(mask_at(mask, 0u, 6u), kMasked);
+
+ // row 2: outside the [0,2) vision run, unaffected by the overlay.
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 0u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 1u), kMasked);
+ EXPECT_FLOAT_EQ(mask_at(mask, 2u, 6u), 0.f);
+}
+
+TEST_F(FillSlidingWindowAttentionMaskTest, TokenTypeIdsSizeMismatchThrows) {
+ auto mask = make_mask_tensor(/*rows=*/3u, /*cols=*/7u, /*init_value=*/777.f);
+
+ auto fake_request = std::make_shared<FakeAsyncInferRequest>();
+ auto mask_port = make_param_port(ov::element::f32, ov::Shape{1u, 3u, 7u});
+ fake_request->bind(mask_port, mask);
+
+ // token_type_ids tensor (size 2) is smaller than num_new_tokens (3).
+ auto token_type_ids = ov::get_tensor_impl(ov::Tensor(ov::element::i64, ov::Shape{2u}));
+ auto token_type_ids_port = make_param_port(ov::element::i64, ov::Shape{2u});
+ fake_request->bind(token_type_ids_port, token_type_ids);
+
+ std::unordered_map<std::string, ov::Output<const ov::Node>> in_ports;
+ in_ports[uu::kSlidingWindowAttentionMaskParamName] = mask_port;
+ in_ports[uu::kTokenTypeIdsParamName] = token_type_ids_port;
+
+ EXPECT_THROW(uu::fill_sliding_window_attention_mask(fake_request,
+ in_ports,
+ /*num_stored_tokens=*/3u,
+ /*num_new_tokens=*/3u,
+ /*window_size=*/4u),
+ ov::Exception);
+}
+
+} // namespace ov::test::npuw
diff --git a/src/plugins/intel_npu/tests/unit/npuw/sliding_window_manager_update_kv_cache_test.cpp b/src/plugins/intel_npu/tests/unit/npuw/sliding_window_manager_update_kv_cache_test.cpp
new file mode 100644
index 00000000000..826422e7514
--- /dev/null
+++ b/src/plugins/intel_npu/tests/unit/npuw/sliding_window_manager_update_kv_cache_test.cpp
@@ -0,0 +1,489 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+
+#include <cstdint>
+#include <vector>
+
+#include "infer_request_utils.hpp"
+#include "kv_cache_sliding_window_manager.hpp"
+#include "openvino/openvino.hpp"
+#include "openvino/runtime/make_tensor.hpp"
+
+namespace ov::test::npuw {
+
+namespace {
+
+namespace uu = ov::npuw::util;
+
+ov::SoPtr<ov::ITensor> make_cpu_tensor(const ov::Shape& shape) {
+ return ov::get_tensor_impl(ov::Tensor(ov::element::f32, shape));
+}
+
+// [1, heads, seq_len, emb] for kv_dim == 2, [1, heads, emb, seq_len] for kv_dim == 3.
+ov::Shape kv_shape(uint32_t kv_dim, uint32_t seq_len, uint32_t heads = 2u, uint32_t emb = 3u) {
+ return (kv_dim == 3u) ? ov::Shape{1u, heads, emb, seq_len} : ov::Shape{1u, heads, seq_len, emb};
+}
+
+// Walk all logical f32 elements of a tensor (including non-contiguous views).
+template <typename Fn>
+void for_each_element(const ov::SoPtr<ov::ITensor>& tensor, Fn&& fn) {
+ const auto& shape = tensor->get_shape();
+ const auto& strides = tensor->get_strides(); // byte strides
+ auto* base = static_cast<uint8_t*>(tensor->data());
+ std::vector<size_t> idx(shape.size(), 0u);
+ const size_t total = tensor->get_size();
+ for (size_t linear = 0; linear < total; ++linear) {
+ size_t byte_offset = 0u;
+ for (size_t d = 0; d < shape.size(); ++d) {
+ byte_offset += idx[d] * strides[d];
+ }
+ fn(*reinterpret_cast<float*>(base + byte_offset));
+ for (int d = static_cast<int>(shape.size()) - 1; d >= 0; --d) {
+ if (++idx[d] < shape[d]) {
+ break;
+ }
+ idx[d] = 0u;
+ }
+ }
+}
+
+// Fill one token column at `pos` along `kv_dim` with `value`.
+void write_token_value(const ov::SoPtr<ov::ITensor>& tensor, uint32_t kv_dim, uint32_t pos, float value) {
+ auto slice = uu::make_tensor_slice(tensor, kv_dim, pos, pos + 1);
+ for_each_element(slice, [&](float& v) {
+ v = value;
+ });
+}
+
+// Assert one token column at `pos` along `kv_dim` equals `value`.
+void expect_token_value(const ov::SoPtr<ov::ITensor>& tensor, uint32_t kv_dim, uint32_t pos, float value) {
+ auto slice = uu::make_tensor_slice(tensor, kv_dim, pos, pos + 1);
+ for_each_element(slice, [&](float& v) {
+ EXPECT_FLOAT_EQ(v, value) << "kv_dim=" << kv_dim << " pos=" << pos;
+ });
+}
+
+// Build contiguous source tokens with values [first_value, first_value+count).
+ov::SoPtr<ov::ITensor> make_src_tokens(uint32_t kv_dim, uint32_t count, float first_value) {
+ auto src = make_cpu_tensor(kv_shape(kv_dim, count));
+ for (uint32_t i = 0; i < count; ++i) {
+ write_token_value(src, kv_dim, i, first_value + static_cast<float>(i));
+ }
+ return src;
+}
+
+void expect_cross_layout_write(uint32_t src_kv_dim, uint32_t dst_kv_dim, bool circular_write) {
+ const uint32_t capacity = 6u;
+ auto dst = make_cpu_tensor(kv_shape(dst_kv_dim, capacity));
+ auto src = make_src_tokens(src_kv_dim, 3u, /*first_value=*/10.f);
+
+ if (circular_write) {
+ uu::write_swa_kv_slice_circular(dst,
+ src,
+ dst_kv_dim,
+ src_kv_dim,
+ /*num_stored_tokens=*/0u,
+ /*num_new_tokens=*/3u);
+ } else {
+ uu::write_swa_kv_slice_left_aligned(dst,
+ src,
+ dst_kv_dim,
+ src_kv_dim,
+ /*num_stored_tokens=*/0u,
+ /*num_new_tokens=*/3u);
+ }
+
+ for (uint32_t i = 0; i < 3u; ++i) {
+ expect_token_value(dst, dst_kv_dim, i, 10.f + static_cast<float>(i));
+ }
+}
+
+// Cross-layout write into an already-saturated (6/6) left-aligned buffer: forces the shift
+// path (needs_shift=true) while src_kv_dim != dst_kv_dim, covering both the generic partial-
+// slice shift and the dst_kv_dim==3 bulk round-trip shift together with layout conversion.
+void expect_cross_layout_shift_write(uint32_t src_kv_dim, uint32_t dst_kv_dim) {
+ const uint32_t capacity = 6u;
+ auto dst = make_cpu_tensor(kv_shape(dst_kv_dim, capacity));
+ for (uint32_t i = 0; i < capacity; ++i) {
+ write_token_value(dst, dst_kv_dim, i, 100.f + static_cast<float>(i)); // o1..o6
+ }
+ auto src = make_src_tokens(src_kv_dim, 3u, /*first_value=*/200.f); // n1..n3
+
+ uu::write_swa_kv_slice_left_aligned(dst,
+ src,
+ dst_kv_dim,
+ src_kv_dim,
+ /*num_stored_tokens=*/6u,
+ /*num_new_tokens=*/3u);
+
+ // Surviving tail (o4,o5,o6) shifts to front, then n1,n2,n3 are appended.
+ const std::vector<float> expected = {103.f, 104.f, 105.f, 200.f, 201.f, 202.f};
+ for (uint32_t i = 0; i < capacity; ++i) {
+ expect_token_value(dst, dst_kv_dim, i, expected[i]);
+ }
+}
+
+} // namespace
+
+class WriteKvSliceSlidingWindowTest : public ::testing::TestWithParam<uint32_t> {};
+
+// kv_dim is parameterized: 2 ([1,H,S,E]) and 3 ([1,H,E,S]).
+INSTANTIATE_TEST_SUITE_P(KvDims, WriteKvSliceSlidingWindowTest, ::testing::Values(2u, 3u));
+
+TEST_P(WriteKvSliceSlidingWindowTest, CircularWarmupMatchesLeftAligned) {
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 8u;
+
+ auto dst_left = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ auto dst_circ = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ auto src = make_src_tokens(kv_dim, 5u, /*first_value=*/100.f);
+
+ uu::write_swa_kv_slice_left_aligned(dst_left,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/0u,
+ /*num_new_tokens=*/5u);
+ uu::write_swa_kv_slice_circular(dst_circ,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/0u,
+ /*num_new_tokens=*/5u);
+
+ for (uint32_t i = 0; i < 5u; ++i) {
+ expect_token_value(dst_left, kv_dim, i, 100.f + static_cast<float>(i));
+ expect_token_value(dst_circ, kv_dim, i, 100.f + static_cast<float>(i));
+ }
+}
+
+TEST_P(WriteKvSliceSlidingWindowTest, CircularWrapsToStartWithoutSplit) {
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 8u;
+
+ auto dst = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ // Seed slots [0..7] with distinct values.
+ for (uint32_t i = 0; i < capacity; ++i) {
+ write_token_value(dst, kv_dim, i, 1000.f + static_cast<float>(i));
+ }
+
+ // New token at absolute position 8 overwrites slot 0.
+ auto src = make_src_tokens(kv_dim, 1u, /*first_value=*/2000.f);
+ uu::write_swa_kv_slice_circular(dst,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/capacity,
+ /*num_new_tokens=*/1u);
+
+ expect_token_value(dst, kv_dim, 0u, 2000.f);
+ for (uint32_t i = 1; i < capacity; ++i) {
+ expect_token_value(dst, kv_dim, i, 1000.f + static_cast<float>(i));
+ }
+}
+
+TEST_P(WriteKvSliceSlidingWindowTest, CircularWriteSplitsAcrossWrapBoundary) {
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 8u;
+
+ auto dst = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ // Seed a pre-wrapped layout with 13 prior writes.
+ const std::vector<float> initial = {2000.f, 2001.f, 2002.f, 2003.f, 2004.f, 1005.f, 1006.f, 1007.f};
+ for (uint32_t i = 0; i < capacity; ++i) {
+ write_token_value(dst, kv_dim, i, initial[i]);
+ }
+
+ // 6-token write wraps at slot 5 and splits into tail+head legs.
+ auto src = make_src_tokens(kv_dim, 6u, /*first_value=*/3013.f);
+ uu::write_swa_kv_slice_circular(dst,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/13u,
+ /*num_new_tokens=*/6u);
+
+ const std::vector<float> expected = {3016.f, 3017.f, 3018.f, 2003.f, 2004.f, 3013.f, 3014.f, 3015.f};
+ for (uint32_t i = 0; i < capacity; ++i) {
+ expect_token_value(dst, kv_dim, i, expected[i]);
+ }
+}
+
+TEST_P(WriteKvSliceSlidingWindowTest, CircularChunkLargerThanCapacityKeepsOnlyNewestTail) {
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 4u;
+
+ auto dst = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ // Writing 10 tokens into capacity 4 keeps only newest tail [6,7,8,9].
+ auto src = make_src_tokens(kv_dim, 10u, /*first_value=*/0.f);
+ uu::write_swa_kv_slice_circular(dst,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/0u,
+ /*num_new_tokens=*/10u);
+
+ const std::vector<float> expected = {8.f, 9.f, 6.f, 7.f};
+ for (uint32_t i = 0; i < capacity; ++i) {
+ expect_token_value(dst, kv_dim, i, expected[i]);
+ }
+}
+
+TEST_P(WriteKvSliceSlidingWindowTest, CircularAndLeftAlignedHoldSameLogicalContentOverManySteps) {
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 5u;
+
+ auto dst_left = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ auto dst_circ = make_cpu_tensor(kv_shape(kv_dim, capacity));
+
+ uint32_t stored = 0u;
+ for (uint32_t step = 0; step < 20u; ++step) {
+ // One new token per step; value equals absolute position.
+ auto src = make_src_tokens(kv_dim, 1u, /*first_value=*/static_cast<float>(stored));
+ uu::write_swa_kv_slice_left_aligned(dst_left, src, kv_dim, kv_dim, stored, 1u);
+ uu::write_swa_kv_slice_circular(dst_circ, src, kv_dim, kv_dim, stored, 1u);
+ stored += 1u;
+
+ const uint32_t valid = std::min(stored, capacity);
+ const uint32_t window_start = stored - valid; // oldest absolute position still in window
+ for (uint32_t rank = 0; rank < valid; ++rank) {
+ const uint32_t abs_pos = window_start + rank;
+ // LeftAligned keeps oldest-surviving tokens packed from index 0.
+ expect_token_value(dst_left, kv_dim, rank, static_cast<float>(abs_pos));
+ // Circular keeps token at physical slot abs_pos % capacity.
+ expect_token_value(dst_circ, kv_dim, abs_pos % capacity, static_cast<float>(abs_pos));
+ }
+ }
+}
+
+TEST_P(WriteKvSliceSlidingWindowTest, LeftAlignedChunkEqualsCapacityFillsWholeWindow) {
+ // Case A: chunk == capacity, old_total == 0 -> single full-buffer overwrite.
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 6u;
+
+ auto dst = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ for (uint32_t i = 0; i < capacity; ++i) {
+ write_token_value(dst, kv_dim, i, -1.f); // sentinel: must be fully overwritten
+ }
+ auto src = make_src_tokens(kv_dim, 6u, /*first_value=*/1.f);
+
+ uu::write_swa_kv_slice_left_aligned(dst,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/0u,
+ /*num_new_tokens=*/6u);
+
+ for (uint32_t i = 0; i < capacity; ++i) {
+ expect_token_value(dst, kv_dim, i, 1.f + static_cast<float>(i));
+ }
+}
+
+TEST_P(WriteKvSliceSlidingWindowTest, LeftAlignedChunkLargerThanCapacityKeepsOnlyNewestTail) {
+ // Case C: chunk (8) > capacity (6), old_total == 0 -> only the newest `capacity` tokens
+ // of the input chunk are written; the chunk's own oldest tokens (n1,n2) are dropped.
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 6u;
+
+ auto dst = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ for (uint32_t i = 0; i < capacity; ++i) {
+ write_token_value(dst, kv_dim, i, -1.f);
+ }
+ auto src = make_src_tokens(kv_dim, 8u, /*first_value=*/1.f); // n1..n8
+
+ uu::write_swa_kv_slice_left_aligned(dst,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/0u,
+ /*num_new_tokens=*/8u);
+
+ for (uint32_t i = 0; i < capacity; ++i) {
+ expect_token_value(dst, kv_dim, i, 3.f + static_cast<float>(i)); // n3..n8
+ }
+}
+
+TEST_P(WriteKvSliceSlidingWindowTest, LeftAlignedSaturatedShiftsOldTailThenAppends) {
+ // Case B2: buffer already full (6/6); appending 3 new tokens shifts the surviving old
+ // tail (o4,o5,o6) to the front before appending. Matches the doc-comment example.
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 6u;
+
+ auto dst = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ for (uint32_t i = 0; i < capacity; ++i) {
+ write_token_value(dst, kv_dim, i, 1.f + static_cast<float>(i)); // o1..o6
+ }
+ auto src = make_src_tokens(kv_dim, 3u, /*first_value=*/11.f); // n1..n3
+
+ uu::write_swa_kv_slice_left_aligned(dst,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/6u,
+ /*num_new_tokens=*/3u);
+
+ const std::vector<float> expected = {4.f, 5.f, 6.f, 11.f, 12.f, 13.f};
+ for (uint32_t i = 0; i < capacity; ++i) {
+ expect_token_value(dst, kv_dim, i, expected[i]);
+ }
+}
+
+TEST_P(WriteKvSliceSlidingWindowTest, LeftAlignedClampsToShortSourceTensor) {
+ // num_new_tokens=5 but the source tensor itself only holds 3 tokens (it was
+ // capacity-limited upstream). keep=new_valid(5)-tokens_to_write(3)=2 slots are reserved
+ // by the arithmetic but never populated (old_valid=0, nothing to shift into them).
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 8u;
+
+ auto dst = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ for (uint32_t i = 0; i < capacity; ++i) {
+ write_token_value(dst, kv_dim, i, -1.f); // sentinel: untouched slots stay -1
+ }
+ auto src = make_src_tokens(kv_dim, /*count=*/3u, /*first_value=*/50.f);
+
+ uu::write_swa_kv_slice_left_aligned(dst,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/0u,
+ /*num_new_tokens=*/5u);
+
+ expect_token_value(dst, kv_dim, 0u, -1.f);
+ expect_token_value(dst, kv_dim, 1u, -1.f);
+ expect_token_value(dst, kv_dim, 2u, 50.f);
+ expect_token_value(dst, kv_dim, 3u, 51.f);
+ expect_token_value(dst, kv_dim, 4u, 52.f);
+ expect_token_value(dst, kv_dim, 5u, -1.f);
+ expect_token_value(dst, kv_dim, 6u, -1.f);
+ expect_token_value(dst, kv_dim, 7u, -1.f);
+}
+
+TEST_P(WriteKvSliceSlidingWindowTest, LeftAlignedZeroNewTokensIsNoOp) {
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 6u;
+
+ auto dst = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ for (uint32_t i = 0; i < capacity; ++i) {
+ write_token_value(dst, kv_dim, i, 9.f + static_cast<float>(i));
+ }
+ auto src = make_src_tokens(kv_dim, 1u, /*first_value=*/0.f); // never read
+
+ uu::write_swa_kv_slice_left_aligned(dst,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/3u,
+ /*num_new_tokens=*/0u);
+
+ for (uint32_t i = 0; i < capacity; ++i) {
+ expect_token_value(dst, kv_dim, i, 9.f + static_cast<float>(i));
+ }
+}
+
+TEST_P(WriteKvSliceSlidingWindowTest, CircularSingleLegWriteAtNonZeroOffset) {
+ // Non-wrapping, non-zero dst_start single-leg write: 3 tokens already "stored" at
+ // slots [0,3), 2 more appended at [3,5) without touching the rest of the buffer.
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 8u;
+
+ auto dst = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ for (uint32_t i = 0; i < capacity; ++i) {
+ write_token_value(dst, kv_dim, i, -1.f);
+ }
+ auto src = make_src_tokens(kv_dim, 2u, /*first_value=*/42.f);
+
+ uu::write_swa_kv_slice_circular(dst,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/3u,
+ /*num_new_tokens=*/2u);
+
+ expect_token_value(dst, kv_dim, 3u, 42.f);
+ expect_token_value(dst, kv_dim, 4u, 43.f);
+ expect_token_value(dst, kv_dim, 0u, -1.f);
+ expect_token_value(dst, kv_dim, 5u, -1.f);
+}
+
+TEST_P(WriteKvSliceSlidingWindowTest, CircularClampsToShortSourceTensor) {
+ // Same short-source scenario as LeftAlignedClampsToShortSourceTensor, but for the
+ // circular writer: dst_start is computed from the nominal num_new_tokens (5), while
+ // only the 3 actually-available src tokens get copied.
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 8u;
+
+ auto dst = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ for (uint32_t i = 0; i < capacity; ++i) {
+ write_token_value(dst, kv_dim, i, -1.f);
+ }
+ auto src = make_src_tokens(kv_dim, /*count=*/3u, /*first_value=*/50.f);
+
+ uu::write_swa_kv_slice_circular(dst,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/0u,
+ /*num_new_tokens=*/5u);
+
+ expect_token_value(dst, kv_dim, 0u, -1.f);
+ expect_token_value(dst, kv_dim, 1u, -1.f);
+ expect_token_value(dst, kv_dim, 2u, 50.f);
+ expect_token_value(dst, kv_dim, 3u, 51.f);
+ expect_token_value(dst, kv_dim, 4u, 52.f);
+ expect_token_value(dst, kv_dim, 5u, -1.f);
+ expect_token_value(dst, kv_dim, 6u, -1.f);
+ expect_token_value(dst, kv_dim, 7u, -1.f);
+}
+
+TEST_P(WriteKvSliceSlidingWindowTest, CircularZeroNewTokensIsNoOp) {
+ const uint32_t kv_dim = GetParam();
+ const uint32_t capacity = 6u;
+
+ auto dst = make_cpu_tensor(kv_shape(kv_dim, capacity));
+ for (uint32_t i = 0; i < capacity; ++i) {
+ write_token_value(dst, kv_dim, i, 9.f + static_cast<float>(i));
+ }
+ auto src = make_src_tokens(kv_dim, 1u, /*first_value=*/0.f); // never read
+
+ uu::write_swa_kv_slice_circular(dst,
+ src,
+ kv_dim,
+ kv_dim,
+ /*num_stored_tokens=*/3u,
+ /*num_new_tokens=*/0u);
+
+ for (uint32_t i = 0; i < capacity; ++i) {
+ expect_token_value(dst, kv_dim, i, 9.f + static_cast<float>(i));
+ }
+}
+
+TEST(WriteKvSliceSlidingWindowCrossLayoutTest, CircularConvertsKvDim2To3) {
+ expect_cross_layout_write(/*src_kv_dim=*/2u, /*dst_kv_dim=*/3u, /*circular_write=*/true);
+}
+
+TEST(WriteKvSliceSlidingWindowCrossLayoutTest, CircularConvertsKvDim3To2) {
+ expect_cross_layout_write(/*src_kv_dim=*/3u, /*dst_kv_dim=*/2u, /*circular_write=*/true);
+}
+
+TEST(WriteKvSliceSlidingWindowCrossLayoutTest, LeftAlignedConvertsKvDim2To3) {
+ expect_cross_layout_write(/*src_kv_dim=*/2u, /*dst_kv_dim=*/3u, /*circular_write=*/false);
+}
+
+TEST(WriteKvSliceSlidingWindowCrossLayoutTest, LeftAlignedConvertsKvDim3To2) {
+ expect_cross_layout_write(/*src_kv_dim=*/3u, /*dst_kv_dim=*/2u, /*circular_write=*/false);
+}
+
+TEST(WriteKvSliceSlidingWindowCrossLayoutTest, LeftAlignedShiftConvertsKvDim2To3) {
+ // dst_kv_dim=3 exercises the bulk round-trip shift path together with layout conversion.
+ expect_cross_layout_shift_write(/*src_kv_dim=*/2u, /*dst_kv_dim=*/3u);
+}
+
+TEST(WriteKvSliceSlidingWindowCrossLayoutTest, LeftAlignedShiftConvertsKvDim3To2) {
+ // dst_kv_dim=2 exercises the generic partial-slice shift path together with layout
+ // conversion.
+ expect_cross_layout_shift_write(/*src_kv_dim=*/3u, /*dst_kv_dim=*/2u);
+}
+
+} // namespace ov::test::npuw