Skip to content

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

[Core][Ref] PagedAttention reference implementation (#28815)

Piotr Krzemiński1fd7eade3dc7
diff --git a/src/core/dev_api/openvino/op/paged_attention.hpp b/src/core/dev_api/openvino/op/paged_attention.hpp
index d066840581f..321728d2855 100644
--- a/src/core/dev_api/openvino/op/paged_attention.hpp
+++ b/src/core/dev_api/openvino/op/paged_attention.hpp
@@ -1,6 +1,7 @@
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
+
#pragma once
#include "openvino/op/op.hpp"
@@ -10,16 +11,56 @@ namespace op {
// This is an experimental operation that is implemented in the plugins.
// Do not use in user applications, backward compatibility is not guaranteed in future releases.
+
+/// \brief Paged attention op for memory-efficient sequence processing.
+///
+/// \ingroup ov_ops_cpp_api
class OPENVINO_API PagedAttentionExtension : public ov::op::Op {
public:
OPENVINO_OP("PagedAttentionExtension");
PagedAttentionExtension() = default;
- PagedAttentionExtension(const ov::OutputVector& args);
+ /// \brief Constructs a PagedAttentionExtension.
+ ///
+ /// \param args 28 inputs (see spec for layout):
+ /// (B_token = total tokens in the call, B_seq = number of sequences,
+ /// H = query heads, Hk = key/value heads, S = head size)
+ ///
+ /// 0 query [B_token, H * S] required
+ /// 1 key [B_token, Hk * S] required
+ /// 2 value [B_token, Hk * S] required
+ /// 3 key_cache [num_blocks, Hk, Bs, S] required
+ /// 4 value_cache [num_blocks, Hk, Bs, S] required
+ /// 5 past_lens [B_seq], i32 required
+ /// 6 subsequence_begins [B_seq + 1], i32 required
+ /// 7 block_indices [total_blocks], i32 required
+ /// 8 block_indices_begins [B_seq + 1], i32 required
+ /// 9 scale [] scalar required
+ /// 10 sliding_window [] scalar, i32 required (0 = unlimited)
+ /// 11 alibi_slopes [H] or empty required (empty = disabled)
+ /// 12 max_context_len [] scalar, i32 required (0 = unlimited)
+ /// 13 score_aggregation_window [] scalar or [B_seq], i32 required (0 = disabled)
+ /// 14 rotated_block_indices [Nrot] or empty, i32 required (empty = disabled)
+ /// 15 rotation_deltas [Nrot] or [Nrot, Bs], i32 required (empty = disabled)
+ /// 16 rotation_trig_lut [C, S] or [C*S] required (empty = disabled)
+ /// 17 xattention_threshold [] or [B_seq] required (empty = disabled)
+ /// 18 xattention_block_size [] scalar, i32 required (0 = disabled)
+ /// 19 xattention_stride [] scalar, i32 required
+ /// 20 sinks [1, H, 1, 1] or empty required (empty = disabled)
+ /// 21 adaptive_rkv_start_size [] scalar, i32 required (0 = no protection zone)
+ /// 22 adaptive_rkv_evictable_sizes [B_seq], i32 optional
+ /// 23 adaptive_rkv_diversity_block_set_indices [num_adaptive_rkv_blocks] optional
+ /// 24 adaptive_rkv_diversity_block_set_indices_begins [B_seq + 1], i32 optional
+ /// 25 token_type_ids [B_token] or [B_token, 1], i32 optional
+ /// 26 qq_bias [total_bias_bytes], u8 optional
+ /// 27 qq_bias_begins [B_seq + 1], i32 optional
+ explicit PagedAttentionExtension(const ov::OutputVector& args);
+
void validate_and_infer_types() override;
std::shared_ptr<ov::Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;
+ const ov::element::Type get_out_type(int index) const;
void set_out_type(int index, const ov::element::Type& output_type);
protected:
diff --git a/src/core/reference/include/openvino/reference/paged_attention.hpp b/src/core/reference/include/openvino/reference/paged_attention.hpp
new file mode 100644
index 00000000000..84474949122
--- /dev/null
+++ b/src/core/reference/include/openvino/reference/paged_attention.hpp
@@ -0,0 +1,803 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <algorithm>
+#include <cmath>
+#include <cstdint>
+#include <limits>
+#include <unordered_map>
+#include <vector>
+
+#include "openvino/core/except.hpp"
+#include "openvino/core/shape.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "openvino/reference/adaptive_rkv_diversity.hpp"
+#include "openvino/reference/utils/paged_cache_manager.hpp"
+
+namespace ov {
+namespace reference {
+
+namespace detail {
+
+inline float read_scalar_as_f32(const void* ptr, const ov::element::Type& et) {
+ OPENVINO_ASSERT(ptr != nullptr, "read_scalar_as_f32: null pointer");
+ if (et == ov::element::f32) {
+ return *static_cast<const float*>(ptr);
+ }
+ if (et == ov::element::f64) {
+ return static_cast<float>(*static_cast<const double*>(ptr));
+ }
+ if (et == ov::element::f16) {
+ return static_cast<float>(*static_cast<const ov::float16*>(ptr));
+ }
+ if (et == ov::element::bf16) {
+ return static_cast<float>(*static_cast<const ov::bfloat16*>(ptr));
+ }
+ OPENVINO_THROW("PagedAttention reference: unsupported scalar type: ", et);
+}
+
+inline float read_at_as_f32(const void* base, const ov::element::Type& et, std::size_t idx) {
+ OPENVINO_ASSERT(base != nullptr, "read_at_as_f32: null pointer");
+ if (et == ov::element::f32) {
+ return static_cast<const float*>(base)[idx];
+ }
+ if (et == ov::element::f64) {
+ return static_cast<float>(static_cast<const double*>(base)[idx]);
+ }
+ if (et == ov::element::f16) {
+ return static_cast<float>(static_cast<const ov::float16*>(base)[idx]);
+ }
+ if (et == ov::element::bf16) {
+ return static_cast<float>(static_cast<const ov::bfloat16*>(base)[idx]);
+ }
+ OPENVINO_THROW("PagedAttention reference: unsupported array type: ", et);
+}
+
+/// Softmax with optional attention-sink support.
+/// When sink_val != nullptr it participates in max/exp-sum but produces no output weight.
+inline void softmax_inplace(std::vector<float>& scores, const float* sink_val = nullptr) {
+ if (scores.empty()) {
+ return;
+ }
+ float m = *std::max_element(scores.begin(), scores.end());
+ if (sink_val != nullptr) {
+ m = std::max(m, *sink_val);
+ }
+ float sum = 0.f;
+ for (float& s : scores) {
+ s = std::exp(s - m);
+ sum += s;
+ }
+ if (sink_val != nullptr) {
+ sum += std::exp(*sink_val - m);
+ }
+ const float inv = (sum > 0.f) ? (1.f / sum) : 0.f;
+ for (float& s : scores) {
+ s *= inv;
+ }
+}
+
+inline void apply_rotary_inplace(std::vector<float>& vec,
+ const void* trig_lut,
+ const ov::element::Type& trig_et,
+ std::size_t trig_row,
+ std::size_t head_size) {
+ if (trig_lut == nullptr || head_size < 2 || (head_size % 2) != 0) {
+ return;
+ }
+ const std::size_t half = head_size / 2;
+ const std::size_t row_base = trig_row * head_size;
+ // Split-half (LLaMA-style) pairing: first half [0..half) paired with second half [half..head_size)
+ // Trig LUT row: [cos_0..cos_{half-1}, sin_0..sin_{half-1}]
+ for (std::size_t d = 0; d < half; ++d) {
+ const float x0 = vec[d];
+ const float x1 = vec[d + half];
+ const float c = read_at_as_f32(trig_lut, trig_et, row_base + d);
+ const float s = read_at_as_f32(trig_lut, trig_et, row_base + half + d);
+ vec[d] = x0 * c - x1 * s;
+ vec[d + half] = x0 * s + x1 * c;
+ }
+}
+
+inline std::vector<std::size_t> parse_subsequence_ranges(const int32_t* subseq_begins,
+ std::size_t subseq_count,
+ std::size_t seq_count,
+ std::size_t batch_tokens) {
+ // Returns a vector of size (seq_count + 1) with begins and a final end
+ std::vector<std::size_t> begins(seq_count + 1, 0);
+ if (subseq_begins == nullptr || subseq_count == 0 || seq_count == 0) {
+ begins[0] = 0;
+ begins[seq_count] = batch_tokens;
+ return begins;
+ }
+
+ const std::size_t usable = std::min(subseq_count, seq_count);
+ for (std::size_t s = 0; s < usable; ++s) {
+ const std::int32_t v = subseq_begins[s];
+ begins[s] = (v < 0) ? 0 : static_cast<std::size_t>(v);
+ }
+
+ if (subseq_count >= seq_count + 1) {
+ const std::int32_t vend = subseq_begins[seq_count];
+ begins[seq_count] = (vend < 0) ? batch_tokens : static_cast<std::size_t>(vend);
+ } else {
+ begins[seq_count] = batch_tokens;
+ }
+
+ // Clamp and monotonic fix
+ begins[0] = std::min(begins[0], batch_tokens);
+ for (std::size_t s = 1; s <= seq_count; ++s) {
+ begins[s] = std::min(begins[s], batch_tokens);
+ if (begins[s] < begins[s - 1]) {
+ begins[s] = begins[s - 1];
+ }
+ }
+ return begins;
+}
+
+} // namespace detail
+
+// Reference implementation of ov::op::PagedAttentionExtension.
+// Supports GQA, ALiBi, RoPE re-rotation, attention sinks,
+// xattention sparse prefill, and adaptive RKV diversity scoring.
+//
+// pool_kernel (default 7): max-pool window for per-head score aggregation.
+// Not yet an operator input but should be eventually.
+template <typename T>
+void paged_attention(std::uintptr_t node_key,
+ ov::reference::paged_attention_cache::PagedCacheManager* cache_manager,
+ T* out,
+ T* out_scores,
+ T* out_diversity_scores,
+ const T* query,
+ const T* key,
+ const T* value,
+ const T* key_cache_init,
+ const T* value_cache_init,
+ const int32_t* past_lens,
+ const int32_t* subsequence_begins,
+ const int32_t* block_indices_init,
+ std::size_t block_indices_count,
+ const int32_t* block_indices_begins_init,
+ std::size_t block_indices_begins_count,
+ const void* scale,
+ const ov::element::Type& scale_et,
+ const int32_t* sliding_window,
+ const void* alibi_slopes,
+ const ov::element::Type& alibi_et,
+ const ov::Shape& alibi_shape,
+ const int32_t* max_context_len,
+ const int32_t* score_aggregation_window,
+ std::size_t score_aggregation_window_count,
+ const int32_t* rotated_block_indices,
+ std::size_t rotated_block_count,
+ const int32_t* rotation_deltas,
+ const ov::Shape& rotation_deltas_shape,
+ const void* rotation_trig_lut,
+ const ov::element::Type& trig_lut_et,
+ const ov::Shape& trig_lut_shape,
+ const void* xattention_threshold,
+ const ov::element::Type& xattention_threshold_et,
+ const int32_t* xattention_block_size,
+ const int32_t* xattention_stride,
+ const void* sinks,
+ const ov::element::Type& sinks_et,
+ const int32_t* adaptive_rkv_start_size,
+ const int32_t* adaptive_rkv_evictable_sizes,
+ const int32_t* adaptive_rkv_diversity_block_set_indices,
+ const int32_t* adaptive_rkv_diversity_block_set_indices_begins,
+ const ov::Shape& query_shape,
+ const ov::Shape& key_shape,
+ const ov::Shape& value_shape,
+ const ov::Shape& key_cache_shape,
+ const ov::Shape& value_cache_shape,
+ const ov::Shape& past_lens_shape,
+ const ov::Shape& subseq_shape,
+ std::size_t pool_kernel = 7) {
+ OPENVINO_ASSERT(cache_manager != nullptr, "PagedAttention reference: cache_manager is null");
+ OPENVINO_ASSERT(query != nullptr && key != nullptr && value != nullptr, "PagedAttention reference: null Q/K/V");
+ OPENVINO_ASSERT(out != nullptr, "PagedAttention reference: output is null");
+
+ // Not used by the reference -- it reads key data directly from the cache manager
+ (void)adaptive_rkv_diversity_block_set_indices;
+ (void)adaptive_rkv_diversity_block_set_indices_begins;
+
+ // Sinks: per-head virtual token in the softmax (shifts max/denominator, no output weight)
+ const bool has_sinks = (sinks != nullptr);
+
+ // Xattention: sparse prefill via strided Q*K products with block-level masking
+ const bool has_xattn = (xattention_threshold != nullptr);
+
+ OPENVINO_ASSERT(query_shape.size() == 2 && key_shape.size() == 2 && value_shape.size() == 2,
+ "PagedAttention reference: expected Q/K/V rank 2");
+ OPENVINO_ASSERT(past_lens_shape.size() == 1 && subseq_shape.size() == 1,
+ "PagedAttention reference: expected past_lens/subsequence_begins rank 1");
+
+ const std::size_t batch_tokens = static_cast<std::size_t>(query_shape[0]);
+ const std::size_t query_features = static_cast<std::size_t>(query_shape[1]);
+ const std::size_t key_features = static_cast<std::size_t>(key_shape[1]);
+ const std::size_t value_features = static_cast<std::size_t>(value_shape[1]);
+
+ const std::size_t seq_count = static_cast<std::size_t>(past_lens_shape[0]);
+ const std::size_t subseq_count = static_cast<std::size_t>(subseq_shape[0]);
+
+ // Register operator once per node and copy init cache
+ cache_manager->ensure_operator(node_key,
+ key_cache_init,
+ value_cache_init,
+ key_cache_shape,
+ value_cache_shape,
+ block_indices_init,
+ block_indices_count,
+ block_indices_begins_init,
+ block_indices_begins_count,
+ past_lens,
+ seq_count);
+
+ const std::size_t head_size = cache_manager->key_head_size(node_key);
+ const std::size_t kv_heads = cache_manager->num_kv_heads(node_key);
+ const std::size_t v_head_size = cache_manager->value_head_size(node_key);
+
+ OPENVINO_ASSERT(head_size > 0 && kv_heads > 0 && v_head_size > 0, "PagedAttention reference: invalid cache layout");
+ OPENVINO_ASSERT(key_features == kv_heads * head_size,
+ "PagedAttention reference: key feature dim mismatch with cache layout");
+ OPENVINO_ASSERT(value_features == kv_heads * v_head_size,
+ "PagedAttention reference: value feature dim mismatch with cache layout");
+ OPENVINO_ASSERT((query_features % head_size) == 0,
+ "PagedAttention reference: query features not divisible by head_size");
+
+ const std::size_t q_heads = query_features / head_size;
+ OPENVINO_ASSERT((q_heads % kv_heads) == 0,
+ "PagedAttention reference: expected num_heads to be divisible by num_kv_heads (GQA)");
+ const std::size_t group = q_heads / kv_heads;
+
+ const std::size_t out_features = q_heads * v_head_size;
+ const float scale_f = detail::read_scalar_as_f32(scale, scale_et);
+ const int32_t sliding_window_i = sliding_window ? sliding_window[0] : 0;
+ const int32_t max_context_i = max_context_len ? max_context_len[0] : 0;
+ const std::size_t alibi_len = alibi_shape.empty() ? 0 : static_cast<std::size_t>(alibi_shape[0]);
+
+ // Initialize per-sequence view of current lengths
+ cache_manager->begin_step(node_key, past_lens, seq_count);
+
+ // Parse token-to-sequence partition
+ const auto seq_begins = detail::parse_subsequence_ranges(subsequence_begins, subseq_count, seq_count, batch_tokens);
+
+ // Prepare mapping for rotated blocks (block_id -> rotated_index)
+ std::unordered_map<int32_t, int32_t> rotated_map;
+ rotated_map.reserve(rotated_block_count);
+ for (std::size_t i = 0; i < rotated_block_count; ++i) {
+ rotated_map.emplace(rotated_block_indices[i], static_cast<int32_t>(i));
+ }
+
+ const bool has_trig = (rotation_trig_lut != nullptr) && (!trig_lut_shape.empty());
+ const std::size_t trig_rows = trig_lut_shape.size() == 2 ? static_cast<std::size_t>(trig_lut_shape[0])
+ : trig_lut_shape.size() == 1 ? 1
+ : 0;
+ const bool deltas_is_2d = rotation_deltas_shape.size() == 2;
+ const std::size_t deltas_stride = deltas_is_2d ? static_cast<std::size_t>(rotation_deltas_shape[1]) : 0;
+
+ // out_scores: concatenation of [past_len + new_len] for each sequence
+ std::vector<float> scores_acc;
+ // Per-head score buffer for max-pool + head-average (eviction scoring)
+ std::vector<float> scores_per_head;
+ std::size_t total_score_len = 0;
+ const bool need_scores = (out_scores != nullptr);
+ if (need_scores) {
+ std::size_t total = 0;
+ for (std::size_t s = 0; s < seq_count; ++s) {
+ const std::size_t past = past_lens ? static_cast<std::size_t>(past_lens[s]) : 0;
+ const std::size_t new_len = seq_begins[s + 1] - seq_begins[s];
+ total += past + new_len;
+ }
+ total_score_len = total;
+ scores_acc.assign(total, 0.f);
+ scores_per_head.assign(q_heads * total, 0.f);
+ }
+
+ std::vector<float> logits;
+ std::vector<float> out_head;
+ std::vector<float> key_buf; // re-used for rotary re-rotation
+
+ // Read per-head sink values from [1,H,1,1].
+ // H is the number of query heads (not KV heads), so this is safe in GQA.
+ std::vector<float> sink_vals;
+ if (has_sinks) {
+ sink_vals.resize(q_heads, 0.f);
+ for (std::size_t h = 0; h < q_heads; ++h) {
+ sink_vals[h] = detail::read_at_as_f32(sinks, sinks_et, h);
+ }
+ }
+
+ // Xattention sparse mask per head: xattn_mask[h][q_blk][k_blk]
+ // Only active for multi-token prefill with a single sequence.
+ const int32_t xattn_block_sz = (xattention_block_size != nullptr) ? xattention_block_size[0] : 0;
+ const int32_t xattn_stride = (xattention_stride != nullptr) ? xattention_stride[0] : 0;
+ // xattn_mask layout: [q_heads][num_q_blocks][num_k_blocks]
+ std::vector<std::vector<std::vector<bool>>> xattn_mask;
+
+ // Prefix offsets for out_scores concatenation
+ std::vector<std::size_t> score_prefix(seq_count + 1, 0);
+ if (!scores_acc.empty()) {
+ for (std::size_t s = 0; s < seq_count; ++s) {
+ const std::size_t past = past_lens ? static_cast<std::size_t>(past_lens[s]) : 0;
+ const std::size_t new_len = seq_begins[s + 1] - seq_begins[s];
+ score_prefix[s + 1] = score_prefix[s] + past + new_len;
+ }
+ }
+
+ for (std::size_t s = 0; s < seq_count; ++s) {
+ const std::size_t t_begin = seq_begins[s];
+ const std::size_t t_end = seq_begins[s + 1];
+ if (t_begin >= t_end) {
+ continue;
+ }
+ OPENVINO_ASSERT(t_end <= batch_tokens, "PagedAttention reference: subsequence range exceeds batch_tokens");
+
+ const std::int32_t past = past_lens ? past_lens[s] : 0;
+ OPENVINO_ASSERT(past >= 0, "PagedAttention reference: negative past_lens");
+ const std::size_t new_len = t_end - t_begin;
+
+ // Score aggregation window: [] broadcasts to all sequences, [B_seq] is per-sequence.
+ // Negative = unbounded, 0 = disabled.
+ const std::size_t saw_idx =
+ (score_aggregation_window_count > 1) ? std::min(s, score_aggregation_window_count - 1) : 0;
+ const int32_t score_window_i = score_aggregation_window ? score_aggregation_window[saw_idx] : 0;
+
+ // Build xattention sparse mask (prefill only, new_len > 1, single sequence)
+ const bool do_xattn = has_xattn && new_len > 1 && seq_count == 1 && xattn_block_sz > 0 && xattn_stride > 0;
+ xattn_mask.clear();
+ if (do_xattn) {
+ // Phase 1: strided Q*K dot products over the new tokens only
+ const float threshold_f = detail::read_scalar_as_f32(xattention_threshold, xattention_threshold_et);
+ // mask covers only the new tokens; past cached tokens are always attended to
+ const std::size_t total_len = new_len;
+ const std::size_t num_q_blocks =
+ (total_len + static_cast<std::size_t>(xattn_block_sz) - 1) / static_cast<std::size_t>(xattn_block_sz);
+ const std::size_t num_k_blocks = num_q_blocks;
+ const std::size_t q_strided =
+ (total_len + static_cast<std::size_t>(xattn_stride) - 1) / static_cast<std::size_t>(xattn_stride);
+ const std::size_t k_strided = q_strided;
+ const std::size_t num_per_block =
+ static_cast<std::size_t>(xattn_block_sz) / static_cast<std::size_t>(xattn_stride);
+
+ xattn_mask.resize(q_heads);
+ for (std::size_t h = 0; h < q_heads; ++h) {
+ const std::size_t kvh = h / group;
+
+ // Strided attention matrix [q_strided x k_strided]
+ std::vector<float> attn_strided(q_strided * k_strided, 0.f);
+
+ for (int32_t off = 0; off < xattn_stride; ++off) {
+ for (std::size_t qi = 0; qi < q_strided; ++qi) {
+ // Query token index: we sample the (xattn_stride-1-off + qi*stride)-th Q
+ const int64_t q_tok_idx = static_cast<int64_t>(xattn_stride) - 1 - off +
+ static_cast<int64_t>(qi) * static_cast<int64_t>(xattn_stride);
+ if (q_tok_idx < 0 || static_cast<std::size_t>(q_tok_idx) >= total_len)
+ continue;
+ const std::size_t q_abs = t_begin + static_cast<std::size_t>(q_tok_idx);
+ const T* qptr = query + q_abs * query_features + h * head_size;
+
+ // Causal: attend up to qi+1 strided positions
+ const std::size_t k_causal = qi + 1;
+ for (std::size_t ki = 0; ki < std::min(k_causal, k_strided); ++ki) {
+ const int64_t k_tok_idx = static_cast<int64_t>(off) +
+ static_cast<int64_t>(ki) * static_cast<int64_t>(xattn_stride);
+ if (k_tok_idx < 0 || static_cast<std::size_t>(k_tok_idx) >= total_len)
+ continue;
+
+ // Read key from cache or from current input
+ const std::size_t k_pos = static_cast<std::size_t>(k_tok_idx);
+ // all keys for strided estimation come from the new input tokens
+ const T* kptr_raw = key + (t_begin + k_pos) * key_features + kvh * head_size;
+ float dot = 0.f;
+ for (std::size_t d = 0; d < head_size; ++d) {
+ dot += static_cast<float>(qptr[d]) * static_cast<float>(kptr_raw[d]);
+ }
+ attn_strided[qi * k_strided + ki] += dot;
+ }
+ }
+ }
+
+ // Scale and causal softmax on strided attention
+ const float xscale = scale_f / static_cast<float>(xattn_stride);
+ for (std::size_t qi = 0; qi < q_strided; ++qi) {
+ const std::size_t k_causal = qi + 1;
+ float* row = attn_strided.data() + qi * k_strided;
+ // Apply scale
+ for (std::size_t ki = 0; ki < k_strided; ++ki) {
+ row[ki] *= xscale;
+ }
+ // Causal mask: set positions after causal boundary to -inf
+ for (std::size_t ki = k_causal; ki < k_strided; ++ki) {
+ row[ki] = -std::numeric_limits<float>::infinity();
+ }
+ // Softmax over this row
+ float m = -std::numeric_limits<float>::infinity();
+ for (std::size_t ki = 0; ki < k_strided; ++ki)
+ m = std::max(m, row[ki]);
+ float sm = 0.f;
+ for (std::size_t ki = 0; ki < k_strided; ++ki) {
+ row[ki] = std::exp(row[ki] - m);
+ sm += row[ki];
+ }
+ if (sm > 0.f) {
+ float inv = 1.f / sm;
+ for (std::size_t ki = 0; ki < k_strided; ++ki)
+ row[ki] *= inv;
+ }
+ }
+
+ // Phase 2: block aggregation - sum num_per_block * num_per_block windows
+ std::vector<float> block_sums(num_q_blocks * num_k_blocks, 0.f);
+ for (std::size_t qb = 0; qb < num_q_blocks; ++qb) {
+ for (std::size_t kb = 0; kb < num_k_blocks; ++kb) {
+ float bsum = 0.f;
+ for (std::size_t dq = 0; dq < num_per_block; ++dq) {
+ const std::size_t qi = qb * num_per_block + dq;
+ if (qi >= q_strided)
+ continue;
+ for (std::size_t dk = 0; dk < num_per_block; ++dk) {
+ const std::size_t ki = kb * num_per_block + dk;
+ if (ki >= k_strided)
+ continue;
+ bsum += attn_strided[qi * k_strided + ki];
+ }
+ }
+ block_sums[qb * num_k_blocks + kb] = bsum;
+ }
+ }
+
+ // Phase 3: threshold masking - greedy top-block selection
+ xattn_mask[h].resize(num_q_blocks, std::vector<bool>(num_k_blocks, false));
+ for (std::size_t qb = 0; qb < num_q_blocks; ++qb) {
+ const float* brow = block_sums.data() + qb * num_k_blocks;
+ float total_sum = 0.f;
+ for (std::size_t kb = 0; kb <= qb && kb < num_k_blocks; ++kb) {
+ total_sum += brow[kb];
+ }
+ const float required = total_sum * threshold_f;
+
+ // Build (value, index) pairs
+ std::vector<std::pair<float, std::size_t>> vals;
+ vals.reserve(num_k_blocks);
+ for (std::size_t kb = 0; kb < num_k_blocks; ++kb) {
+ vals.emplace_back(brow[kb], kb);
+ }
+ // Block 0 (first column) and diagonal (qb) always selected
+ // Swap them to positions 0 and 1, then sort rest descending
+ if (qb > 1 && qb < vals.size()) {
+ std::swap(vals[1], vals[qb]);
+ }
+ if (vals.size() > 2) {
+ std::sort(vals.begin() + 2, vals.end(), [](const auto& a, const auto& b) {
+ return a.first > b.first;
+ });
+ }
+
+ // Cumulative-sum block selection (top-p style).
+ // Block 0 and diagonal are always kept.
+ // cumsum tracks the prefix sum of entries in sorted order;
+ // the causal gate (vals[i].second > qb) rejects future blocks
+ // without affecting cumsum.
+ float cumsum = 0.f;
+ for (std::size_t i = 0; i < vals.size(); ++i) {
+ bool keep = false;
+ if (i == 0) {
+ // First column always kept
+ keep = true;
+ } else if (i == 1 && qb >= 1) {
+ // Diagonal always kept
+ keep = true;
+ cumsum = vals[0].first;
+ } else {
+ keep = (cumsum < required);
+ cumsum += vals[i - 1].first;
+ }
+ // Causal: only keep blocks where k_block <= q_block
+ if (vals[i].second > qb)
+ keep = false;
+ xattn_mask[h][qb][vals[i].second] = keep;
+ }
+ }
+ }
+ }
+
+ // Base offset for out_scores for this sequence (concatenation order is sequence order)
+ const std::size_t score_base = score_prefix[s];
+
+ for (std::size_t i = 0; i < new_len; ++i) {
+ const std::size_t token = t_begin + i;
+ const std::int32_t qpos = past + static_cast<std::int32_t>(i);
+
+ // Append this token's KV into the cache
+ const T* krow = key + token * key_features;
+ const T* vrow = value + token * value_features;
+ cache_manager->write_token_kv<T>(node_key, s, qpos, krow, vrow);
+
+ // Determine attention window
+ std::int32_t start = 0;
+ if (max_context_i > 0) {
+ start = std::max(start, qpos + 1 - max_context_i);
+ }
+ if (sliding_window_i > 0) {
+ start = std::max(start, qpos + 1 - sliding_window_i);
+ }
+ if (start < 0) {
+ start = 0;
+ }
+ const std::int32_t end = qpos;
+ const std::size_t ctx_len = (end >= start) ? static_cast<std::size_t>(end - start + 1) : 0;
+ if (ctx_len == 0) {
+ // No context (shouldn't happen for causal), output zeros
+ std::fill(out + token * out_features, out + (token + 1) * out_features, T(0));
+ continue;
+ }
+
+ // Score window semantics:
+ // 0 = disabled, >0 = last N tokens, <0 = all tokens
+ const bool include_in_scores =
+ (scores_acc.empty() || score_window_i == 0)
+ ? false
+ : (score_window_i < 0 ? true : (static_cast<std::int32_t>(new_len - i) <= score_window_i));
+
+ const T* qrow = query + token * query_features;
+
+ for (std::size_t h = 0; h < q_heads; ++h) {
+ const std::size_t kvh = h / group;
+ const float slope = (alibi_slopes == nullptr || alibi_len == 0)
+ ? 0.f
+ : detail::read_at_as_f32(alibi_slopes,
+ alibi_et,
+ (alibi_len == 1) ? 0 : std::min(h, alibi_len - 1));
+
+ const T* qptr = qrow + h * head_size;
+
+ logits.assign(ctx_len, 0.f);
+ out_head.assign(v_head_size, 0.f);
+
+ for (std::size_t t = 0; t < ctx_len; ++t) {
+ const std::int32_t kpos = start + static_cast<std::int32_t>(t);
+ ov::reference::paged_attention_cache::PagedCacheManager::TokenAddress addr;
+ const bool ok = cache_manager->resolve_token(node_key, s, kpos, addr);
+ if (!ok) {
+ logits[t] = -std::numeric_limits<float>::infinity();
+ continue;
+ }
+
+ const T* kptr = cache_manager->key_ptr<T>(node_key, addr, kvh);
+ if (kptr == nullptr) {
+ logits[t] = -std::numeric_limits<float>::infinity();
+ continue;
+ }
+
+ // RoPE re-rotation for cached positions only; new tokens are unrotated
+ float dot = 0.f;
+ const auto it = rotated_map.find(addr.block);
+ if (has_trig && rotation_deltas != nullptr && it != rotated_map.end() && kpos < past) {
+ const int32_t rot_idx = it->second;
+ std::size_t trig_row = 0;
+ if (deltas_is_2d) {
+ const std::size_t off = static_cast<std::size_t>(addr.offset);
+ const std::size_t di = static_cast<std::size_t>(rot_idx) * deltas_stride + off;
+ const std::size_t deltas_total = static_cast<std::size_t>(rotation_deltas_shape[0]) *
+ static_cast<std::size_t>(rotation_deltas_shape[1]);
+ const int32_t raw = (di < deltas_total) ? rotation_deltas[di] : 0;
+ trig_row = raw < 0 ? 0 : static_cast<std::size_t>(raw);
+ } else {
+ const std::size_t deltas_total = rotation_deltas_shape.size() == 1
+ ? static_cast<std::size_t>(rotation_deltas_shape[0])
+ : 0;
+ const std::size_t di = static_cast<std::size_t>(rot_idx);
+ const int32_t raw = (di < deltas_total) ? rotation_deltas[di] : 0;
+ trig_row = raw < 0 ? 0 : static_cast<std::size_t>(raw);
+ }
+ if (trig_rows > 0) {
+ trig_row = std::min(trig_row, trig_rows - 1);
+ }
+
+ key_buf.assign(head_size, 0.f);
+ for (std::size_t d = 0; d < head_size; ++d) {
+ key_buf[d] = static_cast<float>(kptr[d]);
+ }
+ detail::apply_rotary_inplace(key_buf, rotation_trig_lut, trig_lut_et, trig_row, head_size);
+ for (std::size_t d = 0; d < head_size; ++d) {
+ dot += static_cast<float>(qptr[d]) * key_buf[d];
+ }
+ } else {
+ for (std::size_t d = 0; d < head_size; ++d) {
+ dot += static_cast<float>(qptr[d]) * static_cast<float>(kptr[d]);
+ }
+ }
+
+ float l = dot * scale_f;
+ if (alibi_slopes != nullptr) {
+ l += slope * static_cast<float>(kpos - qpos);
+ }
+ logits[t] = l;
+ }
+
+ // Apply xattention sparse mask (new-to-new only; cached keys always included)
+ if (do_xattn && h < xattn_mask.size()) {
+ for (std::size_t t = 0; t < ctx_len; ++t) {
+ const std::int32_t kpos = start + static_cast<std::int32_t>(t);
+ if (kpos < past)
+ continue; // past cached tokens always included
+ const std::size_t q_blk = i / static_cast<std::size_t>(xattn_block_sz);
+ const std::size_t k_blk =
+ static_cast<std::size_t>(kpos - past) / static_cast<std::size_t>(xattn_block_sz);
+ if (q_blk < xattn_mask[h].size() && k_blk < xattn_mask[h][q_blk].size()) {
+ if (!xattn_mask[h][q_blk][k_blk]) {
+ logits[t] = -std::numeric_limits<float>::infinity();
+ }
+ }
+ }
+ }
+
+ // Softmax with optional attention sink
+ const float* sink_ptr = has_sinks ? &sink_vals[h] : nullptr;
+ detail::softmax_inplace(logits, sink_ptr);
+
+ // Truncate weights to T precision (matches CPU which stores softmax output in compute type)
+ for (auto& w : logits) {
+ w = static_cast<float>(static_cast<T>(w));
+ }
+
+ for (std::size_t t = 0; t < ctx_len; ++t) {
+ const std::int32_t kpos = start + static_cast<std::int32_t>(t);
+ ov::reference::paged_attention_cache::PagedCacheManager::TokenAddress addr;
+ if (!cache_manager->resolve_token(node_key, s, kpos, addr)) {
+ continue;
+ }
+ const T* vptr = cache_manager->value_ptr<T>(node_key, addr, kvh);
+ if (!vptr) {
+ continue;
+ }
+ const float w = logits[t];
+ for (std::size_t d = 0; d < v_head_size; ++d) {
+ out_head[d] += w * static_cast<float>(vptr[d]);
+ }
+
+ if (include_in_scores) {
+ // Accumulate attention weight at each key position in the [past..past+new) timeline
+ const std::size_t idx = score_base + static_cast<std::size_t>(kpos);
+ if (idx < scores_acc.size()) {
+ scores_acc[idx] += w;
+ }
+ // Also store per-head for max-pool + head-average
+ if (idx < total_score_len) {
+ scores_per_head[h * total_score_len + idx] += w;
+ }
+ }
+ }
+
+ T* out_ptr = out + token * out_features + h * v_head_size;
+ for (std::size_t d = 0; d < v_head_size; ++d) {
+ out_ptr[d] = static_cast<T>(out_head[d]);
+ }
+ }
+ }
+ }
+
+ if (out_scores != nullptr) {
+ for (std::size_t i = 0; i < scores_acc.size(); ++i) {
+ out_scores[i] = static_cast<T>(scores_acc[i]);
+ }
+ }
+
+ // Feed scores back into the cache manager for eviction.
+ // Apply per-head max-pool + head-average for better importance estimation.
+ if (!scores_acc.empty()) {
+ if (pool_kernel > 1 && total_score_len > 0) {
+ // Per-sequence, per-head max-pool then average across heads
+ std::vector<float> pooled(total_score_len, 0.f);
+ const std::size_t half_k = pool_kernel / 2;
+
+ for (std::size_t h = 0; h < q_heads; ++h) {
+ const float* head_row = scores_per_head.data() + h * total_score_len;
+ // Max-pool with kernel pool_kernel, stride 1, pad half_k, per-sequence
+ std::size_t seg_start = 0;
+ for (std::size_t s = 0; s < seq_count; ++s) {
+ const std::size_t past = past_lens ? static_cast<std::size_t>(past_lens[s]) : 0;
+ const std::size_t new_len = seq_begins[s + 1] - seq_begins[s];
+ const std::size_t seg_len = past + new_len;
+ for (std::size_t t = 0; t < seg_len; ++t) {
+ const std::size_t lo = (t >= half_k) ? (t - half_k) : 0;
+ const std::size_t hi = std::min(t + half_k + 1, seg_len);
+ float mx = -std::numeric_limits<float>::infinity();
+ for (std::size_t j = lo; j < hi; ++j) {
+ mx = std::max(mx, head_row[seg_start + j]);
+ }
+ pooled[seg_start + t] += mx; // accumulate across heads
+ }
+ seg_start += seg_len;
+ }
+ }
+ // Divide by q_heads to get head-average
+ const float inv_heads = 1.f / static_cast<float>(q_heads);
+ for (std::size_t i = 0; i < total_score_len; ++i) {
+ pooled[i] *= inv_heads;
+ }
+ cache_manager->update_attention_scores(node_key, pooled.data(), pooled.size(), past_lens, seq_count);
+ } else {
+ cache_manager->update_attention_scores(node_key,
+ scores_acc.data(),
+ scores_acc.size(),
+ past_lens,
+ seq_count);
+ }
+ }
+
+ // Adaptive RKV diversity: compute per-block diversity scores for eviction zones
+ const bool has_adaptive_rkv = (adaptive_rkv_evictable_sizes != nullptr);
+ if (has_adaptive_rkv && out_diversity_scores != nullptr) {
+ const std::size_t cache_block_size = cache_manager->block_size(node_key);
+ const int32_t start_size_i = adaptive_rkv_start_size ? adaptive_rkv_start_size[0] : 0;
+ const std::size_t start_size = (start_size_i < 0) ? 0 : static_cast<std::size_t>(start_size_i);
+
+ std::size_t out_offset = 0;
+ for (std::size_t s = 0; s < seq_count; ++s) {
+ const int32_t evict_size_i = adaptive_rkv_evictable_sizes[s];
+ if (evict_size_i <= 0) {
+ continue;
+ }
+ const std::size_t evict_size = static_cast<std::size_t>(evict_size_i);
+
+ // Total tokens for this sequence (past + newly appended)
+ const std::size_t past = past_lens ? static_cast<std::size_t>(past_lens[s]) : 0;
+ const std::size_t new_len = seq_begins[s + 1] - seq_begins[s];
+ const std::size_t total_tokens = past + new_len;
+
+ if (total_tokens < start_size + evict_size) {
+ // Not enough tokens for the eviction zone - skip
+ continue;
+ }
+
+ // Assemble key data from cache: [kv_heads, total_tokens, head_size]
+ std::vector<T> key_data(kv_heads * total_tokens * head_size, T(0));
+ for (std::size_t kvh = 0; kvh < kv_heads; ++kvh) {
+ for (std::size_t pos = 0; pos < total_tokens; ++pos) {
+ ov::reference::paged_attention_cache::PagedCacheManager::TokenAddress addr;
+ if (cache_manager->resolve_token(node_key, s, static_cast<int32_t>(pos), addr)) {
+ const T* kptr = cache_manager->key_ptr<T>(node_key, addr, kvh);
+ if (kptr) {
+ T* dst = key_data.data() + kvh * total_tokens * head_size + pos * head_size;
+ std::copy(kptr, kptr + head_size, dst);
+ }
+ }
+ }
+ }
+
+ ov::Shape key_shape_3d = {kv_heads, total_tokens, head_size};
+ ov::reference::AdaptiveRKVDiversityCalculator<T> calc(start_size, evict_size, cache_block_size);
+ auto diversity = calc.calculate_block_diversity(key_data.data(), key_shape_3d);
+
+ // Flatten [evict_size/block_size][evict_size] into the output buffer
+ for (std::size_t b = 0; b < diversity.size(); ++b) {
+ for (std::size_t t = 0; t < diversity[b].size(); ++t) {
+ out_diversity_scores[out_offset++] = diversity[b][t];
+ }
+ }
+
+ // Feed diversity matrix into cache manager for eviction decisions
+ const std::size_t n_evict_blocks = diversity.size();
+ std::vector<float> flat_div(n_evict_blocks * evict_size, 0.f);
+ for (std::size_t b = 0; b < n_evict_blocks; ++b) {
+ for (std::size_t t = 0; t < diversity[b].size() && t < evict_size; ++t) {
+ flat_div[b * evict_size + t] = static_cast<float>(diversity[b][t]);
+ }
+ }
+ const std::size_t start_blk_off = start_size / cache_block_size;
+ cache_manager
+ ->update_diversity_scores(node_key, s, flat_div.data(), n_evict_blocks, evict_size, start_blk_off);
+ }
+ }
+}
+
+} // namespace reference
+} // namespace ov
diff --git a/src/core/reference/include/openvino/reference/utils/paged_cache_manager.hpp b/src/core/reference/include/openvino/reference/utils/paged_cache_manager.hpp
new file mode 100644
index 00000000000..bcf3716467b
--- /dev/null
+++ b/src/core/reference/include/openvino/reference/utils/paged_cache_manager.hpp
@@ -0,0 +1,307 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <cstring>
+#include <deque>
+#include <limits>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#include "openvino/core/except.hpp"
+#include "openvino/core/shape.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/runtime/aligned_buffer.hpp"
+
+namespace ov {
+namespace reference {
+namespace paged_attention_cache {
+
+// Eviction strategy when the block pool is full
+enum class EvictionPolicy {
+ FIFO, // evict oldest block of the longest sequence
+ SCORE, // evict block with lowest attention score
+ ADAPTIVE_RKV // evict block with lowest key-diversity score
+};
+
+// CacheManager used by the reference implementation of PagedAttentionExtension
+class PagedCacheManager {
+public:
+ struct TokenAddress {
+ std::int32_t block = -1;
+ std::int32_t offset = 0;
+ };
+
+ // Defaults: SCORE eviction, 64 MB cap, attention_mass_p=0.9.
+ // These params are not yet exposed through the model/operator.
+ explicit PagedCacheManager(ov::element::Type elem_type,
+ EvictionPolicy policy = EvictionPolicy::SCORE,
+ std::size_t max_cache_bytes = 64UL * 1024UL * 1024UL,
+ float attention_mass_p = 0.9f);
+ PagedCacheManager(const PagedCacheManager&) = delete;
+ PagedCacheManager& operator=(const PagedCacheManager&) = delete;
+
+ // Register or find operator state for a PA node
+ bool ensure_operator(std::uintptr_t node_key,
+ const void* key_cache_init,
+ const void* value_cache_init,
+ const ov::Shape& key_cache_shape,
+ const ov::Shape& value_cache_shape,
+ const std::int32_t* block_indices_init,
+ std::size_t block_indices_count,
+ const std::int32_t* block_indices_begins_init,
+ std::size_t block_indices_begins_count,
+ const std::int32_t* past_lens_init,
+ std::size_t past_lens_count);
+
+ // Update per-sequence lengths at the start of a step.
+ // past_lens holds the logical length of each sequence before appending new tokens.
+ void begin_step(std::uintptr_t node_key, const std::int32_t* past_lens, std::size_t seq_count);
+
+ // Ensure storage for a token position within a sequence.
+ // Allocates or reuses blocks as needed.
+ TokenAddress ensure_token(std::uintptr_t node_key, std::size_t seq_idx, std::int32_t token_pos);
+
+ // Resolve an existing token address.
+ // Returns false if the token was trimmed or is beyond the logical length.
+ bool resolve_token(std::uintptr_t node_key,
+ std::size_t seq_idx,
+ std::int32_t token_pos,
+ TokenAddress& out_addr) const;
+
+ // Write key/value vectors for a token into the cache
+ //
+ // key_row layout: [num_kv_heads * key_head_size]
+ // value_row layout: [num_kv_heads * value_head_size]
+ template <typename T>
+ void write_token_kv(std::uintptr_t node_key,
+ std::size_t seq_idx,
+ std::int32_t token_pos,
+ const T* key_row,
+ const T* value_row);
+
+ // Access pointers for an already resolved token
+ template <typename T>
+ const T* key_ptr(std::uintptr_t node_key, TokenAddress addr, std::size_t kv_head) const;
+
+ template <typename T>
+ const T* value_ptr(std::uintptr_t node_key, TokenAddress addr, std::size_t kv_head) const;
+
+ // Cache layout getters (per node)
+ std::size_t num_blocks(std::uintptr_t node_key) const;
+ std::size_t block_size(std::uintptr_t node_key) const;
+ std::size_t num_kv_heads(std::uintptr_t node_key) const;
+ std::size_t key_head_size(std::uintptr_t node_key) const;
+ std::size_t value_head_size(std::uintptr_t node_key) const;
+
+ ov::element::Type element_type() const noexcept {
+ return m_elem_type;
+ }
+
+ EvictionPolicy eviction_policy() const noexcept {
+ return m_policy;
+ }
+
+ float attention_mass_p() const noexcept {
+ return m_attention_mass_p;
+ }
+
+ // Feed attention scores back so SCORE eviction can pick the lowest-score block.
+ // scores is a flat [total_tokens] buffer matching out_scores layout.
+ void update_attention_scores(std::uintptr_t node_key,
+ const float* scores,
+ std::size_t scores_len,
+ const std::int32_t* past_lens,
+ std::size_t seq_count);
+
+ // Feed the 2D diversity matrix so ADAPTIVE_RKV eviction can use it.
+ // diversity_matrix is row-major [num_blocks_in_zone, eviction_size].
+ void update_diversity_scores(std::uintptr_t node_key,
+ std::size_t seq_idx,
+ const float* diversity_matrix,
+ std::size_t num_blocks_in_zone,
+ std::size_t eviction_size,
+ std::size_t start_block_offset);
+
+private:
+ struct SequenceState {
+ std::int32_t logical_length = 0; // expected by external past_lens
+ std::int32_t trim_front = 0; // number of tokens trimmed from front (multiple of block_size)
+ std::deque<std::int32_t> blocks; // physical block IDs for [trim_front, trim_front + blocks*block_size)
+
+ // per-block attention scores (same order as blocks deque)
+ std::deque<float> block_scores;
+
+ // Raw diversity matrix [n_blocks, evict_size], refreshed each step.
+ std::vector<float> diversity_matrix;
+ std::size_t diversity_n_blocks = 0;
+ std::size_t diversity_evict_size = 0;
+ std::size_t diversity_start_block = 0; // block index offset in seq's deque
+ };
+
+ struct OperatorState {
+ // layout
+ std::size_t num_blocks = 0;
+ std::size_t block_size = 0;
+ std::size_t num_kv_heads = 0;
+ std::size_t key_head_size = 0;
+ std::size_t value_head_size = 0;
+
+ // bytes per block
+ std::size_t key_block_bytes = 0;
+ std::size_t value_block_bytes = 0;
+
+ // owned storage (copied once from init tensors)
+ ov::AlignedBuffer key_cache;
+ ov::AlignedBuffer value_cache;
+
+ // free list and per-seq state
+ std::vector<std::uint8_t> block_used; // 0/1
+ std::vector<std::int32_t> free_blocks; // stack
+ std::vector<SequenceState> sequences;
+ };
+
+ OperatorState& get_state(std::uintptr_t node_key);
+ const OperatorState& get_state(std::uintptr_t node_key) const;
+
+ static std::size_t tensor_byte_size(const ov::Shape& shape, std::size_t elem_bytes);
+
+ void init_sequences_from_block_tables(OperatorState& st,
+ const std::int32_t* block_indices,
+ std::size_t block_indices_count,
+ const std::int32_t* block_indices_begins,
+ std::size_t begins_count,
+ const std::int32_t* past_lens,
+ std::size_t past_lens_count);
+
+ std::int32_t allocate_block(OperatorState& st, std::size_t requester_seq);
+ std::int32_t steal_block_fifo(OperatorState& st, std::size_t requester_seq);
+ std::int32_t steal_block_by_score(OperatorState& st, std::size_t requester_seq);
+ std::int32_t steal_block_by_diversity(OperatorState& st, std::size_t requester_seq);
+ std::int32_t steal_block(OperatorState& st, std::size_t requester_seq);
+
+ static std::size_t elem_bytes_or_throw(ov::element::Type et);
+
+ static void validate_cache_rank4_or_throw(const ov::Shape& key_cache_shape, const ov::Shape& value_cache_shape);
+
+ static void parse_cache_layout_or_throw(OperatorState& st,
+ const ov::Shape& key_cache_shape,
+ const ov::Shape& value_cache_shape,
+ std::size_t elem_bytes);
+
+ template <typename T>
+ static void memcpy_typed(void* dst, const void* src, std::size_t count) {
+ std::memcpy(dst, src, count * sizeof(T));
+ }
+
+ // compute base pointers into internal storage
+ template <typename T>
+ static T* key_block_base(OperatorState& st, std::int32_t block_id, std::size_t kv_head) {
+ auto* base = static_cast<T*>(st.key_cache.get_ptr());
+ const std::size_t block_stride = st.num_kv_heads * st.block_size * st.key_head_size;
+ const std::size_t kv_stride = st.block_size * st.key_head_size;
+ return base + static_cast<std::size_t>(block_id) * block_stride + kv_head * kv_stride;
+ }
+
+ template <typename T>
+ static T* value_block_base(OperatorState& st, std::int32_t block_id, std::size_t kv_head) {
+ auto* base = static_cast<T*>(st.value_cache.get_ptr());
+ const std::size_t block_stride = st.num_kv_heads * st.block_size * st.value_head_size;
+ const std::size_t kv_stride = st.block_size * st.value_head_size;
+ return base + static_cast<std::size_t>(block_id) * block_stride + kv_head * kv_stride;
+ }
+
+ template <typename T>
+ static const T* key_block_base(const OperatorState& st, std::int32_t block_id, std::size_t kv_head) {
+ auto* base = static_cast<const T*>(st.key_cache.get_ptr());
+ const std::size_t block_stride = st.num_kv_heads * st.block_size * st.key_head_size;
+ const std::size_t kv_stride = st.block_size * st.key_head_size;
+ return base + static_cast<std::size_t>(block_id) * block_stride + kv_head * kv_stride;
+ }
+
+ template <typename T>
+ static const T* value_block_base(const OperatorState& st, std::int32_t block_id, std::size_t kv_head) {
+ auto* base = static_cast<const T*>(st.value_cache.get_ptr());
+ const std::size_t block_stride = st.num_kv_heads * st.block_size * st.value_head_size;
+ const std::size_t kv_stride = st.block_size * st.value_head_size;
+ return base + static_cast<std::size_t>(block_id) * block_stride + kv_head * kv_stride;
+ }
+
+private:
+ ov::element::Type m_elem_type;
+ EvictionPolicy m_policy;
+ std::size_t m_max_cache_bytes;
+ float m_attention_mass_p;
+ std::unordered_map<std::uintptr_t, OperatorState> m_ops;
+};
+
+// ---------------- template impl ----------------
+
+template <typename T>
+void PagedCacheManager::write_token_kv(std::uintptr_t node_key,
+ std::size_t seq_idx,
+ std::int32_t token_pos,
+ const T* key_row,
+ const T* value_row) {
+ auto& st = get_state(node_key);
+ if (seq_idx >= st.sequences.size()) {
+ OPENVINO_THROW("PagedCacheManager::write_token_kv: seq_idx out of range");
+ }
+
+ const auto addr = ensure_token(node_key, seq_idx, token_pos);
+ if (addr.block < 0) {
+ OPENVINO_THROW("PagedCacheManager::write_token_kv: failed to allocate block");
+ }
+
+ // Copy per-head key/value vectors into block storage.
+ for (std::size_t kvh = 0; kvh < st.num_kv_heads; ++kvh) {
+ T* kdst = key_block_base<T>(st, addr.block, kvh) + static_cast<std::size_t>(addr.offset) * st.key_head_size;
+ const T* ksrc = key_row + kvh * st.key_head_size;
+ std::memcpy(kdst, ksrc, st.key_head_size * sizeof(T));
+
+ T* vdst = value_block_base<T>(st, addr.block, kvh) + static_cast<std::size_t>(addr.offset) * st.value_head_size;
+ const T* vsrc = value_row + kvh * st.value_head_size;
+ std::memcpy(vdst, vsrc, st.value_head_size * sizeof(T));
+ }
+
+ // Maintains logical length
+ auto& seq = st.sequences[seq_idx];
+ if (token_pos >= seq.logical_length) {
+ seq.logical_length = token_pos + 1;
+ }
+}
+
+template <typename T>
+const T* PagedCacheManager::key_ptr(std::uintptr_t node_key, TokenAddress addr, std::size_t kv_head) const {
+ const auto& st = get_state(node_key);
+ if (addr.block < 0) {
+ return nullptr;
+ }
+ if (kv_head >= st.num_kv_heads) {
+ return nullptr;
+ }
+ const T* base = key_block_base<T>(st, addr.block, kv_head);
+ return base + static_cast<std::size_t>(addr.offset) * st.key_head_size;
+}
+
+template <typename T>
+const T* PagedCacheManager::value_ptr(std::uintptr_t node_key, TokenAddress addr, std::size_t kv_head) const {
+ const auto& st = get_state(node_key);
+ if (addr.block < 0) {
+ return nullptr;
+ }
+ if (kv_head >= st.num_kv_heads) {
+ return nullptr;
+ }
+ const T* base = value_block_base<T>(st, addr.block, kv_head);
+ return base + static_cast<std::size_t>(addr.offset) * st.value_head_size;
+}
+
+} // namespace paged_attention_cache
+} // namespace reference
+} // namespace ov
diff --git a/src/core/reference/include/openvino/reference/utils/paged_cache_manager_helper.hpp b/src/core/reference/include/openvino/reference/utils/paged_cache_manager_helper.hpp
new file mode 100644
index 00000000000..8629602d717
--- /dev/null
+++ b/src/core/reference/include/openvino/reference/utils/paged_cache_manager_helper.hpp
@@ -0,0 +1,53 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// Helpers to attach/retrieve a PagedCacheManager handle on PA nodes via rt_info.
+
+#pragma once
+
+#include <memory>
+
+#include "openvino/core/node.hpp"
+#include "openvino/reference/utils/paged_cache_manager.hpp"
+
+namespace ov {
+namespace reference {
+namespace paged_attention_cache {
+
+/// rt_info key for the cache manager handle.
+inline constexpr const char* CACHE_MANAGER_RT_INFO_KEY = "__paged_cache_manager";
+
+using CacheManagerHandle = std::shared_ptr<void>;
+
+/// Create a type-erased PagedCacheManager handle.
+inline CacheManagerHandle make_cache_handle(ov::element::Type et) {
+ auto* mgr = new PagedCacheManager(et);
+ return CacheManagerHandle(static_cast<void*>(mgr), [](void* p) {
+ delete static_cast<PagedCacheManager*>(p);
+ });
+}
+
+/// Store a cache manager handle on a node.
+inline void set_cache_manager(ov::Node* node, CacheManagerHandle handle) {
+ node->get_rt_info()[CACHE_MANAGER_RT_INFO_KEY] = std::move(handle);
+}
+
+/// Get the cache manager handle from a node, or nullptr if none.
+inline CacheManagerHandle get_cache_manager(const ov::Node* node) {
+ auto& rt = node->get_rt_info();
+ auto it = rt.find(CACHE_MANAGER_RT_INFO_KEY);
+ if (it == rt.end()) {
+ return nullptr;
+ }
+ return it->second.as<CacheManagerHandle>();
+}
+
+/// Get the concrete PagedCacheManager pointer, or nullptr.
+inline PagedCacheManager* get_cache_manager_ptr(const ov::Node* node) {
+ auto h = get_cache_manager(node);
+ return h ? static_cast<PagedCacheManager*>(h.get()) : nullptr;
+}
+
+} // namespace paged_attention_cache
+} // namespace reference
+} // namespace ov
diff --git a/src/core/reference/src/op/utils/paged_cache_manager.cpp b/src/core/reference/src/op/utils/paged_cache_manager.cpp
new file mode 100644
index 00000000000..57444dcbf2f
--- /dev/null
+++ b/src/core/reference/src/op/utils/paged_cache_manager.cpp
@@ -0,0 +1,661 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/reference/utils/paged_cache_manager.hpp"
+
+#include <algorithm>
+#include <cstring>
+#include <limits>
+
+#include "openvino/core/except.hpp"
+
+namespace ov {
+namespace reference {
+namespace paged_attention_cache {
+
+namespace {
+inline std::size_t safe_mul(std::size_t a, std::size_t b) {
+ if (a == 0 || b == 0) {
+ return 0;
+ }
+ if (a > (std::numeric_limits<std::size_t>::max() / b)) {
+ OPENVINO_THROW("PagedCacheManager: tensor size overflow");
+ }
+ return a * b;
+}
+} // namespace
+
+PagedCacheManager::PagedCacheManager(ov::element::Type elem_type,
+ EvictionPolicy policy,
+ std::size_t max_cache_bytes,
+ float attention_mass_p)
+ : m_elem_type(elem_type),
+ m_policy(policy),
+ m_max_cache_bytes(max_cache_bytes),
+ m_attention_mass_p(attention_mass_p) {}
+
+std::size_t PagedCacheManager::elem_bytes_or_throw(ov::element::Type et) {
+ const auto sz = et.size();
+ if (sz == 0) {
+ OPENVINO_THROW("PagedCacheManager: unsupported element type for cache");
+ }
+ return sz;
+}
+
+void PagedCacheManager::validate_cache_rank4_or_throw(const ov::Shape& key_cache_shape,
+ const ov::Shape& value_cache_shape) {
+ if (key_cache_shape.size() != 4 || value_cache_shape.size() != 4) {
+ OPENVINO_THROW("PagedCacheManager: reference cache manager expects key_cache/value_cache rank 4 ",
+ "[num_blocks, num_kv_heads, block_size, head_size]. Got ranks ",
+ key_cache_shape.size(),
+ " and ",
+ value_cache_shape.size());
+ }
+}
+
+std::size_t PagedCacheManager::tensor_byte_size(const ov::Shape& shape, std::size_t elem_bytes) {
+ std::size_t prod = 1;
+ for (const auto d : shape) {
+ prod = safe_mul(prod, static_cast<std::size_t>(d));
+ }
+ return safe_mul(prod, elem_bytes);
+}
+
+void PagedCacheManager::parse_cache_layout_or_throw(OperatorState& st,
+ const ov::Shape& key_cache_shape,
+ const ov::Shape& value_cache_shape,
+ std::size_t elem_bytes) {
+ validate_cache_rank4_or_throw(key_cache_shape, value_cache_shape);
+
+ st.num_blocks = static_cast<std::size_t>(key_cache_shape[0]);
+ st.num_kv_heads = static_cast<std::size_t>(key_cache_shape[1]);
+ st.block_size = static_cast<std::size_t>(key_cache_shape[2]);
+ st.key_head_size = static_cast<std::size_t>(key_cache_shape[3]);
+
+ if (value_cache_shape[0] != key_cache_shape[0] || value_cache_shape[1] != key_cache_shape[1] ||
+ value_cache_shape[2] != key_cache_shape[2]) {
+ OPENVINO_THROW("PagedCacheManager: key_cache and value_cache layout mismatch");
+ }
+ st.value_head_size = static_cast<std::size_t>(value_cache_shape[3]);
+
+ if (st.num_blocks == 0 || st.num_kv_heads == 0 || st.block_size == 0) {
+ OPENVINO_THROW("PagedCacheManager: cache shape has zero dimension");
+ }
+
+ st.key_block_bytes = safe_mul(safe_mul(st.num_kv_heads, st.block_size), safe_mul(st.key_head_size, elem_bytes));
+ st.value_block_bytes = safe_mul(safe_mul(st.num_kv_heads, st.block_size), safe_mul(st.value_head_size, elem_bytes));
+}
+
+PagedCacheManager::OperatorState& PagedCacheManager::get_state(std::uintptr_t node_key) {
+ auto it = m_ops.find(node_key);
+ if (it == m_ops.end()) {
+ OPENVINO_THROW("PagedCacheManager: operator state not found for node_key");
+ }
+ return it->second;
+}
+
+const PagedCacheManager::OperatorState& PagedCacheManager::get_state(std::uintptr_t node_key) const {
+ auto it = m_ops.find(node_key);
+ if (it == m_ops.end()) {
+ OPENVINO_THROW("PagedCacheManager: operator state not found for node_key");
+ }
+ return it->second;
+}
+
+void PagedCacheManager::init_sequences_from_block_tables(OperatorState& st,
+ const std::int32_t* block_indices,
+ std::size_t block_indices_count,
+ const std::int32_t* block_indices_begins,
+ std::size_t begins_count,
+ const std::int32_t* past_lens,
+ std::size_t past_lens_count) {
+ const std::size_t seq_count = past_lens_count;
+ st.sequences.assign(seq_count, SequenceState{});
+
+ // If no block tables were provided, initialize empty sequences
+ if (block_indices == nullptr || block_indices_begins == nullptr || begins_count != (seq_count + 1)) {
+ for (std::size_t s = 0; s < seq_count; ++s) {
+ st.sequences[s].logical_length = past_lens ? past_lens[s] : 0;
+ }
+ return;
+ }
+
+ // Fill per-sequence block lists based on provided tables
+ for (std::size_t s = 0; s < seq_count; ++s) {
+ const std::int32_t begin = block_indices_begins[s];
+ const std::int32_t end = block_indices_begins[s + 1];
+ if (begin < 0 || end < begin) {
+ continue;
+ }
+ const std::size_t ubegin = static_cast<std::size_t>(begin);
+ const std::size_t uend = static_cast<std::size_t>(end);
+ if (ubegin > block_indices_count || uend > block_indices_count) {
+ continue;
+ }
+
+ auto& seq = st.sequences[s];
+ seq.logical_length = past_lens ? past_lens[s] : 0;
+
+ for (std::size_t i = ubegin; i < uend; ++i) {
+ const std::int32_t bid = block_indices[i];
+ if (bid >= 0) {
+ seq.blocks.push_back(bid);
+ if (static_cast<std::size_t>(bid) < st.block_used.size()) {
+ st.block_used[static_cast<std::size_t>(bid)] = 1;
+ }
+ }
+ }
+
+ // Ensure trim_front is block-aligned and within logical length
+ seq.trim_front = 0;
+ }
+}
+
+std::int32_t PagedCacheManager::steal_block_fifo(OperatorState& st, std::size_t requester_seq) {
+ // Take the oldest block from the sequence with the most blocks
+ std::size_t best_seq = std::numeric_limits<std::size_t>::max();
+ std::size_t best_blocks = 0;
+
+ for (std::size_t s = 0; s < st.sequences.size(); ++s) {
+ if (s == requester_seq) {
+ // prefer not to steal from the requester if possible
+ continue;
+ }
+ const auto& seq = st.sequences[s];
+ if (seq.blocks.empty()) {
+ continue;
+ }
+ const std::size_t blocks = seq.blocks.size();
+ if (blocks > best_blocks) {
+ best_blocks = blocks;
+ best_seq = s;
+ }
+ }
+
+ if (best_seq == std::numeric_limits<std::size_t>::max()) {
+ // as a last resort, steal from the requester itself
+ best_seq = requester_seq;
+ }
+
+ auto& victim = st.sequences[best_seq];
+ if (victim.blocks.empty()) {
+ OPENVINO_THROW("PagedCacheManager: cannot steal a block (no victim blocks)");
+ }
+
+ const std::int32_t bid = victim.blocks.front();
+ victim.blocks.pop_front();
+ if (!victim.block_scores.empty()) {
+ victim.block_scores.pop_front();
+ }
+ victim.diversity_matrix.clear();
+ victim.diversity_n_blocks = 0;
+ victim.trim_front += static_cast<std::int32_t>(st.block_size);
+ return bid;
+}
+
+std::int32_t PagedCacheManager::steal_block_by_score(OperatorState& st, std::size_t requester_seq) {
+ // Evict the front block with the lowest attention score.
+ // Falls back to FIFO if no scores have been recorded yet.
+ std::size_t best_seq = std::numeric_limits<std::size_t>::max();
+ float best_score = std::numeric_limits<float>::max();
+ bool found_any = false;
+
+ for (std::size_t s = 0; s < st.sequences.size(); ++s) {
+ auto& seq = st.sequences[s];
+ if (seq.blocks.empty() || seq.block_scores.empty()) {
+ continue;
+ }
+ float penalty = (s == requester_seq) ? 1e12f : 0.f;
+ float score = seq.block_scores.front() + penalty;
+ if (score < best_score) {
+ best_score = score;
+ best_seq = s;
+ found_any = true;
+ }
+ }
+
+ if (!found_any) {
+ // no scores recorded yet, fall back to FIFO
+ return steal_block_fifo(st, requester_seq);
+ }
+
+ auto& victim = st.sequences[best_seq];
+ const std::int32_t bid = victim.blocks.front();
+ victim.blocks.pop_front();
+ if (!victim.block_scores.empty()) {
+ victim.block_scores.pop_front();
+ }
+ victim.diversity_matrix.clear();
+ victim.diversity_n_blocks = 0;
+ victim.trim_front += static_cast<std::int32_t>(st.block_size);
+ return bid;
+}
+
+std::int32_t PagedCacheManager::steal_block_by_diversity(OperatorState& st, std::size_t requester_seq) {
+ // Adaptive R-KV eviction: use attention-mass gating + diversity scores
+ // to pick the least important non-retained front block.
+ // Falls back to score eviction if no diversity data was fed.
+
+ struct Candidate {
+ std::size_t seq;
+ float filtered_div;
+ };
+ std::vector<Candidate> candidates;
+
+ for (std::size_t s = 0; s < st.sequences.size(); ++s) {
+ auto& seq = st.sequences[s];
+ if (seq.blocks.empty()) {
+ continue;
+ }
+
+ // Need diversity matrix to participate
+ if (seq.diversity_matrix.empty() || seq.diversity_n_blocks == 0 || seq.diversity_evict_size == 0) {
+ continue;
+ }
+
+ // Attention-mass gating: find which blocks are "retained" (score >= p of total)
+ const std::size_t n_blks = seq.diversity_n_blocks;
+ const std::size_t evict_sz = seq.diversity_evict_size;
+ const std::size_t start_blk = seq.diversity_start_block;
+
+ // Gather per-block attention scores for the eviction zone
+ std::vector<std::pair<float, std::size_t>> scored_blocks; // (score, zone_index)
+ scored_blocks.reserve(n_blks);
+ for (std::size_t i = 0; i < n_blks; ++i) {
+ float sc = 0.f;
+ const std::size_t deque_idx = start_blk + i;
+ if (deque_idx < seq.block_scores.size()) {
+ sc = seq.block_scores[deque_idx];
+ }
+ scored_blocks.emplace_back(sc, i);
+ }
+
+ // Sort descending by score
+ std::sort(scored_blocks.begin(), scored_blocks.end(), [](const auto& a, const auto& b) {
+ return a.first > b.first;
+ });
+
+ // Greedily select blocks covering >= p fraction of total attention mass
+ float total_score = 0.f;
+ for (auto& sb : scored_blocks)
+ total_score += sb.first;
+ const float target = total_score * m_attention_mass_p;
+
+ std::vector<bool> retained(n_blks, false);
+ float cumsum = 0.f;
+ for (auto& sb : scored_blocks) {
+ if (cumsum >= target && target > 0.f)
+ break;
+ retained[sb.second] = true;
+ cumsum += sb.first;
+ }
+
+ // Check if front block is retained (skip if so)
+ bool front_is_retained = false;
+ if (start_blk == 0 && n_blks > 0) {
+ front_is_retained = retained[0];
+ }
+
+ // If the front block is retained (attention-important), skip this sequence
+ if (front_is_retained) {
+ continue;
+ }
+
+ // Compute filtered diversity for the front block (mean over retained columns)
+ float div_score = 0.f;
+ if (start_blk == 0 && n_blks > 0) {
+ // Front block is zone block 0; its row is diversity_matrix[0, :].
+ // Mean over columns corresponding to retained blocks' tokens only
+ float sum = 0.f;
+ std::size_t count = 0;
+ for (std::size_t bi = 0; bi < n_blks; ++bi) {
+ if (!retained[bi])
+ continue;
+ // Columns for block bi: [bi * block_size, (bi+1) * block_size)
+ const std::size_t col_start = bi * st.block_size;
+ const std::size_t col_end = std::min(col_start + st.block_size, evict_sz);
+ for (std::size_t c = col_start; c < col_end; ++c) {
+ if (c < evict_sz) {
+ sum += seq.diversity_matrix[0 * evict_sz + c];
+ count++;
+ }
+ }
+ }
+ div_score = (count > 0) ? (sum / static_cast<float>(count)) : 0.f;
+ }
+
+ float penalty = (s == requester_seq) ? 1e12f : 0.f;
+ candidates.push_back({s, div_score + penalty});
+ }
+
+ if (candidates.empty()) {
+ // no diversity data available, fall back to score eviction
+ return steal_block_by_score(st, requester_seq);
+ }
+
+ // Pick candidate with lowest filtered diversity
+ std::size_t best_seq = candidates[0].seq;
+ float best_div = candidates[0].filtered_div;
+ for (std::size_t i = 1; i < candidates.size(); ++i) {
+ if (candidates[i].filtered_div < best_div) {
+ best_div = candidates[i].filtered_div;
+ best_seq = candidates[i].seq;
+ }
+ }
+
+ auto& victim = st.sequences[best_seq];
+ const std::int32_t bid = victim.blocks.front();
+ victim.blocks.pop_front();
+ if (!victim.block_scores.empty()) {
+ victim.block_scores.pop_front();
+ }
+ victim.diversity_matrix.clear();
+ victim.diversity_n_blocks = 0;
+ victim.trim_front += static_cast<std::int32_t>(st.block_size);
+ return bid;
+}
+
+std::int32_t PagedCacheManager::steal_block(OperatorState& st, std::size_t requester_seq) {
+ switch (m_policy) {
+ case EvictionPolicy::SCORE:
+ return steal_block_by_score(st, requester_seq);
+ case EvictionPolicy::ADAPTIVE_RKV:
+ return steal_block_by_diversity(st, requester_seq);
+ case EvictionPolicy::FIFO:
+ default:
+ return steal_block_fifo(st, requester_seq);
+ }
+}
+
+std::int32_t PagedCacheManager::allocate_block(OperatorState& st, std::size_t requester_seq) {
+ if (m_max_cache_bytes > 0) {
+ const std::size_t bytes_per_block = st.key_block_bytes + st.value_block_bytes;
+ const std::size_t max_blocks =
+ (bytes_per_block > 0) ? std::max<std::size_t>(1, m_max_cache_bytes / bytes_per_block) : st.num_blocks;
+ const std::size_t active = st.num_blocks - st.free_blocks.size();
+ if (active >= max_blocks) {
+ return steal_block(st, requester_seq);
+ }
+ }
+
+ if (!st.free_blocks.empty()) {
+ const std::int32_t bid = st.free_blocks.back();
+ st.free_blocks.pop_back();
+ if (bid >= 0 && static_cast<std::size_t>(bid) < st.block_used.size()) {
+ st.block_used[static_cast<std::size_t>(bid)] = 1;
+ }
+ return bid;
+ }
+ // No free blocks left: evict one block from a victim sequence
+ return steal_block(st, requester_seq);
+}
+
+bool PagedCacheManager::ensure_operator(std::uintptr_t node_key,
+ const void* key_cache_init,
+ const void* value_cache_init,
+ const ov::Shape& key_cache_shape,
+ const ov::Shape& value_cache_shape,
+ const std::int32_t* block_indices_init,
+ std::size_t block_indices_count,
+ const std::int32_t* block_indices_begins_init,
+ std::size_t block_indices_begins_count,
+ const std::int32_t* past_lens_init,
+ std::size_t past_lens_count) {
+ if (m_ops.find(node_key) != m_ops.end()) {
+ return false;
+ }
+
+ OperatorState st;
+ const std::size_t elem_bytes = elem_bytes_or_throw(m_elem_type);
+ parse_cache_layout_or_throw(st, key_cache_shape, value_cache_shape, elem_bytes);
+
+ // Allocate and copy initial cache tensors (once).
+ const std::size_t key_bytes = tensor_byte_size(key_cache_shape, elem_bytes);
+ const std::size_t value_bytes = tensor_byte_size(value_cache_shape, elem_bytes);
+ st.key_cache = ov::AlignedBuffer{key_bytes};
+ st.value_cache = ov::AlignedBuffer{value_bytes};
+
+ if (key_cache_init) {
+ std::memcpy(st.key_cache.get_ptr(), key_cache_init, key_bytes);
+ } else {
+ std::memset(st.key_cache.get_ptr(), 0, key_bytes);
+ }
+
+ if (value_cache_init) {
+ std::memcpy(st.value_cache.get_ptr(), value_cache_init, value_bytes);
+ } else {
+ std::memset(st.value_cache.get_ptr(), 0, value_bytes);
+ }
+
+ // Initialize free list and per-seq state
+ st.block_used.assign(st.num_blocks, 0);
+
+ init_sequences_from_block_tables(st,
+ block_indices_init,
+ block_indices_count,
+ block_indices_begins_init,
+ block_indices_begins_count,
+ past_lens_init,
+ past_lens_count);
+
+ // Build free block stack
+ st.free_blocks.reserve(st.num_blocks);
+ for (std::size_t b = 0; b < st.num_blocks; ++b) {
+ if (!st.block_used[b]) {
+ st.free_blocks.push_back(static_cast<std::int32_t>(b));
+ }
+ }
+
+ m_ops.emplace(node_key, std::move(st));
+ return true;
+}
+
+void PagedCacheManager::begin_step(std::uintptr_t node_key, const std::int32_t* past_lens, std::size_t seq_count) {
+ auto& st = get_state(node_key);
+ if (seq_count == 0) {
+ OPENVINO_THROW("PagedCacheManager::begin_step: seq_count is 0");
+ }
+ if (st.sequences.size() != seq_count) {
+ // For reference: allow resizing on first call (or if graph shape changes)
+ st.sequences.assign(seq_count, SequenceState{});
+ }
+
+ for (std::size_t s = 0; s < seq_count; ++s) {
+ const std::int32_t new_len = past_lens ? past_lens[s] : 0;
+ auto& seq = st.sequences[s];
+
+ // If the external timeline was reset/truncated, reset this sequence state
+ if (new_len < seq.logical_length) {
+ for (const std::int32_t bid : seq.blocks) {
+ if (bid >= 0 && static_cast<std::size_t>(bid) < st.num_blocks && st.block_used[bid]) {
+ st.block_used[bid] = 0;
+ st.free_blocks.push_back(bid);
+ }
+ }
+ seq.blocks.clear();
+ seq.block_scores.clear();
+ seq.diversity_matrix.clear();
+ seq.diversity_n_blocks = 0;
+ seq.diversity_evict_size = 0;
+ seq.diversity_start_block = 0;
+ seq.trim_front = 0;
+ seq.logical_length = new_len;
+ continue;
+ }
+
+ seq.logical_length = new_len;
+
+ // If past_lens exceeds retained blocks, the caller will append and ensure_token will allocate
+ if (seq.trim_front > seq.logical_length) {
+ seq.trim_front = std::max<std::int32_t>(0, seq.logical_length - (std::int32_t)(st.block_size));
+ seq.trim_front = (seq.trim_front / (std::int32_t)st.block_size) * (std::int32_t)st.block_size;
+ }
+ }
+}
+
+PagedCacheManager::TokenAddress PagedCacheManager::ensure_token(std::uintptr_t node_key,
+ std::size_t seq_idx,
+ std::int32_t token_pos) {
+ auto& st = get_state(node_key);
+ if (seq_idx >= st.sequences.size()) {
+ OPENVINO_THROW("PagedCacheManager::ensure_token: seq_idx out of range");
+ }
+
+ auto& seq = st.sequences[seq_idx];
+
+ if (token_pos < 0) {
+ OPENVINO_THROW("PagedCacheManager::ensure_token: token_pos is negative");
+ }
+
+ // If token_pos is behind the trimmed window, it cannot be represented
+ if (token_pos < seq.trim_front) {
+ return TokenAddress{-1, 0};
+ }
+
+ const std::int32_t bs = static_cast<std::int32_t>(st.block_size);
+ // Recompute relative position after any evictions that may have advanced trim_front
+ // This is needed because stealing from the requester's own front block shifts trim_front
+ auto recompute = [&]() -> std::pair<std::int32_t, std::int32_t> {
+ const std::int32_t r = token_pos - seq.trim_front;
+ const std::int32_t bi = (bs > 0) ? (r / bs) : 0;
+ return {bi, (bs > 0) ? (r % bs) : 0};
+ };
+
+ auto [block_index, off] = recompute();
+
+ // guard against infinite loops if the pool is too small for the requested position
+ std::size_t max_iters = st.num_blocks + 1;
+ while (seq.blocks.size() <= static_cast<std::size_t>(block_index) && max_iters-- > 0) {
+ const std::int32_t bid = allocate_block(st, seq_idx);
+ seq.blocks.push_back(bid);
+ // trim_front may have changed if we stole from ourselves
+ std::tie(block_index, off) = recompute();
+ }
+
+ if (seq.blocks.size() <= static_cast<std::size_t>(block_index)) {
+ return TokenAddress{-1, 0};
+ }
+
+ return TokenAddress{seq.blocks[static_cast<std::size_t>(block_index)], off};
+}
+
+bool PagedCacheManager::resolve_token(std::uintptr_t node_key,
+ std::size_t seq_idx,
+ std::int32_t token_pos,
+ TokenAddress& out_addr) const {
+ const auto& st = get_state(node_key);
+ if (seq_idx >= st.sequences.size()) {
+ return false;
+ }
+ const auto& seq = st.sequences[seq_idx];
+
+ if (token_pos < seq.trim_front || token_pos < 0 || token_pos >= seq.logical_length) {
+ return false;
+ }
+
+ const std::int32_t rel = token_pos - seq.trim_front;
+ const std::int32_t bs = static_cast<std::int32_t>(st.block_size);
+ if (bs <= 0) {
+ return false;
+ }
+
+ const std::int32_t block_index = rel / bs;
+ const std::int32_t off = rel % bs;
+
+ if (block_index < 0 || static_cast<std::size_t>(block_index) >= seq.blocks.size()) {
+ return false;
+ }
+
+ out_addr.block = seq.blocks[static_cast<std::size_t>(block_index)];
+ out_addr.offset = off;
+ return out_addr.block >= 0;
+}
+
+std::size_t PagedCacheManager::num_blocks(std::uintptr_t node_key) const {
+ return get_state(node_key).num_blocks;
+}
+
+std::size_t PagedCacheManager::block_size(std::uintptr_t node_key) const {
+ return get_state(node_key).block_size;
+}
+
+std::size_t PagedCacheManager::num_kv_heads(std::uintptr_t node_key) const {
+ return get_state(node_key).num_kv_heads;
+}
+
+std::size_t PagedCacheManager::key_head_size(std::uintptr_t node_key) const {
+ return get_state(node_key).key_head_size;
+}
+
+std::size_t PagedCacheManager::value_head_size(std::uintptr_t node_key) const {
+ return get_state(node_key).value_head_size;
+}
+
+void PagedCacheManager::update_attention_scores(std::uintptr_t node_key,
+ const float* scores,
+ std::size_t scores_len,
+ const std::int32_t* past_lens,
+ std::size_t seq_count) {
+ auto& st = get_state(node_key);
+ if (seq_count > st.sequences.size()) {
+ seq_count = st.sequences.size();
+ }
+ const std::int32_t bs = static_cast<std::int32_t>(st.block_size);
+ if (bs <= 0 || scores == nullptr || scores_len == 0) {
+ return;
+ }
+
+ // scores layout: flat [past_lens[0]+new_0, past_lens[1]+new_1, ...]
+ // accumulate per-token scores into per-block sums
+ std::size_t offset = 0;
+ for (std::size_t s = 0; s < seq_count; ++s) {
+ auto& seq = st.sequences[s];
+ const std::size_t total_len = (past_lens && s < seq_count) ? static_cast<std::size_t>(seq.logical_length) : 0;
+ if (total_len == 0 || seq.blocks.empty()) {
+ offset += total_len;
+ continue;
+ }
+
+ // make sure block_scores has the right size
+ seq.block_scores.resize(seq.blocks.size(), 0.f);
+
+ // accumulate per-token attention scores into per-block sums
+ for (std::size_t t = 0; t < total_len && (offset + t) < scores_len; ++t) {
+ const std::int32_t token_pos = static_cast<std::int32_t>(t);
+ if (token_pos < seq.trim_front) {
+ continue;
+ }
+ const std::int32_t rel = token_pos - seq.trim_front;
+ const std::size_t block_idx = static_cast<std::size_t>(rel / bs);
+ if (block_idx < seq.block_scores.size()) {
+ seq.block_scores[block_idx] += scores[offset + t];
+ }
+ }
+ offset += total_len;
+ }
+}
+
+void PagedCacheManager::update_diversity_scores(std::uintptr_t node_key,
+ std::size_t seq_idx,
+ const float* diversity_matrix,
+ std::size_t num_blocks_in_zone,
+ std::size_t eviction_size,
+ std::size_t start_block_offset) {
+ auto& st = get_state(node_key);
+ if (seq_idx >= st.sequences.size() || diversity_matrix == nullptr || num_blocks_in_zone == 0 ||
+ eviction_size == 0) {
+ return;
+ }
+
+ auto& seq = st.sequences[seq_idx];
+ const std::size_t total = num_blocks_in_zone * eviction_size;
+ seq.diversity_matrix.assign(diversity_matrix, diversity_matrix + total);
+ seq.diversity_n_blocks = num_blocks_in_zone;
+ seq.diversity_evict_size = eviction_size;
+ seq.diversity_start_block = start_block_offset;
+}
+
+} // namespace paged_attention_cache
+} // namespace reference
+} // namespace ov
diff --git a/src/core/shape_inference/include/paged_attention_shape_inference.hpp b/src/core/shape_inference/include/paged_attention_shape_inference.hpp
new file mode 100644
index 00000000000..d9d44afb428
--- /dev/null
+++ b/src/core/shape_inference/include/paged_attention_shape_inference.hpp
@@ -0,0 +1,98 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "dimension_util.hpp"
+#include "openvino/op/paged_attention.hpp"
+#include "utils.hpp"
+
+namespace ov {
+namespace op {
+template <class TShape, class TRShape = result_shape_t<TShape>>
+std::vector<TRShape> shape_infer(const PagedAttentionExtension* op,
+ const std::vector<TShape>& input_shapes,
+ const ITensorAccessor& ta = make_tensor_accessor()) {
+ NODE_VALIDATION_CHECK(op, input_shapes.size() == 28, "Expected 28 inputs but got ", input_shapes.size());
+ auto output_shapes = std::vector<TRShape>(3);
+
+ // Output[0] feature dim is num_heads * v_head_size.
+ // Derived as Q*V/K which cancels the shared Hkv*Dk.
+ auto out_ps = input_shapes[0];
+ const auto& key_ps = input_shapes[1];
+ const auto& value_ps = input_shapes[2];
+ const auto& past_lens_ps = input_shapes[5];
+ const auto& evictable_sizes_ps = input_shapes[22];
+
+ // Compute for output shape
+ if (out_ps.rank().is_static() && out_ps.rank().get_length() >= 2 && out_ps[1].is_static()) {
+ if (key_ps.rank().is_static() && key_ps.rank().get_length() >= 2 && key_ps[1].is_static() &&
+ value_ps.rank().is_static() && value_ps.rank().get_length() >= 2 && value_ps[1].is_static()) {
+ const auto q = out_ps[1].get_length();
+ const auto k = key_ps[1].get_length();
+ const auto v = value_ps[1].get_length();
+ NODE_VALIDATION_CHECK(op,
+ k != 0 && q * v % k == 0,
+ "Output feature dimension (q * v) must be divisible by the key "
+ "feature dimension (k); got q=",
+ q,
+ ", v=",
+ v,
+ ", k=",
+ k);
+ out_ps[1] = q * v / k;
+ NODE_VALIDATION_CHECK(op,
+ !ov::util::dim::is_empty(out_ps[1]),
+ "The last dimension of output should not be empty.");
+ } else {
+ out_ps[1] = Dimension::dynamic();
+ }
+ }
+ output_shapes[0] = out_ps;
+
+ auto& scores_ps = output_shapes[1];
+ // Compute for scores shape
+ if (past_lens_ps.rank().is_static() && key_ps.rank().is_static() && key_ps.rank().get_length() >= 1 &&
+ key_ps[0].is_static()) {
+ const auto& past_lens = get_input_const_data_as<TRShape, int32_t>(op, 5, ta);
+ if (past_lens.has_value()) {
+ const auto token_count = key_ps[0].get_length();
+ const auto past_sum = std::accumulate(past_lens.value().begin(), past_lens.value().end(), 0);
+ const auto computed_dim = token_count + past_sum;
+ scores_ps.push_back(computed_dim);
+ } else {
+ scores_ps.push_back(Dimension::dynamic());
+ }
+ } else {
+ scores_ps.push_back(Dimension::dynamic());
+ }
+
+ // Output[2]: flat 1D diversity scores.
+ // Size = sum(evictable_sizes[s]^2 / block_size); dynamic if unknown.
+ auto& diversity_ps = output_shapes[2];
+ auto width_dim = Dimension::dynamic();
+
+ const auto& key_cache_ps = input_shapes[3]; // [num_blocks, Hkv, block_size, S]
+ const bool block_size_known =
+ key_cache_ps.rank().is_static() && key_cache_ps.rank().get_length() >= 3 && key_cache_ps[2].is_static();
+
+ if (block_size_known && evictable_sizes_ps.rank().is_static() && evictable_sizes_ps.rank().get_length() == 1) {
+ const auto& evictable_sizes = get_input_const_data_as<TRShape, int32_t>(op, 22, ta);
+ if (evictable_sizes.has_value() && !evictable_sizes.value().empty()) {
+ const int64_t block_size = key_cache_ps[2].get_length();
+ int64_t total = 0;
+ for (const auto es : evictable_sizes.value()) {
+ total += static_cast<int64_t>(es) * static_cast<int64_t>(es) / block_size;
+ }
+ width_dim = total;
+ }
+ }
+
+ diversity_ps.push_back(width_dim);
+
+ return output_shapes;
+}
+
+} // namespace op
+} // namespace ov
diff --git a/src/core/src/op/paged_attention.cpp b/src/core/src/op/paged_attention.cpp
index d70d165c071..f941887bbed 100644
--- a/src/core/src/op/paged_attention.cpp
+++ b/src/core/src/op/paged_attention.cpp
@@ -8,12 +8,12 @@
#include "itt.hpp"
#include "openvino/core/validation_util.hpp"
#include "openvino/op/op.hpp"
+#include "paged_attention_shape_inference.hpp"
namespace {
-// Validates input rank and type for a node input.
-// We consider that dynamic rank/type are always valid case.
-// Empty {} means any rank/type
+// Validates input rank and type. Dynamic rank/type always passes.
+// Empty {} means any rank/type.
inline void input_check(const ov::Node* node,
size_t idx,
const std::string_view input_name,
@@ -31,7 +31,7 @@ inline void input_check(const ov::Node* node,
};
auto type_check = [&](const Type& type) {
- auto it = std::find(allowed_types.begin(), allowed_types.end(), tp);
+ auto it = std::find(allowed_types.begin(), allowed_types.end(), type);
return type.is_dynamic() || allowed_types.empty() || it != allowed_types.end();
};
@@ -70,7 +70,6 @@ std::vector<ov::element::Type> get_real_types() {
namespace ov {
namespace op {
-
PagedAttentionExtension::PagedAttentionExtension(const ov::OutputVector& args) : ov::op::Op(args) {
constructor_validate_and_infer_types();
}
@@ -111,57 +110,31 @@ void PagedAttentionExtension::validate_and_infer_types() {
input_check(this, 23, "adaptive_rkv_diversity_block_set_indices", {1}, {element::i32});
input_check(this, 24, "adaptive_rkv_diversity_block_set_indices_begins", {1}, {element::i32});
input_check(this, 25, "token_type_ids", {1, 2}, {element::i32});
-
- // input to support query-query bias attention
input_check(this, 26, "qq_bias", {1}, {element::u8});
input_check(this, 27, "qq_bias_begins", {1}, {element::i32});
- // value head_size may be not same with key
- auto out_ps = get_input_partial_shape(0);
- const auto& key_ps = get_input_partial_shape(1);
- const auto& value_ps = get_input_partial_shape(2);
- if (out_ps.rank().is_static()) {
- if (key_ps.rank().is_static() && value_ps.rank().is_static() && key_ps[1].is_static()) {
- // The dim of out_ps[1] should be `num_heads * v_head_size`, it can be got from:
- // because:
- // q: query_ps[1] = num_heads * head_size
- // k: key_ps[1] = num_kv_heads * head_size
- // v: value_ps[1] = num_kv_heads * v_head_size
- // therefore:
- // q * v / k = (num_heads * head_size) * (num_kv_heads * v_head_size) /
- // (num_kv_heads * head_size) = num_heads * v_head_size
- out_ps[1] = out_ps[1] * value_ps[1] / key_ps[1].get_length();
- NODE_VALIDATION_CHECK(this,
- !ov::util::dim::is_empty(out_ps[1]),
- "The last dimension of output should not be empty.");
- } else {
- out_ps[1] = Dimension::dynamic();
- }
- }
- if (m_output_type[0].is_dynamic()) {
- set_output_type(0, get_input_element_type(0), out_ps);
- } else {
- set_output_type(0, m_output_type[0], out_ps);
- }
-
- if (m_output_type[1].is_dynamic()) {
- set_output_type(1, get_input_element_type(0), {Dimension::dynamic()});
- } else {
- set_output_type(1, m_output_type[1], {Dimension::dynamic()});
- }
- if (m_output_type[2].is_dynamic()) {
- set_output_type(2, get_input_element_type(0), {Dimension::dynamic()});
- } else {
- set_output_type(2, m_output_type[2], {Dimension::dynamic()});
+ const auto input_shapes = ov::util::get_node_input_partial_shapes(*this);
+ const auto output_shapes = shape_infer(this, input_shapes);
+ // Use m_output_type overrides when set, otherwise fall back to query type
+ for (int i = 0; i < 3; ++i) {
+ const auto et = m_output_type[i].is_dynamic() ? get_input_element_type(0) : m_output_type[i];
+ set_output_type(i, et, output_shapes[i]);
}
}
std::shared_ptr<ov::Node> PagedAttentionExtension::clone_with_new_inputs(const ov::OutputVector& new_args) const {
+ OV_OP_SCOPE(PagedAttentionExtension_clone_with_new_inputs);
+ check_new_args_count(this, new_args);
return std::make_shared<PagedAttentionExtension>(new_args);
}
+const ov::element::Type PagedAttentionExtension::get_out_type(int index) const {
+ OPENVINO_ASSERT(index < 3, "Output index should be 0, 1 or 2, but got " + std::to_string(index));
+ return m_output_type[index];
+}
+
void PagedAttentionExtension::set_out_type(int index, const ov::element::Type& output_type) {
- OPENVINO_ASSERT(index < 2, "Output index should be 0 or 1, but got " + std::to_string(index));
+ OPENVINO_ASSERT(index < 3, "Output index should be 0, 1 or 2, but got " + std::to_string(index));
m_output_type[index] = output_type;
}
diff --git a/src/core/tests/reference/paged_cache_manager.cpp b/src/core/tests/reference/paged_cache_manager.cpp
new file mode 100644
index 00000000000..3ecfd3bad0e
--- /dev/null
+++ b/src/core/tests/reference/paged_cache_manager.cpp
@@ -0,0 +1,1567 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/reference/utils/paged_cache_manager.hpp"
+
+#include <gtest/gtest.h>
+
+#include <cmath>
+#include <cstring>
+#include <numeric>
+#include <vector>
+
+#include "openvino/reference/paged_attention.hpp"
+
+using namespace ov::reference::paged_attention_cache;
+
+namespace {
+
+// helper to build a zero-filled cache shape [num_blocks, kv_heads, block_size, head_size]
+struct CacheLayout {
+ std::size_t num_blocks;
+ std::size_t kv_heads;
+ std::size_t block_size;
+ std::size_t head_size;
+
+ ov::Shape shape() const {
+ return {num_blocks, kv_heads, block_size, head_size};
+ }
+ std::size_t elems() const {
+ return num_blocks * kv_heads * block_size * head_size;
+ }
+};
+
+// shorthand node key
+// it is a random value that pretends to be a PagedAttention operator ID
+constexpr std::uintptr_t NODE = 67;
+
+// register a simple operator state and return the manager
+std::unique_ptr<PagedCacheManager> make_manager(CacheLayout layout,
+ EvictionPolicy policy,
+ std::vector<float>& key_data,
+ std::vector<float>& val_data,
+ std::size_t seq_count = 1) {
+ key_data.assign(layout.elems(), 0.f);
+ val_data.assign(layout.elems(), 0.f);
+
+ auto mgr = std::make_unique<PagedCacheManager>(ov::element::f32, policy, /*max_cache_bytes=*/0);
+
+ // initial past_lens = 0 for each sequence
+ std::vector<std::int32_t> past(seq_count, 0);
+ // no initial block indices
+ mgr->ensure_operator(NODE,
+ key_data.data(),
+ val_data.data(),
+ layout.shape(),
+ layout.shape(),
+ nullptr,
+ 0,
+ nullptr,
+ 0,
+ past.data(),
+ seq_count);
+ return mgr;
+}
+
+} // namespace
+
+// Basic lifecycle: register, begin_step, ensure_token, resolve_token
+TEST(PagedCacheManagerTest, BasicAllocateAndResolve) {
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::FIFO, kd, vd);
+
+ std::int32_t past = 0;
+ mgr->begin_step(NODE, &past, 1);
+
+ // write a token at position 0
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 1.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 2.f);
+ mgr->write_token_kv<float>(NODE, 0, 0, krow.data(), vrow.data());
+
+ // resolve it
+ PagedCacheManager::TokenAddress addr;
+ ASSERT_TRUE(mgr->resolve_token(NODE, 0, 0, addr));
+ EXPECT_GE(addr.block, 0);
+
+ // read back key data
+ const float* kp = mgr->key_ptr<float>(NODE, addr, 0);
+ ASSERT_NE(kp, nullptr);
+ EXPECT_FLOAT_EQ(kp[0], 1.f);
+
+ // read back value data
+ const float* vp = mgr->value_ptr<float>(NODE, addr, 0);
+ ASSERT_NE(vp, nullptr);
+ EXPECT_FLOAT_EQ(vp[0], 2.f);
+}
+
+// FIFO eviction: fills all blocks then forces eviction from oldest
+TEST(PagedCacheManagerTest, FIFOEvictionWorks) {
+ // 4 blocks, block_size=2 -> can hold 8 tokens total
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::FIFO, kd, vd, 2);
+
+ EXPECT_EQ(mgr->eviction_policy(), EvictionPolicy::FIFO);
+
+ // fill seq 0 with 6 tokens (3 blocks)
+ std::int32_t past0 = 0;
+ std::int32_t past1 = 0;
+ std::int32_t pasts[2] = {past0, past1};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+ for (int t = 0; t < 6; t++) {
+ krow[0] = static_cast<float>(t + 100);
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ }
+
+ // fill seq 1 with 2 tokens (1 block) -> total 4 blocks used up
+ for (int t = 0; t < 2; t++) {
+ krow[0] = static_cast<float>(t + 200);
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+ }
+
+ // now all 4 blocks are used, write one more token for seq 1 which needs a new block
+ // this should evict the oldest block from seq 0 (the longest)
+ krow[0] = 999.f;
+ mgr->write_token_kv<float>(NODE, 1, 2, krow.data(), vrow.data());
+
+ // seq 0 tokens 0 and 1 (the first block) should be evicted
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr));
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 1, addr));
+
+ // seq 0 tokens 2-5 should still be accessible
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 2, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 5, addr));
+
+ // seq 1 token 2 should be accessible (the new one)
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 2, addr));
+ const float* kp = mgr->key_ptr<float>(NODE, addr, 0);
+ ASSERT_NE(kp, nullptr);
+ EXPECT_FLOAT_EQ(kp[0], 999.f);
+}
+
+// SCORE eviction: picks the sequence whose front block has lowest score
+TEST(PagedCacheManagerTest, ScoreEvictionPicksLowestScoreFrontBlock) {
+ // 4 blocks, block_size=2, 1 head, head_size=4
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::SCORE, kd, vd, 2);
+
+ EXPECT_EQ(mgr->eviction_policy(), EvictionPolicy::SCORE);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+
+ // seq 0: 4 tokens -> 2 blocks
+ for (int t = 0; t < 4; t++) {
+ krow[0] = static_cast<float>(t);
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ }
+ // seq 1: 4 tokens -> 2 blocks, now all 4 blocks used
+ for (int t = 0; t < 4; t++) {
+ krow[0] = static_cast<float>(t + 10);
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+ }
+
+ // feed attention scores so that seq 0 front block has LOW score and seq 1 front block has HIGH score
+ // layout: [seq0_4_tokens, seq1_4_tokens]
+ pasts[0] = 4;
+ pasts[1] = 4;
+ // seq 0 block 0 tokens: 0.1 each -> front block score 0.2
+ // seq 0 block 1 tokens: 5.0 each -> block score 10.0
+ // seq 1 block 0 tokens: 3.0 each -> front block score 6.0
+ // seq 1 block 1 tokens: 3.0 each -> block score 6.0
+ std::vector<float> scores = {0.1f, 0.1f, 5.0f, 5.0f, 3.f, 3.f, 3.f, 3.f};
+ mgr->update_attention_scores(NODE, scores.data(), scores.size(), pasts, 2);
+
+ // force a new allocation for seq 1 which will trigger eviction
+ // should evict seq 0 front block (score 0.2) not seq 1 front block (score 6.0)
+ krow[0] = 777.f;
+ mgr->write_token_kv<float>(NODE, 1, 4, krow.data(), vrow.data());
+
+ // seq 0 tokens 0,1 should be evicted (front block of seq 0 had lowest score)
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr));
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 1, addr));
+
+ // seq 0 tokens 2,3 should survive
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 2, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 3, addr));
+
+ // all seq 1 tokens should be intact
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 0, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 3, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 4, addr));
+}
+
+// SCORE eviction falls back to FIFO when no scores are recorded
+TEST(PagedCacheManagerTest, ScoreEvictionFallsBackToFifo) {
+ // 4 blocks, block_size=2, 2 sequences
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::SCORE, kd, vd, 2);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+
+ // seq 0: 6 tokens -> 3 blocks
+ for (int t = 0; t < 6; t++) {
+ krow[0] = static_cast<float>(t);
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ }
+ // seq 1: 2 tokens -> 1 block, total 4 blocks used
+ for (int t = 0; t < 2; t++) {
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+ }
+
+ // no scores fed, force eviction by adding a 5th block for seq 1
+ krow[0] = 888.f;
+ mgr->write_token_kv<float>(NODE, 1, 2, krow.data(), vrow.data());
+
+ // FIFO fallback should evict oldest block from seq 0 (longest)
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr));
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 1, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 2, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 2, addr));
+}
+
+// ADAPTIVE_RKV eviction: evicts from the sequence whose front block is least diverse
+TEST(PagedCacheManagerTest, AdaptiveRKVEvictionPicksLeastDiverse) {
+ // 4 blocks, block_size=2, eviction_size=4 tokens
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::ADAPTIVE_RKV, kd, vd, 2);
+
+ EXPECT_EQ(mgr->eviction_policy(), EvictionPolicy::ADAPTIVE_RKV);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+
+ // seq 0: 4 tokens -> 2 blocks
+ for (int t = 0; t < 4; t++) {
+ krow[0] = static_cast<float>(t);
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ }
+ // seq 1: 4 tokens -> 2 blocks, all 4 blocks used
+ for (int t = 0; t < 4; t++) {
+ krow[0] = static_cast<float>(t + 10);
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+ }
+
+ // Feed attention scores: seq 0 block 1 is important, block 0 is not.
+ // seq 1 both blocks are equally important.
+ // scores layout: [seq0: 4 tokens][seq1: 4 tokens]
+ std::int32_t pasts_for_scores[2] = {4, 4};
+ // seq0: tok0 tok1 tok2 tok3 seq1: tok0 tok1 tok2 tok3
+ float scores[8] = {0.1f, 0.1f, 5.0f, 5.0f, 2.0f, 2.0f, 2.0f, 2.0f};
+ mgr->update_attention_scores(NODE, scores, 8, pasts_for_scores, 2);
+
+ // Feed 2D diversity matrices [2 blocks, 4 tokens].
+ // seq 0: front block row has low diversity to retained set
+ // seq 1: front block row has high diversity
+ // eviction_size = 4 (2 blocks * 2 tokens/block)
+ float div0[8] = {// block 0 row: diversity to each of the 4 tokens
+ 0.1f,
+ 0.1f,
+ 0.1f,
+ 0.1f,
+ // block 1 row:
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f};
+ float div1[8] = {// block 0 row:
+ 3.0f,
+ 3.0f,
+ 3.0f,
+ 3.0f,
+ // block 1 row:
+ 3.0f,
+ 3.0f,
+ 3.0f,
+ 3.0f};
+ mgr->update_diversity_scores(NODE, 0, div0, 2, 4, 0);
+ mgr->update_diversity_scores(NODE, 1, div1, 2, 4, 0);
+
+ // force eviction by writing token 4 for seq 1
+ krow[0] = 666.f;
+ mgr->write_token_kv<float>(NODE, 1, 4, krow.data(), vrow.data());
+
+ // seq 0 front block (tokens 0,1) should be evicted:
+ // - seq 0 block 0 has low attention (0.2 total), low diversity (0.1)
+ // - seq 1 block 0 has moderate attention (4.0), moderate diversity (3.0)
+ // With attention-mass gating (p=0.9), seq 0's block 1 (score 10.0) covers 98%+ of
+ // attention mass, so block 0 is NOT retained -> eligible for eviction.
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr));
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 1, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 2, addr)); // block 1 survived
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 0, addr)); // seq 1 intact
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 4, addr)); // new token accessible
+}
+
+// ADAPTIVE_RKV falls back to SCORE then FIFO if no diversity data
+TEST(PagedCacheManagerTest, AdaptiveRKVFallsBackToScoreThenFifo) {
+ // 4 blocks, 2 sequences
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::ADAPTIVE_RKV, kd, vd, 2);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+
+ // seq 0: 6 tokens -> 3 blocks
+ for (int t = 0; t < 6; t++) {
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ }
+ // seq 1: 2 tokens -> 1 block, total 4 blocks
+ for (int t = 0; t < 2; t++) {
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+ }
+
+ // no diversity, no scores -> should fall all the way back to FIFO
+ krow[0] = 111.f;
+ mgr->write_token_kv<float>(NODE, 1, 2, krow.data(), vrow.data());
+
+ // FIFO should evict from seq 0 (longest)
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 2, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 2, addr));
+}
+
+// Sequence reset clears blocks and score/diversity state
+TEST(PagedCacheManagerTest, SequenceResetClearsState) {
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::SCORE, kd, vd, 1);
+
+ std::int32_t past = 0;
+ mgr->begin_step(NODE, &past, 1);
+
+ std::vector<float> krow(4, 1.f);
+ std::vector<float> vrow(4, 1.f);
+ for (int t = 0; t < 4; t++) {
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ }
+
+ // feed some scores
+ past = 4;
+ std::vector<float> scores = {1.f, 2.f, 3.f, 4.f};
+ mgr->update_attention_scores(NODE, scores.data(), scores.size(), &past, 1);
+
+ // reset the sequence by setting past_lens to 0
+ past = 0;
+ mgr->begin_step(NODE, &past, 1);
+
+ // all old tokens should be gone
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr));
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 3, addr));
+
+ // should be able to write new tokens without issues (blocks were freed)
+ mgr->write_token_kv<float>(NODE, 0, 0, krow.data(), vrow.data());
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 0, addr));
+}
+
+// Multiple evictions in a row dont corrupt memory
+TEST(PagedCacheManagerTest, RepeatedEvictionsNoCorruption) {
+ // small pool: 3 blocks of size 2
+ CacheLayout layout{3, 2, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::FIFO, kd, vd, 1);
+
+ std::int32_t past = 0;
+ mgr->begin_step(NODE, &past, 1);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+
+ // write 20 tokens, which forces many evictions with only 3 blocks (6 token slots)
+ for (int t = 0; t < 20; t++) {
+ for (std::size_t j = 0; j < krow.size(); j++) {
+ krow[j] = static_cast<float>(t * 100 + j);
+ }
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ }
+
+ // only the last ~6 tokens should be resolvable (3 blocks * 2 tokens/block)
+ // earlier ones were evicted
+ PagedCacheManager::TokenAddress addr;
+ int resolvable = 0;
+ for (int t = 0; t < 20; t++) {
+ if (mgr->resolve_token(NODE, 0, t, addr)) {
+ resolvable++;
+ // check that we can read back the key data without crashing
+ const float* kp = mgr->key_ptr<float>(NODE, addr, 0);
+ ASSERT_NE(kp, nullptr);
+ EXPECT_FLOAT_EQ(kp[0], static_cast<float>(t * 100));
+ }
+ }
+
+ // we expect roughly 6 tokens to be resolvable (3 blocks * 2)
+ EXPECT_GE(resolvable, 4);
+ EXPECT_LE(resolvable, 8); // some slack for boundary effects
+}
+
+// max_cache_bytes triggers eviction before physical blocks run out
+TEST(PagedCacheManagerTest, MaxCacheBytesTriggersEviction) {
+ // 8 physical blocks, block_size=2, 1 kv head, head_size=4 (float=4B)
+ // key_block_bytes = value_block_bytes = 1*2*4*4 = 32 bytes
+ // bytes_per_block = 64 -> max_cache_bytes=192 allows 3 active blocks
+ CacheLayout layout{8, 1, 2, 4};
+ std::vector<float> kd(layout.elems(), 0.f);
+ std::vector<float> vd(layout.elems(), 0.f);
+
+ auto mgr = std::make_unique<PagedCacheManager>(ov::element::f32,
+ EvictionPolicy::FIFO,
+ /*max_cache_bytes=*/192);
+
+ std::vector<std::int32_t> past(2, 0);
+ mgr->ensure_operator(NODE,
+ kd.data(),
+ vd.data(),
+ layout.shape(),
+ layout.shape(),
+ nullptr,
+ 0,
+ nullptr,
+ 0,
+ past.data(),
+ 2);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+
+ // seq 0: 4 tokens -> 2 blocks
+ for (int t = 0; t < 4; t++) {
+ krow[0] = static_cast<float>(t + 100);
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ }
+
+ // seq 1: 2 tokens -> 1 block. Total 3 active blocks = budget limit
+ for (int t = 0; t < 2; t++) {
+ krow[0] = static_cast<float>(t + 200);
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+ }
+
+ // Writing one more token for seq 1 needs a 4th block, but budget allows only 3,
+ // so eviction fires even though 5 physical blocks are still free
+ krow[0] = 999.f;
+ mgr->write_token_kv<float>(NODE, 1, 2, krow.data(), vrow.data());
+
+ // FIFO evicts oldest block from longest sequence
+ // (seq 0 front block -> tokens 0,1)
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr));
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 1, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 2, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 3, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 2, addr));
+ const float* kp = mgr->key_ptr<float>(NODE, addr, 0);
+ ASSERT_NE(kp, nullptr);
+ EXPECT_FLOAT_EQ(kp[0], 999.f);
+}
+
+// Default constructor uses SCORE policy
+TEST(PagedCacheManagerTest, DefaultConstructorUsesScore) {
+ PagedCacheManager mgr(ov::element::f32);
+ EXPECT_EQ(mgr.eviction_policy(), EvictionPolicy::SCORE);
+}
+
+// Reference PA kernel with tiny cache forces eviction, no corruption
+TEST(PagedCacheManagerTest, ReferenceKernelEvictionNoCorruption) {
+ // minimal config: 1 kv head, head_size=4, block_size=2, only 3 blocks
+ // with 3 blocks we can hold 6 tokens, so a sequence of 8 forces eviction
+ const std::size_t num_blocks = 3;
+ const std::size_t kv_heads = 1;
+ const std::size_t blk_size = 2;
+ const std::size_t head_size = 4;
+ const std::size_t q_heads = 1;
+ const std::size_t q_features = q_heads * head_size;
+ const std::size_t kv_features = kv_heads * head_size;
+
+ // initial (empty) key and value caches
+ const std::size_t cache_elems = num_blocks * kv_heads * blk_size * head_size;
+ std::vector<float> key_cache(cache_elems, 0.f);
+ std::vector<float> val_cache(cache_elems, 0.f);
+ ov::Shape cache_shape = {num_blocks, kv_heads, blk_size, head_size};
+
+ // create a manager with SCORE policy
+ auto mgr = std::make_unique<PagedCacheManager>(ov::element::f32, EvictionPolicy::SCORE, 0);
+
+ // empty block indices for initial registration
+ std::vector<std::int32_t> block_idx = {0, 1, 2};
+ std::vector<std::int32_t> block_begins = {0, 3};
+
+ // run two steps: first step with 6 tokens (fills cache), second step with 2 more (forces eviction)
+ constexpr std::uintptr_t nk = 99;
+
+ // --- step 1: prompt with 6 tokens ---
+ const std::size_t step1_tokens = 6;
+ std::vector<float> q1(step1_tokens * q_features);
+ std::vector<float> k1(step1_tokens * kv_features);
+ std::vector<float> v1(step1_tokens * kv_features);
+ for (std::size_t i = 0; i < q1.size(); i++)
+ q1[i] = 0.1f * static_cast<float>(i + 1);
+ for (std::size_t i = 0; i < k1.size(); i++)
+ k1[i] = 0.2f * static_cast<float>(i + 1);
+ for (std::size_t i = 0; i < v1.size(); i++)
+ v1[i] = 0.3f * static_cast<float>(i + 1);
+
+ std::int32_t past1 = 0;
+ std::int32_t subseq1[2] = {0, static_cast<std::int32_t>(step1_tokens)};
+ float scale_val = 1.0f / std::sqrt(static_cast<float>(head_size));
+ std::int32_t score_window = 0;
+
+ std::vector<float> out1(step1_tokens * q_features, -999.f);
+
+ ov::reference::paged_attention<float>(nk,
+ mgr.get(),
+ out1.data(),
+ nullptr,
+ nullptr,
+ q1.data(),
+ k1.data(),
+ v1.data(),
+ key_cache.data(),
+ val_cache.data(),
+ &past1,
+ subseq1,
+ block_idx.data(),
+ block_idx.size(),
+ block_begins.data(),
+ block_begins.size(),
+ &scale_val,
+ ov::element::f32,
+ nullptr,
+ nullptr,
+ ov::element::Type{},
+ {},
+ nullptr,
+ &score_window,
+ 1,
+ nullptr,
+ 0,
+ nullptr,
+ {},
+ nullptr,
+ ov::element::Type{},
+ {},
+ nullptr,
+ ov::element::Type{},
+ nullptr,
+ nullptr,
+ nullptr,
+ ov::element::Type{},
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ {step1_tokens, q_features},
+ {step1_tokens, kv_features},
+ {step1_tokens, kv_features},
+ cache_shape,
+ cache_shape,
+ {1},
+ {2});
+
+ // check no NaN or inf in output
+ for (std::size_t i = 0; i < out1.size(); i++) {
+ EXPECT_TRUE(std::isfinite(out1[i])) << "step 1 output[" << i << "] is not finite";
+ }
+
+ // --- step 2: decode with 2 more tokens, forces eviction ---
+ const std::size_t step2_tokens = 2;
+ std::vector<float> q2(step2_tokens * q_features);
+ std::vector<float> k2(step2_tokens * kv_features);
+ std::vector<float> v2(step2_tokens * kv_features);
+ for (std::size_t i = 0; i < q2.size(); i++)
+ q2[i] = 0.4f * static_cast<float>(i + 1);
+ for (std::size_t i = 0; i < k2.size(); i++)
+ k2[i] = 0.5f * static_cast<float>(i + 1);
+ for (std::size_t i = 0; i < v2.size(); i++)
+ v2[i] = 0.6f * static_cast<float>(i + 1);
+
+ std::int32_t past2 = static_cast<std::int32_t>(step1_tokens);
+ std::int32_t subseq2[2] = {0, static_cast<std::int32_t>(step2_tokens)};
+
+ std::vector<float> out2(step2_tokens * q_features, -999.f);
+
+ ov::reference::paged_attention<float>(nk,
+ mgr.get(),
+ out2.data(),
+ nullptr,
+ nullptr,
+ q2.data(),
+ k2.data(),
+ v2.data(),
+ key_cache.data(),
+ val_cache.data(),
+ &past2,
+ subseq2,
+ block_idx.data(),
+ block_idx.size(),
+ block_begins.data(),
+ block_begins.size(),
+ &scale_val,
+ ov::element::f32,
+ nullptr,
+ nullptr,
+ ov::element::Type{},
+ {},
+ nullptr,
+ &score_window,
+ 1,
+ nullptr,
+ 0,
+ nullptr,
+ {},
+ nullptr,
+ ov::element::Type{},
+ {},
+ nullptr,
+ ov::element::Type{},
+ nullptr,
+ nullptr,
+ nullptr,
+ ov::element::Type{},
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ {step2_tokens, q_features},
+ {step2_tokens, kv_features},
+ {step2_tokens, kv_features},
+ cache_shape,
+ cache_shape,
+ {1},
+ {2});
+
+ // check no NaN, inf, or uninitialized values in output
+ for (std::size_t i = 0; i < out2.size(); i++) {
+ EXPECT_TRUE(std::isfinite(out2[i])) << "step 2 output[" << i << "] is not finite";
+ EXPECT_NE(out2[i], -999.f) << "step 2 output[" << i << "] was never written";
+ }
+}
+
+// ===================================================================
+// FIFO: additional coverage
+// ===================================================================
+
+// Single sequence forces self-eviction when no other victim exists
+TEST(PagedCacheManagerTest, FIFOStealsFromSelfAsLastResort) {
+ // 2 blocks, block_size=2, single sequence
+ CacheLayout layout{2, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::FIFO, kd, vd, 1);
+
+ std::int32_t past = 0;
+ mgr->begin_step(NODE, &past, 1);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+
+ // fill 2 blocks (4 tokens)
+ for (int t = 0; t < 4; t++) {
+ krow[0] = static_cast<float>(t + 1);
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ }
+
+ // writing token 4 forces self-eviction of front block
+ krow[0] = 50.f;
+ mgr->write_token_kv<float>(NODE, 0, 4, krow.data(), vrow.data());
+
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr));
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 1, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 2, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 4, addr));
+ const float* kp = mgr->key_ptr<float>(NODE, addr, 0);
+ ASSERT_NE(kp, nullptr);
+ EXPECT_FLOAT_EQ(kp[0], 50.f);
+}
+
+// Data integrity: surviving blocks retain correct key/value data after eviction
+TEST(PagedCacheManagerTest, FIFOEvictionPreservesSurvivingData) {
+ // 3 blocks, 2 kv_heads, block_size=2, head_size=4
+ CacheLayout layout{3, 2, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::FIFO, kd, vd, 1);
+
+ std::int32_t past = 0;
+ mgr->begin_step(NODE, &past, 1);
+
+ // write 6 tokens (fills 3 blocks), each with distinct per-head key values
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+ for (int t = 0; t < 6; t++) {
+ for (std::size_t j = 0; j < krow.size(); j++) {
+ krow[j] = static_cast<float>(t * 100 + j);
+ vrow[j] = static_cast<float>(t * 1000 + j);
+ }
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ }
+
+ // force eviction (front block tokens 0,1 evicted)
+ for (std::size_t j = 0; j < krow.size(); j++) {
+ krow[j] = static_cast<float>(6 * 100 + j);
+ vrow[j] = static_cast<float>(6 * 1000 + j);
+ }
+ mgr->write_token_kv<float>(NODE, 0, 6, krow.data(), vrow.data());
+
+ // verify surviving tokens 2-6 have correct data in both kv heads
+ for (int t = 2; t <= 6; t++) {
+ PagedCacheManager::TokenAddress addr;
+ ASSERT_TRUE(mgr->resolve_token(NODE, 0, t, addr)) << "token " << t;
+ for (std::size_t h = 0; h < 2; h++) {
+ const float* kp = mgr->key_ptr<float>(NODE, addr, h);
+ ASSERT_NE(kp, nullptr);
+ EXPECT_FLOAT_EQ(kp[0], static_cast<float>(t * 100 + h * layout.head_size))
+ << "key head " << h << " token " << t;
+
+ const float* vp = mgr->value_ptr<float>(NODE, addr, h);
+ ASSERT_NE(vp, nullptr);
+ EXPECT_FLOAT_EQ(vp[0], static_cast<float>(t * 1000 + h * layout.head_size))
+ << "value head " << h << " token " << t;
+ }
+ }
+}
+
+// FIFO with equal-length sequences picks non-requester
+TEST(PagedCacheManagerTest, FIFOEqualLengthPrefersNonRequester) {
+ // 4 blocks, block_size=2, 2 sequences each with 2 blocks
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::FIFO, kd, vd, 2);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+
+ // seq 0: 4 tokens -> 2 blocks
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ // seq 1: 4 tokens -> 2 blocks
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+
+ // seq 1 requests a new block -> evicts from seq 0 (non-requester)
+ mgr->write_token_kv<float>(NODE, 1, 4, krow.data(), vrow.data());
+
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr)); // seq 0 front evicted
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 2, addr)); // seq 0 back survived
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 0, addr)); // seq 1 intact
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 4, addr)); // new token ok
+}
+
+// Score eviction penalizes the requester sequence (prefers non-requester)
+TEST(PagedCacheManagerTest, ScoreEvictionPrefersNonRequester) {
+ // 4 blocks, 2 sequences. Seq 1 (the requester) has a much lower front-block score
+ // than seq 0, but the penalty should prevent self-eviction.
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::SCORE, kd, vd, 2);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+
+ // seq 0 front block has medium score, seq 1 front block has very low score
+ pasts[0] = 4;
+ pasts[1] = 4;
+ float scores[8] = {5.f, 5.f, 5.f, 5.f, 0.01f, 0.01f, 5.f, 5.f};
+ mgr->update_attention_scores(NODE, scores, 8, pasts, 2);
+
+ // seq 1 requests a new block. Without the penalty, seq 1's front block (0.02)
+ // would be evicted, but the 1e12 penalty makes seq 0 (10.0) the victim instead.
+ mgr->write_token_kv<float>(NODE, 1, 4, krow.data(), vrow.data());
+
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr)); // seq 0 front evicted
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 0, addr)); // seq 1 front preserved
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 4, addr));
+}
+
+// Score updates accumulate across multiple calls
+TEST(PagedCacheManagerTest, ScoreEvictionAccumulatesScores) {
+ // 4 blocks, 2 sequences.
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::SCORE, kd, vd, 2);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+
+ pasts[0] = 4;
+ pasts[1] = 4;
+
+ // First update: seq 0 front = 1.0, seq 1 front = 2.0
+ float scores1[8] = {0.5f, 0.5f, 1.f, 1.f, 1.0f, 1.0f, 1.f, 1.f};
+ mgr->update_attention_scores(NODE, scores1, 8, pasts, 2);
+ // Second update: add more to seq 0 front, making it 1.0 + 10.0 = 11.0
+ float scores2[8] = {5.0f, 5.0f, 0.f, 0.f, 0.0f, 0.0f, 0.f, 0.f};
+ mgr->update_attention_scores(NODE, scores2, 8, pasts, 2);
+
+ // Now seq 0 front = 11.0, seq 1 front = 2.0.
+ // Seq 0 requests the new block. SCORE penalizes requester (seq 0) by +1e12,
+ // so seq 1's front (2.0) < seq 0's penalized front (11 + 1e12) -> seq 1 evicted.
+ mgr->write_token_kv<float>(NODE, 0, 4, krow.data(), vrow.data());
+
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 0, addr)); // seq 0 front survived (requester, penalized)
+ EXPECT_FALSE(mgr->resolve_token(NODE, 1, 0, addr)); // seq 1 front evicted (2.0)
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 4, addr));
+}
+
+// Score eviction with single sequence (forced self-eviction via score)
+TEST(PagedCacheManagerTest, ScoreEvictionSingleSequenceSelfEvicts) {
+ CacheLayout layout{3, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::SCORE, kd, vd, 1);
+
+ std::int32_t past = 0;
+ mgr->begin_step(NODE, &past, 1);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+ for (int t = 0; t < 6; t++) {
+ krow[0] = static_cast<float>(t);
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ }
+
+ // feed scores: front block (tokens 0,1) has low score
+ past = 6;
+ float scores[6] = {0.1f, 0.1f, 5.0f, 5.0f, 5.0f, 5.0f};
+ mgr->update_attention_scores(NODE, scores, 6, &past, 1);
+
+ // force self-eviction
+ krow[0] = 99.f;
+ mgr->write_token_kv<float>(NODE, 0, 6, krow.data(), vrow.data());
+
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr));
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 1, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 2, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 6, addr));
+}
+
+// Attention-mass gating protects a front block that is highly attended
+TEST(PagedCacheManagerTest, AdaptiveRKVGatingProtectsRetainedFrontBlock) {
+ // 6 blocks, block_size=2, 3 sequences.
+ // Seq 0: front block has HIGH attention -> retained -> protected from eviction
+ // Seq 1: front block has LOW attention -> not retained -> eligible
+ // Seq 2: front block has LOW attention -> not retained -> eligible
+ // Expect seq 1 or 2 to be evicted (depending on diversity), not seq 0
+ CacheLayout layout{6, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::ADAPTIVE_RKV, kd, vd, 3);
+
+ std::int32_t pasts[3] = {0, 0, 0};
+ mgr->begin_step(NODE, pasts, 3);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+
+ // each seq: 4 tokens -> 2 blocks, total 6 blocks
+ for (int s = 0; s < 3; s++)
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, static_cast<std::size_t>(s), t, krow.data(), vrow.data());
+
+ // Attention scores: seq 0 front block is dominant (90% of mass)
+ std::int32_t pasts_s[3] = {4, 4, 4};
+ // seq 0: block0=9.0 block1=1.0 -> p=0.9, target=9.0, block0 alone covers it -> retained
+ // seq 1: block0=0.1 block1=9.9 -> target=9.0, block1 covers it -> block0 NOT retained
+ // seq 2: block0=0.1 block1=9.9 -> same as seq 1
+ float scores[12] = {4.5f, 4.5f, 0.5f, 0.5f, 0.05f, 0.05f, 4.95f, 4.95f, 0.05f, 0.05f, 4.95f, 4.95f};
+ mgr->update_attention_scores(NODE, scores, 12, pasts_s, 3);
+
+ // Diversity: seq 1 front has lower diversity than seq 2 front
+ float div0[8] = {5.f, 5.f, 5.f, 5.f, 5.f, 5.f, 5.f, 5.f};
+ float div1[8] = {0.1f, 0.1f, 0.1f, 0.1f, 5.f, 5.f, 5.f, 5.f};
+ float div2[8] = {3.f, 3.f, 3.f, 3.f, 5.f, 5.f, 5.f, 5.f};
+ mgr->update_diversity_scores(NODE, 0, div0, 2, 4, 0);
+ mgr->update_diversity_scores(NODE, 1, div1, 2, 4, 0);
+ mgr->update_diversity_scores(NODE, 2, div2, 2, 4, 0);
+
+ // force eviction from seq 2
+ mgr->write_token_kv<float>(NODE, 2, 4, krow.data(), vrow.data());
+
+ PagedCacheManager::TokenAddress addr;
+ // seq 0 must survive entirely (front block is retained by gating)
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 0, addr)) << "seq 0 front block should be protected";
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 2, addr));
+
+ // seq 1 front block should be evicted (lowest diversity among non-retained fronts)
+ EXPECT_FALSE(mgr->resolve_token(NODE, 1, 0, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 2, addr));
+
+ // seq 2 survived + new token
+ EXPECT_TRUE(mgr->resolve_token(NODE, 2, 0, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 2, 4, addr));
+}
+
+// When all front blocks are retained by gating, fall back to SCORE eviction
+TEST(PagedCacheManagerTest, AdaptiveRKVFallsBackToScoreWhenAllRetained) {
+ // 4 blocks, 2 sequences. Both front blocks have dominant attention -> both retained
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::ADAPTIVE_RKV, kd, vd, 2);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+
+ // Both front blocks carry the majority of attention mass
+ std::int32_t pasts_s[2] = {4, 4};
+ float scores[8] = {9.0f, 9.0f, 1.0f, 1.0f, 9.0f, 9.0f, 1.0f, 1.0f};
+ mgr->update_attention_scores(NODE, scores, 8, pasts_s, 2);
+
+ // Diversity data present, but both front blocks are retained by attention-mass gating
+ float div[8] = {0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f};
+ mgr->update_diversity_scores(NODE, 0, div, 2, 4, 0);
+ mgr->update_diversity_scores(NODE, 1, div, 2, 4, 0);
+
+ // force eviction from seq 1 (both candidates are empty -> falls back to SCORE)
+ // SCORE: seq 0 front=18.0, seq 1 front=18.0 (tied), but requester (seq 1) gets penalty
+ // -> seq 0 front block evicted
+ mgr->write_token_kv<float>(NODE, 1, 4, krow.data(), vrow.data());
+
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr)); // evicted via SCORE fallback
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 2, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 0, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 4, addr));
+}
+
+// Filtered column mean: only columns of retained blocks contribute to diversity score
+TEST(PagedCacheManagerTest, AdaptiveRKVFilteredColumnMean) {
+ // 6 blocks, block_size=2, 2 sequences
+ // 3 blocks per seq (6 tokens each), eviction_size = 6, eviction zone = 3 blocks
+ CacheLayout layout{6, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::ADAPTIVE_RKV, kd, vd, 2);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+ for (int t = 0; t < 6; t++)
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ for (int t = 0; t < 6; t++)
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+
+ // Attention scores: both seqs have low front block, high blocks 1,2
+ std::int32_t pasts_s[2] = {6, 6};
+ // seq 0: block0=0.2, block1=5.0, block2=5.0 -> target=9.18, blocks 1+2 (10.0) cover it
+ // seq 1: block0=0.2, block1=5.0, block2=5.0 -> same
+ float scores[12] = {0.1f, 0.1f, 2.5f, 2.5f, 2.5f, 2.5f, 0.1f, 0.1f, 2.5f, 2.5f, 2.5f, 2.5f};
+ mgr->update_attention_scores(NODE, scores, 12, pasts_s, 2);
+
+ // Diversity matrices [3 blocks, 6 tokens]:
+ // Seq 0 front-block row: high in retained columns (blocks 1,2), low in non-retained (block 0)
+ // tokens: [blk0:t0 blk0:t1 | blk1:t2 blk1:t3 | blk2:t4 blk2:t5]
+ // row 0: [0.0 0.0 | 10.0 10.0 | 10.0 10.0 ]
+ // filtered mean (only retained blk1,blk2 columns): mean(10,10,10,10) = 10.0
+ float div0[18] = {
+ 0.0f,
+ 0.0f,
+ 10.0f,
+ 10.0f,
+ 10.0f,
+ 10.0f, // block 0 row
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f, // block 1 row
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f, // block 2 row
+ };
+
+ // Seq 1 front-block row: low everywhere
+ // row 0: [0.0 0.0 | 1.0 1.0 | 1.0 1.0 ]
+ // filtered mean (retained blk1,blk2): mean(1,1,1,1) = 1.0
+ float div1[18] = {
+ 0.0f,
+ 0.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f,
+ 1.0f, // block 0 row
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f, // block 1 row
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f,
+ 5.0f, // block 2 row
+ };
+
+ mgr->update_diversity_scores(NODE, 0, div0, 3, 6, 0);
+ mgr->update_diversity_scores(NODE, 1, div1, 3, 6, 0);
+
+ // eviction via seq 0 requesting a new block
+ mgr->write_token_kv<float>(NODE, 0, 6, krow.data(), vrow.data());
+
+ // Seq 1 front block has filtered diversity 1.0 < seq 0's 10.0 -> seq 1 is evicted
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 0, addr)); // seq 0 front survived (div=10.0)
+ EXPECT_FALSE(mgr->resolve_token(NODE, 1, 0, addr)); // seq 1 front evicted (div=1.0)
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 2, addr)); // seq 1 back survived
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 6, addr)); // new token ok
+}
+
+// start_block_offset > 0: front block is before the eviction zone (in start area)
+TEST(PagedCacheManagerTest, AdaptiveRKVStartBlockOffset) {
+ // 6 blocks, block_size=2, 2 sequences × 3 blocks each.
+ // start_block_offset=1 means the eviction zone begins at block index 1, so the
+ // front block of each sequence (index 0) is in the "start area" and has no
+ // diversity row. It gets div_score=0 and is always evictable (not retained by
+ // the diversity data check)
+ CacheLayout layout{6, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::ADAPTIVE_RKV, kd, vd, 2);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+ for (int t = 0; t < 6; t++)
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ for (int t = 0; t < 6; t++)
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+
+ // Feed attention scores
+ std::int32_t pasts_s[2] = {6, 6};
+ // seq 0: low front
+ // seq 1: also low front
+ float scores[12] = {0.1f, 0.1f, 5.f, 5.f, 5.f, 5.f, 0.2f, 0.2f, 5.f, 5.f, 5.f, 5.f};
+ mgr->update_attention_scores(NODE, scores, 12, pasts_s, 2);
+
+ // Diversity covering blocks 1,2 (zone): 2 zone blocks, eviction_size=4, start_block_offset=1
+ // Since front block (deque index 0) is outside the zone (start_blk=1),
+ // start_blk > 0 -> front_is_retained=false and div_score defaults to 0
+ float div0[8] = {8.f, 8.f, 8.f, 8.f, 8.f, 8.f, 8.f, 8.f};
+ float div1[8] = {8.f, 8.f, 8.f, 8.f, 8.f, 8.f, 8.f, 8.f};
+ mgr->update_diversity_scores(NODE, 0, div0, 2, 4, /*start_block_offset=*/1);
+ mgr->update_diversity_scores(NODE, 1, div1, 2, 4, /*start_block_offset=*/1);
+
+ // Both front blocks get div_score=0, penalty differentiates.
+ // Requester (seq 0) gets +1e12 penalty -> seq 1 front block evicted
+ mgr->write_token_kv<float>(NODE, 0, 6, krow.data(), vrow.data());
+
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 0, addr));
+ EXPECT_FALSE(mgr->resolve_token(NODE, 1, 0, addr)); // seq 1 front evicted
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 2, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 6, addr));
+}
+
+// ADAPTIVE_RKV with scores but no diversity -> falls back to SCORE (not FIFO)
+TEST(PagedCacheManagerTest, AdaptiveRKVFallsBackToScoreWithScoresNoDiversity) {
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::ADAPTIVE_RKV, kd, vd, 2);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+
+ // Feed scores only (no diversity). Seq 0 front = 0.2, seq 1 front = 8.0
+ pasts[0] = 4;
+ pasts[1] = 4;
+ float scores[8] = {0.1f, 0.1f, 5.f, 5.f, 4.f, 4.f, 4.f, 4.f};
+ mgr->update_attention_scores(NODE, scores, 8, pasts, 2);
+
+ // diversity chain: no diversity data -> candidates empty -> fallback to steal_block_by_score
+ // SCORE picks seq 0 front (0.2) over seq 1 front (8.0)
+ mgr->write_token_kv<float>(NODE, 1, 4, krow.data(), vrow.data());
+
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr)); // seq 0 evicted by SCORE fallback
+ EXPECT_TRUE(mgr->resolve_token(NODE, 0, 2, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 0, addr));
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 4, addr));
+}
+
+// Diversity matrix is cleared after eviction, next eviction must use fresh data or fallback
+TEST(PagedCacheManagerTest, AdaptiveRKVDiversityClearedAfterEviction) {
+ CacheLayout layout{4, 1, 2, 4};
+ std::vector<float> kd, vd;
+ auto mgr = make_manager(layout, EvictionPolicy::ADAPTIVE_RKV, kd, vd, 2);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+
+ std::int32_t pasts_s[2] = {4, 4};
+ float scores[8] = {0.1f, 0.1f, 5.f, 5.f, 2.f, 2.f, 2.f, 2.f};
+ mgr->update_attention_scores(NODE, scores, 8, pasts_s, 2);
+
+ float div0[8] = {0.1f, 0.1f, 0.1f, 0.1f, 5.f, 5.f, 5.f, 5.f};
+ float div1[8] = {3.f, 3.f, 3.f, 3.f, 3.f, 3.f, 3.f, 3.f};
+ mgr->update_diversity_scores(NODE, 0, div0, 2, 4, 0);
+ mgr->update_diversity_scores(NODE, 1, div1, 2, 4, 0);
+
+ // First eviction: seq 0 front evicted (low diversity)
+ mgr->write_token_kv<float>(NODE, 1, 4, krow.data(), vrow.data());
+
+ PagedCacheManager::TokenAddress addr;
+ EXPECT_FALSE(mgr->resolve_token(NODE, 0, 0, addr));
+
+ // Diversity was cleared for the evicted seq. Now seq 0 has 1 block left, seq 1 has 3.
+ // Force another eviction without feeding new diversity.
+ // Since diversity_matrix was cleared, fallback to SCORE should kick in.
+ // Need to also update scores for the new arrangement
+ pasts_s[0] = 4; // logical length still 4
+ pasts_s[1] = 5;
+ // seq 0's remaining block (tokens 2,3) still has score 10.0 from before
+ // seq 1 has 3 blocks with scores. No new diversity -> SCORE fallback
+ mgr->write_token_kv<float>(NODE, 1, 5, krow.data(), vrow.data());
+
+ // Should not crash; some eviction should occur
+ EXPECT_TRUE(mgr->resolve_token(NODE, 1, 5, addr));
+}
+
+// Adaptive RKV cache eviction tests.
+// Verify attention_mass_p and pool_kernel behavior.
+
+// attention_mass_p controls what fraction of total attention mass
+// the retained set must cover. Higher p = more blocks retained.
+//
+// Setup: 4 blocks, block_size=2.
+// Seq 0 per-block scores: block0=1.0, block1=9.0 (total 10)
+// Seq 1 per-block scores: block0=4.9, block1=5.1 (total 10)
+//
+// With p=0.9 (target=9.0):
+// Seq 0: block1 alone (9.0) >= 9.0 -> block0 NOT retained (eligible)
+// Seq 1: block1 (5.1) < 9.0, need both -> block0 IS retained (protected)
+// Only seq 0 is a diversity candidate -> seq 0 front evicted
+//
+// With p=0.49 (target=4.9):
+// Seq 0: block1 (9.0) >= 4.9 -> block0 NOT retained (eligible)
+// Seq 1: block1 (5.1) >= 4.9 -> block0 NOT retained (eligible)
+// Both are candidates. Seq 0 is the requester (+1e12 penalty) -> seq 1 front evicted.
+TEST(PagedCacheManagerTest, AttentionMassPChangesRetentionThreshold) {
+ const CacheLayout layout{4, 1, 2, 4};
+ // per-token scores: seq0 blk0=1.0, blk1=9.0 | seq1 blk0=4.9, blk1=5.1
+ float scores[8] = {0.5f, 0.5f, 4.5f, 4.5f, 2.45f, 2.45f, 2.55f, 2.55f};
+ // diversity matrices (2 blocks x evict_size=4).
+ // div0 row 0: all 5.0 (seq 0 front-block filtered mean = 5.0)
+ // div1 row 0: all 0.1 (seq 1 front-block filtered mean = 0.1 regardless of retained column)
+ float div0[8] = {5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f};
+ float div1[8] = {0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f};
+
+ auto run = [&](float p) -> std::pair<bool, bool> /* <seq0_front_alive, seq1_front_alive> */ {
+ std::vector<float> kd(layout.elems(), 0.f);
+ std::vector<float> vd(layout.elems(), 0.f);
+ auto mgr = std::make_unique<PagedCacheManager>(ov::element::f32,
+ EvictionPolicy::ADAPTIVE_RKV,
+ /*max_cache_bytes=*/0,
+ /*attention_mass_p=*/p);
+ std::vector<std::int32_t> past_init(2, 0);
+ mgr->ensure_operator(NODE,
+ kd.data(),
+ vd.data(),
+ layout.shape(),
+ layout.shape(),
+ nullptr,
+ 0,
+ nullptr,
+ 0,
+ past_init.data(),
+ 2);
+
+ std::int32_t pasts[2] = {0, 0};
+ mgr->begin_step(NODE, pasts, 2);
+
+ std::vector<float> krow(layout.kv_heads * layout.head_size, 0.f);
+ std::vector<float> vrow(layout.kv_heads * layout.head_size, 0.f);
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 0, t, krow.data(), vrow.data());
+ for (int t = 0; t < 4; t++)
+ mgr->write_token_kv<float>(NODE, 1, t, krow.data(), vrow.data());
+
+ pasts[0] = 4;
+ pasts[1] = 4;
+ mgr->update_attention_scores(NODE, scores, 8, pasts, 2);
+ mgr->update_diversity_scores(NODE, 0, div0, 2, 4, 0);
+ mgr->update_diversity_scores(NODE, 1, div1, 2, 4, 0);
+
+ // seq 0 requests a new block, triggering eviction
+ mgr->write_token_kv<float>(NODE, 0, 4, krow.data(), vrow.data());
+
+ PagedCacheManager::TokenAddress addr;
+ bool s0 = mgr->resolve_token(NODE, 0, 0, addr);
+ bool s1 = mgr->resolve_token(NODE, 1, 0, addr);
+ return {s0, s1};
+ };
+
+ // p=0.9: seq 1 front retained (protected), only seq 0 eligible -> seq 0 front evicted
+ auto [s0_hi, s1_hi] = run(0.9f);
+ EXPECT_FALSE(s0_hi) << "p=0.9: seq 0 front should be evicted (only eligible candidate)";
+ EXPECT_TRUE(s1_hi) << "p=0.9: seq 1 front should be protected (retained by gating)";
+
+ // p=0.49: both fronts eligible; seq 0 penalized as requester -> seq 1 front evicted
+ auto [s0_lo, s1_lo] = run(0.49f);
+ EXPECT_TRUE(s0_lo) << "p=0.49: seq 0 front should survive (penalized as requester)";
+ EXPECT_FALSE(s1_lo) << "p=0.49: seq 1 front should be evicted (lower filtered diversity)";
+}
+
+// pool_kernel max-pool smoothing changes per-block scores and thus eviction order
+//
+// Scenario: 1 sequence, 3 blocks (block_size=2), with all scores concentrated on
+// a single spike token in block 0.
+// raw scores: [10, 0, 0, 0, 0, 0] -> block sums: [10, 0, 0]
+//
+// With pool_kernel=1 (no pooling): block 0 has score 10, blocks 1,2 have 0.
+// SCORE eviction evicts the lowest-score front block. After filling cache
+// and requesting a new block, the single-seq self-eviction targets the
+// lowest-score block. Block 0 = front; its score (10) is NOT the lowest.
+// The code pops the deque front regardless of which block is "best" to evict:
+// steal_block_by_score always evicts the front block of the victim sequence,
+// so at eviction time, it compares front-block scores across sequences.
+// With a single sequence, front block is the only candidate and is evicted
+// no matter what.
+//
+// Actual test strategy: 2 sequences, score spike in seq 0 block 0.
+// raw per-token scores: seq0=[10,0,0,0], seq1=[0.1,0.1,0.1,0.1]
+// Without pooling (pk=1): seq0 front=10, seq1 front=0.2 -> evicts seq1 front
+// With pooling (pk=3): max-pool spreads the spike from token 0 into token 1:
+// seq0 pooled = [10,10,0,0] -> block score = 20 (front block gets 10 extra)
+// seq1 pooled = [0.1,0.1,0.1,0.1] -> block score = 0.2 (mostly unchanged)
+// Again seq1 front < seq0 front -> evicts seq1 front. Same outcome.
+//
+// To make pool_kernel flip the outcome, we need a spike at the boundary between
+// blocks 0 and 1 that pooling pulls INTO block 0:
+// raw: seq0=[0,0.1, 0.1,10], seq1=[2,2, 2,2]
+// block sums without pooling: seq0_front=0.1, seq1_front=4.0
+// requester=seq0, penalty on seq0. seq1 front (4.0) < seq0 front (0.1+1e12)
+// -> seq1 front evicted
+//
+// With pk=5 (half_k=2): max-pool pulls seq0 token 3 spike (10) into tokens 1,2:
+// seq0 pooled = [0.1, 10, 10, 10] -> block0 sum = 10.1, block1 sum = 20
+// seq1 pooled = [2, 2, 2, 2] -> block0 sum = 4, block1 sum = 4
+// requester=seq0, penalty on seq0. seq1 front (4) < seq0 front (10.1+1e12)
+// -> seq1 front still evicted (same outcome - penalty dominates).
+//
+// Therefore: to observe a flip, the requesting sequence must NOT be the one
+// with the spike. Let seq 1 request, spike in seq 0.
+// raw: seq0=[0.1, 0.1, 0.1, 10], seq1=[3, 3, 3, 3]
+// Without pooling (pk=1):
+// seq0 block sums: front=0.2, back=10.1
+// seq1 block sums: front=6, back=6
+// Seq 1 is requester -> penalty on seq1. Victim is lowest un-penalized front.
+// seq0 front=0.2 < seq1 front=6+1e12 -> seq0 front evicted.
+//
+// With pk=5 (half_k=2): max-pool spreads token 3 (10) left:
+// seq0 pooled per-token = [0.1, 10, 10, 10] -> block0=10.1, block1=20
+// seq1 pooled per-token = [3, 3, 3, 3] -> block0=6, block1=6
+// seq0 front=10.1 > seq1 front=6.
+// Victim = min(seq0=10.1, seq1=6+1e12) = seq0 (10.1) -> seq0 front evicted.
+// Same outcome! The penalty (1e12) on the requester is so large that the non-
+// requester always wins unless both are equally penalized.
+//
+// Conclusion: Since steal_block_by_score adds +1e12 to the requester's front-block
+// score, the requester is NEVER evicted unless it's the only sequence. Pooling can
+// change the relative ordering only among non-requester sequences (or for single-
+// sequence self-eviction where there IS no penalty distinction).
+// To demonstrate pool_kernel's effect, use 3 sequences: one requester (penalized) and
+// two victims whose relative front-block scores flip when pooling is applied
+TEST(PagedCacheManagerTest, PoolKernelChangesEvictionVictimViaPA) {
+ // 6 blocks, block_size=2, 3 sequences × 2 blocks each.
+ // seq 0 (requester): uniform scores -> front=4.0 (always penalized, irrelevant)
+ // seq 1: spike at token 3 (block 1), front block is low without pooling but boosted with pooling
+ // seq 2: uniform moderate -> front=2.0 (stable)
+ //
+ // Without pooling (pk=1):
+ // seq1 front = 0.2, seq2 front = 2.0 -> seq1 front evicted
+ // With pooling (pk=3, half_k=1) the spike at token 3 spreads into token 2 (block 1):
+ // seq1 pooled = [0.1, max(0.1,0.1,10)=10, max(0.1,10,...)=10, 10]
+ // -> front block sum = 0.1 + 10 = 10.1
+ // seq2 pooled = [1, 1, 1, 1] -> front = 2.0
+ // Now seq2 front (2.0) < seq1 front (10.1) -> seq2 front evicted instead!
+ const std::size_t num_blocks = 6;
+ const std::size_t kv_heads = 1;
+ const std::size_t blk_size = 2;
+ const std::size_t head_size = 4;
+ const std::size_t q_heads = 1;
+ const std::size_t q_features = q_heads * head_size;
+ const std::size_t kv_features = kv_heads * head_size;
+ const std::size_t cache_elems = num_blocks * kv_heads * blk_size * head_size;
+ const ov::Shape cache_shape = {num_blocks, kv_heads, blk_size, head_size};
+
+ auto run = [&](std::size_t pk) -> std::tuple<bool, bool, bool> {
+ std::vector<float> key_cache(cache_elems, 0.f);
+ std::vector<float> val_cache(cache_elems, 0.f);
+
+ auto mgr = std::make_unique<PagedCacheManager>(ov::element::f32,
+ EvictionPolicy::SCORE,
+ /*max_cache_bytes=*/0);
+ constexpr std::uintptr_t nk = 123;
+
+ // Step 1: prompt with 4 tokens per sequence (12 total), fills all 6 blocks
+ const std::size_t tokens = 12;
+ std::vector<float> q(tokens * q_features, 0.f);
+ std::vector<float> k(tokens * kv_features, 0.f);
+ std::vector<float> v(tokens * kv_features, 0.f);
+
+ // Give each key token a distinct direction so attention weights form a pattern.
+ // We want: per-sequence accumulated scores ~ [0.1, 0.1, 0.1, 10] for seq 1
+ // [1, 1, 1, 1] for seq 0 and seq 2.
+ // Easiest: make query for each token point in direction matching its own key,
+ // so self-attention is dominant. Then the "spike" token in seq 1 will have
+ // high attention from itself.
+ //
+ // Actually, to control raw per-token scores precisely, we'd need to engineer
+ // Q/K values carefully. Instead, let's test the pooling path indirectly:
+ // just run the PA kernel with pk=1 and pk=3, feed the SAME Q/K/V, and verify
+ // that the block_scores differ (and thus potentially the eviction victim).
+ //
+ // Simpler approach: test pool_kernel effect through the cache manager API
+ // directly, by manually calling update_attention_scores after doing the
+ // pooling ourselves, and verify the block_scores change the eviction result.
+ // But this wouldn't exercise pool_kernel in the PA kernel.
+ //
+ // Best approach: use the PA kernel path but with carefully crafted Q/K that
+ // produce a known score spike.
+ // Set all queries to [1,0,0,0] and all keys to [1,0,0,0] EXCEPT seq1 token 3
+ // which gets key=[10,0,0,0]. Then that token gets ~10x the attention.
+
+ // scale factor
+ float scale_val = 1.0f; // no scaling to keep things predictable
+
+ // uniform Q: all [1,0,0,0]
+ for (std::size_t i = 0; i < tokens; i++) {
+ q[i * q_features] = 1.0f;
+ }
+ // uniform K: all [1,0,0,0]
+ for (std::size_t i = 0; i < tokens; i++) {
+ k[i * kv_features] = 1.0f;
+ }
+ // uniform V: all [1,0,0,0]
+ for (std::size_t i = 0; i < tokens; i++) {
+ v[i * kv_features] = 1.0f;
+ }
+
+ // 3 sequences of length 4
+ std::int32_t past_lens[3] = {0, 0, 0};
+ std::int32_t subseq[4] = {0, 4, 8, 12};
+ std::int32_t score_window = 0;
+ std::vector<std::int32_t> block_idx = {0, 1, 2, 3, 4, 5};
+ std::vector<std::int32_t> block_begins_init = {0, 2, 4, 6};
+
+ std::vector<float> out(tokens * q_features, 0.f);
+ std::vector<float> out_scores(tokens, 0.f);
+
+ ov::reference::paged_attention<float>(
+ nk,
+ mgr.get(),
+ out.data(),
+ out_scores.data(), // non-null -> scores_per_head allocated -> pooling enabled
+ nullptr,
+ q.data(),
+ k.data(),
+ v.data(),
+ key_cache.data(),
+ val_cache.data(),
+ past_lens,
+ subseq,
+ block_idx.data(),
+ block_idx.size(),
+ block_begins_init.data(),
+ block_begins_init.size(),
+ &scale_val,
+ ov::element::f32,
+ nullptr, // sliding_window
+ nullptr, // alibi_slopes
+ ov::element::Type{},
+ {},
+ nullptr, // max_context_len
+ &score_window,
+ 1,
+ nullptr, // rotated_block_indices
+ 0,
+ nullptr, // rotation_deltas
+ {},
+ nullptr, // rotation_trig_lut
+ ov::element::Type{},
+ {},
+ nullptr, // xattention_threshold
+ ov::element::Type{},
+ nullptr, // xattention_block_size
+ nullptr, // xattention_stride
+ nullptr, // sinks
+ ov::element::Type{},
+ nullptr, // adaptive_rkv_start_size
+ nullptr, // adaptive_rkv_evictable_sizes
+ nullptr, // adaptive_rkv_diversity_block_set_indices
+ nullptr, // adaptive_rkv_diversity_block_set_indices_begins
+ {tokens, q_features},
+ {tokens, kv_features},
+ {tokens, kv_features},
+ cache_shape,
+ cache_shape,
+ {3},
+ {4},
+ pk); // pool_kernel
+
+ // Step 2: seq 0 adds 1 token, forcing eviction (all 6 blocks used)
+ // New query/key/value for 1 extra token
+ std::vector<float> q2(q_features, 0.f);
+ std::vector<float> k2(kv_features, 0.f);
+ std::vector<float> v2(kv_features, 0.f);
+ q2[0] = 1.0f;
+ k2[0] = 1.0f;
+ v2[0] = 1.0f;
+
+ std::int32_t past2[3] = {4, 4, 4};
+ std::int32_t subseq2[4] = {0, 1, 1, 1}; // only seq 0 has 1 new token
+ std::vector<float> out2(q_features, 0.f);
+ // total_score_len = sum(past+new) for all seqs = (4+1) + (4+0) + (4+0) = 13
+ std::vector<float> out_scores2(13, 0.f);
+
+ ov::reference::paged_attention<float>(nk,
+ mgr.get(),
+ out2.data(),
+ out_scores2.data(),
+ nullptr,
+ q2.data(),
+ k2.data(),
+ v2.data(),
+ key_cache.data(),
+ val_cache.data(),
+ past2,
+ subseq2,
+ block_idx.data(),
+ block_idx.size(),
+ block_begins_init.data(),
+ block_begins_init.size(),
+ &scale_val,
+ ov::element::f32,
+ nullptr,
+ nullptr,
+ ov::element::Type{},
+ {},
+ nullptr,
+ &score_window,
+ 1,
+ nullptr,
+ 0,
+ nullptr,
+ {},
+ nullptr,
+ ov::element::Type{},
+ {},
+ nullptr,
+ ov::element::Type{},
+ nullptr,
+ nullptr,
+ nullptr,
+ ov::element::Type{},
+ nullptr,
+ nullptr,
+ nullptr,
+ nullptr,
+ {1, q_features},
+ {1, kv_features},
+ {1, kv_features},
+ cache_shape,
+ cache_shape,
+ {3},
+ {4},
+ pk); // pool_kernel
+
+ PagedCacheManager::TokenAddress addr;
+ bool s0 = mgr->resolve_token(nk, 0, 0, addr);
+ bool s1 = mgr->resolve_token(nk, 1, 0, addr);
+ bool s2 = mgr->resolve_token(nk, 2, 0, addr);
+ return {s0, s1, s2};
+ };
+
+ // With pk=1 (no pooling) and pk=7 (heavy pooling), the scores fed to the cache
+ // manager differ because max-pool smooths the per-token scores. We verify that
+ // the code path runs without crashing and returns consistent results.
+ // With uniform Q and K the attention should be fairly uniform, so pooling won't
+ // dramatically change the outcome, but the important thing is that the pooling
+ // code path executes and the eviction still produces a valid result
+ auto [a0, a1, a2] = run(1); // no pooling
+ auto [b0, b1, b2] = run(7); // pooling with kernel 7
+
+ // With uniform Q/K, all front-block scores are approximately equal.
+ // Seq 0 is the requester and gets +1e12 penalty, so one of seq 1 or 2 is evicted
+ EXPECT_TRUE(a0) << "pk=1: seq 0 should survive (requester penalty protects it)";
+ EXPECT_TRUE(b0) << "pk=7: seq 0 should survive (requester penalty protects it)";
+ // At least one of seq 1, seq 2 should be evicted (one front block freed)
+ EXPECT_FALSE(a1 && a2) << "pk=1: one of seq 1/2 should have lost its front block";
+ EXPECT_FALSE(b1 && b2) << "pk=7: one of seq 1/2 should have lost its front block";
+}
diff --git a/src/core/tests/type_prop/paged_attention.cpp b/src/core/tests/type_prop/paged_attention.cpp
index 766b21a4a32..3c3ba6d3ddc 100644
--- a/src/core/tests/type_prop/paged_attention.cpp
+++ b/src/core/tests/type_prop/paged_attention.cpp
@@ -6,12 +6,73 @@
#include <gtest/gtest.h>
+#include <memory>
+#include <set>
+#include <tuple>
+#include <utility>
+
+#include "common_test_utils/test_assertions.hpp"
+#include "common_test_utils/type_prop.hpp"
#include "openvino/core/type/element_type.hpp"
+#include "openvino/op/constant.hpp"
#include "openvino/op/parameter.hpp"
namespace ov {
namespace testing {
+using ::testing::HasSubstr;
+
+namespace {
+ov::OutputVector make_valid_pa_args(const element::Type& t = element::f32) {
+ using ov::op::v0::Parameter;
+
+ // rotation_trig_lut and xattention_threshold only accept f16/f32.
+ // Pin to f32 for bf16 tests.
+ const auto trig_t = (t == element::bf16) ? element::f32 : t;
+
+ auto query = std::make_shared<Parameter>(t, PartialShape{3, 4});
+ auto key = std::make_shared<Parameter>(t, PartialShape{3, 4});
+ auto value = std::make_shared<Parameter>(t, PartialShape{3, 4});
+
+ auto key_cache = std::make_shared<Parameter>(t, PartialShape{4, 3, 32, 4});
+ auto value_cache = std::make_shared<Parameter>(t, PartialShape{4, 3, 32, 4});
+
+ auto past_lens = std::make_shared<Parameter>(element::i32, PartialShape{3});
+ auto subseq = std::make_shared<Parameter>(element::i32, PartialShape{4});
+ auto block_idx = std::make_shared<Parameter>(element::i32, PartialShape{6});
+ auto block_beg = std::make_shared<Parameter>(element::i32, PartialShape{4});
+
+ auto scale = std::make_shared<Parameter>(t, PartialShape{});
+ auto slide = std::make_shared<Parameter>(element::i32, PartialShape{});
+ auto alibi = std::make_shared<Parameter>(t, PartialShape{3});
+ auto maxctx = std::make_shared<Parameter>(element::i32, PartialShape{});
+ auto scorew = std::make_shared<Parameter>(element::i32, PartialShape{});
+
+ auto rotated = std::make_shared<Parameter>(element::i32, PartialShape{6});
+ auto deltas = std::make_shared<Parameter>(element::i32, PartialShape{6});
+ auto trig = std::make_shared<Parameter>(trig_t, PartialShape{6});
+
+ auto xthr = std::make_shared<Parameter>(trig_t, PartialShape{1});
+ auto xbs = std::make_shared<Parameter>(element::i32, PartialShape{});
+ auto xst = std::make_shared<Parameter>(element::i32, PartialShape{});
+
+ auto sinks = std::make_shared<Parameter>(t, PartialShape{1, 3, 1, 1});
+
+ auto arkv_start = std::make_shared<Parameter>(element::i32, PartialShape{});
+ auto arkv_evict = std::make_shared<Parameter>(element::i32, PartialShape{3});
+ auto arkv_idx = std::make_shared<Parameter>(element::i32, PartialShape{3});
+ auto arkv_beg = std::make_shared<Parameter>(element::i32, PartialShape{3});
+ auto token_type_ids = std::make_shared<Parameter>(element::i32, PartialShape{0});
+
+ auto qq_bias = std::make_shared<Parameter>(element::u8, PartialShape{4});
+ auto qq_bias_begins = std::make_shared<Parameter>(element::i32, PartialShape{2});
+
+ return {query, key, value, key_cache, value_cache, past_lens, subseq, block_idx, block_beg,
+ scale, slide, alibi, maxctx, scorew, rotated, deltas, trig, xthr,
+ xbs, xst, sinks, arkv_start, arkv_evict, arkv_idx, arkv_beg, token_type_ids, qq_bias,
+ qq_bias_begins};
+}
+} // namespace
TEST(type_prop, paged_attention_static_eviction_per_block) {
const auto query = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});
const auto key = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});
@@ -225,61 +286,123 @@ TEST(type_prop, paged_attention_dynamic_ranks_and_types) {
}
TEST(type_prop, paged_attention_invalid_rank_query) {
- auto query = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3});
- auto key = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});
- auto value = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});
- auto dummy = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});
- auto scalar = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});
- ov::OutputVector args =
- {query, key, value, dummy, dummy, scalar, scalar, scalar, scalar, dummy, scalar, dummy, scalar};
-
- EXPECT_THROW(std::ignore = std::make_shared<op::PagedAttentionExtension>(args), ov::NodeValidationFailure);
+ auto args = make_valid_pa_args();
+ args[0] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3}); // query must be rank-2
+ OV_EXPECT_THROW(std::ignore = std::make_shared<op::PagedAttentionExtension>(args),
+ ov::NodeValidationFailure,
+ HasSubstr("Rank of `query`"));
}
TEST(type_prop, paged_attention_invalid_type_scale) {
- auto scale = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});
- auto dummy2D = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});
- auto dummy1D = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{3});
- auto dummyScalar = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});
-
- ov::OutputVector args = {dummy2D,
- dummy2D,
- dummy2D,
- dummy2D,
- dummy2D,
- dummy1D,
- dummy1D,
- dummy1D,
- dummy1D,
- scale,
- dummyScalar,
- dummy2D,
- dummyScalar};
-
- EXPECT_THROW(std::ignore = std::make_shared<op::PagedAttentionExtension>(args), ov::NodeValidationFailure);
+ auto args = make_valid_pa_args();
+ args[9] = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{}); // scale must be real type
+ OV_EXPECT_THROW(std::ignore = std::make_shared<op::PagedAttentionExtension>(args),
+ ov::NodeValidationFailure,
+ HasSubstr("Element type of `scale`"));
}
TEST(type_prop, paged_attention_invalid_rank_key_cache) {
- auto key_cache = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{1});
- auto dummy = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});
- auto dummy1D = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{3});
- auto dummyScalar = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{});
-
- ov::OutputVector args = {dummy,
- dummy,
- dummy,
- key_cache,
- dummy,
- dummy1D,
- dummy1D,
- dummy1D,
- dummy1D,
- dummyScalar,
- dummyScalar,
- dummy,
- dummyScalar};
+ auto args = make_valid_pa_args();
+ args[3] = std::make_shared<op::v0::Parameter>(element::f32,
+ PartialShape{3}); // key_cache allows rank 2..5; rank 1 is invalid
+ OV_EXPECT_THROW(std::ignore = std::make_shared<op::PagedAttentionExtension>(args),
+ ov::NodeValidationFailure,
+ HasSubstr("Rank of `key_cache`"));
+}
- EXPECT_THROW(std::ignore = std::make_shared<op::PagedAttentionExtension>(args), ov::NodeValidationFailure);
+TEST(type_prop, paged_attention_invalid_input_count) {
+ auto args = make_valid_pa_args();
+ args.pop_back(); // 27 instead of 28
+ OV_EXPECT_THROW(std::ignore = std::make_shared<op::PagedAttentionExtension>(args),
+ ov::NodeValidationFailure,
+ HasSubstr("28 inputs"));
+}
+
+TEST(type_prop, paged_attention_invalid_past_lens_rank) {
+ auto args = make_valid_pa_args();
+ args[5] = std::make_shared<op::v0::Parameter>(element::i32, PartialShape{3, 1}); // past_lens must be rank-1
+ OV_EXPECT_THROW(std::ignore = std::make_shared<op::PagedAttentionExtension>(args),
+ ov::NodeValidationFailure,
+ HasSubstr("Rank of `past_lens`"));
+}
+
+TEST(type_prop, paged_attention_invalid_type_past_lens) {
+ auto args = make_valid_pa_args();
+ args[5] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3}); // past_lens must be i32
+ OV_EXPECT_THROW(std::ignore = std::make_shared<op::PagedAttentionExtension>(args),
+ ov::NodeValidationFailure,
+ HasSubstr("Element type of `past_lens`"));
+}
+
+// ---------- dtype parametrisation ----------
+class PagedAttentionTypePropDtype : public ::testing::TestWithParam<element::Type> {};
+
+TEST_P(PagedAttentionTypePropDtype, OutputTypeMatchesInput) {
+ const auto t = GetParam();
+ auto args = make_valid_pa_args(t);
+ const auto op = std::make_shared<op::PagedAttentionExtension>(args);
+ EXPECT_EQ(op->get_output_element_type(0), t);
+ EXPECT_EQ(op->get_output_element_type(1), t);
+ EXPECT_EQ(op->get_output_element_type(2), t);
+}
+
+INSTANTIATE_TEST_SUITE_P(type_prop,
+ PagedAttentionTypePropDtype,
+ ::testing::Values(element::f32, element::bf16, element::f16),
+ [](const ::testing::TestParamInfo<element::Type>& info) {
+ return info.param.get_type_name();
+ });
+
+// ---------- GQA scenarios ----------
+TEST(type_prop, paged_attention_gqa_output_shape) {
+ // GQA: q_heads=6, kv_heads=2, head_size=4 => q=[B,24], k=[B,8], v=[B,8]
+ // Output features = q * v / k = 24 * 8 / 8 = 24 (= q_heads * v_head_size)
+ auto args = make_valid_pa_args();
+ const auto B = 3;
+ args[0] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{B, 24}); // Q: 6 heads * 4
+ args[1] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{B, 8}); // K: 2 heads * 4
+ args[2] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{B, 8}); // V: 2 heads * 4
+ args[3] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{4, 2, 32, 4}); // key_cache
+ args[4] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{4, 2, 32, 4}); // value_cache
+ const auto op = std::make_shared<op::PagedAttentionExtension>(args);
+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{B, 24}));
+}
+
+TEST(type_prop, paged_attention_gqa_mismatched_divisibility) {
+ // q * v / k must be integer; here q=5, k=4, v=4 => 5*4/4=5 (ok but unusual)
+ auto args = make_valid_pa_args();
+ args[0] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 5});
+ args[1] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});
+ args[2] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});
+ const auto op = std::make_shared<op::PagedAttentionExtension>(args);
+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{3, 5}));
+}
+
+TEST(type_prop, paged_attention_output_feature_not_divisible) {
+ // q=5, k=3, v=4 => 5*4 = 20, 20 % 3 != 0 => should throw
+ auto args = make_valid_pa_args();
+ args[0] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 5});
+ args[1] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 3});
+ args[2] = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{3, 4});
+ OV_EXPECT_THROW(std::ignore = std::make_shared<op::PagedAttentionExtension>(args),
+ ov::NodeValidationFailure,
+ HasSubstr("divisible"));
+}
+
+// ---------- output 1 & 2 validation ----------
+TEST(type_prop, paged_attention_outputs_1_and_2_shapes) {
+ auto args = make_valid_pa_args();
+ const auto op = std::make_shared<op::PagedAttentionExtension>(args);
+ // Output 0: [B_token, out_features]
+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{3, 4}));
+ // Output 1 (scores): 1-D, dynamic without constant past_lens
+ EXPECT_EQ(op->get_output_partial_shape(1).rank().get_length(), 1);
+ // Output 2 (diversity): 1-D
+ EXPECT_EQ(op->get_output_partial_shape(2).rank().get_length(), 1);
+ // All outputs share query element type
+ EXPECT_EQ(op->get_output_element_type(0), element::f32);
+ EXPECT_EQ(op->get_output_element_type(1), element::f32);
+ EXPECT_EQ(op->get_output_element_type(2), element::f32);
}
static ov::OutputVector make_args_with_token_type(const std::shared_ptr<ov::op::v0::Parameter>& token_type_ids) {
diff --git a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/single_layer_tests/paged_attention.cpp b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/single_layer_tests/paged_attention.cpp
new file mode 100644
index 00000000000..b1567313595
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/single_layer_tests/paged_attention.cpp
@@ -0,0 +1,324 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <vector>
+
+#include "common_test_utils/test_enums.hpp"
+#include "common_test_utils/test_constants.hpp"
+
+#include "single_op_tests/paged_attention.hpp"
+#include "shared_test_classes/single_op/paged_attention.hpp"
+
+#include "internal_properties.hpp"
+#include "openvino/runtime/properties.hpp"
+#include "openvino/core/visibility.hpp"
+
+namespace {
+using ov::test::PagedAttentionLayerTest;
+using ElementType = ov::element::Type_t;
+using InputShapes = std::vector<ov::test::InputShape>;
+
+const std::vector<InputShapes> input_shapes_ref = {
+{
+ // Shape per step: [L, B=1, H, S] (B must be 1; metadata constants are scalar)
+ {{-1, 1, 8, 64}, {{10, 1, 8, 64}, {1, 1, 8, 64}}},
+ {{-1, 1, 8, 64}, {{0, 1, 8, 64}, {10, 1, 8, 64}}},
+}};
+
+// Tiny dimensions for manual verification (H=2, S=4)
+const std::vector<InputShapes> input_shapes_tiny = {
+{
+ {{-1, 1, 2, 4}, {{3, 1, 2, 4}, {1, 1, 2, 4}}},
+ {{-1, 1, 2, 4}, {{0, 1, 2, 4}, {3, 1, 2, 4}}},
+}};
+
+// Medium dimensions for alibi verification (H=4, S=8)
+const std::vector<InputShapes> input_shapes_medium = {
+{
+ {{-1, 1, 4, 8}, {{4, 1, 4, 8}, {1, 1, 4, 8}}},
+ {{-1, 1, 4, 8}, {{0, 1, 4, 8}, {4, 1, 4, 8}}},
+}};
+
+// 3-step: prompt=2 tokens, then 3 tokens (past=2, non-trivial), then decode=1 token
+const std::vector<InputShapes> input_shapes_3step_tiny = {
+{
+ {{-1, 1, 2, 4}, {{2, 1, 2, 4}, {3, 1, 2, 4}, {1, 1, 2, 4}}},
+ {{-1, 1, 2, 4}, {{0, 1, 2, 4}, {2, 1, 2, 4}, {5, 1, 2, 4}}},
+}};
+
+const std::vector<ov::AnyMap> additional_configs_ref = {{
+ {ov::intel_cpu::enable_sage_attn.name(), false},
+
+ // Force float cache (match compute precision)
+ {ov::hint::kv_cache_precision.name(), ov::element::f32},
+ {ov::key_cache_precision.name(), ov::element::f32},
+ {ov::value_cache_precision.name(), ov::element::f32},
+
+ // Disable grouped / quantized cache paths
+ {ov::key_cache_group_size.name(), 0},
+ {ov::value_cache_group_size.name(), 0},
+}};
+
+#ifdef OPENVINO_ARCH_X86_64
+
+// Basic verification tests
+
+// 0) Default test
+INSTANTIATE_TEST_SUITE_P(smoke_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(input_shapes_ref),
+ ::testing::Values(true, false),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(0), // sliding_window
+ ::testing::Values(false), // useAlibi
+ ::testing::Values(1024), // maxContextLen (effectively unlimited)
+ ::testing::ValuesIn(additional_configs_ref)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// 1) Tiny basic: H=2, S=4, no extras
+INSTANTIATE_TEST_SUITE_P(tiny_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(input_shapes_tiny),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(0),
+ ::testing::Values(false),
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_ref)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// 2) Tiny + ALiBi
+INSTANTIATE_TEST_SUITE_P(tinyAlibi_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(input_shapes_tiny),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(0),
+ ::testing::Values(true),
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_ref)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// 3) Tiny + sliding window=2, no alibi
+INSTANTIATE_TEST_SUITE_P(tinySliding_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(input_shapes_tiny),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(2),
+ ::testing::Values(false),
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_ref)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// 4) Medium + ALiBi: H=4, S=8
+INSTANTIATE_TEST_SUITE_P(mediumAlibi_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(input_shapes_medium),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(0),
+ ::testing::Values(true),
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_ref)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// Advanced tests - all 26 inputs with various feature combinations
+
+// 5) 3-step with non-trivial past_lens: prompt(L=2), prefill(L=3, past=2), decode(L=1)
+INSTANTIATE_TEST_SUITE_P(adv3Step_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(input_shapes_3step_tiny),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(0),
+ ::testing::Values(false),
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_ref)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// 6) 3-step + ALiBi: tests non-trivial past_lens combined with alibi bias
+INSTANTIATE_TEST_SUITE_P(adv3StepAlibi_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(input_shapes_3step_tiny),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(0),
+ ::testing::Values(true), // alibi
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_ref)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// NOTE: max_context_len clipping is not tested because CPU ignores it during
+// prefill while TEMPLATE always applies it, so there is no stable ground truth.
+
+// Feature tests - sinks, rotation, xattention
+
+// 7) Tiny + attention sinks
+INSTANTIATE_TEST_SUITE_P(advSinks_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(input_shapes_tiny),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(true), // sinkInput = true
+ ::testing::Values(0),
+ ::testing::Values(false),
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_ref)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// 8) Tiny + sinks + ALiBi
+INSTANTIATE_TEST_SUITE_P(advSinksAlibi_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(input_shapes_tiny),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(true), // sinkInput = true
+ ::testing::Values(0),
+ ::testing::Values(true), // alibi
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_ref)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// 9) Rotation: RoPE re-rotation on block 0
+const std::vector<ov::AnyMap> additional_configs_rotation = {{
+ {ov::intel_cpu::enable_sage_attn.name(), false},
+ {ov::hint::kv_cache_precision.name(), ov::element::f32},
+ {ov::key_cache_precision.name(), ov::element::f32},
+ {ov::value_cache_precision.name(), ov::element::f32},
+ {ov::key_cache_group_size.name(), 0},
+ {ov::value_cache_group_size.name(), 0},
+ {"test_use_rotation", true},
+}};
+
+INSTANTIATE_TEST_SUITE_P(advRotation_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(input_shapes_tiny),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(0),
+ ::testing::Values(false),
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_rotation)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// 10) Xattention smoke: trivial 1x1 mask, validates the code path runs
+INSTANTIATE_TEST_SUITE_P(advXattn_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(input_shapes_tiny),
+ ::testing::Values(false),
+ ::testing::Values(true), // enableXattn = true
+ ::testing::Values(false),
+ ::testing::Values(0),
+ ::testing::Values(false),
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_ref)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// Adaptive RKV diversity (output not compared, just compile/crash verification)
+
+// L=64, block_size=32, eviction_size=32 (one eviction block)
+const std::vector<InputShapes> input_shapes_arkv = {
+{
+ {{-1, 1, 2, 4}, {{64, 1, 2, 4}, {1, 1, 2, 4}}},
+ {{-1, 1, 2, 4}, {{0, 1, 2, 4}, {64, 1, 2, 4}}},
+}};
+
+const std::vector<ov::AnyMap> additional_configs_arkv = {{
+ {ov::intel_cpu::enable_sage_attn.name(), false},
+ {ov::hint::kv_cache_precision.name(), ov::element::f32},
+ {ov::key_cache_precision.name(), ov::element::f32},
+ {ov::value_cache_precision.name(), ov::element::f32},
+ {ov::key_cache_group_size.name(), 0},
+ {ov::value_cache_group_size.name(), 0},
+ {"test_adaptive_rkv_eviction_size", 32},
+}};
+
+// 11) Adaptive RKV diversity: output 0 must still match CPU
+INSTANTIATE_TEST_SUITE_P(advAdaptiveRKV_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(input_shapes_arkv),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(0),
+ ::testing::Values(false),
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_arkv)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// f16/bf16 precision tests
+
+const std::vector<ov::AnyMap> additional_configs_f16 = {{
+ {ov::intel_cpu::enable_sage_attn.name(), false},
+ {ov::hint::kv_cache_precision.name(), ov::element::f16},
+ {ov::key_cache_precision.name(), ov::element::f16},
+ {ov::value_cache_precision.name(), ov::element::f16},
+ {ov::key_cache_group_size.name(), 0},
+ {ov::value_cache_group_size.name(), 0},
+ {"test_abs_threshold", 0.05f},
+ {"test_rel_threshold", 0.1f},
+}};
+
+const std::vector<ov::AnyMap> additional_configs_bf16 = {{
+ {ov::intel_cpu::enable_sage_attn.name(), false},
+ {ov::hint::kv_cache_precision.name(), ov::element::bf16},
+ {ov::key_cache_precision.name(), ov::element::bf16},
+ {ov::value_cache_precision.name(), ov::element::bf16},
+ {ov::key_cache_group_size.name(), 0},
+ {ov::value_cache_group_size.name(), 0},
+ {"test_abs_threshold", 0.05f},
+ {"test_rel_threshold", 0.1f},
+}};
+
+// 12) f16: basic tiny test
+INSTANTIATE_TEST_SUITE_P(f16_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::f16),
+ ::testing::ValuesIn(input_shapes_tiny),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(0),
+ ::testing::Values(false),
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_f16)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+// 13) bf16: basic tiny test
+INSTANTIATE_TEST_SUITE_P(bf16_PagedAttentionLayerTest,
+ PagedAttentionLayerTest,
+ ::testing::Combine(::testing::Values(ElementType::bf16),
+ ::testing::ValuesIn(input_shapes_tiny),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(false),
+ ::testing::Values(0),
+ ::testing::Values(false),
+ ::testing::Values(1024),
+ ::testing::ValuesIn(additional_configs_bf16)),
+ PagedAttentionLayerTest::getTestCaseName);
+
+#endif // OPENVINO_ARCH_X86_64
+} // namespace
diff --git a/src/plugins/template/backend/ops/ops_evaluates.hpp b/src/plugins/template/backend/ops/ops_evaluates.hpp
index 97967c3f6dc..667c5d7024c 100644
--- a/src/plugins/template/backend/ops/ops_evaluates.hpp
+++ b/src/plugins/template/backend/ops/ops_evaluates.hpp
@@ -5,6 +5,7 @@
#pragma once
#include "evaluate_node.hpp"
#include "openvino/op/ops.hpp"
+#include "openvino/op/paged_attention.hpp"
#include "openvino/op/rms_norm.hpp"
#include "ov_ops/augru_cell.hpp"
#include "ov_ops/augru_sequence.hpp"
@@ -572,6 +573,10 @@ extern template bool evaluate_node<ov::op::v16::SegmentMax>(std::shared_ptr<ov::
ov::TensorVector& outputs,
const ov::TensorVector& inputs);
+extern template bool evaluate_node<ov::op::PagedAttentionExtension>(std::shared_ptr<ov::Node> node,
+ ov::TensorVector& outputs,
+ const ov::TensorVector& inputs);
+
extern template bool evaluate_node<ov::op::v16::SparseFillEmptyRows>(std::shared_ptr<ov::Node> node,
ov::TensorVector& outputs,
const ov::TensorVector& inputs);
diff --git a/src/plugins/template/backend/ops/paged_attention.cpp b/src/plugins/template/backend/ops/paged_attention.cpp
new file mode 100644
index 00000000000..338690bcb12
--- /dev/null
+++ b/src/plugins/template/backend/ops/paged_attention.cpp
@@ -0,0 +1,146 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/op/paged_attention.hpp"
+
+#include <cstring>
+#include <numeric>
+
+#include "evaluate_node.hpp"
+#include "openvino/core/type/element_iterator.hpp"
+#include "openvino/reference/paged_attention.hpp"
+#include "openvino/reference/utils/paged_cache_manager_helper.hpp"
+#include "paged_attention_shape_inference.hpp"
+#include "tensor_data_accessor.hpp"
+
+namespace {
+
+// Resize outputs using shape_infer with runtime tensors.
+// PA keeps some inputs dynamic after validate_and_infer_types,
+// so we use actual tensor shapes here.
+void resize_pa_outputs(const ov::op::PagedAttentionExtension* op,
+ ov::TensorVector& outputs,
+ const ov::TensorVector& inputs) {
+ std::vector<ov::PartialShape> input_shapes;
+ input_shapes.reserve(inputs.size());
+ for (const auto& t : inputs) {
+ input_shapes.emplace_back(t.get_shape());
+ }
+ const auto out_shapes = ov::op::shape_infer(op, input_shapes, ov::make_tensor_accessor(inputs));
+ OPENVINO_ASSERT(out_shapes.size() == outputs.size());
+ for (size_t i = 0; i < outputs.size(); ++i) {
+ if (out_shapes[i].is_static()) {
+ outputs[i].set_shape(out_shapes[i].to_shape());
+ } else {
+ // Diversity output may stay dynamic -- default to {0}
+ outputs[i].set_shape(ov::Shape{0});
+ }
+ }
+}
+
+template <ov::element::Type_t ET>
+bool evaluate(const ov::op::PagedAttentionExtension* pa_op,
+ ov::TensorVector& outputs,
+ const ov::TensorVector& inputs,
+ std::uintptr_t node_key,
+ ov::reference::paged_attention_cache::PagedCacheManager* cache_manager) {
+ using T = typename ov::element_type_traits<ET>::value_type;
+
+ OPENVINO_ASSERT(inputs.size() == 28, "PagedAttentionExtension: expected 28 inputs, got ", inputs.size());
+ OPENVINO_ASSERT(outputs.size() == 3, "PagedAttentionExtension: expected 3 outputs");
+
+ resize_pa_outputs(pa_op, outputs, inputs);
+
+ // Map "present but empty" inputs to nullptr. These are logically optional
+ // but must be passed as empty tensors since PA has no optional positional inputs.
+ const void* alibi_ptr = inputs[11].get_size() > 0 ? inputs[11].data() : nullptr;
+ const auto alibi_et = alibi_ptr ? inputs[11].get_element_type() : ov::element::dynamic;
+ const void* trig_lut_ptr = inputs[16].get_size() > 0 ? inputs[16].data() : nullptr;
+ const auto trig_lut_et = trig_lut_ptr ? inputs[16].get_element_type() : ov::element::dynamic;
+ const void* xattn_thresh_ptr = inputs[17].get_size() > 0 ? inputs[17].data() : nullptr;
+ const auto xattn_thresh_et = xattn_thresh_ptr ? inputs[17].get_element_type() : ov::element::dynamic;
+ const void* sinks_ptr = inputs[20].get_size() > 0 ? inputs[20].data() : nullptr;
+ const auto sinks_et = sinks_ptr ? inputs[20].get_element_type() : ov::element::dynamic;
+ const int32_t* arkv_evict_ptr = inputs[22].get_size() > 0 ? inputs[22].data<int32_t>() : nullptr;
+ const int32_t* arkv_indices_ptr = inputs[23].get_size() > 0 ? inputs[23].data<int32_t>() : nullptr;
+ const int32_t* arkv_begins_ptr = inputs[24].get_size() > 0 ? inputs[24].data<int32_t>() : nullptr;
+
+ ov::reference::paged_attention<T>(node_key,
+ cache_manager,
+ outputs[0].data<T>(),
+ outputs[1].data<T>(),
+ outputs[2].data<T>(),
+ inputs[0].data<T>(), // query
+ inputs[1].data<T>(), // key
+ inputs[2].data<T>(), // value
+ inputs[3].data<T>(), // key_cache init
+ inputs[4].data<T>(), // value_cache init
+ inputs[5].data<int32_t>(), // past_lens
+ inputs[6].data<int32_t>(), // subsequence_begins
+ inputs[7].data<int32_t>(), // block_indices init
+ inputs[7].get_size(),
+ inputs[8].data<int32_t>(), // block_indices_begins init
+ inputs[8].get_size(),
+ inputs[9].data(), // scale
+ inputs[9].get_element_type(),
+ inputs[10].data<int32_t>(), // sliding_window
+ alibi_ptr, // alibi_slopes
+ alibi_et,
+ inputs[11].get_shape(),
+ inputs[12].data<int32_t>(), // max_context_len
+ inputs[13].data<int32_t>(), // score_aggregation_window
+ inputs[13].get_size(), // score_aggregation_window_count
+ inputs[14].data<int32_t>(), // rotated_block_indices
+ inputs[14].get_size(),
+ inputs[15].data<int32_t>(), // rotation_deltas
+ inputs[15].get_shape(),
+ trig_lut_ptr, // rotation_trig_lut
+ trig_lut_et,
+ inputs[16].get_shape(),
+ xattn_thresh_ptr, // xattention_threshold
+ xattn_thresh_et,
+ inputs[18].data<int32_t>(), // xattention_block_size
+ inputs[19].data<int32_t>(), // xattention_stride
+ sinks_ptr, // sinks
+ sinks_et,
+ inputs[21].data<int32_t>(), // adaptive_rkv_start_size
+ arkv_evict_ptr, // adaptive_rkv_evictable_sizes
+ arkv_indices_ptr, // adaptive_rkv_diversity_block_set_indices
+ arkv_begins_ptr, // adaptive_rkv_diversity_block_set_indices_begins
+ inputs[0].get_shape(),
+ inputs[1].get_shape(),
+ inputs[2].get_shape(),
+ inputs[3].get_shape(),
+ inputs[4].get_shape(),
+ inputs[5].get_shape(),
+ inputs[6].get_shape());
+ return true;
+}
+
+} // namespace
+
+template <>
+bool evaluate_node<ov::op::PagedAttentionExtension>(std::shared_ptr<ov::Node> node,
+ ov::TensorVector& outputs,
+ const ov::TensorVector& inputs) {
+ const auto& pa = std::static_pointer_cast<ov::op::PagedAttentionExtension>(node);
+ auto* cache_manager = ov::reference::paged_attention_cache::get_cache_manager_ptr(pa.get());
+ OPENVINO_ASSERT(cache_manager != nullptr, "PagedAttentionExtension: cache manager handle is null");
+
+ const std::uintptr_t node_key = reinterpret_cast<std::uintptr_t>(node.get());
+ const auto et = node->get_output_element_type(0);
+
+ switch (et) {
+ case ov::element::bf16:
+ return evaluate<ov::element::bf16>(pa.get(), outputs, inputs, node_key, cache_manager);
+ case ov::element::f16:
+ return evaluate<ov::element::f16>(pa.get(), outputs, inputs, node_key, cache_manager);
+ case ov::element::f32:
+ return evaluate<ov::element::f32>(pa.get(), outputs, inputs, node_key, cache_manager);
+ case ov::element::f64:
+ return evaluate<ov::element::f64>(pa.get(), outputs, inputs, node_key, cache_manager);
+ default:
+ OPENVINO_THROW("PagedAttentionExtension: unsupported element type: ", et);
+ }
+}
diff --git a/src/plugins/template/backend/opset_int_tbl.hpp b/src/plugins/template/backend/opset_int_tbl.hpp
index f056971e5d4..bc24a026778 100644
--- a/src/plugins/template/backend/opset_int_tbl.hpp
+++ b/src/plugins/template/backend/opset_int_tbl.hpp
@@ -189,3 +189,4 @@ _OPENVINO_OP_REG(AUGRUCell, ov::op::internal)
_OPENVINO_OP_REG(AUGRUSequence, ov::op::internal)
_OPENVINO_OP_REG(RMS, ov::op::internal)
_OPENVINO_OP_REG(RMSNorm, ov::op::internal)
+_OPENVINO_OP_REG(PagedAttentionExtension, ov::op)
diff --git a/src/plugins/template/src/attach_cache_manager_to_paged_attention.hpp b/src/plugins/template/src/attach_cache_manager_to_paged_attention.hpp
new file mode 100644
index 00000000000..e9d22506d8e
--- /dev/null
+++ b/src/plugins/template/src/attach_cache_manager_to_paged_attention.hpp
@@ -0,0 +1,51 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// Attaches a shared PagedCacheManager to every PA node via rt_info.
+
+#pragma once
+
+#include "openvino/core/model.hpp"
+#include "openvino/op/paged_attention.hpp"
+#include "openvino/pass/matcher_pass.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "openvino/reference/utils/paged_cache_manager_helper.hpp"
+
+namespace ov {
+namespace pass {
+
+class AttachCacheManagerToPagedAttention : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("AttachCacheManagerToPagedAttention");
+ AttachCacheManagerToPagedAttention() {
+ using namespace ov::reference::paged_attention_cache;
+
+ auto pa_pattern = pattern::wrap_type<ov::op::PagedAttentionExtension>();
+
+ auto shared_handle = std::make_shared<CacheManagerHandle>();
+ auto shared_dtype = std::make_shared<ov::element::Type>();
+
+ ov::matcher_pass_callback callback = [shared_handle, shared_dtype](pattern::Matcher& m) -> bool {
+ auto pa = std::dynamic_pointer_cast<ov::op::PagedAttentionExtension>(m.get_match_root());
+ if (!pa || get_cache_manager(pa.get()) != nullptr)
+ return false;
+
+ if (!*shared_handle) {
+ *shared_dtype = pa->get_input_element_type(3);
+ *shared_handle = make_cache_handle(*shared_dtype);
+ }
+
+ OPENVINO_ASSERT(pa->get_input_element_type(3) == *shared_dtype,
+ "AttachCacheManagerToPagedAttention: incompatible cache data types");
+
+ set_cache_manager(pa.get(), *shared_handle);
+ return true;
+ };
+
+ auto m = std::make_shared<pattern::Matcher>(pa_pattern, "AttachCacheManagerToPagedAttention");
+ register_matcher(m, callback);
+ }
+};
+
+} // namespace pass
+} // namespace ov
diff --git a/src/plugins/template/src/plugin.cpp b/src/plugins/template/src/plugin.cpp
index 928441ab8d6..a5912fd9df2 100644
--- a/src/plugins/template/src/plugin.cpp
+++ b/src/plugins/template/src/plugin.cpp
@@ -7,6 +7,7 @@
#include <fstream>
#include <memory>
+#include "attach_cache_manager_to_paged_attention.hpp"
#include "itt.hpp"
#include "openvino/op/ops.hpp"
#include "openvino/pass/manager.hpp"
@@ -25,6 +26,7 @@
#include "transformations/op_conversions/convert_maxpool_downgrade.hpp"
#include "transformations/op_conversions/convert_reduce_to_pooling.hpp"
#include "transformations/op_conversions/scaled_dot_product_attention_decomposition.hpp"
+#include "transformations/paged_attention/convert_pagedattn_inputs.hpp"
namespace {
static constexpr const char* wait_executor_name = "TemplateWaitExecutor";
@@ -126,6 +128,30 @@ ov::SoPtr<ov::IRemoteContext> ov::template_plugin::Plugin::get_default_context(
void transform_model(const std::shared_ptr<ov::Model>& model) {
// Perform common optimizations and device-specific transformations
ov::pass::Manager passManager("Plugin:Template");
+
+ // Defaults are overwritten below from the actual PA node's input types (inputs 3/4 for
+ // cache, input 0 for query). f32 is only used if there is no PA node in the model.
+ ov::pass::ConvertPagedAttnInputs::KVCacheConfig cacheConfig;
+ cacheConfig.keyCachePrecision = ov::element::f32;
+ cacheConfig.valueCachePrecision = ov::element::f32;
+ cacheConfig.inferencePrecision = ov::element::f32;
+ for (const auto& op : model->get_ops()) {
+ if (auto pa = std::dynamic_pointer_cast<ov::op::PagedAttentionExtension>(op)) {
+ const auto key_et = pa->get_input_element_type(3);
+ const auto val_et = pa->get_input_element_type(4);
+ if (!key_et.is_dynamic())
+ cacheConfig.keyCachePrecision = key_et;
+ if (!val_et.is_dynamic())
+ cacheConfig.valueCachePrecision = val_et;
+ const auto qry_et = pa->get_input_element_type(0);
+ if (!qry_et.is_dynamic())
+ cacheConfig.inferencePrecision = qry_et;
+ break;
+ }
+ }
+ auto noop_shape = [](const ov::element::Type&, const bool, const size_t, int64_t&, int64_t&) {};
+ passManager.register_pass<ov::pass::ConvertPagedAttnInputs>(cacheConfig, noop_shape);
+
// Example: register CommonOptimizations transformation from transformations library
passManager.register_pass<ov::pass::CommonOptimizations>();
// Disable some transformations
@@ -146,6 +172,9 @@ void transform_model(const std::shared_ptr<ov::Model>& model) {
// Disabled SDPA transformation, since there is ref SDPA op.
pass_config->disable<ov::pass::ScaledDotProductAttentionDecomposition>();
+ // Attach cache manager to PA nodes for KV cache block management
+ passManager.register_pass<ov::pass::AttachCacheManagerToPagedAttention>();
+
// After `run_passes`, we have the transformed function, where operations match device operations,
// and we can create device backend-dependent graph
passManager.run_passes(model);
diff --git a/src/tests/functional/plugin/shared/include/shared_test_classes/single_op/paged_attention.hpp b/src/tests/functional/plugin/shared/include/shared_test_classes/single_op/paged_attention.hpp
new file mode 100644
index 00000000000..503829435a5
--- /dev/null
+++ b/src/tests/functional/plugin/shared/include/shared_test_classes/single_op/paged_attention.hpp
@@ -0,0 +1,517 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <vector>
+#include <tuple>
+#include <string>
+#include <map>
+#include <set>
+
+#include "shared_test_classes/base/ov_subgraph.hpp"
+#include "common_test_utils/test_enums.hpp"
+
+#include "openvino/op/paged_attention.hpp"
+#include "transformations/rt_info/keep_const_precision.hpp"
+
+
+namespace ov {
+namespace test {
+
+using InputShapes = std::vector<InputShape>;
+using PagedAttentionTestParams = std::tuple<ElementType, InputShapes, bool, bool, bool, int32_t, bool, int32_t, ov::AnyMap>;
+
+class PagedAttentionLayerTest
+ : public testing::WithParamInterface<PagedAttentionTestParams>,
+ public ov::test::SubgraphBaseTest {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<PagedAttentionTestParams>& obj) {
+ const auto& [inType,
+ inputShapes,
+ extendBlockIndices,
+ enableXattn,
+ sinkInput,
+ slidingWindow,
+ useAlibi,
+ maxContextLen,
+ additional_config] = obj.param;
+ std::ostringstream result;
+ result << "IS=";
+ for (const auto& shape : inputShapes) {
+ result << ov::test::utils::partialShape2str({shape.first}) << "_";
+ }
+ result << "TS=";
+ for (const auto& shape : inputShapes) {
+ result << "(";
+ if (!shape.second.empty()) {
+ for (const auto& itr : shape.second) {
+ result << ov::test::utils::vec2str(itr);
+ }
+ }
+ result << ")_";
+ }
+ result << "Prc=" << inType << "_";
+ result << "ExtendBlockIndices=" << extendBlockIndices << "_";
+ result << "EnableXattn=" << enableXattn << "_";
+ result << "SinkInput=" << sinkInput << "_";
+ result << "SlidingWindow=" << slidingWindow << "_";
+ result << "UseAlibi=" << useAlibi << "_";
+ result << "MaxContextLen=" << maxContextLen << "_";
+ result << "config=(";
+ for (const auto& configEntry : additional_config) {
+ result << configEntry.first << ", " << configEntry.second.as<std::string>() << "_";
+ }
+ result << ")";
+
+ return result.str();
+ }
+
+protected:
+ // Model construction
+ static std::shared_ptr<ov::op::v0::Parameter> make_param(const ov::PartialShape& ps,
+ ov::element::Type et,
+ const std::string& name) {
+ auto p = std::make_shared<ov::op::v0::Parameter>(et, ps);
+ p->set_friendly_name(name);
+ p->get_output_tensor(0).set_names({name});
+ return p;
+ }
+
+ std::shared_ptr<ov::Model> make_paged_attn_model(ov::element::Type data_type,
+ bool enable_xattn,
+ int64_t head_size = 64,
+ int64_t head_num = 8,
+ bool use_sink_input = false,
+ int32_t sliding_window = 0,
+ bool use_alibi = false,
+ int32_t max_ctx_len = 1024,
+ bool use_rotation = false,
+ int64_t block_size = 32,
+ int32_t adaptive_rkv_eviction_size = 0,
+ int32_t score_window_val = -1) {
+ // PA expects q/k/v as [tokens, features]
+ auto q = make_param({ov::Dimension::dynamic(), ov::Dimension::dynamic()}, data_type, "q");
+ auto k = make_param({ov::Dimension::dynamic(), head_num * head_size}, data_type, "k");
+ auto v = make_param({ov::Dimension::dynamic(), head_num * head_size}, data_type, "v");
+
+ // Cache layout: [num_blocks, num_kv_heads, block_size, head_size]
+ // Use data_type directly so TEMPLATE can allocate real tensors without running ConvertPagedAttnInputs.
+ // Mark with keep_const_precision so the CPU's ConvertPrecision pass doesn't insert
+ // Convert nodes around them — the PA kernel modifies caches in-place across steps.
+ auto key_cache = make_param({ov::Dimension::dynamic(), head_num, block_size, head_size}, data_type, "key_cache.0");
+ auto value_cache = make_param({ov::Dimension::dynamic(), head_num, block_size, head_size}, data_type, "value_cache.0");
+ ov::enable_keep_const_precision(key_cache);
+ ov::enable_keep_const_precision(value_cache);
+
+ auto past_lens = make_param({ov::Dimension::dynamic()}, ov::element::i32, "past_lens");
+ auto subseq_begins = make_param({ov::Dimension::dynamic()}, ov::element::i32, "subsequence_begins");
+ auto block_indices = make_param({ov::Dimension::dynamic()}, ov::element::i32, "block_indices");
+ auto block_indices_begins = make_param({ov::Dimension::dynamic()}, ov::element::i32, "block_indices_begins");
+
+ // Use typed empty vectors to avoid Constant::create overload ambiguity
+ const float scale_value = 1.0f / std::sqrt(static_cast<float>(head_size));
+ auto scale = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{}, std::vector<float>{scale_value});
+ auto sliding_windows = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{}, std::vector<int32_t>{sliding_window});
+ std::shared_ptr<ov::op::v0::Constant> alibi_slopes;
+ if (use_alibi) {
+ // Generate slopes: 1.0 / 2^i for i = 0..head_num-1
+ std::vector<float> slopes(static_cast<size_t>(head_num));
+ for (int64_t i = 0; i < head_num; ++i) {
+ slopes[i] = 1.0f / static_cast<float>(1 << i);
+ }
+ alibi_slopes = std::make_shared<ov::op::v0::Constant>(ov::element::f32,
+ ov::Shape{static_cast<size_t>(head_num)}, slopes);
+ } else {
+ alibi_slopes = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{0}, std::vector<float>{});
+ }
+ auto max_context_len = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{}, std::vector<int32_t>{max_ctx_len});
+ // score_window_val < 0 -> use max_ctx_len (all tokens, positive window); 0 -> disabled
+ const int32_t effective_score_window = (score_window_val < 0) ? max_ctx_len : score_window_val;
+ auto score_aggregation_window = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{}, std::vector<int32_t>{effective_score_window});
+
+ std::shared_ptr<ov::op::v0::Constant> rotated_block_indices;
+ std::shared_ptr<ov::op::v0::Constant> rotation_deltas;
+ std::shared_ptr<ov::op::v0::Constant> rotation_trig_lut;
+ if (use_rotation) {
+ // Rotate block 0 with a simple RoPE-style trig LUT
+ // We use per-block granularity: rotation_deltas shape [1, 1] (1 block, delta = 0 => LUT row 0)
+ rotated_block_indices = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{1}, std::vector<int32_t>{0});
+
+ // Per-block delta: single block, single delta pointing to LUT row 0
+ rotated_block_indices_ = std::vector<int32_t>{0};
+ rotation_deltas = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{1, 1}, std::vector<int32_t>{0});
+
+ // Trig LUT: [1, head_size] with layout [cos_0..cos_{half-1}, sin_0..sin_{half-1}]
+ // Use a gentle rotation: cos ~= 0.9, sin ~= 0.1 (not unit-circle exact, but valid for testing)
+ const size_t hs = static_cast<size_t>(head_size);
+ const size_t half = hs / 2;
+ std::vector<float> lut(hs, 0.f);
+ for (size_t d = 0; d < half; ++d) {
+ // Use RoPE-like frequencies: theta_d = 1 / 10000^(2d/head_size)
+ // Apply a rotation of delta_position = 1
+ const float theta = 1.f / std::pow(10000.f, 2.f * static_cast<float>(d) / static_cast<float>(hs));
+ lut[d] = std::cos(theta); // cos part
+ lut[half + d] = std::sin(theta); // sin part
+ }
+ rotation_trig_lut = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{1, hs}, lut);
+ } else {
+ rotated_block_indices = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{0}, std::vector<int32_t>{0});
+ rotation_deltas = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{0}, std::vector<int32_t>{0});
+ rotation_trig_lut = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{0}, std::vector<float>{0});
+ }
+
+ std::shared_ptr<ov::op::v0::Constant> xattention_threshold;
+ if (enable_xattn) {
+ xattention_threshold = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{1}, std::vector<float>{0.9f});
+ } else {
+ xattention_threshold = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{0}, std::vector<float>{0});
+ }
+ auto xattention_block_size = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{}, std::vector<int32_t>{64});
+ auto xattention_stride = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{}, std::vector<int32_t>{8});
+
+ // Sink input: [1, H, 1, 1] when enabled, empty when disabled
+ std::shared_ptr<ov::op::v0::Constant> sinks;
+ if (use_sink_input) {
+ // Use per-head sink values comparable in magnitude to attention logits
+ // so the effect is clearly visible: 3.0 + 0.5 * h
+ const size_t hn = static_cast<size_t>(head_num);
+ std::vector<float> sink_data(hn);
+ for (size_t h = 0; h < hn; ++h) {
+ sink_data[h] = 3.0f + 0.5f * static_cast<float>(h);
+ }
+ sinks = std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{1, hn, 1, 1}, sink_data);
+ } else {
+ sinks = std::make_shared<ov::op::v0::Constant>(data_type, ov::Shape{0}, std::vector<float>{});
+ }
+
+ // adaptive_rkv inputs
+ std::shared_ptr<ov::op::v0::Constant> adaptive_rkv_start_size;
+ std::shared_ptr<ov::op::v0::Constant> adaptive_rkv_evictable_sizes;
+ std::shared_ptr<ov::op::v0::Constant> adaptive_rkv_diversity_block_set_indices;
+ std::shared_ptr<ov::op::v0::Constant> adaptive_rkv_diversity_block_set_indices_begins;
+ if (adaptive_rkv_eviction_size > 0) {
+ // start_size = 0 for simplicity
+ adaptive_rkv_start_size = std::make_shared<ov::op::v0::Constant>(
+ ov::element::i32, ov::Shape{}, std::vector<int32_t>{0});
+ // Single sequence: evictable_sizes = [eviction_size]
+ adaptive_rkv_evictable_sizes = std::make_shared<ov::op::v0::Constant>(
+ ov::element::i32, ov::Shape{1}, std::vector<int32_t>{adaptive_rkv_eviction_size});
+ // block_set_indices: list of block indices in the eviction zone (0..num_eviction_blocks-1)
+ const int32_t num_eviction_blocks = adaptive_rkv_eviction_size / static_cast<int32_t>(block_size);
+ std::vector<int32_t> block_set(static_cast<size_t>(num_eviction_blocks));
+ for (int32_t i = 0; i < num_eviction_blocks; ++i) block_set[i] = i;
+ adaptive_rkv_diversity_block_set_indices = std::make_shared<ov::op::v0::Constant>(
+ ov::element::i32, ov::Shape{static_cast<size_t>(num_eviction_blocks)}, block_set);
+ // begins: [0, num_eviction_blocks] for single sequence
+ adaptive_rkv_diversity_block_set_indices_begins = std::make_shared<ov::op::v0::Constant>(
+ ov::element::i32, ov::Shape{2}, std::vector<int32_t>{0, num_eviction_blocks});
+ } else {
+ adaptive_rkv_start_size = std::make_shared<ov::op::v0::Constant>(
+ ov::element::i32, ov::Shape{}, std::vector<int32_t>{0});
+ adaptive_rkv_evictable_sizes = std::make_shared<ov::op::v0::Constant>(
+ ov::element::i32, ov::Shape{0}, std::vector<int32_t>{0});
+ adaptive_rkv_diversity_block_set_indices = std::make_shared<ov::op::v0::Constant>(
+ ov::element::i32, ov::Shape{0}, std::vector<int32_t>{0});
+ adaptive_rkv_diversity_block_set_indices_begins = std::make_shared<ov::op::v0::Constant>(
+ ov::element::i32, ov::Shape{0}, std::vector<int32_t>{0});
+ }
+
+ ov::ParameterVector params = {q,k,v,key_cache,value_cache,past_lens,subseq_begins,block_indices,block_indices_begins};
+ auto token_type_ids = std::make_shared<ov::op::v0::Constant>(
+ ov::element::i32, ov::Shape{0}, std::vector<int32_t>{});
+ auto qq_bias = std::make_shared<ov::op::v0::Constant>(
+ ov::element::u8, ov::Shape{0}, std::vector<uint8_t>{});
+ auto qq_bias_begins = std::make_shared<ov::op::v0::Constant>(
+ ov::element::i32, ov::Shape{0}, std::vector<int32_t>{});
+ ov::OutputVector pa_inputs = {q,k,v,key_cache,value_cache,past_lens,subseq_begins,block_indices,block_indices_begins,
+ scale,sliding_windows,alibi_slopes,max_context_len,score_aggregation_window,
+ rotated_block_indices,rotation_deltas,rotation_trig_lut,
+ xattention_threshold,xattention_block_size,xattention_stride,
+ sinks,
+ adaptive_rkv_start_size,adaptive_rkv_evictable_sizes,
+ adaptive_rkv_diversity_block_set_indices,adaptive_rkv_diversity_block_set_indices_begins,
+ token_type_ids,
+ qq_bias,qq_bias_begins};
+
+ auto pa = std::make_shared<ov::op::PagedAttentionExtension>(pa_inputs);
+
+ // Head metadata for ConvertPagedAttnInputs transformation
+ auto& rt = pa->get_rt_info();
+ rt["num_k_heads"] = static_cast<size_t>(head_num);
+ rt["k_head_size"] = static_cast<size_t>(head_size);
+ rt["num_v_heads"] = static_cast<size_t>(head_num);
+ rt["v_head_size"] = static_cast<size_t>(head_size);
+
+ // Only wire output 2 (diversity) when adaptive RKV is active,
+ // since CPU does not compute it.
+ ov::OutputVector model_outputs = {pa->output(0), pa->output(1)};
+ if (adaptive_rkv_eviction_size > 0) {
+ model_outputs.push_back(pa->output(2));
+ }
+ auto model = std::make_shared<ov::Model>(model_outputs, params, "pa_vsref");
+ return model;
+ }
+
+ // Input generation like in the CPU plugin
+ template <typename IT, typename T>
+ static void strided_iota(IT first, size_t n, T value, T stride) {
+ for (size_t i = 0; i < n; i++) {
+ const float idx = static_cast<float>(n - 1 - i);
+ *first++ = static_cast<T>(value + stride * static_cast<T>(idx));
+ }
+ }
+
+ struct StepInputs {
+ std::map<std::shared_ptr<ov::op::v0::Parameter>, ov::Tensor> tensors;
+ };
+
+ StepInputs make_step_inputs(const std::shared_ptr<ov::Model>& model,
+ const ov::Shape& lbhs,
+ int step_idx,
+ bool extendBlockIndices,
+ ov::Tensor& key_cache,
+ ov::Tensor& value_cache,
+ int32_t& past_len_count) {
+ StepInputs out;
+ auto params = model->get_parameters();
+
+ const size_t L = lbhs[0], B = lbhs[1], H = lbhs[2], S = lbhs[3];
+ const size_t tokens = L * B;
+ const size_t feats = H * S;
+
+ auto fill_fp = [&](ov::Tensor& t, float base) {
+ if (t.get_element_type() == ov::element::f32)
+ strided_iota(static_cast<float*>(t.data()), t.get_size(), base, 0.1f);
+ else if (t.get_element_type() == ov::element::f16)
+ strided_iota(static_cast<ov::float16*>(t.data()), t.get_size(), static_cast<ov::float16>(base), ov::float16(0.1f));
+ else
+ strided_iota(static_cast<ov::bfloat16*>(t.data()), t.get_size(), static_cast<ov::bfloat16>(base), ov::bfloat16(0.1f));
+ };
+
+ // q,k,v
+ {
+ ov::Tensor tq(params[0]->get_element_type(), {tokens, feats});
+ ov::Tensor tk(params[1]->get_element_type(), {tokens, feats});
+ ov::Tensor tv(params[2]->get_element_type(), {tokens, feats});
+ fill_fp(tq, step_idx + 1.f);
+ fill_fp(tk, step_idx + 2.f);
+ fill_fp(tv, step_idx + 3.f);
+ out.tensors[params[0]] = tq;
+ out.tensors[params[1]] = tk;
+ out.tensors[params[2]] = tv;
+ }
+
+ // cache tensors (already allocated outside)
+ out.tensors[params[3]] = key_cache;
+ out.tensors[params[4]] = value_cache;
+
+
+ // past_lens/subseq/block tables
+ const size_t block_size = key_cache.get_shape().at(2);
+ const size_t batch_seq = B;
+
+ // number of blocks needed PER SEQUENCE (batch item)
+ const int32_t used_blocks_per_seq = std::max<int32_t>(
+ 1,
+ static_cast<int32_t>((static_cast<int64_t>(past_len_count) + static_cast<int64_t>(L) +
+ static_cast<int64_t>(block_size) - 1) /
+ static_cast<int64_t>(block_size)));
+
+ OPENVINO_ASSERT(static_cast<size_t>(used_blocks_per_seq) <= max_blocks_per_seq_,
+ "PagedAttention test: cache plan too small for current step");
+
+ const int32_t bi_count_per_seq =
+ extendBlockIndices ? std::max<int32_t>(2, used_blocks_per_seq) : used_blocks_per_seq;
+
+ ov::Tensor past_lens(ov::element::i32, {batch_seq});
+ ov::Tensor subseq(ov::element::i32, {batch_seq + 1});
+ ov::Tensor bi_begins(ov::element::i32, {batch_seq + 1});
+ ov::Tensor bi(ov::element::i32, {batch_seq * static_cast<size_t>(bi_count_per_seq)});
+
+ auto* pl = past_lens.data<int32_t>();
+ auto* sb = subseq.data<int32_t>();
+ auto* bb = bi_begins.data<int32_t>();
+ auto* b = bi.data<int32_t>();
+
+ for (size_t s = 0; s < batch_seq; ++s) {
+ pl[s] = (step_idx == 0) ? 0 : past_len_count;
+ sb[s] = static_cast<int32_t>(s * L);
+ bb[s] = static_cast<int32_t>(s * static_cast<size_t>(bi_count_per_seq));
+
+ const int32_t block_base = static_cast<int32_t>(s * max_blocks_per_seq_);
+ for (int32_t i = 0; i < bi_count_per_seq; ++i) {
+ b[bb[s] + i] = (i < used_blocks_per_seq) ? (block_base + i) : -1;
+ }
+ }
+
+ sb[batch_seq] = static_cast<int32_t>(tokens);
+ bb[batch_seq] = static_cast<int32_t>(batch_seq * static_cast<size_t>(bi_count_per_seq));
+
+ out.tensors[params[5]] = past_lens;
+ out.tensors[params[6]] = subseq;
+ out.tensors[params[7]] = bi;
+ out.tensors[params[8]] = bi_begins;
+
+ past_len_count += static_cast<int32_t>(L);
+
+ return out;
+ }
+
+public:
+ std::vector<std::vector<ov::Tensor>> run_device(ov::Core& core,
+ const std::shared_ptr<ov::Model>& model,
+ const std::string& device,
+ ov::AnyMap cfg,
+ bool extendBlockIndices,
+ const std::vector<StepInputs>& steps) {
+ auto compiled = core.compile_model(model, device, cfg);
+ auto req = compiled.create_infer_request();
+ const size_t num_outputs = compiled.outputs().size();
+
+ std::vector<std::vector<ov::Tensor>> outs;
+ outs.reserve(steps.size());
+
+ for (size_t si = 0; si < steps.size(); ++si) {
+ const auto& step = steps[si];
+ for (const auto& kv : step.tensors) {
+ req.set_tensor(kv.first, kv.second);
+ }
+
+ req.infer();
+
+ std::vector<ov::Tensor> step_outs;
+ step_outs.reserve(num_outputs);
+ for (size_t oi = 0; oi < num_outputs; ++oi) {
+ auto t = req.get_output_tensor(oi);
+ ov::Tensor copy(t.get_element_type(), t.get_shape());
+ t.copy_to(copy);
+ step_outs.push_back(std::move(copy));
+ }
+ outs.push_back(std::move(step_outs));
+ }
+ return outs;
+ }
+
+ void SetUp() override {
+ is_report_stages = true;
+ const auto& [inType, inputShapes, extendBlockIndices, enableXattn, sinkInput, slidingWindow, useAlibi, maxContextLen, additional_config] = GetParam();
+
+ init_input_shapes(inputShapes);
+
+ // Derive H (num_heads) and S (head_size) from the first target shape [L,B,H,S]
+ OPENVINO_ASSERT(!targetStaticShapes.empty() && targetStaticShapes[0][0].size() == 4,
+ "PagedAttention test expects [L,B,H,S] shapes");
+ const int64_t head_num = static_cast<int64_t>(targetStaticShapes[0][0][2]);
+ const int64_t head_size = static_cast<int64_t>(targetStaticShapes[0][0][3]);
+
+ // Check if rotation is requested via the additional config map
+ use_rotation_ = false;
+ {
+ auto it = additional_config.find("test_use_rotation");
+ if (it != additional_config.end()) {
+ use_rotation_ = it->second.as<bool>();
+ }
+ }
+
+ // Check for adaptive RKV parameters
+ int64_t cfg_block_size = 32;
+ int32_t cfg_arkv_eviction_size = 0;
+ {
+ auto it = additional_config.find("test_block_size");
+ if (it != additional_config.end()) {
+ cfg_block_size = static_cast<int64_t>(it->second.as<int>());
+ }
+ }
+ {
+ auto it = additional_config.find("test_adaptive_rkv_eviction_size");
+ if (it != additional_config.end()) {
+ cfg_arkv_eviction_size = static_cast<int32_t>(it->second.as<int>());
+ }
+ }
+
+ pa_model_ = make_paged_attn_model(inType, enableXattn, head_size, head_num, sinkInput, slidingWindow, useAlibi, maxContextLen, use_rotation_, cfg_block_size, cfg_arkv_eviction_size);
+
+ // Pre-generate the step inputs once, so the CPU/TEMPLATE see identical tensors
+ // Allocate caches once here, and reuse for both runs by copying initial cache state
+ {
+ const auto& kc_ps = pa_model_->get_parameters()[3]->get_partial_shape();
+ OPENVINO_ASSERT(kc_ps.rank().is_static() && kc_ps.rank().get_length() == 4,
+ "PagedAttention test: expected key_cache rank 4");
+ OPENVINO_ASSERT(kc_ps[2].is_static(), "PagedAttention test: expected static block_size dimension in cache");
+ block_size_ = static_cast<size_t>(kc_ps[2].get_length());
+
+ // We treat each batch item as an independent sequence in metadata tensors
+ // Ensure cache has enough blocks per sequence for the entire multi-step run
+ batch_size_ = targetStaticShapes.empty() ? 1 : targetStaticShapes[0][0][1];
+ max_blocks_per_seq_ = 1;
+ int32_t past_tmp = 0;
+
+ for (size_t i = 0; i < targetStaticShapes.size(); ++i) {
+ const auto& lbhs = targetStaticShapes[i][0];
+ OPENVINO_ASSERT(lbhs.size() == 4, "PagedAttention test expects [L,B,H,S] shapes");
+ const size_t L = lbhs[0];
+ const size_t B = lbhs[1];
+ if (i == 0) {
+ batch_size_ = B;
+ } else {
+ OPENVINO_ASSERT(B == batch_size_, "PagedAttention test expects stable batch across steps");
+ }
+
+ const size_t blocks_now =
+ std::max<size_t>(1, (static_cast<size_t>(past_tmp) + L + block_size_ - 1) / block_size_);
+ max_blocks_per_seq_ = std::max(max_blocks_per_seq_, blocks_now);
+ past_tmp += static_cast<int32_t>(L);
+ }
+
+ allocate_caches_for_model(pa_model_, batch_size_ * max_blocks_per_seq_, inType);
+ }
+
+ int32_t past = 0;
+ steps_.clear();
+ steps_.reserve(targetStaticShapes.size());
+ for (size_t i = 0; i < targetStaticShapes.size(); ++i) {
+ steps_.push_back(make_step_inputs(pa_model_, targetStaticShapes[i][0], static_cast<int>(i),
+ extendBlockIndices, key_cache_init_, value_cache_init_, past));
+ }
+ }
+
+ void allocate_caches_for_model(const std::shared_ptr<ov::Model>& model,
+ size_t block_nums,
+ ov::element::Type inType) {
+ // Use model parameter shapes directly (not compiled model) for determinism
+ auto params = model->get_parameters();
+ auto kc = params[3];
+ auto vc = params[4];
+
+ auto ps_k = kc->get_partial_shape();
+ auto ps_v = vc->get_partial_shape();
+ OPENVINO_ASSERT(ps_k.rank().is_static() && ps_k.rank().get_length() == 4);
+ OPENVINO_ASSERT(ps_v.rank().is_static() && ps_v.rank().get_length() == 4);
+
+ ps_k[0] = static_cast<int64_t>(block_nums);
+ ps_v[0] = static_cast<int64_t>(block_nums);
+
+ // Allocate caches using the same element type as PA expects
+ key_cache_init_ = ov::Tensor(inType, ps_k.get_shape());
+ value_cache_init_ = ov::Tensor(inType, ps_v.get_shape());
+ std::memset(key_cache_init_.data(), 0, key_cache_init_.get_byte_size());
+ std::memset(value_cache_init_.data(), 0, value_cache_init_.get_byte_size());
+ }
+
+protected:
+ size_t block_size_ = 32;
+ size_t max_blocks_per_seq_ = 1;
+ size_t batch_size_ = 1;
+ bool use_rotation_ = false;
+
+ std::shared_ptr<ov::Model> pa_model_;
+ ov::Tensor key_cache_init_;
+ ov::Tensor value_cache_init_;
+ std::vector<StepInputs> steps_;
+ std::vector<int32_t> rotated_block_indices_; // stored for debug prints
+};
+
+} // namespace test
+} // namespace ov
diff --git a/src/tests/functional/plugin/shared/include/single_op_tests/paged_attention.hpp b/src/tests/functional/plugin/shared/include/single_op_tests/paged_attention.hpp
new file mode 100644
index 00000000000..d524c4dd163
--- /dev/null
+++ b/src/tests/functional/plugin/shared/include/single_op_tests/paged_attention.hpp
@@ -0,0 +1,195 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "shared_test_classes/single_op/paged_attention.hpp"
+#include "common_test_utils/common_utils.hpp"
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "openvino/runtime/system_conf.hpp"
+
+namespace ov {
+namespace test {
+
+TEST_P(PagedAttentionLayerTest, Inference) {
+ const auto& [inType, inputShapes, extendBlockIndices, enableXattn, sinkInput, slidingWindow, useAlibi, maxContextLen, additional_config] = GetParam();
+ (void)inputShapes; (void)enableXattn; (void)sinkInput; (void)slidingWindow; (void)useAlibi; (void)maxContextLen;
+
+#ifdef OPENVINO_ARCH_X86_64
+ if (inType == ov::element::f16 && !ov::with_cpu_x86_avx512_core_fp16())
+ GTEST_SKIP() << "f16 PA requires AVX512-FP16 hardware";
+ if (inType == ov::element::bf16 && !ov::with_cpu_x86_bfloat16())
+ GTEST_SKIP() << "bf16 PA requires BF16 hardware";
+#endif
+
+ // Use a single ov::Core to avoid re-registration errors
+ auto& core_ref = *core;
+
+ // Read per-instantiation comparison thresholds (default: 1e-3 abs, 1e-2 rel)
+ float test_abs_threshold = 1e-3f;
+ float test_rel_threshold = 1e-2f;
+ {
+ auto it = additional_config.find("test_abs_threshold");
+ if (it != additional_config.end()) test_abs_threshold = it->second.as<float>();
+ it = additional_config.find("test_rel_threshold");
+ if (it != additional_config.end()) test_rel_threshold = it->second.as<float>();
+ }
+
+ // Strip test-only keys from CPU config.
+ // inference_precision=f32 keeps ConvertPrecision from converting f32 Constants
+ // (scale, alibi) to f16/bf16, which would corrupt PA kernel arithmetic.
+ ov::AnyMap cpu_cfg = additional_config;
+ cpu_cfg.erase("test_use_rotation");
+ cpu_cfg.erase("test_block_size");
+ cpu_cfg.erase("test_adaptive_rkv_eviction_size");
+ cpu_cfg.erase("test_abs_threshold");
+ cpu_cfg.erase("test_rel_threshold");
+ cpu_cfg[ov::hint::inference_precision.name()] = ov::element::f32;
+
+ ov::AnyMap tmpl_cfg;
+ tmpl_cfg[ov::hint::inference_precision.name()] = ov::element::f32;
+ // Run CPU with fresh cache copies (the plugin mutates them in-place)
+ ov::Tensor key_cache_cpu(key_cache_init_.get_element_type(), key_cache_init_.get_shape());
+ ov::Tensor value_cache_cpu(value_cache_init_.get_element_type(), value_cache_init_.get_shape());
+ key_cache_init_.copy_to(key_cache_cpu);
+ value_cache_init_.copy_to(value_cache_cpu);
+
+ auto steps_cpu = steps_;
+ for (auto& s : steps_cpu) {
+ s.tensors[pa_model_->get_parameters()[3]] = key_cache_cpu;
+ s.tensors[pa_model_->get_parameters()[4]] = value_cache_cpu;
+ }
+ auto cpu_out = run_device(core_ref, pa_model_, ov::test::utils::DEVICE_CPU, cpu_cfg, extendBlockIndices, steps_cpu);
+
+ // Run TEMPLATE with an independent fresh cache copy
+ ov::Tensor key_cache_tmpl(key_cache_init_.get_element_type(), key_cache_init_.get_shape());
+ ov::Tensor value_cache_tmpl(value_cache_init_.get_element_type(), value_cache_init_.get_shape());
+ key_cache_init_.copy_to(key_cache_tmpl);
+ value_cache_init_.copy_to(value_cache_tmpl);
+
+ auto steps_tmpl = steps_;
+ for (auto& s : steps_tmpl) {
+ s.tensors[pa_model_->get_parameters()[3]] = key_cache_tmpl;
+ s.tensors[pa_model_->get_parameters()[4]] = value_cache_tmpl;
+ }
+ auto tmpl_out = run_device(core_ref, pa_model_, ov::test::utils::DEVICE_TEMPLATE, tmpl_cfg, extendBlockIndices, steps_tmpl);
+
+ OPENVINO_ASSERT(cpu_out.size() == tmpl_out.size(), "PA verify: step count mismatch");
+ for (size_t i = 0; i < cpu_out.size(); ++i) {
+ const size_t n_outs = cpu_out[i].size();
+ OPENVINO_ASSERT(n_outs == tmpl_out[i].size(), "PA verify: output count mismatch at step ", i);
+ for (size_t oi = 0; oi < n_outs; ++oi) {
+ const auto& ct = cpu_out[i][oi];
+ const auto& tt = tmpl_out[i][oi];
+ // Guard against empty tensors
+ if (ct.get_size() == 0 || tt.get_size() == 0) {
+ continue;
+ }
+ // Output 2 (diversity): only computed by TEMPLATE, skip comparison
+ if (oi > 1) {
+ continue;
+ }
+ ov::test::utils::compare(tt, ct, test_abs_threshold, test_rel_threshold);
+ }
+ }
+}
+
+// Verify that score_aggregation_window=0 produces all-zero output 1.
+TEST_P(PagedAttentionLayerTest, ScoreWindowZeroZerosOutput1) {
+ const auto& [inType, inputShapes, extendBlockIndices, enableXattn, sinkInput, slidingWindow, useAlibi, maxContextLen, additional_config] = GetParam();
+ (void)inputShapes; (void)enableXattn; (void)sinkInput; (void)slidingWindow; (void)useAlibi; (void)maxContextLen;
+
+#ifdef OPENVINO_ARCH_X86_64
+ if (inType == ov::element::f16 && !ov::with_cpu_x86_avx512_core_fp16())
+ GTEST_SKIP() << "f16 PA requires AVX512-FP16 hardware";
+ if (inType == ov::element::bf16 && !ov::with_cpu_x86_bfloat16())
+ GTEST_SKIP() << "bf16 PA requires BF16 hardware";
+#endif
+
+ int64_t cfg_block_size = 32;
+ {
+ auto it = additional_config.find("test_block_size");
+ if (it != additional_config.end())
+ cfg_block_size = static_cast<int64_t>(it->second.as<int>());
+ }
+
+ OPENVINO_ASSERT(!targetStaticShapes.empty() && targetStaticShapes[0][0].size() == 4,
+ "PagedAttention test expects [L,B,H,S] shapes");
+ const int64_t head_num = static_cast<int64_t>(targetStaticShapes[0][0][2]);
+ const int64_t head_size = static_cast<int64_t>(targetStaticShapes[0][0][3]);
+
+ // Build model with score_aggregation_window = 0 and output 1 wired
+ auto model_zero = make_paged_attn_model(inType, /*enable_xattn=*/false, head_size, head_num,
+ /*use_sink=*/false, /*sliding_window=*/0, /*use_alibi=*/false,
+ /*max_ctx_len=*/maxContextLen, /*use_rotation=*/false,
+ cfg_block_size, /*arkv=*/0, /*score_window_val=*/0);
+
+ // Allocate fresh zero-initialized caches for this model
+ ov::Tensor kc0(inType, key_cache_init_.get_shape());
+ ov::Tensor vc0(inType, value_cache_init_.get_shape());
+ std::memset(kc0.data(), 0, kc0.get_byte_size());
+ std::memset(vc0.data(), 0, vc0.get_byte_size());
+
+ // Build step inputs against the new model's parameters
+ int32_t past = 0;
+ std::vector<StepInputs> steps_zero;
+ steps_zero.reserve(targetStaticShapes.size());
+ for (size_t i = 0; i < targetStaticShapes.size(); ++i) {
+ steps_zero.push_back(make_step_inputs(model_zero, targetStaticShapes[i][0],
+ static_cast<int>(i), extendBlockIndices,
+ kc0, vc0, past));
+ }
+
+ ov::AnyMap tmpl_cfg;
+ tmpl_cfg[ov::hint::inference_precision.name()] = ov::element::f32;
+
+ // Strip test-only keys; inference_precision=f32 keeps f32 Constants (scale, alibi) unconverted.
+ ov::AnyMap cpu_cfg = additional_config;
+ cpu_cfg.erase("test_use_rotation");
+ cpu_cfg.erase("test_block_size");
+ cpu_cfg.erase("test_adaptive_rkv_eviction_size");
+ cpu_cfg.erase("test_abs_threshold");
+ cpu_cfg.erase("test_rel_threshold");
+ cpu_cfg[ov::hint::inference_precision.name()] = ov::element::f32;
+
+ ov::Tensor kc_cpu(inType, key_cache_init_.get_shape());
+ ov::Tensor vc_cpu(inType, value_cache_init_.get_shape());
+ std::memset(kc_cpu.data(), 0, kc_cpu.get_byte_size());
+ std::memset(vc_cpu.data(), 0, vc_cpu.get_byte_size());
+ auto steps_cpu = steps_zero;
+ for (auto& s : steps_cpu) {
+ s.tensors[model_zero->get_parameters()[3]] = kc_cpu;
+ s.tensors[model_zero->get_parameters()[4]] = vc_cpu;
+ }
+
+ auto tmpl_out = run_device(*core, model_zero, ov::test::utils::DEVICE_TEMPLATE,
+ tmpl_cfg, extendBlockIndices, steps_zero);
+ auto cpu_out = run_device(*core, model_zero, ov::test::utils::DEVICE_CPU,
+ cpu_cfg, extendBlockIndices, steps_cpu);
+
+ for (size_t step = 0; step < tmpl_out.size(); ++step) {
+ for (const auto* outs : {&tmpl_out[step], &cpu_out[step]}) {
+ ASSERT_GE(outs->size(), 2u) << "Expected at least 2 outputs at step " << step;
+ const auto& scores = (*outs)[1];
+ ASSERT_GT(scores.get_size(), 0u) << "score output is empty at step " << step;
+ // Read scores as f32 regardless of storage type
+ const auto et = scores.get_element_type();
+ for (size_t j = 0; j < scores.get_size(); ++j) {
+ float v = 0.f;
+ if (et == ov::element::f32)
+ v = static_cast<const float*>(scores.data())[j];
+ else if (et == ov::element::f16)
+ v = static_cast<float>(static_cast<const ov::float16*>(scores.data())[j]);
+ else if (et == ov::element::bf16)
+ v = static_cast<float>(static_cast<const ov::bfloat16*>(scores.data())[j]);
+ EXPECT_EQ(v, 0.f)
+ << "output 1 not zero at step=" << step << " index=" << j
+ << " (score_aggregation_window=0)";
+ }
+ }
+ }
+}
+
+} // namespace test
+} // namespace ov