Skip to content

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

[CPU] enable adaptive r-kv algorithm support (#35254)

Xiuchuan Zhai28217a1f1385
diff --git a/src/common/transformations/src/transformations/paged_attention/convert_pagedattn_inputs.cpp b/src/common/transformations/src/transformations/paged_attention/convert_pagedattn_inputs.cpp
index cfd935978eb..ed72bf59283 100644
--- a/src/common/transformations/src/transformations/paged_attention/convert_pagedattn_inputs.cpp
+++ b/src/common/transformations/src/transformations/paged_attention/convert_pagedattn_inputs.cpp
@@ -16,6 +16,7 @@
#include "openvino/op/paged_gated_delta_net.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
#include "openvino/util/log.hpp"
+#include "transformations/rt_info/keep_const_precision.hpp"
#include "transformations/utils/utils.hpp"
using namespace ov::pass;
@@ -118,6 +119,15 @@ ConvertPagedAttnInputs::ConvertPagedAttnInputs(const KVCacheConfig& config,
value_cache->set_element_type(value_cache_precision);
}
+ // Prevent the ConvertPrecision pass from converting sub-byte cache
+ // precisions (e.g. u4→u8). The PA executor handles quantized caches natively.
+ if (key_cache_precision.bitwidth() < 8) {
+ enable_keep_const_precision(key_cache);
+ }
+ if (value_cache_precision.bitwidth() < 8) {
+ enable_keep_const_precision(value_cache);
+ }
+
key_cache->validate_and_infer_types();
value_cache->validate_and_infer_types();
}
diff --git a/src/core/shape_inference/include/paged_attention_shape_inference.hpp b/src/core/shape_inference/include/paged_attention_shape_inference.hpp
index d9d44afb428..ebf81e874e3 100644
--- a/src/core/shape_inference/include/paged_attention_shape_inference.hpp
+++ b/src/core/shape_inference/include/paged_attention_shape_inference.hpp
@@ -4,6 +4,8 @@
#pragma once
+#include <optional>
+
#include "dimension_util.hpp"
#include "openvino/op/paged_attention.hpp"
#include "utils.hpp"
@@ -68,8 +70,8 @@ std::vector<TRShape> shape_infer(const PagedAttentionExtension* op,
scores_ps.push_back(Dimension::dynamic());
}
- // Output[2]: flat 1D diversity scores.
- // Size = sum(evictable_sizes[s]^2 / block_size); dynamic if unknown.
+ // Output[2]: flat 1D Adaptive-RKV diversity scores.
+ // Size = sum(evictable_sizes[s]^2 / adaptive_rkv_block_size); dynamic if unknown.
auto& diversity_ps = output_shapes[2];
auto width_dim = Dimension::dynamic();
@@ -77,10 +79,50 @@ std::vector<TRShape> shape_infer(const PagedAttentionExtension* op,
const bool block_size_known =
key_cache_ps.rank().is_static() && key_cache_ps.rank().get_length() >= 3 && key_cache_ps[2].is_static();
+ auto infer_adaptive_rkv_diversity_block_size = [&]() -> std::optional<int64_t> {
+ if (!block_size_known) {
+ return std::nullopt;
+ }
+
+ int64_t block_size = key_cache_ps[2].get_length();
+ if (!(key_cache_ps.rank().is_static() && key_cache_ps.rank().get_length() >= 4 && key_cache_ps[1].is_static() &&
+ key_cache_ps[3].is_static() && key_ps.rank().is_static() && key_ps.rank().get_length() >= 2 &&
+ key_ps[1].is_static())) {
+ return block_size;
+ }
+
+ const auto key_cache_et = op->get_input_element_type(3);
+ const auto key_cache_bitwidth = key_cache_et.bitwidth();
+ if (key_cache_bitwidth != 8 && key_cache_bitwidth != 4) {
+ return block_size;
+ }
+
+ const int64_t hkv = key_cache_ps[1].get_length();
+ const int64_t key_feature_size = key_ps[1].get_length();
+ if (hkv == 0 || key_feature_size % hkv != 0) {
+ return block_size;
+ }
+
+ const int64_t head_size = key_feature_size / hkv;
+ const bool by_channel_layout = key_cache_ps[3].get_length() == head_size;
+ if (!by_channel_layout) {
+ return block_size;
+ }
+
+ const int64_t params_count = (key_cache_et == element::i8 || key_cache_et == element::i4) ? 1 : 2;
+ const int64_t sub_byte_multiplier = 8 / key_cache_bitwidth;
+ return block_size - static_cast<int64_t>(sizeof(float)) * params_count * sub_byte_multiplier;
+ };
+
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();
+ const auto inferred_block_size = infer_adaptive_rkv_diversity_block_size();
+ if (!inferred_block_size.has_value() || inferred_block_size.value() <= 0) {
+ diversity_ps.push_back(width_dim);
+ return output_shapes;
+ }
+ const int64_t block_size = inferred_block_size.value();
int64_t total = 0;
for (const auto es : evictable_sizes.value()) {
total += static_cast<int64_t>(es) * static_cast<int64_t>(es) / block_size;
diff --git a/src/core/tests/type_prop/paged_attention.cpp b/src/core/tests/type_prop/paged_attention.cpp
index 3c3ba6d3ddc..90509d63a25 100644
--- a/src/core/tests/type_prop/paged_attention.cpp
+++ b/src/core/tests/type_prop/paged_attention.cpp
@@ -405,6 +405,74 @@ TEST(type_prop, paged_attention_outputs_1_and_2_shapes) {
EXPECT_EQ(op->get_output_element_type(2), element::f32);
}
+TEST(type_prop, paged_attention_adaptive_rkv_quantized_bychannel_diversity_shape) {
+ using namespace ov::op;
+
+ const auto query = std::make_shared<v0::Parameter>(element::f32, PartialShape{1, 64});
+ const auto key = std::make_shared<v0::Parameter>(element::f32, PartialShape{1, 64});
+ const auto value = std::make_shared<v0::Parameter>(element::f32, PartialShape{1, 64});
+ const auto key_cache = std::make_shared<v0::Parameter>(element::u4, PartialShape{4, 2, 48, 32});
+ const auto value_cache = std::make_shared<v0::Parameter>(element::u4, PartialShape{4, 2, 48, 32});
+ const auto past_lens = std::make_shared<v0::Constant>(element::i32, Shape{1}, std::vector<int32_t>{0});
+ const auto subsequence_begins = std::make_shared<v0::Parameter>(element::i32, PartialShape{2});
+ const auto block_indices = std::make_shared<v0::Parameter>(element::i32, PartialShape{1});
+ const auto block_indices_begins = std::make_shared<v0::Parameter>(element::i32, PartialShape{2});
+ const auto scale = std::make_shared<v0::Parameter>(element::f32, PartialShape{});
+ const auto sliding_window = std::make_shared<v0::Parameter>(element::i32, PartialShape{});
+ const auto alibi_slopes = std::make_shared<v0::Parameter>(element::f32, PartialShape{0});
+ const auto max_context_len = std::make_shared<v0::Parameter>(element::i32, PartialShape{});
+ const auto score_aggregation_window = std::make_shared<v0::Parameter>(element::i32, PartialShape{});
+ const auto rotated_block_indices = std::make_shared<v0::Parameter>(element::i32, PartialShape{0});
+ const auto rotation_deltas = std::make_shared<v0::Parameter>(element::i32, PartialShape{0});
+ const auto rotation_trig_lut = std::make_shared<v0::Parameter>(element::f32, PartialShape{0});
+ const auto xattention_threshold = std::make_shared<v0::Parameter>(element::f32, PartialShape{0});
+ const auto xattention_block_size = std::make_shared<v0::Parameter>(element::i32, PartialShape{});
+ const auto xattention_stride = std::make_shared<v0::Parameter>(element::i32, PartialShape{});
+ const auto sinks = std::make_shared<v0::Parameter>(element::f32, PartialShape{0});
+ const auto adaptive_rkv_start_size = std::make_shared<v0::Constant>(element::i32, Shape{}, std::vector<int32_t>{0});
+ const auto adaptive_rkv_evictable_sizes =
+ std::make_shared<v0::Constant>(element::i32, Shape{1}, std::vector<int32_t>{32});
+ const auto adaptive_rkv_diversity_block_set_indices =
+ std::make_shared<v0::Parameter>(element::i32, PartialShape{1});
+ const auto adaptive_rkv_diversity_block_set_indices_begins =
+ std::make_shared<v0::Parameter>(element::i32, PartialShape{2});
+ const auto token_type_ids = std::make_shared<v0::Parameter>(element::i32, PartialShape{0});
+ const auto qq_bias = std::make_shared<v0::Parameter>(element::u8, PartialShape{0});
+ const auto qq_bias_begins = std::make_shared<v0::Parameter>(element::i32, PartialShape{0});
+
+ OutputVector args = {query,
+ key,
+ value,
+ key_cache,
+ value_cache,
+ past_lens,
+ subsequence_begins,
+ block_indices,
+ block_indices_begins,
+ scale,
+ sliding_window,
+ 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};
+
+ const auto op = std::make_shared<op::PagedAttentionExtension>(args);
+ EXPECT_EQ(op->get_output_partial_shape(2), (PartialShape{32}));
+}
+
static ov::OutputVector make_args_with_token_type(const std::shared_ptr<ov::op::v0::Parameter>& token_type_ids) {
using namespace ov::op;
const auto query = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{3, 4});
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hpp
index f83403c60d6..666bb4ea98c 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hpp
@@ -1255,4 +1255,71 @@ inline void multiply_scalar(ov::float16* a, ov::float16* a_dst, const ov::float1
}
#endif
+inline float reduce_sum(const float* data, size_t n) {
+ float s = 0.0f;
+ size_t i = 0;
+#if defined(HAVE_AVX512F)
+ {
+ auto vsum = _mm512_setzero_ps();
+ for (; i + vec_len_f32_avx512 <= n; i += vec_len_f32_avx512) {
+ vsum = _mm512_add_ps(vsum, _mm512_loadu_ps(data + i));
+ }
+ s = _mm512_reduce_add_ps(vsum);
+ }
+#elif defined(HAVE_AVX2)
+ {
+ auto vsum = _mm256_setzero_ps();
+ for (; i + vec_len_f32_avx2 <= n; i += vec_len_f32_avx2) {
+ vsum = _mm256_add_ps(vsum, _mm256_loadu_ps(data + i));
+ }
+ hsum(vsum);
+ s = _mm256_cvtss_f32(vsum);
+ }
+#elif defined(OPENVINO_ARCH_ARM64) && defined(HAVE_SVE)
+ {
+ auto sve_len = vec_len_f32_sve();
+ svbool_t pg = svptrue_b32();
+ svfloat32_t svs = svdup_n_f32(0.0f);
+ for (; i + sve_len <= n; i += sve_len) {
+ svs = svadd_f32_z(pg, svs, svld1_f32(pg, data + i));
+ }
+ s = svaddv_f32(pg, svs);
+ }
+#endif
+ for (; i < n; i++) {
+ s += data[i];
+ }
+ return s;
+}
+
+// Elementwise subtraction: dst[i] = a[i] - b[i]
+inline void eltwise_sub(const float* a, const float* b, float* dst, size_t n) {
+ size_t i = 0;
+#if defined(HAVE_AVX512F)
+ for (; i + vec_len_f32_avx512 <= n; i += vec_len_f32_avx512) {
+ _mm512_storeu_ps(dst + i, _mm512_sub_ps(_mm512_loadu_ps(a + i), _mm512_loadu_ps(b + i)));
+ }
+#elif defined(HAVE_AVX2)
+ for (; i + vec_len_f32_avx2 <= n; i += vec_len_f32_avx2) {
+ _mm256_storeu_ps(dst + i, _mm256_sub_ps(_mm256_loadu_ps(a + i), _mm256_loadu_ps(b + i)));
+ }
+#elif defined(OPENVINO_ARCH_ARM64) && defined(HAVE_SVE)
+ {
+ auto sve_len = vec_len_f32_sve();
+ svbool_t pg = svptrue_b32();
+ for (; i + sve_len <= n; i += sve_len) {
+ svst1_f32(pg, dst + i, svsub_f32_z(pg, svld1_f32(pg, a + i), svld1_f32(pg, b + i)));
+ }
+ }
+#endif
+ for (; i < n; i++) {
+ dst[i] = a[i] - b[i];
+ }
+}
+
+// Elementwise subtraction in-place: a[i] = a[i] - b[i]
+inline void eltwise_sub_(float* a, const float* b, size_t n) {
+ eltwise_sub(a, b, a, n);
+}
+
} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp
index 6584caff456..04914810f16 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp
@@ -86,7 +86,7 @@ static inline void dequant(float* dst,
template <typename TDST,
ov::element::Type_t SRC_PREC,
- std::enable_if_t<any_of(SRC_PREC, ov::element::u4, ov::element::u8), bool> = true>
+ std::enable_if_t<any_of(SRC_PREC, ov::element::i8, ov::element::u4, ov::element::u8), bool> = true>
void dequant(TDST* dst,
void* src,
const size_t N,
@@ -95,17 +95,20 @@ void dequant(TDST* dst,
const size_t group_size,
const bool quant_bychannel) {
// The layout for per token per head:
- // |scale(f32)|zeropoint(f32)|quantized feature(u8,idx_1)|quantized feature(u8,idx_2)|...|quantized
- // feature(u8,idx_S)| The quantized feature will start from 8bytes=sizeof(float)+sizeof(float)
+ // i8: |scale(f32)|quantized feature(i8,idx_1)|...|quantized feature(i8,idx_S)|
+ // u8/u4: |scale(f32)|zeropoint(f32)|quantized feature(u8,idx_1)|...|quantized feature(u8,idx_S)|
auto* s = reinterpret_cast<uint8_t*>(src);
- const size_t params_offset = sizeof(float) * 2;
constexpr size_t sub_byte_multiplier = get_sub_byte_multiplier(SRC_PREC);
+ constexpr size_t param_count = SRC_PREC == ov::element::i8 ? 1 : 2;
+ constexpr size_t params_offset = sizeof(float) * param_count;
if (quant_bychannel) {
- auto* p_scales = reinterpret_cast<float*>(s);
- auto* p_zps = p_scales + K;
- s = s + sizeof(float) * 2 * K;
if constexpr (any_of(SRC_PREC, ov::element::u8, ov::element::u4)) {
+ auto* p_scales = reinterpret_cast<float*>(s);
+ auto* p_zps = p_scales + K;
+ s = s + sizeof(float) * 2 * K;
attn_dequant_by_channel_kernel<TDST, SRC_PREC>(s, dst, N, K, K / sub_byte_multiplier, K, p_scales, p_zps);
+ } else {
+ OPENVINO_THROW("dequant: i8 doesn't support by-channel quantization.");
}
} else {
for (size_t n = 0; n < N; n++) {
@@ -1939,6 +1942,10 @@ struct AttentionExecutor : public PagedAttentionExecutor {
Xattn _xatt;
# endif
+ // Scratchpads for compute_adaptive_rkv_diversity to avoid per-call allocations.
+ std::vector<float> _arkv_evict_keys;
+ std::vector<float> _arkv_scratch;
+
explicit AttentionExecutor(const CpuParallelPtr& cpu_parallel)
: _helper(MHAHelper<DATA_TYPE, KEY_PREC, VALUE_PREC>(cpu_parallel)),
_kernel(_helper),
@@ -2313,6 +2320,186 @@ struct AttentionExecutor : public PagedAttentionExecutor {
}
}
+ // Compute per-block diversity scores for Adaptive R-KV cache eviction
+ // (https://arxiv.org/pdf/2505.24133v3).
+ //
+ // For each sequence in the batch:
+ // Phase 0 – Gather only eviction-area key tokens from the paged KV cache
+ // Phase 1 – L2-normalize each token vector (dot product → cosine similarity)
+ // Phase 2 – Pairwise cosine similarity within the eviction area
+ // Phase 3 – Per-row: zero diagonal, threshold below row mean
+ // Phase 4 – Average thresholded values across all KV heads
+ // Phase 5 – Block-sum rows and negate → diversity scores
+ //
+ // Output per sequence: [evict_blocks, evictable_size] written to output_arkv_similarity.
+ //
+ // Optimizations vs. the reference implementation:
+ // - Only eviction-area tokens are gathered (start-area and tail skipped)
+ // - Gathering, normalization, similarity, and block-sum are all parallelized
+ // - Dot products / reductions / vector ops use SIMD via common.hpp helpers
+ void compute_adaptive_rkv_diversity(const PlainTensor& k_cache,
+ int32_t adaptive_rkv_start_size,
+ const PlainTensor& adaptive_rkv_evictable_sizes,
+ const PlainTensor& adaptive_rkv_diversity_block_set_indices,
+ const PlainTensor& adaptive_rkv_diversity_block_set_indices_begins,
+ PlainTensor& output_arkv_similarity) {
+ const size_t B_seq = adaptive_rkv_evictable_sizes.size(0);
+ const size_t Hk = _helper.Hk;
+ const size_t S = _helper.S;
+ const size_t block_size = _helper._block_size;
+ auto* output_ptr = output_arkv_similarity.ptr<float>();
+ size_t output_offset = 0;
+
+ for (size_t seq_idx = 0; seq_idx < B_seq; seq_idx++) {
+ const auto evictable_size = static_cast<size_t>(adaptive_rkv_evictable_sizes.ptr<int32_t>()[seq_idx]);
+ if (evictable_size == 0) {
+ continue;
+ }
+
+ const auto block_set_begin =
+ static_cast<size_t>(adaptive_rkv_diversity_block_set_indices_begins.ptr<int32_t>()[seq_idx]);
+ const auto block_set_end =
+ static_cast<size_t>(adaptive_rkv_diversity_block_set_indices_begins.ptr<int32_t>()[seq_idx + 1]);
+ const auto block_count = block_set_end - block_set_begin;
+ const auto token_count = block_count * block_size;
+
+ const auto start_size = static_cast<size_t>(adaptive_rkv_start_size);
+ OPENVINO_ASSERT(start_size % block_size == 0);
+ OPENVINO_ASSERT(evictable_size % block_size == 0);
+ OPENVINO_ASSERT(token_count >= start_size + evictable_size,
+ "Adaptive RKV diversity block set is too small for requested start and eviction sizes");
+
+ // ── Phase 0: Load target data; Gather only the eviction-area key tokens. ─────────
+ // Layout: [Hk, evictable_size, S]. Only the blocks covering the
+ // eviction window [start_size, start_size + evictable_size) are
+ // retrieved; start-area and trailing blocks are skipped entirely.
+ const size_t start_blocks = start_size / block_size;
+ const size_t evict_block_count = evictable_size / block_size;
+ const size_t evict_keys_size = Hk * evictable_size * S;
+ if (_arkv_evict_keys.size() < evict_keys_size) {
+ _arkv_evict_keys.resize(evict_keys_size);
+ }
+ auto& evict_keys = _arkv_evict_keys;
+
+ _cpu_parallel->parallel_for2d(Hk, evict_block_count, [&](size_t hk, size_t eb) {
+ const auto global_block_idx = start_blocks + eb;
+ const auto block_number = static_cast<size_t>(
+ adaptive_rkv_diversity_block_set_indices.ptr<int32_t>()[block_set_begin + global_block_idx]);
+ auto* dst = evict_keys.data() + hk * evictable_size * S + eb * block_size * S;
+
+ if constexpr (any_of(KEY_PREC, ov::element::i8, ov::element::u8, ov::element::u4)) {
+ auto* src =
+ k_cache.ptr<typename ov::element_type_traits<KEY_PREC>::value_type, KEY_PREC>(block_number, hk);
+ dequant<float, KEY_PREC>(dst,
+ src,
+ block_size,
+ S,
+ block_size,
+ _helper._params.key_group_size,
+ _helper._params.quant_key_bychannel);
+ } else {
+ auto* src = k_cache.ptr<typename ov::element_type_traits<KEY_PREC>::value_type>(block_number, hk);
+ cvt_copy(dst, src, block_size, S, S, S);
+ }
+ });
+
+ // ── Phase 1: L2-normalize each eviction token (in-place) ──────
+ // After this step dot(row_i, row_j) == cosine_similarity(i, j).
+ constexpr float eps = std::numeric_limits<float>::epsilon();
+ _cpu_parallel->parallel_for(Hk * evictable_size, [&](size_t idx) {
+ const size_t hk_idx = idx / evictable_size;
+ const size_t t = idx % evictable_size;
+ float* row = evict_keys.data() + hk_idx * evictable_size * S + t * S;
+ float sq_sum = dot_product(row, row, S, nullptr, nullptr, nullptr, 0);
+ multiply_scalar(row, row, 1.0F / std::sqrt(sq_sum + eps), S);
+ });
+
+ // ── Phase 2–5 (fused): Cosine similarity → threshold → subtract into output ─
+ // For each block, iterate its block_size token rows. For each row,
+ // compute per-head cosine similarities, threshold below row mean,
+ // and immediately subtract (scaled by 1/Hk) into the output row.
+ // Parallelized over blocks so each thread owns its output row exclusively.
+ const float inv_hk = 1.0F / static_cast<float>(Hk);
+ const auto nthr = static_cast<size_t>(parallel_get_max_threads());
+ const size_t scratch_size = nthr * evictable_size;
+ if (_arkv_scratch.size() < scratch_size)
+ _arkv_scratch.resize(scratch_size);
+
+ float* out = output_ptr + output_offset;
+ _cpu_parallel->parallel_for(evict_block_count, [&](size_t blk) {
+ const auto ithr = static_cast<size_t>(parallel_get_thread_num());
+ float* sim_row = _arkv_scratch.data() + ithr * evictable_size;
+ float* out_row = out + blk * evictable_size;
+ std::memset(out_row, 0, evictable_size * sizeof(float));
+
+ for (size_t t = 0; t < block_size; t++) {
+ const size_t row = blk * block_size + t;
+ for (size_t hk_idx = 0; hk_idx < Hk; hk_idx++) {
+ const float* head_keys = evict_keys.data() + hk_idx * evictable_size * S;
+ const float* row_key = head_keys + row * S;
+
+ for (size_t col = 0; col < evictable_size; col++) {
+ sim_row[col] =
+ (col == row)
+ ? 0.0F
+ : dot_product(row_key, head_keys + col * S, S, nullptr, nullptr, nullptr, 0);
+ }
+
+ float mean = reduce_sum(sim_row, evictable_size) / static_cast<float>(evictable_size);
+ size_t i = 0;
+# if defined(HAVE_AVX512F)
+ {
+ auto vmean = _mm512_set1_ps(mean);
+ auto vnihk = _mm512_set1_ps(-inv_hk);
+ for (; i + vec_len_f32_avx512 <= evictable_size; i += vec_len_f32_avx512) {
+ auto vsim = _mm512_loadu_ps(sim_row + i);
+ auto vout = _mm512_loadu_ps(out_row + i);
+ auto mask = _mm512_cmp_ps_mask(vsim, vmean, _CMP_GE_OQ);
+ vout = _mm512_fmadd_ps(_mm512_maskz_mov_ps(mask, vsim), vnihk, vout);
+ _mm512_storeu_ps(out_row + i, vout);
+ }
+ }
+# elif defined(HAVE_AVX2)
+ {
+ auto vmean = _mm256_set1_ps(mean);
+ auto vnihk = _mm256_set1_ps(-inv_hk);
+ auto vz = _mm256_setzero_ps();
+ for (; i + vec_len_f32_avx2 <= evictable_size; i += vec_len_f32_avx2) {
+ auto vsim = _mm256_loadu_ps(sim_row + i);
+ auto vout = _mm256_loadu_ps(out_row + i);
+ auto vcmp = _mm256_cmp_ps(vsim, vmean, _CMP_GE_OQ);
+ vout = _mm256_fmadd_ps(_mm256_blendv_ps(vz, vsim, vcmp), vnihk, vout);
+ _mm256_storeu_ps(out_row + i, vout);
+ }
+ }
+# elif defined(OPENVINO_ARCH_ARM64) && defined(HAVE_SVE)
+ {
+ auto sve_len = vec_len_f32_sve();
+ svbool_t pg = svptrue_b32();
+ auto svmean_val = svdup_n_f32(mean);
+ auto svnihk = svdup_n_f32(-inv_hk);
+ for (; i + sve_len <= evictable_size; i += sve_len) {
+ svfloat32_t vsim = svld1_f32(pg, sim_row + i);
+ svfloat32_t vout = svld1_f32(pg, out_row + i);
+ svbool_t ge = svcmpge_f32(pg, vsim, svmean_val);
+ svfloat32_t vt = svsel_f32(ge, vsim, svdup_n_f32(0.0f));
+ vout = svmla_f32_z(pg, vout, vt, svnihk);
+ svst1_f32(pg, out_row + i, vout);
+ }
+ }
+# endif
+ for (; i < evictable_size; i++) {
+ if (sim_row[i] >= mean) {
+ out_row[i] -= sim_row[i] * inv_hk;
+ }
+ }
+ }
+ }
+ });
+ output_offset += evict_block_count * evictable_size;
+ }
+ }
+
void execute(const std::vector<MemoryPtr>& inputs, const std::vector<MemoryPtr> outputs) override {
PlainTensor q;
PlainTensor k;
@@ -2425,6 +2612,15 @@ struct AttentionExecutor : public PagedAttentionExecutor {
score_aggregation_window,
sinks,
sparse_attention_mask);
+
+ if (adaptive_rkv_evictable_sizes && adaptive_rkv_diversity_block_set_indices) {
+ compute_adaptive_rkv_diversity(k_cache,
+ adaptive_rkv_start_size,
+ adaptive_rkv_evictable_sizes,
+ adaptive_rkv_diversity_block_set_indices,
+ adaptive_rkv_diversity_block_set_indices_begins,
+ output_arkv_similarity);
+ }
}
};
#endif
diff --git a/src/plugins/intel_cpu/src/nodes/paged_attn.cpp b/src/plugins/intel_cpu/src/nodes/paged_attn.cpp
index 00136317320..94358187e6a 100644
--- a/src/plugins/intel_cpu/src/nodes/paged_attn.cpp
+++ b/src/plugins/intel_cpu/src/nodes/paged_attn.cpp
@@ -49,6 +49,11 @@ namespace ov::intel_cpu::node {
struct PagedAttentionKey {
ov::element::Type rtPrecision;
+ ov::element::Type keyCachePrecision;
+ ov::element::Type valueCachePrecision;
+ bool quantKeyByChannel;
+ bool quantValueByChannel;
+ bool isSageAttn;
[[nodiscard]] size_t hash() const;
bool operator==(const PagedAttentionKey& rhs) const;
@@ -57,14 +62,19 @@ struct PagedAttentionKey {
size_t PagedAttentionKey::hash() const {
size_t seed = 0;
seed = hash_combine(seed, rtPrecision.hash());
+ seed = hash_combine(seed, keyCachePrecision.hash());
+ seed = hash_combine(seed, valueCachePrecision.hash());
+ seed = hash_combine(seed, quantKeyByChannel);
+ seed = hash_combine(seed, quantValueByChannel);
+ seed = hash_combine(seed, isSageAttn);
return seed;
}
bool PagedAttentionKey::operator==(const PagedAttentionKey& rhs) const {
- auto retVal = rtPrecision == rhs.rtPrecision;
-
- return retVal;
+ return rtPrecision == rhs.rtPrecision && keyCachePrecision == rhs.keyCachePrecision &&
+ valueCachePrecision == rhs.valueCachePrecision && quantKeyByChannel == rhs.quantKeyByChannel &&
+ quantValueByChannel == rhs.quantValueByChannel && isSageAttn == rhs.isSageAttn;
}
PagedAttention::PagedAttention(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context)
@@ -246,19 +256,21 @@ bool PagedAttention::isQuantByChannel(const Config::CacheQuantMode mode,
void PagedAttention::createPrimitive() {
auto rtPrecision = getRuntimePrecision();
- // in one model, kvCachePrecision could not be changed so no need to care whether it may be changed.
- PagedAttentionKey key = {rtPrecision};
+ auto kCachePrecision = getOriginalInputPrecisionAtPort(PagedAttentionExecutor::ID_KCACHE);
+ auto vCachePrecision = getOriginalInputPrecisionAtPort(PagedAttentionExecutor::ID_VCACHE);
+ const auto& cpuConfig = context->getConfig();
+ bool quantKeybyChannel = isQuantByChannel(cpuConfig.keyCacheQuantMode, cpuConfig.keyCachePrecision, true);
+ bool quantValuebyChannel = isQuantByChannel(cpuConfig.valueCacheQuantMode, cpuConfig.valueCachePrecision, false);
+
+ PagedAttentionKey key = {rtPrecision,
+ kCachePrecision,
+ vCachePrecision,
+ quantKeybyChannel,
+ quantValuebyChannel,
+ cpuConfig.enableSageAttn};
auto builder = [&]([[maybe_unused]] const PagedAttentionKey& key) -> std::shared_ptr<PagedAttentionExecutor> {
#if defined(OPENVINO_ARCH_X86_64) || (defined(OPENVINO_ARCH_ARM64))
- // Since we are quantize only last dim it's safe to use the last dim of KV.
- auto kCachePrecision = getOriginalInputPrecisionAtPort(PagedAttentionExecutor::ID_KCACHE);
- auto vCachePrecision = getOriginalInputPrecisionAtPort(PagedAttentionExecutor::ID_VCACHE);
- const auto& cpuConfig = context->getConfig();
-
- bool quantKeybyChannel = isQuantByChannel(cpuConfig.keyCacheQuantMode, cpuConfig.keyCachePrecision, true);
- bool quantValuebyChannel =
- isQuantByChannel(cpuConfig.valueCacheQuantMode, cpuConfig.valueCachePrecision, false);
PagedAttnQuantParams params{cpuConfig.keyCacheGroupSize,
cpuConfig.valueCacheGroupSize,
quantKeybyChannel,
@@ -329,7 +341,17 @@ void PagedAttention::execute([[maybe_unused]] const dnnl::stream& strm) {
size_t num_elements_in_output = 0;
const size_t K_CACHE_IDX = PagedAttentionExecutor::ID_KCACHE;
- const size_t block_size = inputs[K_CACHE_IDX]->getStaticDims()[2];
+ // For by-channel quantized caches, dim[2] includes parameter header rows
+ // (scales/zps). Subtract them to get the actual PA block_size.
+ const auto& cpuConfig = context->getConfig();
+ bool quantKeybyChannel = isQuantByChannel(cpuConfig.keyCacheQuantMode, cpuConfig.keyCachePrecision, true);
+ size_t block_size = inputs[K_CACHE_IDX]->getStaticDims()[2];
+ if (quantKeybyChannel && cpuConfig.keyCachePrecision.is_integral()) {
+ size_t params_count = (cpuConfig.keyCachePrecision == ov::element::i8) ? 1 : 2;
+ size_t key_sub_byte_mult = (cpuConfig.keyCachePrecision == ov::element::u4) ? 2 : 1;
+ size_t key_params_size = sizeof(float) * params_count * key_sub_byte_mult;
+ block_size -= key_params_size;
+ }
const size_t ADAPTIVE_RKV_EVICTABLE_SIZES_IDX = PagedAttentionExecutor::ID_ADAPTIVE_RKV_EVICTABLE_SIZES;
auto evictable_sizes_dims = inputs[ADAPTIVE_RKV_EVICTABLE_SIZES_IDX]->getStaticDims();
diff --git a/src/plugins/intel_cpu/tests/functional/CMakeLists.txt b/src/plugins/intel_cpu/tests/functional/CMakeLists.txt
index f741196da15..a5798d03f65 100644
--- a/src/plugins/intel_cpu/tests/functional/CMakeLists.txt
+++ b/src/plugins/intel_cpu/tests/functional/CMakeLists.txt
@@ -41,7 +41,7 @@ target_include_directories(cpuUtils PRIVATE ${CPU_UTILS_INCLUDE_PATHS})
set(INCLUDES ${CMAKE_CURRENT_SOURCE_DIR} $<TARGET_PROPERTY:openvino_intel_cpu_plugin,SOURCE_DIR>/src)
set(DEPENDENCIES openvino_intel_cpu_plugin openvino_template_extension)
-set(LINK_LIBRARIES funcSharedTests cpuUtils openvino::snippets ov_snippets_models)
+set(LINK_LIBRARIES funcSharedTests cpuUtils openvino::snippets ov_snippets_models openvino::reference)
if(ENABLE_OV_ONNX_FRONTEND)
list(APPEND DEFINES TEST_MODELS="${TEST_MODEL_ZOO}")
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_adaptive_rkv.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_adaptive_rkv.cpp
new file mode 100644
index 00000000000..78e498d323e
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/paged_attn_adaptive_rkv.cpp
@@ -0,0 +1,700 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+
+#include <numeric>
+
+#include "common_test_utils/include/common_test_utils/ov_tensor_utils.hpp"
+#include "common_test_utils/node_builders/constant.hpp"
+#include "internal_properties.hpp"
+#include "openvino/runtime/system_conf.hpp"
+#include "openvino/runtime/internal_properties.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "openvino/reference/adaptive_rkv_diversity.hpp"
+#include "openvino/op/paged_attention.hpp"
+#include "openvino/op/parameter.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+#include "utils/cpu_test_utils.hpp"
+#include "utils/general_utils.h"
+
+using namespace ov::test;
+using namespace CPUTestUtils;
+using namespace ov::op;
+
+namespace ov {
+namespace test {
+
+struct DiversityTestParams {
+ size_t head_size;
+ size_t head_num;
+ size_t block_size;
+ size_t start_size;
+ size_t eviction_size;
+ size_t num_data_blocks;
+ ov::element::Type kv_cache_precision;
+ bool force_by_token;
+ std::string name;
+};
+
+class PagedAttnAdaptiveRKVDiversityTest : public testing::WithParamInterface<DiversityTestParams>,
+ virtual public SubgraphBaseTest,
+ public CPUTestsBase {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<DiversityTestParams>& obj) {
+ const auto& p = obj.param;
+ std::ostringstream result;
+ result << p.name;
+ if (p.kv_cache_precision != ov::element::f32) {
+ result << "_" << p.kv_cache_precision.get_type_name();
+ if (p.force_by_token) {
+ result << "_bytoken";
+ }
+ }
+ return result.str();
+ }
+
+ // model parameters
+ size_t kHeadSize;
+ size_t kHeadNum;
+ // paged attention parameters
+ size_t kBlockSize;
+ size_t kNumDataBlocks;
+ size_t kNumBlocks;
+ size_t kTokenCount;
+ // adaptive RKV parameters
+ size_t kStartSize;
+ size_t kEvictionSize;
+ // cache quantization parameters
+ ov::element::Type kKVCachePrecision;
+ bool kForceByToken;
+ bool kQuantByChannel;
+
+ static std::shared_ptr<ov::op::v0::Parameter> make_param(const PartialShape& pshape,
+ element::Type element_type,
+ const std::string& name) {
+ auto param = std::make_shared<v0::Parameter>(element_type, pshape);
+ param->set_friendly_name(name);
+ param->get_output_tensor(0).set_names({name});
+ return param;
+ }
+
+ void SetUp() override {
+ const auto& p = GetParam();
+ kHeadSize = p.head_size;
+ kHeadNum = p.head_num;
+ kBlockSize = p.block_size;
+ kStartSize = p.start_size;
+ kEvictionSize = p.eviction_size;
+ kNumDataBlocks = p.num_data_blocks;
+ kNumBlocks = kNumDataBlocks + 1;
+ kTokenCount = kNumDataBlocks * kBlockSize;
+ kKVCachePrecision = p.kv_cache_precision;
+ kForceByToken = p.force_by_token;
+ kQuantByChannel = kKVCachePrecision.is_integral() && !kForceByToken && kKVCachePrecision != ov::element::i8;
+
+ if (kKVCachePrecision == ov::element::i8) {
+ #if defined(OPENVINO_ARCH_X86_64)
+ if (!ov::with_cpu_x86_avx512_core_amx_int8()) {
+ GTEST_SKIP() << "i8 KV-cache diversity requires SageAttn support (AMX_INT8 or AVX2 VNNI2).";
+ }
+ #else
+ GTEST_SKIP() << "i8 KV-cache diversity requires x64 SageAttn support.";
+ #endif
+ }
+
+ targetDevice = utils::DEVICE_CPU;
+ configuration[ov::hint::inference_precision.name()] = ov::element::f32;
+ if (kKVCachePrecision == ov::element::i8) {
+ // i8 key cache requires SageAttn; it forces key=i8 by-token, value=u8 by-token
+ configuration[ov::intel_cpu::enable_sage_attn.name()] = true;
+ } else if (kKVCachePrecision == ov::element::u4) {
+ configuration[ov::key_cache_precision.name()] = ov::element::u4;
+ configuration[ov::value_cache_precision.name()] = ov::element::u4;
+ } else {
+ configuration[ov::hint::kv_cache_precision.name()] = kKVCachePrecision;
+ }
+ if (kKVCachePrecision.is_integral() && kForceByToken) {
+ configuration[ov::internal::key_cache_quant_mode.name()] = ov::internal::CacheQuantMode::BY_TOKEN;
+ configuration[ov::internal::value_cache_quant_mode.name()] = ov::internal::CacheQuantMode::BY_TOKEN;
+ }
+ function = build_model();
+ }
+
+ std::shared_ptr<ov::Model> build_model() {
+ const auto hs = static_cast<int64_t>(kHeadSize);
+ const auto hn = static_cast<int64_t>(kHeadNum);
+ const auto bs = static_cast<int64_t>(kBlockSize);
+ const auto nb = static_cast<int64_t>(kNumBlocks);
+
+ auto q = make_param(PartialShape{1, hs * hn}, ov::element::f32, "q");
+ auto k = make_param(PartialShape{1, hs * hn}, ov::element::f32, "k");
+ auto v = make_param(PartialShape{1, hs * hn}, ov::element::f32, "v");
+ auto key_cache = make_param(PartialShape{nb, hn, bs, hs}, ov::element::f32, "key_cache.0");
+ auto value_cache = make_param(PartialShape{nb, hn, bs, hs}, ov::element::f32, "value_cache.0");
+ auto past_lens = make_param(PartialShape{1}, ov::element::i32, "past_lens");
+ auto subsequence_begins = make_param(PartialShape{2}, ov::element::i32, "subsequence_begins");
+ auto block_indices = make_param(PartialShape{nb}, ov::element::i32, "block_indices");
+ auto block_indices_begins = make_param(PartialShape{2}, ov::element::i32, "block_indices_begins");
+
+ auto scale = std::make_shared<v0::Constant>(ov::element::f32, Shape{}, std::vector<float>{0.5f});
+ auto sliding_window = std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{0});
+ auto alibi_slopes = std::make_shared<v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{});
+ auto max_context_len = std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{static_cast<int32_t>(kNumBlocks * kBlockSize)});
+ auto score_aggregation_window = std::make_shared<v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{});
+ auto rotated_block_indices = std::make_shared<v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{});
+ auto rotation_deltas = std::make_shared<v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{});
+ auto rotation_trig_lut = std::make_shared<v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{});
+ auto xattention_threshold = std::make_shared<v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{});
+ auto xattention_block_size = std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{64});
+ auto xattention_stride = std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{8});
+ auto sinks = std::make_shared<v0::Constant>(ov::element::f32, Shape{0}, std::vector<float>{});
+ auto adaptive_rkv_start_size = std::make_shared<v0::Constant>(ov::element::i32, Shape{}, std::vector<int32_t>{static_cast<int32_t>(kStartSize)});
+ auto adaptive_rkv_evictable_sizes = std::make_shared<v0::Constant>(ov::element::i32, Shape{1}, std::vector<int32_t>{static_cast<int32_t>(kEvictionSize)});
+ std::vector<int32_t> block_set_indices_data(kNumDataBlocks);
+ std::iota(block_set_indices_data.begin(), block_set_indices_data.end(), 0);
+ auto adaptive_rkv_diversity_block_set_indices =
+ std::make_shared<v0::Constant>(ov::element::i32, Shape{kNumDataBlocks}, block_set_indices_data);
+ auto adaptive_rkv_diversity_block_set_indices_begins =
+ std::make_shared<v0::Constant>(ov::element::i32, Shape{2}, std::vector<int32_t>{0, static_cast<int32_t>(kNumDataBlocks)});
+ auto token_type_ids = std::make_shared<v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{});
+ auto qq_bias = std::make_shared<v0::Constant>(ov::element::u8, Shape{0}, std::vector<uint8_t>{0});
+ auto qq_bias_begins = std::make_shared<v0::Constant>(ov::element::i32, Shape{0}, std::vector<int32_t>{0});
+
+ OutputVector inputs = {q,
+ k,
+ v,
+ key_cache,
+ value_cache,
+ past_lens,
+ subsequence_begins,
+ block_indices,
+ block_indices_begins,
+ scale,
+ sliding_window,
+ 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 paged_attn = std::make_shared<op::PagedAttentionExtension>(inputs);
+ paged_attn->get_rt_info()["num_k_heads"] = kHeadNum;
+ paged_attn->get_rt_info()["k_head_size"] = kHeadSize;
+ paged_attn->get_rt_info()["num_v_heads"] = kHeadNum;
+ paged_attn->get_rt_info()["v_head_size"] = kHeadSize;
+
+ return std::make_shared<ov::Model>(OutputVector{paged_attn->output(0), paged_attn->output(1), paged_attn->output(2)},
+ ParameterVector{q,
+ k,
+ v,
+ key_cache,
+ value_cache,
+ past_lens,
+ subsequence_begins,
+ block_indices,
+ block_indices_begins});
+ }
+
+ static float make_key_value(size_t token_idx, size_t dim) {
+ constexpr float kDimStride = 0.25f;
+ constexpr float kTokenBiasStride = 0.03125f;
+ constexpr float kPeriodicTokenAmplitude = 0.0625f;
+ const float sign = (token_idx + dim) % 2 == 0 ? 1.0f : -1.0f;
+ return kDimStride * static_cast<float>(dim + 1) +
+ kTokenBiasStride * static_cast<float>(token_idx + 1) +
+ sign * kPeriodicTokenAmplitude * static_cast<float>((token_idx % 7) + 1);
+ }
+
+ // ── Generate float key data: [block][head][token][dim] layout ───────
+ std::vector<float> generate_float_keys() const {
+ std::vector<float> keys(kNumDataBlocks * kHeadNum * kBlockSize * kHeadSize);
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < kHeadNum; head++) {
+ for (size_t token = 0; token < kBlockSize; token++) {
+ const size_t global_token = block * kBlockSize + token;
+ for (size_t dim = 0; dim < kHeadSize; dim++) {
+ keys[((block * kHeadNum + head) * kBlockSize + token) * kHeadSize + dim] =
+ make_key_value(global_token, head * kHeadSize + dim);
+ }
+ }
+ }
+ }
+ return keys;
+ }
+
+ void fill_key_cache(ov::Tensor& key_cache_tensor) const {
+ if (kKVCachePrecision == ov::element::f32) {
+ fill_f32_key_cache(key_cache_tensor);
+ return;
+ }
+
+ const auto float_keys = generate_float_keys();
+ auto* raw = static_cast<uint8_t*>(key_cache_tensor.data());
+ std::memset(raw, 0, key_cache_tensor.get_byte_size());
+
+ if (kKVCachePrecision == ov::element::u8 && kQuantByChannel) {
+ fill_u8_by_channel(raw, float_keys);
+ } else if (kKVCachePrecision == ov::element::u8 && !kQuantByChannel) {
+ fill_u8_by_token(raw, float_keys);
+ } else if (kKVCachePrecision == ov::element::i8) {
+ fill_i8_by_token(raw, float_keys);
+ } else if (kKVCachePrecision == ov::element::u4 && kQuantByChannel) {
+ fill_u4_by_channel(raw, float_keys);
+ } else if (kKVCachePrecision == ov::element::u4 && !kQuantByChannel) {
+ fill_u4_by_token(raw, float_keys);
+ }
+ }
+
+ // dequant_keys layout: [num_heads, token_count, head_size]
+ std::vector<float> dequant_key_cache(const ov::Tensor& key_cache_tensor) const {
+ std::vector<float> dequant_keys(kHeadNum * kTokenCount * kHeadSize);
+
+ if (kKVCachePrecision == ov::element::f32) {
+ dequant_f32_key_cache(key_cache_tensor, dequant_keys);
+ } else {
+ const auto* raw = static_cast<const uint8_t*>(key_cache_tensor.data());
+ if (kKVCachePrecision == ov::element::u8 && kQuantByChannel) {
+ dequant_u8_by_channel(raw, dequant_keys);
+ } else if (kKVCachePrecision == ov::element::u8 && !kQuantByChannel) {
+ dequant_u8_by_token(raw, dequant_keys);
+ } else if (kKVCachePrecision == ov::element::i8) {
+ dequant_i8_by_token(raw, dequant_keys);
+ } else if (kKVCachePrecision == ov::element::u4 && kQuantByChannel) {
+ dequant_u4_by_channel(raw, dequant_keys);
+ } else if (kKVCachePrecision == ov::element::u4 && !kQuantByChannel) {
+ dequant_u4_by_token(raw, dequant_keys);
+ }
+ }
+
+ return dequant_keys;
+ }
+
+ void fill_f32_key_cache(ov::Tensor& key_cache_tensor) const {
+ const size_t S = kHeadSize;
+ const size_t Hk = kHeadNum;
+ auto* ptr = key_cache_tensor.data<float>();
+
+ std::fill_n(ptr, key_cache_tensor.get_size(), 0.0f);
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < Hk; head++) {
+ for (size_t token = 0; token < kBlockSize; token++) {
+ const size_t global_token = block * kBlockSize + token;
+ for (size_t dim = 0; dim < S; dim++) {
+ const size_t offset = ((block * Hk + head) * kBlockSize + token) * S + dim;
+ ptr[offset] = make_key_value(global_token, head * S + dim);
+ }
+ }
+ }
+ }
+ }
+
+ void dequant_f32_key_cache(const ov::Tensor& key_cache_tensor,
+ std::vector<float>& dequant_keys) const {
+ const size_t S = kHeadSize;
+ const size_t Hk = kHeadNum;
+ const auto* ptr = key_cache_tensor.data<const float>();
+
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < Hk; head++) {
+ for (size_t token = 0; token < kBlockSize; token++) {
+ const size_t global_token = block * kBlockSize + token;
+ for (size_t dim = 0; dim < S; dim++) {
+ const size_t src_offset = ((block * Hk + head) * kBlockSize + token) * S + dim;
+ dequant_keys[(head * kTokenCount + global_token) * S + dim] = ptr[src_offset];
+ }
+ }
+ }
+ }
+ }
+
+ // ── u8 by-channel: cache shape [N, Hk, block_size + 8, S] element u8 ───
+ void fill_u8_by_channel(uint8_t* raw, const std::vector<float>& float_keys) const {
+ const size_t S = kHeadSize;
+ const size_t Hk = kHeadNum;
+ const size_t params_size = 8;
+ const size_t dim2 = kBlockSize + params_size;
+ const size_t params_offset_bytes = 2 * sizeof(float) * S;
+
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < Hk; head++) {
+ uint8_t* base = raw + (block * Hk + head) * dim2 * S;
+ auto* scales = reinterpret_cast<float*>(base);
+ auto* zps = scales + S;
+ uint8_t* data = base + params_offset_bytes;
+
+ const float* src = float_keys.data() + ((block * Hk + head) * kBlockSize) * S;
+ scalar_quant_u8_by_channel(src, data, kBlockSize, S, S, scales, zps);
+ }
+ }
+ }
+
+ void dequant_u8_by_channel(const uint8_t* raw, std::vector<float>& dequant_keys) const {
+ const size_t S = kHeadSize;
+ const size_t Hk = kHeadNum;
+ const size_t params_size = 8;
+ const size_t dim2 = kBlockSize + params_size;
+ const size_t params_offset_bytes = 2 * sizeof(float) * S;
+
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < Hk; head++) {
+ const uint8_t* base = raw + (block * Hk + head) * dim2 * S;
+ const auto* scales = reinterpret_cast<const float*>(base);
+ const auto* zps = scales + S;
+ const uint8_t* data = base + params_offset_bytes;
+ std::vector<float> dequant_block(kBlockSize * S);
+
+ scalar_dequant_u8_by_channel(data, dequant_block.data(), kBlockSize, S, S, scales, zps);
+ for (size_t token = 0; token < kBlockSize; token++) {
+ const size_t global_token = block * kBlockSize + token;
+ for (size_t dim = 0; dim < S; dim++) {
+ dequant_keys[(head * kTokenCount + global_token) * S + dim] =
+ dequant_block[token * S + dim];
+ }
+ }
+ }
+ }
+ }
+
+ // ── u8 by-token: cache shape [N, Hk, block_size, S + 8] element u8 ───
+ void fill_u8_by_token(uint8_t* raw, const std::vector<float>& float_keys) const {
+ const size_t S = kHeadSize;
+ const size_t Hk = kHeadNum;
+ const size_t adjusted_S = S + 8;
+
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < Hk; head++) {
+ for (size_t token = 0; token < kBlockSize; token++) {
+ uint8_t* token_base = raw + (((block * Hk + head) * kBlockSize + token) * adjusted_S);
+ auto* params = reinterpret_cast<float*>(token_base);
+ uint8_t* data = token_base + 2 * sizeof(float);
+
+ const float* src = float_keys.data() + ((block * Hk + head) * kBlockSize + token) * S;
+ float scale, zp;
+ scalar_quant_u8(src, data, S, scale, zp);
+ params[0] = scale;
+ params[1] = zp;
+ }
+ }
+ }
+ }
+
+ void dequant_u8_by_token(const uint8_t* raw, std::vector<float>& dequant_keys) const {
+ const size_t S = kHeadSize;
+ const size_t Hk = kHeadNum;
+ const size_t adjusted_S = S + 8;
+
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < Hk; head++) {
+ for (size_t token = 0; token < kBlockSize; token++) {
+ const size_t global_token = block * kBlockSize + token;
+ const uint8_t* token_base = raw + (((block * Hk + head) * kBlockSize + token) * adjusted_S);
+ const auto* params = reinterpret_cast<const float*>(token_base);
+ const uint8_t* data = token_base + 2 * sizeof(float);
+
+ std::vector<float> dequant_token(S);
+ scalar_dequant_u8(data, dequant_token.data(), S, params[0], params[1]);
+ for (size_t dim = 0; dim < S; dim++) {
+ dequant_keys[(head * kTokenCount + global_token) * S + dim] = dequant_token[dim];
+ }
+ }
+ }
+ }
+ }
+
+ // ── i8 by-token: cache shape [N, Hk, block_size, S + 4] element i8 ───
+ void fill_i8_by_token(uint8_t* raw, const std::vector<float>& float_keys) const {
+ const size_t S = kHeadSize;
+ const size_t Hk = kHeadNum;
+ const size_t adjusted_S = S + 4;
+
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < Hk; head++) {
+ for (size_t token = 0; token < kBlockSize; token++) {
+ uint8_t* token_base = raw + (((block * Hk + head) * kBlockSize + token) * adjusted_S);
+ auto* scale_ptr = reinterpret_cast<float*>(token_base);
+ auto* data = reinterpret_cast<int8_t*>(token_base + sizeof(float));
+
+ const float* src = float_keys.data() + ((block * Hk + head) * kBlockSize + token) * S;
+ float scale;
+ scalar_quant_i8(src, data, S, scale);
+ *scale_ptr = scale;
+ }
+ }
+ }
+ }
+
+ void dequant_i8_by_token(const uint8_t* raw, std::vector<float>& dequant_keys) const {
+ const size_t S = kHeadSize;
+ const size_t Hk = kHeadNum;
+ const size_t adjusted_S = S + 4;
+
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < Hk; head++) {
+ for (size_t token = 0; token < kBlockSize; token++) {
+ const size_t global_token = block * kBlockSize + token;
+ const uint8_t* token_base = raw + (((block * Hk + head) * kBlockSize + token) * adjusted_S);
+ const auto* scale_ptr = reinterpret_cast<const float*>(token_base);
+ const auto* data = reinterpret_cast<const int8_t*>(token_base + sizeof(float));
+
+ std::vector<float> dequant_token(S);
+ scalar_dequant_i8(data, dequant_token.data(), S, *scale_ptr);
+ for (size_t dim = 0; dim < S; dim++) {
+ dequant_keys[(head * kTokenCount + global_token) * S + dim] = dequant_token[dim];
+ }
+ }
+ }
+ }
+ }
+
+ // ── u4 by-channel: cache shape [N, Hk, block_size + 16, S] element u4 ──
+ void fill_u4_by_channel(uint8_t* raw, const std::vector<float>& float_keys) const {
+ const size_t S = kHeadSize;
+ const size_t Hk = kHeadNum;
+ const size_t params_size = 16;
+ const size_t dim2 = kBlockSize + params_size;
+ const size_t row_bytes = S / 2;
+ const size_t params_offset_bytes = 2 * sizeof(float) * S;
+
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < Hk; head++) {
+ uint8_t* base = raw + (block * Hk + head) * dim2 * row_bytes;
+ auto* scales = reinterpret_cast<float*>(base);
+ auto* zps = scales + S;
+ uint8_t* data = base + params_offset_bytes;
+
+ const float* src = float_keys.data() + ((block * Hk + head) * kBlockSize) * S;
+ scalar_quant_u4_by_channel(src, data, kBlockSize, S, row_bytes, scales, zps);
+ }
+ }
+ }
+
+ void dequant_u4_by_channel(const uint8_t* raw, std::vector<float>& dequant_keys) const {
+ const size_t S = kHeadSize;
+ const size_t Hk = kHeadNum;
+ const size_t params_size = 16;
+ const size_t dim2 = kBlockSize + params_size;
+ const size_t row_bytes = S / 2;
+ const size_t params_offset_bytes = 2 * sizeof(float) * S;
+
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < Hk; head++) {
+ const uint8_t* base = raw + (block * Hk + head) * dim2 * row_bytes;
+ const auto* scales = reinterpret_cast<const float*>(base);
+ const auto* zps = scales + S;
+ const uint8_t* data = base + params_offset_bytes;
+ std::vector<float> dequant_block(kBlockSize * S);
+
+ scalar_dequant_u4_by_channel(data, dequant_block.data(), kBlockSize, S, row_bytes, scales, zps);
+ for (size_t token = 0; token < kBlockSize; token++) {
+ const size_t global_token = block * kBlockSize + token;
+ for (size_t dim = 0; dim < S; dim++) {
+ dequant_keys[(head * kTokenCount + global_token) * S + dim] =
+ dequant_block[token * S + dim];
+ }
+ }
+ }
+ }
+ }
+
+ // ── u4 by-token: cache shape [N, Hk, block_size, S + 16] element u4 ──
+ void fill_u4_by_token(uint8_t* raw, const std::vector<float>& float_keys) const {
+ const size_t S = kHeadSize;
+ const size_t Hk = kHeadNum;
+ const size_t adjusted_S_u4 = S + 16;
+ const size_t row_bytes = adjusted_S_u4 / 2;
+
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < Hk; head++) {
+ for (size_t token = 0; token < kBlockSize; token++) {
+ uint8_t* token_base = raw +
+ (((block * Hk + head) * kBlockSize + token) * row_bytes);
+ auto* params = reinterpret_cast<float*>(token_base);
+ uint8_t* data = token_base + 2 * sizeof(float);
+
+ const float* src = float_keys.data() + ((block * Hk + head) * kBlockSize + token) * S;
+ float scale, zp;
+ scalar_quant_u4(src, data, S, scale, zp);
+ params[0] = scale;
+ params[1] = zp;
+ }
+ }
+ }
+ }
+
+ void dequant_u4_by_token(const uint8_t* raw, std::vector<float>& dequant_keys) const {
+ const size_t S = kHeadSize;
+ const size_t Hk = kHeadNum;
+ const size_t adjusted_S_u4 = S + 16;
+ const size_t row_bytes = adjusted_S_u4 / 2;
+
+ for (size_t block = 0; block < kNumDataBlocks; block++) {
+ for (size_t head = 0; head < Hk; head++) {
+ for (size_t token = 0; token < kBlockSize; token++) {
+ const size_t global_token = block * kBlockSize + token;
+ const uint8_t* token_base = raw + (((block * Hk + head) * kBlockSize + token) * row_bytes);
+ const auto* params = reinterpret_cast<const float*>(token_base);
+ const uint8_t* data = token_base + 2 * sizeof(float);
+
+ std::vector<float> dequant_token(S);
+ scalar_dequant_u4(data, dequant_token.data(), S, params[0], params[1]);
+ for (size_t dim = 0; dim < S; dim++) {
+ dequant_keys[(head * kTokenCount + global_token) * S + dim] = dequant_token[dim];
+ }
+ }
+ }
+ }
+ }
+
+ // ── Build expected diversity from pre-computed key data ────────────────
+ std::vector<float> build_expected_diversity(const std::vector<float>& key_data) const {
+ ov::reference::AdaptiveRKVDiversityCalculator<float> calculator(kStartSize, kEvictionSize, kBlockSize);
+ auto block_diversity = calculator.calculate_block_diversity(
+ key_data.data(), ov::Shape{kHeadNum, kTokenCount, kHeadSize});
+
+ std::vector<float> flat;
+ for (const auto& row : block_diversity) {
+ flat.insert(flat.end(), row.begin(), row.end());
+ }
+ return flat;
+ }
+};
+
+TEST_P(PagedAttnAdaptiveRKVDiversityTest, smoke_AdaptiveRKVDiversityMatchesReference) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ compile_model();
+ auto infer_request = compiledModel.create_infer_request();
+
+ // Calculate cache shapes/types based on quantization config
+ auto calc_cache_info = [&](ov::element::Type prec, bool bychannel) {
+ size_t extra_bs = 0, extra_hs = 0;
+ if (prec == ov::element::u8) {
+ if (bychannel) {
+ extra_bs = 8;
+ }
+ else {
+ extra_hs = 8;
+ }
+ } else if (prec == ov::element::i8) {
+ extra_hs = 4; // i8 is always by-token
+ } else if (prec == ov::element::u4) {
+ if (bychannel) {
+ extra_bs = 16;
+ } else {
+ extra_hs = 16;
+ }
+ }
+ ov::element::Type type = prec.is_integral() ? prec : ov::element::f32;
+ ov::Shape shape{kNumBlocks, kHeadNum, kBlockSize + extra_bs, kHeadSize + extra_hs};
+ return std::make_pair(type, shape);
+ };
+
+ auto [key_cache_type, key_cache_shape] = calc_cache_info(kKVCachePrecision, kQuantByChannel);
+ // Value cache precision: i8 key cache uses SageAttn which sets value to u8
+ ov::element::Type val_prec = (kKVCachePrecision == ov::element::i8) ? ov::element::u8 : kKVCachePrecision;
+ auto [value_cache_type, value_cache_shape] = calc_cache_info(val_prec, false); // value always by-token
+
+ ov::Tensor q(ov::element::f32, {1, kHeadSize * kHeadNum});
+ ov::Tensor k(ov::element::f32, {1, kHeadSize * kHeadNum});
+ ov::Tensor v(ov::element::f32, {1, kHeadSize * kHeadNum});
+ ov::Tensor key_cache(key_cache_type, key_cache_shape);
+ ov::Tensor value_cache(value_cache_type, value_cache_shape);
+ ov::Tensor past_lens(ov::element::i32, {1});
+ ov::Tensor subsequence_begins(ov::element::i32, {2});
+ ov::Tensor block_indices(ov::element::i32, {kNumBlocks});
+ ov::Tensor block_indices_begins(ov::element::i32, {2});
+
+ std::fill_n(q.data<float>(), kHeadSize * kHeadNum, 0.1f);
+ std::fill_n(k.data<float>(), kHeadSize * kHeadNum, 0.2f);
+ std::fill_n(v.data<float>(), kHeadSize * kHeadNum, 0.3f);
+ std::memset(value_cache.data(), 0, value_cache.get_byte_size());
+
+ past_lens.data<int32_t>()[0] = static_cast<int32_t>(kTokenCount);
+ subsequence_begins.data<int32_t>()[0] = 0;
+ subsequence_begins.data<int32_t>()[1] = 1;
+ for (size_t i = 0; i < kNumBlocks; i++) {
+ block_indices.data<int32_t>()[i] = static_cast<int32_t>(i);
+ }
+ block_indices_begins.data<int32_t>()[0] = 0;
+ block_indices_begins.data<int32_t>()[1] = static_cast<int32_t>(kNumBlocks);
+
+ fill_key_cache(key_cache);
+
+ // Set tensors via compiled model inputs (shapes/types may differ from original model)
+ for (const auto& input_port : compiledModel.inputs()) {
+ for (const auto& name : input_port.get_names()) {
+ if (name == "q") infer_request.set_tensor(input_port, q);
+ else if (name == "k") infer_request.set_tensor(input_port, k);
+ else if (name == "v") infer_request.set_tensor(input_port, v);
+ else if (name == "key_cache.0") infer_request.set_tensor(input_port, key_cache);
+ else if (name == "value_cache.0") infer_request.set_tensor(input_port, value_cache);
+ else if (name == "past_lens") infer_request.set_tensor(input_port, past_lens);
+ else if (name == "subsequence_begins") infer_request.set_tensor(input_port, subsequence_begins);
+ else if (name == "block_indices") infer_request.set_tensor(input_port, block_indices);
+ else if (name == "block_indices_begins") infer_request.set_tensor(input_port, block_indices_begins);
+ }
+ }
+
+ infer_request.infer();
+ const auto actual = infer_request.get_output_tensor(2);
+
+ // Regarding to the reference implementation lacking u8/i8/u4 support,
+ // we dequantize the key cache on the test side
+ // and compare the diversity results against a float reference implementation.
+ // This allows us to validate both the quantization and dequantization logic,
+ // as well as the diversity calculation itself.
+ const auto key_cache_float = dequant_key_cache(key_cache);
+ const auto expected = build_expected_diversity(key_cache_float);
+
+ ASSERT_EQ(actual.get_shape(), ov::Shape({expected.size()}));
+
+ const float tolerance = kKVCachePrecision.is_integral() ? 1e-3f : 1e-4f;
+ const auto* actual_ptr = actual.data<const float>();
+ for (size_t idx = 0; idx < expected.size(); idx++) {
+ EXPECT_NEAR(actual_ptr[idx], expected[idx], tolerance) << "Mismatch at index " << idx;
+ }
+}
+
+const std::vector<DiversityTestParams> diversity_test_configs = {
+ // f32 tests
+ {4, 1, 32, 32, 32, 2, ov::element::f32, false, "single_head_minimal"},
+ {16, 4, 32, 32, 32, 2, ov::element::f32, false, "multi_head_base"},
+ {16, 4, 32, 32, 64, 3, ov::element::f32, false, "large_eviction"},
+ {16, 2, 32, 64, 32, 3, ov::element::f32, false, "large_start"},
+ {16, 4, 32, 64, 64, 4, ov::element::f32, false, "balanced_large"},
+ // u8 by-channel — covers dequant<float, u8> + attn_dequant_by_channel_kernel<u8>
+ {16, 4, 32, 32, 32, 2, ov::element::u8, false, "u8_bychannel_base"},
+ {16, 4, 32, 32, 64, 3, ov::element::u8, false, "u8_bychannel_large_eviction"},
+ // u8 by-token — covers dequant<float, u8> + attn_dequant_kernel<float, u8>
+ {16, 4, 32, 32, 32, 2, ov::element::u8, true, "u8_bytoken_base"},
+ {16, 4, 32, 32, 64, 3, ov::element::u8, true, "u8_bytoken_large_eviction"},
+ // i8 by-token — covers i8-specific group-wise dequant path
+ {16, 4, 32, 32, 32, 2, ov::element::i8, false, "i8_bytoken_base"},
+ {16, 4, 32, 32, 64, 3, ov::element::i8, false, "i8_bytoken_large_eviction"},
+ // u4 by-channel — covers dequant<float, u4> + attn_dequant_by_channel_kernel<u4>
+ {16, 4, 32, 32, 32, 2, ov::element::u4, false, "u4_bychannel_base"},
+ {16, 4, 32, 32, 64, 3, ov::element::u4, false, "u4_bychannel_large_eviction"},
+ // u4 by-token — covers dequant<float, u4> + attn_dequant_kernel<float, u4>
+ {16, 4, 32, 32, 32, 2, ov::element::u4, true, "u4_bytoken_base"},
+ {16, 4, 32, 32, 64, 3, ov::element::u4, true, "u4_bytoken_large_eviction"},
+};
+
+INSTANTIATE_TEST_SUITE_P(smoke_AdaptiveRKVDiversity,
+ PagedAttnAdaptiveRKVDiversityTest,
+ ::testing::ValuesIn(diversity_test_configs),
+ PagedAttnAdaptiveRKVDiversityTest::getTestCaseName);
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/utils/quantization_utils.hpp b/src/plugins/intel_cpu/tests/functional/utils/quantization_utils.hpp
index 19faac43b79..509778b1bf3 100644
--- a/src/plugins/intel_cpu/tests/functional/utils/quantization_utils.hpp
+++ b/src/plugins/intel_cpu/tests/functional/utils/quantization_utils.hpp
@@ -4,6 +4,11 @@
#pragma once
+#include <algorithm>
+#include <cmath>
+#include <cstddef>
+#include <cstdint>
+#include <limits>
#include <ostream>
#include <unordered_map>
@@ -61,4 +66,207 @@ inline std::ostream& operator<<(std::ostream& os, const QuantizationInfo& qinfo)
return os;
}
+// Input: n float values in src.
+// Output: u8 values in dst, plus scale and zp.
+// Algorithm: min/max affine quantization to 255 levels.
+inline void scalar_quant_u8(const float* src, uint8_t* dst, size_t n, float& scale, float& zp) {
+ float max_val = -std::numeric_limits<float>::max();
+ float min_val = std::numeric_limits<float>::max();
+ for (size_t i = 0; i < n; i++) {
+ max_val = std::max(max_val, src[i]);
+ min_val = std::min(min_val, src[i]);
+ }
+ scale = (max_val - min_val) / 255.0f;
+ if (scale == 0.0f)
+ scale = 0.0001f;
+ zp = -min_val / scale;
+ for (size_t i = 0; i < n; i++) {
+ dst[i] = static_cast<uint8_t>(std::round(std::max(src[i] / scale + zp, 0.0f)));
+ }
+}
+
+// Input: n u8 values in src, with scale and zp.
+// Output: float values in dst.
+// Algorithm: inverse affine dequantization.
+inline void scalar_dequant_u8(const uint8_t* src, float* dst, size_t n, float scale, float zp) {
+ for (size_t i = 0; i < n; i++) {
+ dst[i] = (static_cast<float>(src[i]) - zp) * scale;
+ }
+}
+
+// Input: float matrix src with shape [seq_dim, hidden_dims].
+// Output: per-channel u8 rows in dst, plus scale and zp per channel.
+// Algorithm: channel-wise min/max affine quantization.
+inline void scalar_quant_u8_by_channel(const float* src,
+ uint8_t* dst,
+ size_t seq_dim,
+ size_t hidden_dims,
+ size_t dst_stride,
+ float* scale,
+ float* zp) {
+ for (size_t j = 0; j < hidden_dims; j++) {
+ float max_val = -std::numeric_limits<float>::max();
+ float min_val = std::numeric_limits<float>::max();
+ for (size_t i = 0; i < seq_dim; i++) {
+ float v = src[i * hidden_dims + j];
+ max_val = std::max(max_val, v);
+ min_val = std::min(min_val, v);
+ }
+ scale[j] = (max_val - min_val) / 255.0f;
+ if (scale[j] == 0.0f)
+ scale[j] = 0.0001f;
+ zp[j] = -min_val / scale[j];
+ }
+ for (size_t i = 0; i < seq_dim; i++) {
+ for (size_t j = 0; j < hidden_dims; j++) {
+ dst[i * dst_stride + j] =
+ static_cast<uint8_t>(std::round(std::max(src[i * hidden_dims + j] / scale[j] + zp[j], 0.0f)));
+ }
+ }
+}
+
+// Input: per-channel u8 matrix in src, with scale and zp arrays.
+// Output: float matrix in dst.
+// Algorithm: channel-wise inverse affine dequantization.
+inline void scalar_dequant_u8_by_channel(const uint8_t* src,
+ float* dst,
+ size_t seq_dim,
+ size_t hidden_dims,
+ size_t src_stride,
+ const float* scale,
+ const float* zp) {
+ for (size_t i = 0; i < seq_dim; i++) {
+ for (size_t j = 0; j < hidden_dims; j++) {
+ dst[i * hidden_dims + j] = (static_cast<float>(src[i * src_stride + j]) - zp[j]) * scale[j];
+ }
+ }
+}
+
+// Input: n float values in src.
+// Output: i8 values in dst, plus scale.
+// Algorithm: symmetric quantization using max absolute value.
+inline void scalar_quant_i8(const float* src, int8_t* dst, size_t n, float& scale) {
+ float max_abs = 0.0f;
+ for (size_t i = 0; i < n; i++) {
+ max_abs = std::max(max_abs, std::abs(src[i]));
+ }
+ scale = max_abs / 127.0f;
+ if (scale == 0.0f)
+ scale = 0.0001f;
+ for (size_t i = 0; i < n; i++) {
+ float tmp = std::round(src[i] / scale);
+ tmp = std::max(tmp, -128.0f);
+ tmp = std::min(tmp, 127.0f);
+ dst[i] = static_cast<int8_t>(tmp);
+ }
+}
+
+// Input: n i8 values in src, with scale.
+// Output: float values in dst.
+// Algorithm: symmetric dequantization.
+inline void scalar_dequant_i8(const int8_t* src, float* dst, size_t n, float scale) {
+ for (size_t i = 0; i < n; i++) {
+ dst[i] = static_cast<float>(src[i]) * scale;
+ }
+}
+
+// Input: a packed byte, one u4 value, and the target nibble selector.
+// Output: the byte with the selected nibble updated.
+// Algorithm: shift and OR the 4-bit payload into place.
+inline uint8_t insert_u4(uint8_t dst_byte, uint8_t val, bool high_half) {
+ uint8_t shift = high_half ? 0 : 4;
+ return dst_byte | static_cast<uint8_t>(val << shift);
+}
+
+// Input: a packed byte and the nibble selector.
+// Output: the selected u4 value.
+// Algorithm: shift and mask the chosen nibble.
+inline uint8_t extract_u4(uint8_t byte, bool high_half) {
+ uint8_t shift = high_half ? 0 : 4;
+ return static_cast<uint8_t>((byte >> shift) & 0x0F);
+}
+
+// Input: n float values in src.
+// Output: packed u4 values in dst, plus scale and zp.
+// Algorithm: min/max affine quantization to 16 levels, packed two per byte.
+inline void scalar_quant_u4(const float* src, uint8_t* dst, size_t n, float& scale, float& zp) {
+ float max_val = -std::numeric_limits<float>::max();
+ float min_val = std::numeric_limits<float>::max();
+ for (size_t i = 0; i < n; i++) {
+ max_val = std::max(max_val, src[i]);
+ min_val = std::min(min_val, src[i]);
+ }
+ scale = (max_val - min_val) / 15.0f;
+ if (scale == 0.0f)
+ scale = 0.0001f;
+ zp = -min_val / scale;
+ for (size_t i = 0; i < n; i++) {
+ uint8_t val = static_cast<uint8_t>(std::min(15.0f, std::max(0.0f, std::round(src[i] / scale + zp))));
+ uint8_t dst_val = (i % 2 == 0) ? 0 : dst[i / 2];
+ dst[i / 2] = insert_u4(dst_val, val, static_cast<bool>(i % 2));
+ }
+}
+
+// Input: packed u4 data in src, with scale and zp.
+// Output: float values in dst.
+// Algorithm: unpack and inverse affine dequantization.
+inline void scalar_dequant_u4(const uint8_t* src, float* dst, size_t n, float scale, float zp) {
+ for (size_t i = 0; i < n; i++) {
+ uint8_t val = extract_u4(src[i / 2], static_cast<bool>(i % 2));
+ dst[i] = (static_cast<float>(val) - zp) * scale;
+ }
+}
+
+// Input: float matrix src with shape [seq_dim, hidden_dims].
+// Output: per-channel packed u4 rows in dst, plus scale and zp per channel.
+// Algorithm: channel-wise min/max affine quantization to 16 levels.
+inline void scalar_quant_u4_by_channel(const float* src,
+ uint8_t* dst,
+ size_t seq_dim,
+ size_t hidden_dims,
+ size_t dst_stride,
+ float* scale,
+ float* zp) {
+ for (size_t j = 0; j < hidden_dims; j++) {
+ float max_val = -std::numeric_limits<float>::max();
+ float min_val = std::numeric_limits<float>::max();
+ for (size_t i = 0; i < seq_dim; i++) {
+ float v = src[i * hidden_dims + j];
+ max_val = std::max(max_val, v);
+ min_val = std::min(min_val, v);
+ }
+ scale[j] = (max_val - min_val) / 15.0f;
+ if (scale[j] == 0.0f)
+ scale[j] = 0.0001f;
+ zp[j] = -min_val / scale[j];
+ }
+ for (size_t i = 0; i < seq_dim; i++) {
+ for (size_t j = 0; j < hidden_dims; j++) {
+ uint8_t val = static_cast<uint8_t>(
+ std::min(15.0f, std::max(0.0f, std::round(src[i * hidden_dims + j] / scale[j] + zp[j]))));
+ size_t byte_idx = i * dst_stride + j / 2;
+ uint8_t dst_val = (j % 2 == 0) ? 0 : dst[byte_idx];
+ dst[byte_idx] = insert_u4(dst_val, val, static_cast<bool>(j % 2));
+ }
+ }
+}
+
+// Input: per-channel packed u4 rows in src, with scale and zp arrays.
+// Output: float matrix in dst.
+// Algorithm: unpack and channel-wise inverse affine dequantization.
+inline void scalar_dequant_u4_by_channel(const uint8_t* src,
+ float* dst,
+ size_t seq_dim,
+ size_t hidden_dims,
+ size_t src_stride,
+ const float* scale,
+ const float* zp) {
+ for (size_t i = 0; i < seq_dim; i++) {
+ for (size_t j = 0; j < hidden_dims; j++) {
+ uint8_t val = extract_u4(src[i * src_stride + j / 2], static_cast<bool>(j % 2));
+ dst[i * hidden_dims + j] = (static_cast<float>(val) - zp[j]) * scale[j];
+ }
+ }
+}
+
} // namespace CPUTestUtils