Skip to content

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

[CPU] TurboQuant codec for SDPA (#35853)

Egor Duplenskiib9a1f201c109
diff --git a/src/inference/dev_api/openvino/runtime/internal_properties.hpp b/src/inference/dev_api/openvino/runtime/internal_properties.hpp
index 606bff44076..a7a92bd869b 100644
--- a/src/inference/dev_api/openvino/runtime/internal_properties.hpp
+++ b/src/inference/dev_api/openvino/runtime/internal_properties.hpp
@@ -174,6 +174,54 @@ static constexpr Property<CacheQuantMode, PropertyMutability::RW> key_cache_quan
static constexpr Property<CacheQuantMode, PropertyMutability::RW> value_cache_quant_mode{"VALUE_CACHE_QUANT_MODE"};
+/**
+ * @brief KV cache quantization algorithm.
+ * Selects SCALAR vs TURBO for integer cache precision (u8/u4); defaults to SCALAR when unset.
+ * No effect for floating-point cache precision.
+ */
+enum class CacheQuantAlgorithm {
+ SCALAR = 0, // Per-group affine scale/zero-point (metadata in k_scale_zp / v_scale_zp)
+ TURBO = 1, // TurboQuant: random orthogonal rotation + Lloyd-Max codebook + per-head norm
+};
+
+/** @cond INTERNAL */
+inline std::ostream& operator<<(std::ostream& os, const CacheQuantAlgorithm& alg) {
+ switch (alg) {
+ case CacheQuantAlgorithm::SCALAR:
+ return os << "SCALAR";
+ case CacheQuantAlgorithm::TURBO:
+ return os << "TURBO";
+ default:
+ OPENVINO_THROW("Unsupported cache quant algorithm");
+ }
+}
+
+inline std::istream& operator>>(std::istream& is, CacheQuantAlgorithm& alg) {
+ std::string str;
+ is >> str;
+ if (str == "SCALAR") {
+ alg = CacheQuantAlgorithm::SCALAR;
+ } else if (str == "TURBO") {
+ alg = CacheQuantAlgorithm::TURBO;
+ } else {
+ OPENVINO_THROW("Unsupported cache quant algorithm: ", str);
+ }
+ return is;
+}
+/** @endcond */
+
+/**
+ * @brief Define quantization algorithm for key cache.
+ * Set both key_cache_quant_alg and value_cache_quant_alg to the same value
+ * for symmetric K/V; differ them for asymmetric configs.
+ */
+static constexpr Property<CacheQuantAlgorithm, PropertyMutability::RW> key_cache_quant_alg{"KEY_CACHE_QUANT_ALG"};
+
+/**
+ * @brief Define quantization algorithm for value cache. See key_cache_quant_alg.
+ */
+static constexpr Property<CacheQuantAlgorithm, PropertyMutability::RW> value_cache_quant_alg{"VALUE_CACHE_QUANT_ALG"};
+
using WeightSharingCtxPtr = std::shared_ptr<const weight_sharing::Context>;
/**
diff --git a/src/plugins/intel_cpu/CMakeLists.txt b/src/plugins/intel_cpu/CMakeLists.txt
index 48401a7df31..e07bb4dd6e1 100644
--- a/src/plugins/intel_cpu/CMakeLists.txt
+++ b/src/plugins/intel_cpu/CMakeLists.txt
@@ -332,9 +332,19 @@ cross_compiled_file(${TARGET_NAME}
ARCH AVX512F AVX2 ANY
src/nodes/kernels/scaled_attn/mha_kv_cache_codec.cpp
API src/nodes/kernels/scaled_attn/mha_kv_cache_codec.hpp
- NAME mha_kv_cache
+ NAME mha_kv_cache turboq_head_bytes
NAMESPACE ov::Extensions::Cpu::XARCH
)
+cross_compiled_file(${TARGET_NAME}
+ ARCH AVX512F AVX2 ANY
+ src/nodes/kernels/scaled_attn/codecs/turboq_quantize.cpp
+ API src/nodes/kernels/scaled_attn/codecs/turboq_quantize.hpp
+ NAME turboq_quantize_head turboq_quantize
+ NAMESPACE ov::Extensions::Cpu::XARCH
+)
+## turboq_rotation.cpp holds scalar setup only (sign cache, env parsing);
+## SIMD WHT butterfly is inline in turboq_rotation.hpp and gets ISA-specialized
+## when included by cross-compiled translation units.
cross_compiled_file(${TARGET_NAME}
ARCH AVX512F ANY
diff --git a/src/plugins/intel_cpu/src/config.cpp b/src/plugins/intel_cpu/src/config.cpp
index 0c63b0d3546..50531eb3fca 100644
--- a/src/plugins/intel_cpu/src/config.cpp
+++ b/src/plugins/intel_cpu/src/config.cpp
@@ -335,7 +335,8 @@ void Config::readProperties(const ov::AnyMap& prop, const ModelType modelType) {
ov::element::f16,
ov::element::bf16,
ov::element::u8,
- ov::element::u4)) {
+ ov::element::u4,
+ ov::element::u3)) {
kvCachePrecision = prec;
} else {
OPENVINO_THROW("invalid value");
@@ -345,7 +346,7 @@ void Config::readProperties(const ov::AnyMap& prop, const ModelType modelType) {
val.as<std::string>(),
" for property key ",
ov::hint::kv_cache_precision.name(),
- ". Supported values: u8, u4, bf16, f16, f32");
+ ". Supported values: u8, u4, u3, bf16, f16, f32");
}
} else if (key == ov::key_cache_precision.name()) {
try {
@@ -357,7 +358,8 @@ void Config::readProperties(const ov::AnyMap& prop, const ModelType modelType) {
ov::element::bf16,
ov::element::i8,
ov::element::u8,
- ov::element::u4)) {
+ ov::element::u4,
+ ov::element::u3)) {
keyCachePrecision = prec;
} else {
OPENVINO_THROW("keyCachePrecision doesn't support value ", prec);
@@ -367,7 +369,7 @@ void Config::readProperties(const ov::AnyMap& prop, const ModelType modelType) {
val.as<std::string>(),
" for property key ",
ov::key_cache_precision.name(),
- ". Supported values: u8, bf16, f16, f32");
+ ". Supported values: u3, u4, u8, i8, bf16, f16, f32");
}
} else if (key == ov::value_cache_precision.name()) {
try {
@@ -378,7 +380,8 @@ void Config::readProperties(const ov::AnyMap& prop, const ModelType modelType) {
ov::element::f16,
ov::element::bf16,
ov::element::u8,
- ov::element::u4)) {
+ ov::element::u4,
+ ov::element::u3)) {
valueCachePrecision = prec;
} else {
OPENVINO_THROW("valueCachePrecision doesn't support value ", prec);
@@ -388,7 +391,19 @@ void Config::readProperties(const ov::AnyMap& prop, const ModelType modelType) {
val.as<std::string>(),
" for property key ",
ov::value_cache_precision.name(),
- ". Supported values: u4, u8, bf16, f16, f32");
+ ". Supported values: u3, u4, u8, bf16, f16, f32");
+ }
+ } else if (key == ov::internal::key_cache_quant_alg.name()) {
+ auto alg = val.as<ov::internal::CacheQuantAlgorithm>();
+ keyCacheQuantAlg = alg;
+ if (alg == ov::internal::CacheQuantAlgorithm::TURBO && !keyCachePrecisionSetExplicitly) {
+ keyCachePrecision = ov::element::u4;
+ }
+ } else if (key == ov::internal::value_cache_quant_alg.name()) {
+ auto alg = val.as<ov::internal::CacheQuantAlgorithm>();
+ valueCacheQuantAlg = alg;
+ if (alg == ov::internal::CacheQuantAlgorithm::TURBO && !valueCachePrecisionSetExplicitly) {
+ valueCachePrecision = ov::element::u4;
}
} else if (key == ov::key_cache_group_size.name() || key == ov::value_cache_group_size.name()) {
try {
diff --git a/src/plugins/intel_cpu/src/config.h b/src/plugins/intel_cpu/src/config.h
index 6febef685c1..27c37a68ce6 100644
--- a/src/plugins/intel_cpu/src/config.h
+++ b/src/plugins/intel_cpu/src/config.h
@@ -9,6 +9,7 @@
#include <functional>
#include <map>
#include <memory>
+#include <optional>
#include <set>
#include <string>
#include <vector>
@@ -17,6 +18,7 @@
#include "openvino/core/attribute_visitor.hpp"
#include "openvino/core/type/element_type.hpp"
#include "openvino/runtime/intel_cpu/properties.hpp"
+#include "openvino/runtime/internal_properties.hpp"
#include "openvino/runtime/properties.hpp"
#include "openvino/runtime/threading/istreams_executor.hpp"
#include "utils/debug_caps_config.h"
@@ -86,6 +88,10 @@ struct Config {
size_t valueCacheGroupSize = 0UL;
CacheQuantMode keyCacheQuantMode = CacheQuantMode::AUTO;
CacheQuantMode valueCacheQuantMode = CacheQuantMode::AUTO;
+ // SCALAR = per-group affine scale/zp (default). TURBO = TBQ rotation + codebook.
+ // For TURBO: bits derived from cachePrecision (u3→3, u4→4).
+ ov::internal::CacheQuantAlgorithm keyCacheQuantAlg = ov::internal::CacheQuantAlgorithm::SCALAR;
+ ov::internal::CacheQuantAlgorithm valueCacheQuantAlg = ov::internal::CacheQuantAlgorithm::SCALAR;
bool enableSageAttn = false;
ov::threading::IStreamsExecutor::Config streamExecutorConfig;
int streams = 1;
diff --git a/src/plugins/intel_cpu/src/memory_state.cpp b/src/plugins/intel_cpu/src/memory_state.cpp
index 2b3d594dd0a..08991007c04 100644
--- a/src/plugins/intel_cpu/src/memory_state.cpp
+++ b/src/plugins/intel_cpu/src/memory_state.cpp
@@ -24,9 +24,11 @@
#include "memory_desc/cpu_memory_desc.h"
#include "memory_desc/cpu_memory_desc_utils.h"
#include "nodes/kernels/scaled_attn/attn_quant.hpp"
+#include "nodes/kernels/scaled_attn/cache_spec.hpp"
#include "openvino/core/except.hpp"
#include "openvino/core/parallel.hpp"
#include "openvino/core/type/element_type.hpp"
+#include "openvino/runtime/internal_properties.hpp"
#include "openvino/runtime/itensor.hpp"
#include "openvino/runtime/so_ptr.hpp"
#include "utils/general_utils.h"
@@ -225,17 +227,19 @@ void VariableStateSingleBuffer::commit_impl() {
VariableStateKVcache::VariableStateKVcache(const std::string& name,
MemoryDescPtr external_desc,
BlockedMemoryDescPtr dense_internal_desc,
- const bool quant_by_channel,
- const size_t group_size)
+ ov::Extensions::Cpu::CacheSpec spec)
: VariableStateBase(name, std::move(external_desc)),
m_dense_internal_desc(std::move(dense_internal_desc)),
- m_quant_by_channel(quant_by_channel),
- m_group_size(group_size) {
+ m_spec(spec) {
auto&& shape = get_external_desc()->getShape();
OPENVINO_ASSERT(shape.isDynamic(), "VariableStateKVcache is unexpectedly initalized with a static tensor");
}
ov::SoPtr<ov::ITensor> VariableStateKVcache::get_state() const {
+ OPENVINO_ASSERT(m_spec.alg != ov::internal::CacheQuantAlgorithm::TURBO,
+ "get_state() is not supported for KV cache with TURBO quantization. "
+ "TURBO stores packed bits and per-token norm in separate metadata; "
+ "scalar dequant path cannot reconstruct the original tensor.");
if (!m_internal_mem || !m_hidden_state || is_reset_state()) {
auto new_desc = to_static(get_external_desc());
auto external_mem = std::make_shared<Memory>(get_engine(), new_desc);
@@ -273,10 +277,10 @@ ov::SoPtr<ov::ITensor> VariableStateKVcache::get_state() const {
if (pastkv.get_precision() == element::u8) {
auto nthr = parallel_get_max_threads();
std::vector<PlainTensor> buffers(nthr);
- if (m_quant_by_channel) {
+ if (m_spec.by_channel) {
parallel_for3d(L0, B, H, [&](size_t ithr, size_t m, size_t b, size_t h) {
auto b_kv = static_cast<size_t>(beam_table.at<int32_t>({b, m}));
- size_t group_id = m / m_group_size;
+ size_t group_id = m / m_spec.group_size;
buffers[ithr].resize<float>({S});
attn_dequant_by_channel_u8(pastkv.ptr<uint8_t>(m, b_kv, h),
buffers[ithr].ptr<float>(),
@@ -292,10 +296,10 @@ ov::SoPtr<ov::ITensor> VariableStateKVcache::get_state() const {
parallel_for3d(L0, B, H, [&](size_t ithr, size_t m, size_t b, size_t h) {
auto b_kv = static_cast<size_t>(beam_table.at<int32_t>({b, m}));
buffers[ithr].resize<float>({S});
- for (size_t group_id = 0; group_id < S / m_group_size; group_id++) {
- attn_dequant_u8(pastkv.ptr<uint8_t>(m, b_kv, h, group_id * m_group_size),
- buffers[ithr].ptr<float>() + group_id * m_group_size,
- m_group_size,
+ for (size_t group_id = 0; group_id < S / m_spec.group_size; group_id++) {
+ attn_dequant_u8(pastkv.ptr<uint8_t>(m, b_kv, h, group_id * m_spec.group_size),
+ buffers[ithr].ptr<float>() + group_id * m_spec.group_size,
+ m_spec.group_size,
m_scale_zp.ptr<float>(m, b_kv, h, group_id * 2));
}
cpu_convert(buffers[ithr].ptr<float>(), output.ptr_v(m, b, h), element::f32, output.m_dt, S);
@@ -312,6 +316,10 @@ ov::SoPtr<ov::ITensor> VariableStateKVcache::get_state() const {
}
void VariableStateKVcache::set_state_impl(const ov::SoPtr<ov::ITensor>& state) {
+ OPENVINO_ASSERT(m_spec.alg != ov::internal::CacheQuantAlgorithm::TURBO,
+ "set_state() is not supported for KV cache with TURBO quantization. "
+ "TURBO requires rotation+codebook encoding plus per-token norm metadata "
+ "owned by the SDPA node; external state cannot be injected directly.");
// 1. reset the memory object
m_state = state; // simply to extend the lifetime
auto state_desc = MemoryDescUtils::generateCpuBlockedMemoryDesc(m_state);
@@ -339,11 +347,11 @@ void VariableStateKVcache::set_state_impl(const ov::SoPtr<ov::ITensor>& state) {
auto S = internal.size(3);
auto nthr = parallel_get_max_threads();
std::vector<PlainTensor> buffers(nthr);
- if (m_quant_by_channel) {
- size_t group_nums = div_up(L0, m_group_size);
+ if (m_spec.by_channel) {
+ size_t group_nums = div_up(L0, m_spec.group_size);
m_scale_zp.resize<float>({group_nums * 2, B, H, S});
parallel_for3d(group_nums, B, H, [&](size_t ithr, size_t group_id, size_t b, size_t h) {
- size_t valid_seq = std::min(m_group_size, L0 - group_id * m_group_size);
+ size_t valid_seq = std::min(m_spec.group_size, L0 - group_id * m_spec.group_size);
buffers[ithr].resize<float>({valid_seq, S});
cpu_convert(external.ptr_v(valid_seq, b, h),
buffers[ithr].ptr<float>(),
@@ -351,7 +359,7 @@ void VariableStateKVcache::set_state_impl(const ov::SoPtr<ov::ITensor>& state) {
element::f32,
valid_seq * S);
attn_quant_by_channel_u8(buffers[ithr].ptr<float>(),
- internal.ptr<uint8_t>(group_id * m_group_size, b, h),
+ internal.ptr<uint8_t>(group_id * m_spec.group_size, b, h),
valid_seq,
S,
S,
@@ -360,14 +368,14 @@ void VariableStateKVcache::set_state_impl(const ov::SoPtr<ov::ITensor>& state) {
m_scale_zp.ptr<float>(group_id * 2 + 1, b, h));
});
} else {
- m_scale_zp.resize<float>({L0, B, H, 2 * S / m_group_size});
+ m_scale_zp.resize<float>({L0, B, H, 2 * S / m_spec.group_size});
parallel_for3d(B, H, L0, [&](size_t ithr, size_t b, size_t h, size_t m) {
buffers[ithr].resize<float>({S});
cpu_convert(external.ptr_v(m, b, h), buffers[ithr].ptr<float>(), external.m_dt, element::f32, S);
- for (size_t group_id = 0; group_id < S / m_group_size; group_id++) {
- attn_quant_u8(buffers[ithr].ptr<float>() + group_id * m_group_size,
- internal.ptr<uint8_t>(m, b, h, group_id * m_group_size),
- m_group_size,
+ for (size_t group_id = 0; group_id < S / m_spec.group_size; group_id++) {
+ attn_quant_u8(buffers[ithr].ptr<float>() + group_id * m_spec.group_size,
+ internal.ptr<uint8_t>(m, b, h, group_id * m_spec.group_size),
+ m_spec.group_size,
m_scale_zp.at<float>({m, b, h, group_id * 2}),
m_scale_zp.at<float>({m, b, h, group_id * 2 + 1}));
}
diff --git a/src/plugins/intel_cpu/src/memory_state.h b/src/plugins/intel_cpu/src/memory_state.h
index d75efe35bc7..d213196c4d3 100644
--- a/src/plugins/intel_cpu/src/memory_state.h
+++ b/src/plugins/intel_cpu/src/memory_state.h
@@ -13,6 +13,7 @@
#include "cpu_memory.h"
#include "memory_desc/blocked_memory_desc.h"
#include "memory_desc/cpu_memory_desc.h"
+#include "nodes/kernels/scaled_attn/cache_spec.hpp"
#include "openvino/runtime/ivariable_state.hpp"
#include "openvino/runtime/so_ptr.hpp"
#include "openvino/runtime/tensor.hpp"
@@ -123,8 +124,7 @@ public:
VariableStateKVcache(const std::string& name,
MemoryDescPtr external_desc,
BlockedMemoryDescPtr dense_internal_desc,
- bool quant_by_channel,
- size_t group_size = 0);
+ ov::Extensions::Cpu::CacheSpec spec);
// ov::IVariableState
ov::SoPtr<ov::ITensor> get_state() const override;
@@ -162,6 +162,10 @@ public:
m_scale_zp = t;
}
+ const ov::Extensions::Cpu::CacheSpec& get_spec() const {
+ return m_spec;
+ }
+
private:
// ov::intel_cpu::VariableStateBase
void set_state_impl(const ov::SoPtr<ov::ITensor>& state) override;
@@ -178,8 +182,7 @@ private:
// for u8 kv cache: [B, H, L, 2], 0 for scale, 1 for zp
PlainTensor m_scale_zp;
- bool m_quant_by_channel = false;
- size_t m_group_size = 0;
+ ov::Extensions::Cpu::CacheSpec m_spec;
};
using MemStatePtr = std::shared_ptr<IVariableState>;
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/cache_spec.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/cache_spec.hpp
new file mode 100644
index 00000000000..931796f0239
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/cache_spec.hpp
@@ -0,0 +1,21 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+
+#include "openvino/core/type/element_type.hpp"
+#include "openvino/runtime/internal_properties.hpp"
+
+namespace ov::Extensions::Cpu {
+
+struct CacheSpec {
+ ov::internal::CacheQuantAlgorithm alg = ov::internal::CacheQuantAlgorithm::SCALAR;
+ ov::element::Type precision = ov::element::dynamic;
+ size_t group_size = 0;
+ bool by_channel = false;
+};
+
+} // namespace ov::Extensions::Cpu
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/cache_codec.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/cache_codec.hpp
deleted file mode 100644
index b431d2fbc6c..00000000000
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/cache_codec.hpp
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright (C) 2018-2026 Intel Corporation
-// SPDX-License-Identifier: Apache-2.0
-//
-// CacheCodec — identifies the quantization / encoding scheme of one KV cache side.
-// Lightweight header with no dependencies beyond <cstdint>.
-
-#pragma once
-
-#include <cstdint>
-
-namespace ov::Extensions::Cpu {
-
-enum class CacheCodec : uint8_t {
- U8,
- U4,
- U8_BY_CHANNEL,
- RAW_F32,
- RAW_F16,
- RAW_BF16,
-};
-
-} // namespace ov::Extensions::Cpu
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/codec_kernels.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/codec_kernels.hpp
index 13478712b87..de4d3a8fb71 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/codec_kernels.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/codec_kernels.hpp
@@ -16,10 +16,11 @@
#include "nodes/kernels/simd/simd_loop.hpp"
-namespace ov::Extensions::Cpu::XARCH {
+namespace ov::Extensions::Cpu {
// Lightweight strided pointer — wraps (base, stride) for head-strided arrays.
-// Usage: data[head][offset]
+// Usage: data[head][offset]. POD; not ISA-sensitive, lives outside XARCH so
+// cross-compile dispatch symbols don't depend on the active ISA namespace.
template <typename T>
struct StridedData {
T* data;
@@ -30,6 +31,10 @@ struct StridedData {
}
};
+} // namespace ov::Extensions::Cpu
+
+namespace ov::Extensions::Cpu::XARCH {
+
// Decode elements at element index j from packed data using a DecodePlan.
// The plan carries both decoder (how bits become values) and params
// (resolved dequant context). j is NOT passed to the decoder.
@@ -48,7 +53,7 @@ auto decode_at(const uint8_t* data, int j, const Plan& plan, simd::active_lanes<
// Uses simd_loop_reduce: 4x-unrolled SIMD main loop with vector accumulators,
// scalar tail, single final horizontal reduction.
template <typename QT, typename PlanFor>
-float codec_dot(const uint8_t* k, const QT* q, int dim, PlanFor&& plan_for) {
+float codec_dot(const uint8_t* k, const QT* q, int dim, const PlanFor& plan_for) {
return simd::simd_loop_reduce<4>(
dim,
[&](int j, simd::f32& acc) {
@@ -70,7 +75,7 @@ float codec_dot(const uint8_t* k, const QT* q, int dim, PlanFor&& plan_for) {
template <typename PlanFor>
void codec_weighted_accum(const uint8_t* v,
int dim,
- PlanFor&& plan_for,
+ const PlanFor& plan_for,
float outer_scale,
StridedData<const float> weights,
StridedData<float> accum,
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/codecs.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/codecs.hpp
index 1bf98145c7f..036f792518d 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/codecs.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/codecs.hpp
@@ -22,15 +22,98 @@
#pragma once
+#include <cmath>
#include <cstddef>
#include <cstdint>
+#include <cstring>
#include <type_traits>
#include "nodes/kernels/simd/simd.hpp"
#include "utils/plain_tensor.hpp"
+#if defined(HAVE_AVX2) || defined(HAVE_AVX512F)
+# include <immintrin.h>
+#endif
+
namespace ov::Extensions::Cpu::XARCH {
+// ---------------------------------------------------------------------------
+// Helpers shared by TurboQ codecs.
+// ---------------------------------------------------------------------------
+
+// Read a T from a possibly-unaligned byte pointer. Compiles to a single mov.
+template <typename T>
+inline T read_as(const uint8_t* p) {
+ T v{};
+ std::memcpy(&v, p, sizeof(T));
+ return v;
+}
+
+// Convenience alias for integer SIMD vector at the active ISA.
+using i32 = simd::i32;
+
+#if defined(HAVE_AVX2) || defined(HAVE_AVX512F)
+// 4-bit nibble unpack (SSE2): TBQ packing order. Returns raw __m128i.
+inline __m128i unpack_4bit_nibbles(const uint8_t* packed) {
+ const __m128i nibble_mask = _mm_set1_epi8(0x0F);
+ __m128i p = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(packed));
+ return _mm_unpacklo_epi8(_mm_and_si128(p, nibble_mask), _mm_and_si128(_mm_srli_epi16(p, 4), nibble_mask));
+}
+#endif
+
+// 4-bit unpack returning vec<int32_t>. Works for all ISAs.
+// bit_offset: sub-byte starting bit (0 for SIMD, 0 or 4 for scalar).
+template <simd::isa i = simd::active_isa>
+inline simd::vec<int32_t, i> unpack_4bit(const uint8_t* packed, int bit_offset = 0) {
+#if defined(HAVE_AVX2) || defined(HAVE_AVX512F)
+ if constexpr (i != simd::isa::scalar) {
+ (void)bit_offset;
+ return simd::vec<int32_t, i>::widen_u8(unpack_4bit_nibbles(packed));
+ } else
+#endif
+ {
+ return {static_cast<int32_t>((*packed >> bit_offset) & 0x0F)};
+ }
+}
+
+// 3-bit unpack: AVX-512 unpacks 2 groups (16 indices), AVX2 unpacks 1 group (8),
+// scalar unpacks 1 index.
+template <simd::isa i>
+inline simd::vec<int32_t, i> unpack_3bit(const uint8_t* packed,
+ simd::vec<int32_t, i> shifts,
+ simd::vec<int32_t, i> mask7,
+ int bit_offset = 0) {
+ if constexpr (i == simd::isa::avx512) {
+ auto w0 = static_cast<int32_t>(read_as<uint32_t>(packed));
+ auto w1 = static_cast<int32_t>(read_as<uint32_t>(packed + 3));
+ return srlv(simd::vec<int32_t, i>::broadcast_halves(w0, w1), shifts) & mask7;
+ } else {
+ auto w = read_as<uint32_t>(packed);
+ return srlv(simd::vec<int32_t, i>{static_cast<int32_t>(w >> bit_offset)}, shifts) & mask7;
+ }
+}
+
+// 2-bit unpack.
+template <simd::isa i>
+inline simd::vec<int32_t, i> unpack_2bit(const uint8_t* packed,
+ simd::vec<int32_t, i> shifts,
+ simd::vec<int32_t, i> mask3,
+ int bit_offset = 0) {
+ if constexpr (i == simd::isa::avx512) {
+ auto w = read_as<uint32_t>(packed);
+ return srlv(simd::vec<int32_t, i>{static_cast<int32_t>(w)}, shifts) & mask3;
+ } else {
+ auto w = static_cast<uint32_t>(read_as<uint16_t>(packed));
+ return srlv(simd::vec<int32_t, i>{static_cast<int32_t>(w >> bit_offset)}, shifts) & mask3;
+ }
+}
+
+// Per-token magnitude scale (norm / sqrt(dim)) for a TurboQ record.
+// Norm is carried in a parallel meta-data tensor (no longer inline in the packed record).
+inline float turboq_norm_scale(float norm, int dim) {
+ return norm / std::sqrt(static_cast<float>(dim));
+}
+
// ---------------------------------------------------------------------------
// Params — carry per-position dequantization parameters.
//
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_codec.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_codec.hpp
new file mode 100644
index 00000000000..95b2df50bdf
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_codec.hpp
@@ -0,0 +1,107 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "codecs.hpp"
+#include "turboq_tables.hpp"
+
+namespace ov::Extensions::Cpu::XARCH {
+
+// ---------------------------------------------------------------------------
+// TurboQ decoders: SIMD codebook decode for 4-bit, 3-bit, 2-bit quantization.
+//
+// Stateful (hold per-ISA codebook + shifts + mask) to match the stateless
+// Decoder interface used by codec_kernels. decode() takes a Params (ignored)
+// and simd::active_lanes<I> context. When called with scalar active_lanes
+// (e.g. from codec_dot tail), falls back to scalar codebook lookup.
+// ---------------------------------------------------------------------------
+
+template <simd::isa I = simd::active_isa>
+struct TurboQDecoder4 {
+ static constexpr int bits = 4;
+ const float* cb_raw;
+ simd::table<16, I> cb;
+
+ explicit TurboQDecoder4(int head_dim = 0) : cb_raw(turboq_codebook(4, head_dim)), cb(cb_raw) {}
+
+ template <simd::isa Ia, typename Params>
+ simd::f32_t<Ia> decode(const uint8_t* base,
+ int bit_offset,
+ const Params& /*p*/,
+ simd::active_lanes<Ia> /*unused*/) const {
+ if constexpr (Ia == simd::isa::scalar) {
+ int idx = (*base >> bit_offset) & 0x0F;
+ return simd::f32_t<Ia>(cb_raw[idx]);
+ } else {
+ return cb.lookup(unpack_4bit<Ia>(base, bit_offset));
+ }
+ }
+};
+
+template <simd::isa I = simd::active_isa>
+struct TurboQDecoder3 {
+ static constexpr int bits = 3;
+ static constexpr int32_t shifts_data[] = {0, 3, 6, 9, 12, 15, 18, 21, 0, 3, 6, 9, 12, 15, 18, 21};
+ const float* cb_raw;
+ simd::table<8, I> cb;
+ simd::vec<int32_t, I> shifts;
+ simd::vec<int32_t, I> mask;
+
+ explicit TurboQDecoder3(int head_dim = 0)
+ : cb_raw(turboq_codebook(3, head_dim)),
+ cb(cb_raw),
+ shifts(simd::load<simd::vec<int32_t, I>>(shifts_data)),
+ mask(7) {}
+
+ template <simd::isa Ia, typename Params>
+ simd::f32_t<Ia> decode(const uint8_t* base,
+ int bit_offset,
+ const Params& /*p*/,
+ simd::active_lanes<Ia> /*unused*/) const {
+ if constexpr (Ia == simd::isa::scalar) {
+ auto w = read_as<uint32_t>(base);
+ auto idx = static_cast<int>((w >> bit_offset) & 0x7);
+ return simd::f32_t<Ia>(cb_raw[idx]);
+ } else {
+ return cb.lookup(unpack_3bit<Ia>(base, shifts, mask, bit_offset));
+ }
+ }
+};
+
+template <simd::isa I = simd::active_isa>
+struct TurboQDecoder2 {
+ static constexpr int bits = 2;
+ static constexpr int32_t shifts_data[] = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30};
+ const float* cb_raw;
+ simd::table<4, I> cb;
+ simd::vec<int32_t, I> shifts;
+ simd::vec<int32_t, I> mask;
+
+ explicit TurboQDecoder2(int head_dim = 0)
+ : cb_raw(turboq_codebook(2, head_dim)),
+ cb(cb_raw),
+ shifts(simd::load<simd::vec<int32_t, I>>(shifts_data)),
+ mask(3) {}
+
+ template <simd::isa Ia, typename Params>
+ simd::f32_t<Ia> decode(const uint8_t* base,
+ int bit_offset,
+ const Params& /*p*/,
+ simd::active_lanes<Ia> /*unused*/) const {
+ if constexpr (Ia == simd::isa::scalar) {
+ auto w = read_as<uint32_t>(base);
+ auto idx = static_cast<int>((w >> bit_offset) & 0x3);
+ return simd::f32_t<Ia>(cb_raw[idx]);
+ } else {
+ return cb.lookup(unpack_2bit<Ia>(base, shifts, mask, bit_offset));
+ }
+ }
+};
+
+// Packed byte size for a full KV row (all heads for one token).
+// turboq_head_bytes is declared in mha_kv_cache_codec.hpp.
+size_t turboq_row_bytes(int num_kv_heads, int head_dim, int bits);
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_quantize.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_quantize.cpp
new file mode 100644
index 00000000000..48ab69a4701
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_quantize.cpp
@@ -0,0 +1,162 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "turboq_quantize.hpp"
+
+#include <cassert>
+#include <cmath>
+#include <cstdint>
+#include <cstdlib>
+
+#include "common_quantize.hpp"
+#include "cpu_parallel.hpp"
+#include "nodes/kernels/simd/simd.hpp"
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/float16.hpp"
+#include "turboq_rotation.hpp"
+#include "turboq_tables.hpp"
+
+namespace ov::Extensions::Cpu::XARCH {
+
+// Env-var switch (checked once at static init).
+// OV_TURBOQ_NORM_CORRECTION store corrected norm so ||dequant|| == ||src||
+static const bool g_turboq_norm_correction = std::getenv("OV_TURBOQ_NORM_CORRECTION") != nullptr;
+
+// Fused norm + sign-flip + normalize. Templated on input precision T.
+// Reads src as T, writes f32 unit*signs into dst, returns the L2 norm.
+template <typename T>
+inline float turboq_norm_signflip(const T* src, const float* signs, float* dst, int dim) {
+ constexpr int W = simd::f32::width;
+ simd::f32 acc0, acc1;
+ int i = 0;
+ for (; i + 2 * W - 1 < dim; i += 2 * W) {
+ auto v0 = simd::load<simd::f32>(src + i);
+ auto v1 = simd::load<simd::f32>(src + i + W);
+ acc0 = fmadd(v0, v0, acc0);
+ acc1 = fmadd(v1, v1, acc1);
+ }
+ for (; i + W - 1 < dim; i += W) {
+ auto v0 = simd::load<simd::f32>(src + i);
+ acc0 = fmadd(v0, v0, acc0);
+ }
+ const float norm = std::sqrt(reduce(acc0 + acc1));
+ const float inv_norm = (norm < 1e-30F) ? 0.0F : 1.0F / norm;
+
+ auto vn = simd::f32(inv_norm);
+ for (i = 0; i + W - 1 < dim; i += W) {
+ store(simd::load<simd::f32>(src + i) * vn * simd::load<simd::f32>(signs + i), dst + i);
+ }
+ return norm;
+}
+
+// Dispatch helper: bf16 / f16 / f32 — single pass, returns norm.
+static inline float dispatch_norm_signflip(const void* src,
+ const float* signs,
+ float* dst,
+ int dim,
+ ov::element::Type precision) {
+ if (precision == ov::element::bf16) {
+ return turboq_norm_signflip(static_cast<const ov::bfloat16*>(src), signs, dst, dim);
+ }
+ if (precision == ov::element::f16) {
+ return turboq_norm_signflip(static_cast<const ov::float16*>(src), signs, dst, dim);
+ }
+ return turboq_norm_signflip(static_cast<const float*>(src), signs, dst, dim);
+}
+
+void turboq_quantize_head(const void* src,
+ void* dst,
+ float* out_norm,
+ int head_dim,
+ int bits,
+ ov::element::Type src_precision,
+ float* ws,
+ const float* signs) {
+ assert((bits == 3 || bits == 4) && "bits must be 3 or 4");
+ assert(head_dim % 64 == 0 && "head_dim must be divisible by 64");
+ assert(ws != nullptr && "per-thread scratch required");
+ assert(signs != nullptr && "WHT signs required");
+
+ const int dim = head_dim;
+
+ // Step 1: norm + sign-flip + normalize into ws.
+ float* buf = ws;
+ const float norm = dispatch_norm_signflip(src, signs, buf, dim, src_precision);
+
+ // Step 2: WHT in-place. Unscaled butterfly; |buf|² = dim after.
+ turboq_wht_inplace(buf, dim);
+
+ // Step 3: quantize + pack directly to output.
+ auto* out = static_cast<uint8_t*>(dst);
+ const float* boundaries = turboq_boundaries(bits, dim);
+ const float* codebook = turboq_codebook(bits, dim);
+ const int n_bnd = (bits == 4) ? 15 : 7;
+ float recon_sq = 0.0F;
+
+ if (bits == 4) {
+ for (int i = 0; i < dim; i += 2) {
+ uint8_t lo = scalar_quantize(buf[i], boundaries, n_bnd);
+ uint8_t hi = scalar_quantize(buf[i + 1], boundaries, n_bnd);
+ recon_sq += codebook[lo] * codebook[lo] + codebook[hi] * codebook[hi];
+ out[i / 2] = static_cast<uint8_t>((hi << 4) | (lo & 0x0F));
+ }
+ } else {
+ for (int g = 0; g < dim / 8; g++) {
+ const float* r = buf + g * 8;
+ uint8_t i0 = scalar_quantize(r[0], boundaries, n_bnd);
+ uint8_t i1 = scalar_quantize(r[1], boundaries, n_bnd);
+ uint8_t i2 = scalar_quantize(r[2], boundaries, n_bnd);
+ uint8_t i3 = scalar_quantize(r[3], boundaries, n_bnd);
+ uint8_t i4 = scalar_quantize(r[4], boundaries, n_bnd);
+ uint8_t i5 = scalar_quantize(r[5], boundaries, n_bnd);
+ uint8_t i6 = scalar_quantize(r[6], boundaries, n_bnd);
+ uint8_t i7 = scalar_quantize(r[7], boundaries, n_bnd);
+ recon_sq += codebook[i0] * codebook[i0] + codebook[i1] * codebook[i1] + codebook[i2] * codebook[i2] +
+ codebook[i3] * codebook[i3] + codebook[i4] * codebook[i4] + codebook[i5] * codebook[i5] +
+ codebook[i6] * codebook[i6] + codebook[i7] * codebook[i7];
+ uint8_t* d = out + g * 3;
+ d[0] = static_cast<uint8_t>((i0 & 7) | ((i1 & 7) << 3) | ((i2 & 3) << 6));
+ d[1] = static_cast<uint8_t>(((i2 >> 2) & 1) | ((i3 & 7) << 1) | ((i4 & 7) << 4) | ((i5 & 1) << 7));
+ d[2] = static_cast<uint8_t>(((i5 >> 1) & 3) | ((i6 & 7) << 2) | ((i7 & 7) << 5));
+ }
+ }
+
+ // Step 4: store norm (optionally corrected so ||dequant|| == ||src||).
+ float stored_norm = norm;
+ if (g_turboq_norm_correction) {
+ float recon_norm = std::sqrt(recon_sq);
+ float sqrt_dim = std::sqrt(static_cast<float>(dim));
+ if (recon_norm > 1e-30F) {
+ stored_norm = norm * sqrt_dim / recon_norm;
+ }
+ }
+ *out_norm = stored_norm;
+}
+
+void turboq_quantize(const ov::intel_cpu::PlainTensor& cur,
+ ov::intel_cpu::PlainTensor& dst,
+ ov::intel_cpu::PlainTensor& meta_data,
+ size_t L0,
+ int bits,
+ const ov::intel_cpu::CpuParallelPtr& cpu_parallel,
+ ov::Extensions::Cpu::StridedData<float> ws,
+ const ov::intel_cpu::PlainTensor& signs) {
+ const auto B = cur.size(0);
+ const auto H = cur.size(1);
+ const auto L1 = cur.size(2);
+ const auto S = cur.size(3);
+ const auto prec = cur.get_precision();
+ const float* signs_ptr = signs.ptr<float>();
+ cpu_parallel->parallel_for2d(B, H, [&](size_t b, size_t h) {
+ float* tws = ws[parallel_get_thread_num()];
+ for (size_t l = 0; l < L1; l++) {
+ const void* src = cur.ptr_v(b, h, l);
+ auto* d = dst.ptr<uint8_t>(b, h, L0 + l);
+ auto* out_norm = meta_data.ptr<float>(b, h, L0 + l);
+ turboq_quantize_head(src, d, out_norm, static_cast<int>(S), bits, prec, tws, signs_ptr);
+ }
+ });
+}
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_quantize.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_quantize.hpp
new file mode 100644
index 00000000000..88e9bda59ba
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_quantize.hpp
@@ -0,0 +1,45 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+// TurboQuant encode: per-head quantize + pack for bits ∈ {3, 4}.
+// Outputs: packed indices written to dst; per-head fp32 norm written to a
+// separate meta_data tensor (out_norm in the per-head entry point).
+
+#pragma once
+
+#include <cstddef>
+
+#include "codec_kernels.hpp"
+#include "cpu_parallel.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "utils/plain_tensor.hpp"
+
+namespace ov::Extensions::Cpu::XARCH {
+
+// Quantize one head: norm → sign-flip + normalize → WHT in-place → quant + pack.
+// ws: per-thread f32 scratch, ≥ head_dim slots.
+// Entry point with external linkage; resolved against cross-compile dispatcher.
+void turboq_quantize_head(const void* src,
+ void* dst,
+ float* out_norm,
+ int head_dim,
+ int bits,
+ ov::element::Type src_precision,
+ float* ws,
+ const float* signs);
+
+// Quantize a full cache tensor (K or V) using TurboQuant.
+// Writes packed indices to dst and per-head fp32 norm to meta_data[b, h, L0+l, 0].
+// ws: per-thread scratch; ws[tid] gives a head_dim-sized f32 buffer.
+// Fully-qualified StridedData lives in ov::Extensions::Cpu (outside XARCH) so the
+// symbol mangling is identical across per-ISA namespaces in the cross-compile dispatcher.
+void turboq_quantize(const ov::intel_cpu::PlainTensor& cur,
+ ov::intel_cpu::PlainTensor& dst,
+ ov::intel_cpu::PlainTensor& meta_data,
+ size_t L0,
+ int bits,
+ const ov::intel_cpu::CpuParallelPtr& cpu_parallel,
+ ov::Extensions::Cpu::StridedData<float> ws,
+ const ov::intel_cpu::PlainTensor& signs);
+
+} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_rotation.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_rotation.cpp
new file mode 100644
index 00000000000..06d9ada16ff
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_rotation.cpp
@@ -0,0 +1,34 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "turboq_rotation.hpp"
+
+#include <cstdint>
+#include <map>
+#include <random>
+#include <vector>
+
+namespace ov::Extensions::Cpu {
+
+static constexpr uint64_t TURBOQ_SEED = 0x517cc1b727220a95ULL;
+static constexpr uint64_t TURBOQ_WHT_SEED = TURBOQ_SEED ^ 0xfedcba9876543210ULL;
+
+// Per-thread, per-dimension sign cache.
+const float* turboq_get_wht_signs(int dim) {
+ thread_local std::map<int, std::vector<float>> cache;
+ auto [it, inserted] = cache.try_emplace(dim);
+ if (!inserted) {
+ return it->second.data();
+ }
+ auto& signs = it->second;
+ signs.resize(dim);
+ std::mt19937_64 rng(TURBOQ_WHT_SEED);
+ std::uniform_int_distribution<int> dist(0, 1);
+ for (int i = 0; i < dim; i++) {
+ signs[i] = dist(rng) ? 1.0F : -1.0F;
+ }
+ return signs.data();
+}
+
+} // namespace ov::Extensions::Cpu
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_rotation.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_rotation.hpp
new file mode 100644
index 00000000000..25c7dae3da6
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_rotation.hpp
@@ -0,0 +1,82 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cmath>
+
+#include "nodes/kernels/simd/simd.hpp"
+
+namespace ov::Extensions::Cpu {
+
+// Random sign vector (cached, ±1.0f, dim elements) for MSE WHT rotation.
+const float* turboq_get_wht_signs(int dim);
+
+namespace XARCH {
+
+// ---------------------------------------------------------------------------
+// Walsh-Hadamard transform (WHT) — in-place, iterative butterfly.
+// ---------------------------------------------------------------------------
+inline void turboq_wht_inplace(float* data, int dim) {
+ for (int h = 1; h < dim; h <<= 1) {
+ const int stride = h << 1;
+ if (h >= simd::f32::width) {
+ for (int base = 0; base < dim; base += stride) {
+ for (int j = 0; j < h; j += simd::f32::width) {
+ float* lo = data + base + j;
+ float* hi = data + base + j + h;
+ auto a = simd::load<simd::f32>(lo);
+ auto b = simd::load<simd::f32>(hi);
+ store(a + b, lo);
+ store(a - b, hi);
+ }
+ }
+ } else {
+ for (int base = 0; base < dim; base += stride) {
+ for (int j = 0; j < h; j++) {
+ float* lo = data + base + j;
+ float* hi = data + base + j + h;
+ float a = *lo;
+ float b = *hi;
+ *lo = a + b;
+ *hi = a - b;
+ }
+ }
+ }
+ }
+}
+
+// Forward: y = (H * diag(signs) * x) / sqrt(dim)
+// Equivalent to a randomized Hadamard rotation (orthogonal transform).
+inline void turboq_wht_forward(const float* signs, const float* x, float* y, int dim) {
+ constexpr int W = simd::f32::width;
+ const float inv_sqrt_dim = 1.0F / std::sqrt(static_cast<float>(dim));
+ // Step 1: element-wise multiply by signs
+ for (int i = 0; i + W - 1 < dim; i += W) {
+ store(simd::load<simd::f32>(x + i) * simd::load<simd::f32>(signs + i), y + i);
+ }
+ // Step 2: in-place WHT
+ turboq_wht_inplace(y, dim);
+ // Step 3: normalize by 1/sqrt(dim)
+ auto vscale = simd::f32(inv_sqrt_dim);
+ for (int i = 0; i + W - 1 < dim; i += W) {
+ store(simd::load<simd::f32>(y + i) * vscale, y + i);
+ }
+}
+
+// Inverse: x = diag(signs) * H * y / sqrt(dim)
+// WHT runs in-place on y (caller-owned f32 workspace), final scale+signs writes to typed x.
+template <typename T>
+inline void turboq_wht_inverse(const float* signs, float* y, T* x, int dim) {
+ constexpr int W = simd::f32::width;
+ const float inv_sqrt_dim = 1.0F / std::sqrt(static_cast<float>(dim));
+ turboq_wht_inplace(y, dim);
+ auto vscale = simd::f32(inv_sqrt_dim);
+ for (int i = 0; i + W - 1 < dim; i += W) {
+ store(simd::load<simd::f32>(y + i) * vscale * simd::load<simd::f32>(signs + i), x + i);
+ }
+}
+
+} // namespace XARCH
+} // namespace ov::Extensions::Cpu
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_tables.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_tables.hpp
new file mode 100644
index 00000000000..86f9e052841
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/turboq_tables.hpp
@@ -0,0 +1,351 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cassert>
+#include <cstddef>
+#include <stdexcept>
+
+// Lloyd-Max optimal centroids for the marginal distribution of a rotated
+// unit-norm coordinate (scaled by sqrt(d)). This distribution is Beta-derived
+// and converges to N(0,1) as d→∞.
+//
+// Per-dim tables (D128, D256, D512) give slightly better quantization error
+// than the asymptotic N(0,1) values, especially for 4-bit quantization.
+// Asymptotic values (no suffix) are used as fallback for other head_dims.
+//
+// Symmetric: codebook[i] == -codebook[2^b - 1 - i].
+
+// ---------------------------------------------------------------------------
+// Asymptotic (N(0,1), d→∞) — fallback for head_dims other than 128/256/512.
+// ---------------------------------------------------------------------------
+static constexpr float TURBOQ_CODEBOOK_2BIT[4] = {
+ -1.51040113F,
+ -0.45277205F,
+ +0.45277205F,
+ +1.51040113F,
+};
+
+static constexpr float TURBOQ_CODEBOOK_3BIT[8] = {
+ -2.15187458F,
+ -1.34383723F,
+ -0.75595247F,
+ -0.24507484F,
+ +0.24507484F,
+ +0.75595247F,
+ +1.34383723F,
+ +2.15187458F,
+};
+
+static constexpr float TURBOQ_CODEBOOK_4BIT[16] = {
+ -2.73235729F,
+ -2.06875481F,
+ -1.61777864F,
+ -1.25597887F,
+ -0.94212216F,
+ -0.65659074F,
+ -0.38794210F,
+ -0.12835875F,
+ +0.12835875F,
+ +0.38794210F,
+ +0.65659074F,
+ +0.94212216F,
+ +1.25597887F,
+ +1.61777864F,
+ +2.06875481F,
+ +2.73235729F,
+};
+
+// ---------------------------------------------------------------------------
+// head_dim = 128
+// ---------------------------------------------------------------------------
+static constexpr float TURBOQ_CODEBOOK_2BIT_D128[4] = {
+ -1.50517782F,
+ -0.45244580F,
+ +0.45244580F,
+ +1.50517782F,
+};
+
+static constexpr float TURBOQ_CODEBOOK_3BIT_D128[8] = {
+ -2.13140531F,
+ -1.33653124F,
+ -0.75328017F,
+ -0.24440650F,
+ +0.24440650F,
+ +0.75328017F,
+ +1.33653124F,
+ +2.13140531F,
+};
+
+static constexpr float TURBOQ_CODEBOOK_4BIT_D128[16] = {
+ -2.68863793F,
+ -2.04567026F,
+ -1.60407964F,
+ -1.24752097F,
+ -0.93688023F,
+ -0.65345125F,
+ -0.38627496F,
+ -0.12783692F,
+ +0.12783692F,
+ +0.38627496F,
+ +0.65345125F,
+ +0.93688023F,
+ +1.24752097F,
+ +1.60407964F,
+ +2.04567026F,
+ +2.68863793F,
+};
+
+// ---------------------------------------------------------------------------
+// head_dim = 256
+// ---------------------------------------------------------------------------
+static constexpr float TURBOQ_CODEBOOK_2BIT_D256[4] = {
+ -1.50778871F,
+ -0.45260987F,
+ +0.45260987F,
+ +1.50778871F,
+};
+
+static constexpr float TURBOQ_CODEBOOK_3BIT_D256[8] = {
+ -2.14160037F,
+ -1.34017750F,
+ -0.75461598F,
+ -0.24474095F,
+ +0.24474095F,
+ +0.75461598F,
+ +1.34017750F,
+ +2.14160037F,
+};
+
+static constexpr float TURBOQ_CODEBOOK_4BIT_D256[16] = {
+ -2.71033623F,
+ -2.05714788F,
+ -1.61089805F,
+ -1.25173367F,
+ -0.93949232F,
+ -0.65501613F,
+ -0.38710608F,
+ -0.12809709F,
+ +0.12809709F,
+ +0.38710608F,
+ +0.65501613F,
+ +0.93949232F,
+ +1.25173367F,
+ +1.61089805F,
+ +2.05714788F,
+ +2.71033623F,
+};
+
+// ---------------------------------------------------------------------------
+// head_dim = 512
+// ---------------------------------------------------------------------------
+static constexpr float TURBOQ_CODEBOOK_2BIT_D512[4] = {
+ -1.50909473F,
+ -0.45269120F,
+ +0.45269120F,
+ +1.50909473F,
+};
+
+static constexpr float TURBOQ_CODEBOOK_3BIT_D512[8] = {
+ -2.14672756F,
+ -1.34200568F,
+ -0.75528415F,
+ -0.24490797F,
+ +0.24490797F,
+ +0.75528415F,
+ +1.34200568F,
+ +2.14672756F,
+};
+
+static constexpr float TURBOQ_CODEBOOK_4BIT_D512[16] = {
+ -2.72131117F,
+ -2.06294084F,
+ -1.61433642F,
+ -1.25385775F,
+ -0.94080983F,
+ -0.65580594F,
+ -0.38752582F,
+ -0.12822853F,
+ +0.12822853F,
+ +0.38752582F,
+ +0.65580594F,
+ +0.94080983F,
+ +1.25385775F,
+ +1.61433642F,
+ +2.06294084F,
+ +2.72131117F,
+};
+
+// ---------------------------------------------------------------------------
+// Decision boundaries = midpoints between adjacent centroids (per-dim).
+// ---------------------------------------------------------------------------
+#define TBQ_MIDS_2BIT(CB) {((CB)[0] + (CB)[1]) / 2.0F, ((CB)[1] + (CB)[2]) / 2.0F, ((CB)[2] + (CB)[3]) / 2.0F}
+#define TBQ_MIDS_3BIT(CB) \
+ {((CB)[0] + (CB)[1]) / 2.0F, \
+ ((CB)[1] + (CB)[2]) / 2.0F, \
+ ((CB)[2] + (CB)[3]) / 2.0F, \
+ ((CB)[3] + (CB)[4]) / 2.0F, \
+ ((CB)[4] + (CB)[5]) / 2.0F, \
+ ((CB)[5] + (CB)[6]) / 2.0F, \
+ ((CB)[6] + (CB)[7]) / 2.0F}
+#define TBQ_MIDS_4BIT(CB) \
+ {((CB)[0] + (CB)[1]) / 2.0F, \
+ ((CB)[1] + (CB)[2]) / 2.0F, \
+ ((CB)[2] + (CB)[3]) / 2.0F, \
+ ((CB)[3] + (CB)[4]) / 2.0F, \
+ ((CB)[4] + (CB)[5]) / 2.0F, \
+ ((CB)[5] + (CB)[6]) / 2.0F, \
+ ((CB)[6] + (CB)[7]) / 2.0F, \
+ ((CB)[7] + (CB)[8]) / 2.0F, \
+ ((CB)[8] + (CB)[9]) / 2.0F, \
+ ((CB)[9] + (CB)[10]) / 2.0F, \
+ ((CB)[10] + (CB)[11]) / 2.0F, \
+ ((CB)[11] + (CB)[12]) / 2.0F, \
+ ((CB)[12] + (CB)[13]) / 2.0F, \
+ ((CB)[13] + (CB)[14]) / 2.0F, \
+ ((CB)[14] + (CB)[15]) / 2.0F}
+
+static constexpr float TURBOQ_BOUNDARIES_2BIT[3] = TBQ_MIDS_2BIT(TURBOQ_CODEBOOK_2BIT);
+static constexpr float TURBOQ_BOUNDARIES_3BIT[7] = TBQ_MIDS_3BIT(TURBOQ_CODEBOOK_3BIT);
+static constexpr float TURBOQ_BOUNDARIES_4BIT[15] = TBQ_MIDS_4BIT(TURBOQ_CODEBOOK_4BIT);
+
+static constexpr float TURBOQ_BOUNDARIES_2BIT_D128[3] = TBQ_MIDS_2BIT(TURBOQ_CODEBOOK_2BIT_D128);
+static constexpr float TURBOQ_BOUNDARIES_3BIT_D128[7] = TBQ_MIDS_3BIT(TURBOQ_CODEBOOK_3BIT_D128);
+static constexpr float TURBOQ_BOUNDARIES_4BIT_D128[15] = TBQ_MIDS_4BIT(TURBOQ_CODEBOOK_4BIT_D128);
+
+static constexpr float TURBOQ_BOUNDARIES_2BIT_D256[3] = TBQ_MIDS_2BIT(TURBOQ_CODEBOOK_2BIT_D256);
+static constexpr float TURBOQ_BOUNDARIES_3BIT_D256[7] = TBQ_MIDS_3BIT(TURBOQ_CODEBOOK_3BIT_D256);
+static constexpr float TURBOQ_BOUNDARIES_4BIT_D256[15] = TBQ_MIDS_4BIT(TURBOQ_CODEBOOK_4BIT_D256);
+
+static constexpr float TURBOQ_BOUNDARIES_2BIT_D512[3] = TBQ_MIDS_2BIT(TURBOQ_CODEBOOK_2BIT_D512);
+static constexpr float TURBOQ_BOUNDARIES_3BIT_D512[7] = TBQ_MIDS_3BIT(TURBOQ_CODEBOOK_3BIT_D512);
+static constexpr float TURBOQ_BOUNDARIES_4BIT_D512[15] = TBQ_MIDS_4BIT(TURBOQ_CODEBOOK_4BIT_D512);
+
+#undef TBQ_MIDS_2BIT
+#undef TBQ_MIDS_3BIT
+#undef TBQ_MIDS_4BIT
+
+// ---------------------------------------------------------------------------
+// Lookup: returns the right codebook/boundaries pointer for (bits, head_dim).
+// Fallback for unknown head_dim: asymptotic (N(0,1)) values.
+// ---------------------------------------------------------------------------
+inline const float* turboq_codebook(int bits, int head_dim) {
+ switch (bits) {
+ case 4:
+ switch (head_dim) {
+ case 128:
+ return TURBOQ_CODEBOOK_4BIT_D128;
+ case 256:
+ return TURBOQ_CODEBOOK_4BIT_D256;
+ case 512:
+ return TURBOQ_CODEBOOK_4BIT_D512;
+ default:
+ return TURBOQ_CODEBOOK_4BIT;
+ }
+ case 3:
+ switch (head_dim) {
+ case 128:
+ return TURBOQ_CODEBOOK_3BIT_D128;
+ case 256:
+ return TURBOQ_CODEBOOK_3BIT_D256;
+ case 512:
+ return TURBOQ_CODEBOOK_3BIT_D512;
+ default:
+ return TURBOQ_CODEBOOK_3BIT;
+ }
+ case 2:
+ switch (head_dim) {
+ case 128:
+ return TURBOQ_CODEBOOK_2BIT_D128;
+ case 256:
+ return TURBOQ_CODEBOOK_2BIT_D256;
+ case 512:
+ return TURBOQ_CODEBOOK_2BIT_D512;
+ default:
+ return TURBOQ_CODEBOOK_2BIT;
+ }
+ default:
+ throw std::invalid_argument("turboq_codebook: bits must be 2, 3, or 4");
+ }
+}
+
+inline const float* turboq_boundaries(int bits, int head_dim) {
+ switch (bits) {
+ case 4:
+ switch (head_dim) {
+ case 128:
+ return TURBOQ_BOUNDARIES_4BIT_D128;
+ case 256:
+ return TURBOQ_BOUNDARIES_4BIT_D256;
+ case 512:
+ return TURBOQ_BOUNDARIES_4BIT_D512;
+ default:
+ return TURBOQ_BOUNDARIES_4BIT;
+ }
+ case 3:
+ switch (head_dim) {
+ case 128:
+ return TURBOQ_BOUNDARIES_3BIT_D128;
+ case 256:
+ return TURBOQ_BOUNDARIES_3BIT_D256;
+ case 512:
+ return TURBOQ_BOUNDARIES_3BIT_D512;
+ default:
+ return TURBOQ_BOUNDARIES_3BIT;
+ }
+ case 2:
+ switch (head_dim) {
+ case 128:
+ return TURBOQ_BOUNDARIES_2BIT_D128;
+ case 256:
+ return TURBOQ_BOUNDARIES_2BIT_D256;
+ case 512:
+ return TURBOQ_BOUNDARIES_2BIT_D512;
+ default:
+ return TURBOQ_BOUNDARIES_2BIT;
+ }
+ default:
+ throw std::invalid_argument("turboq_boundaries: bits must be 2, 3, or 4");
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Other constants.
+// ---------------------------------------------------------------------------
+
+// v1 integration unit: one KV head = one rotation chunk = 128 elements.
+static constexpr int TURBOQ_HEAD_RECORD_DIM = 128;
+
+// Paper/llama.cpp block size (not used in v1 per-head model).
+static constexpr int TURBOQ_PAPER_BLOCK_SIZE = 256;
+
+// Packed sizes per head record (head_dim == 128).
+// TBQ4: 128 * 4 bits / 8 = 64 bytes data + 4 bytes fp32 norm = 68 bytes.
+// TBQ3: 128 * 3 bits / 8 = 48 bytes data + 4 bytes fp32 norm = 52 bytes.
+static constexpr size_t TURBOQ_HEAD_BYTES_TBQ4 = 68;
+static constexpr size_t TURBOQ_HEAD_BYTES_TBQ3 = 52;
+
+// QJL (Stage 2) constants.
+// Sign bits per head record: 128 coordinates = 16 bytes.
+static constexpr size_t TURBOQ_SIGN_BYTES = 16;
+
+// QJL head record sizes (head_dim == 128).
+// TBQ4+QJL: 48B (3-bit idx) + 16B (signs) + 4B (fp32 norm) + 4B (fp32 gamma) = 72 bytes.
+// TBQ3+QJL: 32B (2-bit idx) + 16B (signs) + 4B (fp32 norm) + 4B (fp32 gamma) = 56 bytes.
+static constexpr size_t TURBOQ_HEAD_BYTES_TBQ4_QJL = 72;
+static constexpr size_t TURBOQ_HEAD_BYTES_TBQ3_QJL = 56;
+
+// Static assertions: codebook symmetry.
+static_assert(TURBOQ_CODEBOOK_2BIT[0] == -TURBOQ_CODEBOOK_2BIT[3], "2-bit codebook must be symmetric");
+static_assert(TURBOQ_CODEBOOK_2BIT[1] == -TURBOQ_CODEBOOK_2BIT[2], "2-bit codebook must be symmetric");
+
+static_assert(TURBOQ_CODEBOOK_3BIT[0] == -TURBOQ_CODEBOOK_3BIT[7], "3-bit codebook must be symmetric");
+static_assert(TURBOQ_CODEBOOK_3BIT[1] == -TURBOQ_CODEBOOK_3BIT[6], "3-bit codebook must be symmetric");
+static_assert(TURBOQ_CODEBOOK_3BIT[2] == -TURBOQ_CODEBOOK_3BIT[5], "3-bit codebook must be symmetric");
+static_assert(TURBOQ_CODEBOOK_3BIT[3] == -TURBOQ_CODEBOOK_3BIT[4], "3-bit codebook must be symmetric");
+
+static_assert(TURBOQ_CODEBOOK_4BIT[0] == -TURBOQ_CODEBOOK_4BIT[15], "4-bit codebook must be symmetric");
+static_assert(TURBOQ_CODEBOOK_4BIT[1] == -TURBOQ_CODEBOOK_4BIT[14], "4-bit codebook must be symmetric");
+static_assert(TURBOQ_CODEBOOK_4BIT[7] == -TURBOQ_CODEBOOK_4BIT[8], "4-bit codebook must be symmetric");
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_codec.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_codec.cpp
index 7b116814c1d..3a7142881c4 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_codec.cpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_codec.cpp
@@ -9,14 +9,19 @@
#include "codecs/codec_kernels.hpp"
#include "codecs/codecs.hpp"
+#include "codecs/turboq_codec.hpp"
+#include "codecs/turboq_rotation.hpp"
#include "common.hpp"
#include "mha_kv_cache_reduce.hpp"
#include "nodes/kernels/simd/simd.hpp"
#include "openvino/core/parallel.hpp"
+#include "openvino/runtime/internal_properties.hpp"
#include "softmax_kernel.hpp"
namespace ov::Extensions::Cpu::XARCH {
+using ov::Extensions::Cpu::CacheSpec;
+
// Prefetch lookahead: number of records ahead to prefetch.
// At ~50 cycles/record and ~200 cycle DRAM latency, 4-8 records ahead hides latency.
static constexpr int PREFETCH_AHEAD = 8;
@@ -25,10 +30,79 @@ static constexpr int PREFETCH_AHEAD = 8;
// mha_kv_cache — fused multi-head attention over raw or quantized KV cache.
// ---------------------------------------------------------------------------
-using ov::Extensions::Cpu::CacheCodec;
using ov::intel_cpu::CpuParallelPtr;
using ov::intel_cpu::PlainTensor;
+size_t turboq_head_bytes(int head_dim, int bits) {
+ // Packed index bytes only. Per-head norm is stored in a parallel meta-data tensor.
+ return static_cast<size_t>((head_dim * bits + 7) / 8);
+}
+
+size_t turboq_row_bytes(int num_kv_heads, int head_dim, int bits) {
+ return static_cast<size_t>(num_kv_heads) * turboq_head_bytes(head_dim, bits);
+}
+
+// Prepare Q for attention: convert to f32 and optionally rotate.
+// When rotate=true: applies forward rotation (R*q).
+// When rotate=false: just converts Q to f32 (for non-codec K paths).
+static void mha_prepare_query(const PlainTensor& q_input,
+ PlainTensor& out_q,
+ bool rotate,
+ const CpuParallelPtr& cpu_parallel,
+ ov::element::Type q_precision,
+ float* per_thread_head_scratch,
+ size_t per_thread_head_stride,
+ const float* signs) {
+ auto B = q_input.size(0);
+ auto num_q_heads = q_input.size(1);
+ auto L1 = q_input.size(2);
+ auto S = q_input.size(3);
+
+ out_q.resize<float>({B, num_q_heads, L1, S});
+ const auto dim = static_cast<int>(S);
+ const bool need_convert = q_precision != ov::element::f32;
+
+ cpu_parallel->parallel_for2d(B, num_q_heads, [&](size_t b, size_t h) {
+ float* q_buf =
+ per_thread_head_scratch + static_cast<size_t>(parallel_get_thread_num()) * per_thread_head_stride;
+ for (size_t l = 0; l < L1; l++) {
+ auto* dst = out_q.ptr<float>(b, h, l);
+ const float* q_src = nullptr;
+ if (need_convert) {
+ float* conv_dst = rotate ? q_buf : dst;
+ if (q_precision == ov::element::bf16) {
+ const auto* src = q_input.ptr<ov::bfloat16>(b, h, l);
+ int d = 0;
+ for (; d + simd::f32::width - 1 < dim; d += simd::f32::width) {
+ store(simd::load<simd::f32>(src + d), conv_dst + d);
+ }
+ for (; d < dim; d++) {
+ conv_dst[d] = static_cast<float>(src[d]);
+ }
+ } else { // f16
+ const auto* src = q_input.ptr<ov::float16>(b, h, l);
+ int d = 0;
+ for (; d + simd::f32::width - 1 < dim; d += simd::f32::width) {
+ store(simd::load<simd::f32>(src + d), conv_dst + d);
+ }
+ for (; d < dim; d++) {
+ conv_dst[d] = static_cast<float>(src[d]);
+ }
+ }
+ q_src = conv_dst;
+ } else {
+ q_src = q_input.ptr<float>(b, h, l);
+ if (!rotate) {
+ std::memcpy(dst, q_src, static_cast<size_t>(dim) * sizeof(float));
+ }
+ }
+ if (rotate) {
+ turboq_wht_forward(signs, q_src, dst, dim);
+ }
+ }
+ });
+}
+
struct NoOpInit {
void operator()(size_t /*unused*/) const {}
};
@@ -134,7 +208,11 @@ static void mha_softmax(const PlainTensor& attn_w,
// ---------------------------------------------------------------------------
template <typename QT, typename View>
-static inline float record_qk_dot(const uint8_t* k, const QT* q, int head_dim, const View& view) {
+static inline float record_qk_dot(const uint8_t* k,
+ const QT* q,
+ int head_dim,
+ const View& view,
+ float input_norm = 0.0F) {
if constexpr (is_affine_v<View>) {
// Deferred dequant: raw dot per group, then affine correction.
const int gd = view.group_dim();
@@ -170,11 +248,17 @@ static inline float record_qk_dot(const uint8_t* k, const QT* q, int head_dim, c
return DecodePlan{D{}, view.params_for(j, a)};
});
} else {
- // RecordView<RawDecoder<T>>: constant plan, no dequant params.
+ // RecordView<Decoder>: constant plan per-record.
auto plan = DecodePlan{view.decoder, NoParams{}};
- return codec_dot<QT>(k, q, head_dim, [&](int, auto) {
+ float raw = codec_dot<QT>(k, q, head_dim, [&](int, auto) {
return plan;
});
+ if constexpr (is_raw_decoder_v<typename View::decoder_t>) {
+ return raw;
+ } else {
+ // TurboQ: per-token norm comes from the meta-data tensor, passed as input_norm.
+ return raw * turboq_norm_scale(input_norm, head_dim);
+ }
}
}
@@ -185,7 +269,8 @@ static inline void record_v_accum(const uint8_t* v,
StridedData<float> accum,
int num_group_heads,
int head_dim,
- const View& view) {
+ const View& view,
+ float input_norm = 0.0F) {
if constexpr (is_head_grouped_v<View>) {
const int gd = view.group_dim();
const int ng = view.n_groups(head_dim);
@@ -219,15 +304,20 @@ static inline void record_v_accum(const uint8_t* v,
accum,
num_group_heads);
} else {
- // RecordView<RawDecoder<T>>: constant plan, no dequant params.
+ // RecordView<Decoder>: constant plan.
auto plan = DecodePlan{view.decoder, NoParams{}};
+ float scale = 1.0F;
+ if constexpr (!is_raw_decoder_v<typename View::decoder_t>) {
+ // TurboQ: per-token norm comes from the meta-data tensor, passed as input_norm.
+ scale = turboq_norm_scale(input_norm, head_dim);
+ }
codec_weighted_accum(
v,
head_dim,
[&](int, auto) {
return plan;
},
- 1.0F,
+ scale,
weights,
accum,
num_group_heads);
@@ -244,6 +334,11 @@ struct KVEntryContext {
size_t start_pos;
size_t h_group;
int head_dim;
+ // TurboQ per-token norm meta-data. Non-null only for TBQ codecs.
+ // Layout: norm[b, h_group, L] — stride values walk batch and position.
+ const float* norm_base = nullptr;
+ size_t norm_stride_batch = 0;
+ size_t norm_stride_pos = 0;
};
template <typename Q, typename RecordView>
@@ -255,15 +350,18 @@ struct QKScorer {
float operator()(const uint8_t* k, int g, size_t t, size_t b_kv) const {
using QT = std::remove_const_t<std::remove_pointer_t<decltype(q.data)>>;
const QT* q_head = q[g];
+ const float norm = ctx.norm_base
+ ? ctx.norm_base[b_kv * ctx.norm_stride_batch + (ctx.start_pos + t) * ctx.norm_stride_pos]
+ : 0.0F;
if constexpr (has_for_head_v<RecordView>) {
auto head_view = record_view.for_head(g);
auto token_view = head_view.for_token(ctx.start_pos, ctx.h_group, t, b_kv);
- return record_qk_dot<QT>(k, q_head, ctx.head_dim, token_view);
+ return record_qk_dot<QT>(k, q_head, ctx.head_dim, token_view, norm);
} else if constexpr (is_token_indexed_v<RecordView>) {
auto token_view = record_view.for_token(ctx.start_pos, ctx.h_group, t, b_kv);
- return record_qk_dot<QT>(k, q_head, ctx.head_dim, token_view);
+ return record_qk_dot<QT>(k, q_head, ctx.head_dim, token_view, norm);
} else {
- return record_qk_dot<QT>(k, q_head, ctx.head_dim, record_view);
+ return record_qk_dot<QT>(k, q_head, ctx.head_dim, record_view, norm);
}
}
};
@@ -288,11 +386,14 @@ struct VAccumulator {
int num_group_heads,
size_t t,
size_t b_kv) const {
+ const float norm = ctx.norm_base
+ ? ctx.norm_base[b_kv * ctx.norm_stride_batch + (ctx.start_pos + t) * ctx.norm_stride_pos]
+ : 0.0F;
if constexpr (is_token_indexed_v<RecordView>) {
auto token_view = record_view.for_token(ctx.start_pos, ctx.h_group, t, b_kv);
- record_v_accum(v, w, a, num_group_heads, ctx.head_dim, token_view);
+ record_v_accum(v, w, a, num_group_heads, ctx.head_dim, token_view, norm);
} else {
- record_v_accum(v, w, a, num_group_heads, ctx.head_dim, record_view);
+ record_v_accum(v, w, a, num_group_heads, ctx.head_dim, record_view, norm);
}
}
};
@@ -311,7 +412,7 @@ static void score_tokens(const uint8_t* kv_base,
StridedData<float> scores,
size_t run_len,
int num_group_heads,
- size_t pf_bytes,
+ [[maybe_unused]] size_t pf_bytes,
TokenScoreFn score_fn) {
for (size_t t = 0; t < run_len; t++) {
const size_t b_kv = beam_tbl ? static_cast<size_t>(beam_tbl[t]) : b;
@@ -340,7 +441,7 @@ static void accum_tokens(const uint8_t* kv_base,
StridedData<float> accum,
int num_group_heads,
size_t run_len,
- size_t pf_bytes,
+ [[maybe_unused]] size_t pf_bytes,
TokenAccumFn accum_fn) {
for (size_t t = 0; t < run_len; t++) {
const size_t b_kv = beam_tbl ? static_cast<size_t>(beam_tbl[t]) : b;
@@ -385,43 +486,63 @@ static void dispatch_q_precision(const PlainTensor& q_input,
template <typename View>
static inline size_t codec_record_bytes(const View& view, int head_dim) {
(void)view;
+ // Packed values only for all codecs. TurboQ norm now lives in a parallel meta-data tensor.
return static_cast<size_t>(head_dim) * View::decoder_t::bits / 8;
}
// ---------------------------------------------------------------------------
-// Codec dispatch: maps runtime CacheCodec to concrete HeadCodec type.
+// Codec dispatch: resolves (alg, precision, by_channel) to a concrete RecordView.
+// Outer switch is on algorithm (TURBO vs SCALAR); inner on precision.
// ---------------------------------------------------------------------------
-template <typename Fn>
-static void dispatch_codec(CacheCodec codec,
+template <typename ProcessTokens>
+static void dispatch_codec(const CacheSpec& spec,
int head_dim,
- size_t group_size,
const PlainTensor& scale_zp,
- Fn&& fn,
+ ProcessTokens&& process_tokens,
const float* q_group_sums = nullptr,
size_t q_group_sums_stride = 0) {
- (void)head_dim;
- switch (codec) {
- case CacheCodec::U8:
- if (q_group_sums) {
- fn(AffineRecordView{scale_zp, group_size, q_group_sums, q_group_sums_stride});
- } else {
- fn(GroupedRecordView<U8Decoder>{scale_zp, group_size});
+ switch (spec.alg) {
+ case ov::internal::CacheQuantAlgorithm::TURBO:
+ switch (spec.precision.bitwidth()) {
+ case 4:
+ process_tokens(RecordView<TurboQDecoder4<>>{TurboQDecoder4<>{head_dim}});
+ break;
+ case 3:
+ process_tokens(RecordView<TurboQDecoder3<>>{TurboQDecoder3<>{head_dim}});
+ break;
+ case 2:
+ process_tokens(RecordView<TurboQDecoder2<>>{TurboQDecoder2<>{head_dim}});
+ break;
+ default:
+ OPENVINO_THROW("Unsupported TURBO precision: ", spec.precision);
}
break;
- case CacheCodec::U4:
- fn(GroupedRecordView<U4Decoder>{scale_zp, group_size});
- break;
- case CacheCodec::U8_BY_CHANNEL:
- fn(ByChannelRecordView{scale_zp, group_size});
- break;
- case CacheCodec::RAW_F32:
- fn(RecordView<RawDecoder<float>>{{}});
- break;
- case CacheCodec::RAW_F16:
- fn(RecordView<RawDecoder<ov::float16>>{{}});
- break;
- case CacheCodec::RAW_BF16:
- fn(RecordView<RawDecoder<ov::bfloat16>>{{}});
+ case ov::internal::CacheQuantAlgorithm::SCALAR:
+ switch (spec.precision) {
+ case ov::element::u8:
+ if (spec.by_channel) {
+ process_tokens(ByChannelRecordView{scale_zp, spec.group_size});
+ } else if (q_group_sums) {
+ process_tokens(AffineRecordView{scale_zp, spec.group_size, q_group_sums, q_group_sums_stride});
+ } else {
+ process_tokens(GroupedRecordView<U8Decoder>{scale_zp, spec.group_size});
+ }
+ break;
+ case ov::element::u4:
+ process_tokens(GroupedRecordView<U4Decoder>{scale_zp, spec.group_size});
+ break;
+ case ov::element::f16:
+ process_tokens(RecordView<RawDecoder<ov::float16>>{{}});
+ break;
+ case ov::element::bf16:
+ process_tokens(RecordView<RawDecoder<ov::bfloat16>>{{}});
+ break;
+ case ov::element::f32:
+ process_tokens(RecordView<RawDecoder<float>>{{}});
+ break;
+ default:
+ OPENVINO_THROW("Unsupported SCALAR precision: ", spec.precision);
+ }
break;
}
}
@@ -439,17 +560,20 @@ void mha_kv_cache(PlainTensor& q_input,
PlainTensor& buf_attn_score,
bool has_out_transpose,
float d_scale,
- CacheCodec k_codec,
- CacheCodec v_codec,
+ const CacheSpec& k_spec,
+ const CacheSpec& v_spec,
bool auto_causal,
const PlainTensor& sink_input,
const CpuParallelPtr& cpu_parallel,
const PlainTensor& k_scale_zp,
- size_t key_group_size,
const PlainTensor& v_scale_zp,
- size_t value_group_size,
ov::element::Type q_precision,
- size_t value_head_dim) {
+ size_t value_head_dim,
+ float* per_thread_head_scratch,
+ size_t per_thread_head_stride,
+ const PlainTensor& k_quant_meta_data,
+ const PlainTensor& v_quant_meta_data,
+ const PlainTensor& wht_signs) {
// ---------------------------------------------------------------------------
// Setup: dimensions, scratch buffers, precomputed constants.
// ---------------------------------------------------------------------------
@@ -468,6 +592,19 @@ void mha_kv_cache(PlainTensor& q_input,
d_scale = 1.0F / std::sqrt(static_cast<float>(S));
}
+ // Prepare f32 Q only when K has codec — rotation needed for QK dot in rotated domain.
+ PlainTensor prepared_q;
+ if (k_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO) {
+ mha_prepare_query(q_input,
+ prepared_q,
+ /*rotate=*/true,
+ cpu_parallel,
+ q_precision,
+ per_thread_head_scratch,
+ per_thread_head_stride,
+ wht_signs.ptr<float>());
+ }
+
buf_attn_w.resize<float>({B, num_q_heads, q_len, (kv_len + 15) / 16 * 16});
buf_attn_score.resize<float>({static_cast<size_t>(nthr), B, q_len, num_q_heads, SV});
@@ -476,8 +613,9 @@ void mha_kv_cache(PlainTensor& q_input,
// AVX2-only: defer u8 zp subtraction from per-element to per-group-after-dot.
// AVX-512 has enough throughput to absorb the per-element sub — not worth the overhead.
constexpr bool is_avx2 = simd::f32::isa_value == simd::isa::avx2;
- const bool use_affine_k = is_avx2 && (k_codec == CacheCodec::U8);
- const size_t n_key_groups = use_affine_k ? S / key_group_size : 0;
+ const bool use_affine_k = is_avx2 && k_spec.alg != ov::internal::CacheQuantAlgorithm::TURBO &&
+ k_spec.precision == ov::element::u8 && !k_spec.by_channel;
+ const size_t n_key_groups = use_affine_k ? S / k_spec.group_size : 0;
PlainTensor q_group_sums_buf;
if (use_affine_k) {
q_group_sums_buf.resize<float>({B, num_q_heads, q_len, n_key_groups});
@@ -494,13 +632,13 @@ void mha_kv_cache(PlainTensor& q_input,
for (size_t g = 0; g < n_key_groups; g++) {
constexpr int W = simd::f32::width;
simd::f32 acc;
- const size_t offset = g * key_group_size;
+ const size_t offset = g * k_spec.group_size;
size_t i = 0;
- for (; i + W <= key_group_size; i += W) {
+ for (; i + W <= k_spec.group_size; i += W) {
acc = acc + simd::load<simd::f32>(q_head + offset + i);
}
sums[g] = reduce(acc);
- for (; i < key_group_size; i++) {
+ for (; i < k_spec.group_size; i++) {
sums[g] += static_cast<float>(q_head[offset + i]);
}
}
@@ -520,13 +658,13 @@ void mha_kv_cache(PlainTensor& q_input,
mha_foreach_kv(
kv_traversal,
S,
- [&, k_codec, m](size_t run_len,
- int num_group_heads,
- int head_dim,
- size_t b,
- size_t h_group,
- size_t start_pos,
- size_t /*ithr*/) {
+ [&, m](size_t run_len,
+ int num_group_heads,
+ int head_dim,
+ size_t b,
+ size_t h_group,
+ size_t start_pos,
+ size_t /*ithr*/) {
const size_t h_start = h_group * heads_per_kv_group;
const auto* kv_base = static_cast<const uint8_t*>(key_cache.ptr_v(size_t{0}, h_group, start_pos));
const size_t stride_batch = key_cache.stride_bytes(0);
@@ -535,21 +673,28 @@ void mha_kv_cache(PlainTensor& q_input,
const int32_t* beam_tbl_ptr = use_beams ? beams.ptr<int32_t>(b) + start_pos : nullptr;
float* scores_row_base = buf_attn_w.ptr<float>(b, h_start, m) + start_pos;
StridedData<float> scores{scores_row_base, buf_attn_w.stride(1)};
- const KVEntryContext entry_ctx{start_pos, h_group, head_dim};
+ KVEntryContext entry_ctx{start_pos, h_group, head_dim, nullptr, 0, 0};
+ if (k_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO && k_quant_meta_data) {
+ entry_ctx.norm_base = k_quant_meta_data.ptr<float>(0, h_group, 0);
+ entry_ctx.norm_stride_batch = k_quant_meta_data.stride(0);
+ entry_ctx.norm_stride_pos = k_quant_meta_data.stride(2);
+ }
// q_group_sums base for first head in group; stride to step between heads.
const float* q_group_sums = use_affine_k ? q_group_sums_buf.ptr<float>(b, h_start, m) : nullptr;
const size_t q_group_sums_stride = use_affine_k ? q_group_sums_buf.stride(1) : 0;
+ const bool encoded = k_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO;
+ const auto& q_src = encoded ? prepared_q : q_input;
+ const auto q_prec = encoded ? ov::element::f32 : q_precision;
dispatch_q_precision(
- q_input,
+ q_src,
b,
h_start,
- q_precision,
+ q_prec,
[&](auto q) {
dispatch_codec(
- k_codec,
+ k_spec,
head_dim,
- key_group_size,
k_scale_zp,
[&](auto record_view) {
auto scorer = QKScorer{q, record_view, entry_ctx};
@@ -589,18 +734,19 @@ void mha_kv_cache(PlainTensor& q_input,
// ---------------------------------------------------------------------------
// Phases 3+4: V accumulation + reduce, per query position.
// ---------------------------------------------------------------------------
+ const bool do_inv_rotate = v_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO;
for (size_t m = 0; m < q_len; m++) {
// Phase 3: V accumulation for query position m.
mha_foreach_kv(
kv_traversal,
SV,
- [&, v_codec, m](size_t run_len,
- int num_group_heads,
- int head_dim,
- size_t b,
- size_t h_group,
- size_t start_pos,
- size_t ithr) {
+ [&, m](size_t run_len,
+ int num_group_heads,
+ int head_dim,
+ size_t b,
+ size_t h_group,
+ size_t start_pos,
+ size_t ithr) {
const size_t h_start = h_group * heads_per_kv_group;
const auto* kv_base = static_cast<const uint8_t*>(packed_value.ptr_v(size_t{0}, h_group, start_pos));
const size_t stride_batch = packed_value.stride_bytes(0);
@@ -611,9 +757,14 @@ void mha_kv_cache(PlainTensor& q_input,
StridedData<const float> weights{weights_row_base, buf_attn_w.stride(1)};
auto* accum_row_base = buf_attn_score.ptr<float>(ithr, b, m, h_start);
StridedData<float> accum{accum_row_base, buf_attn_score.stride(3)};
- const KVEntryContext entry_ctx{start_pos, h_group, head_dim};
+ KVEntryContext entry_ctx{start_pos, h_group, head_dim, nullptr, 0, 0};
+ if (v_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO && v_quant_meta_data) {
+ entry_ctx.norm_base = v_quant_meta_data.ptr<float>(0, h_group, 0);
+ entry_ctx.norm_stride_batch = v_quant_meta_data.stride(0);
+ entry_ctx.norm_stride_pos = v_quant_meta_data.stride(2);
+ }
- dispatch_codec(v_codec, head_dim, value_group_size, v_scale_zp, [&](auto record_view) {
+ dispatch_codec(v_spec, head_dim, v_scale_zp, [&](auto record_view) {
auto vaccum = VAccumulator{record_view, entry_ctx};
accum_tokens(kv_base,
stride_batch,
@@ -640,12 +791,14 @@ void mha_kv_cache(PlainTensor& q_input,
mha_reduce(buf_attn_score,
output_emb,
has_out_transpose,
+ do_inv_rotate,
B,
num_q_heads,
1, // reduce one query position at a time
SV,
nthr,
cpu_parallel,
+ do_inv_rotate ? wht_signs.ptr<float>() : nullptr,
m);
}
}
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_codec.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_codec.hpp
index 2feb3215baa..2fcb29aee77 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_codec.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_codec.hpp
@@ -7,17 +7,20 @@
#include <cstddef>
-#include "codecs/cache_codec.hpp"
+#include "cache_spec.hpp"
#include "cpu_parallel.hpp"
#include "openvino/core/type/element_type.hpp"
+#include "openvino/runtime/internal_properties.hpp"
#include "utils/plain_tensor.hpp"
namespace ov::Extensions::Cpu::XARCH {
+// Packed byte size helper (used by scaled_attn.cpp to size cache buffers).
+size_t turboq_head_bytes(int head_dim, int bits);
+
// Generic codec-aware fused multi-head attention pipeline.
-// k_codec / v_codec: identify the encoding scheme of cached K/V.
+// k_spec / v_spec: per-side cache specification.
// k_scale_zp / v_scale_zp: scale/zp tensor (empty when cache is raw).
-// key_group_size / value_group_size: u8 group size (ignored when not u8).
// q_precision: element type of q_input (f32, bf16, or f16).
void mha_kv_cache(ov::intel_cpu::PlainTensor& q_input,
const ov::intel_cpu::PlainTensor& key_cache,
@@ -30,16 +33,19 @@ void mha_kv_cache(ov::intel_cpu::PlainTensor& q_input,
ov::intel_cpu::PlainTensor& buf_attn_score,
bool has_out_transpose,
float d_scale,
- ov::Extensions::Cpu::CacheCodec k_codec,
- ov::Extensions::Cpu::CacheCodec v_codec,
+ const ov::Extensions::Cpu::CacheSpec& k_spec,
+ const ov::Extensions::Cpu::CacheSpec& v_spec,
bool auto_causal,
const ov::intel_cpu::PlainTensor& sink_input,
const ov::intel_cpu::CpuParallelPtr& cpu_parallel,
const ov::intel_cpu::PlainTensor& k_scale_zp,
- size_t key_group_size,
const ov::intel_cpu::PlainTensor& v_scale_zp,
- size_t value_group_size,
ov::element::Type q_precision,
- size_t value_head_dim);
+ size_t value_head_dim,
+ float* per_thread_head_scratch,
+ size_t per_thread_head_stride,
+ const ov::intel_cpu::PlainTensor& k_quant_meta_data,
+ const ov::intel_cpu::PlainTensor& v_quant_meta_data,
+ const ov::intel_cpu::PlainTensor& wht_signs);
} // namespace ov::Extensions::Cpu::XARCH
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_reduce.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_reduce.hpp
index 467cd76afcd..23e1ee3a1ce 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_reduce.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_reduce.hpp
@@ -4,8 +4,10 @@
#pragma once
+#include <cassert>
#include <cstddef>
+#include "codecs/turboq_rotation.hpp"
#include "cpu_parallel.hpp"
#include "nodes/kernels/simd/simd_loop.hpp"
#include "openvino/core/type/bfloat16.hpp"
@@ -34,24 +36,41 @@ static void reduce_thread_accumulators(T* dst, const float* src, size_t stride,
});
}
+// Typed reduce: reduces thread accumulators + optional inverse rotation,
+// writing the final result directly to typed output dst.
+template <typename T>
+static void
+reduce_head(int dim, T* dst, float* src, int nthr, size_t stride, bool apply_inv_rotation, const float* signs) {
+ if (!apply_inv_rotation) {
+ reduce_thread_accumulators(dst, src, stride, dim, nthr);
+ } else {
+ assert(dim % 64 == 0 && "dim must be divisible by 64");
+ assert(signs != nullptr && "WHT signs required for inverse rotation");
+ reduce_thread_accumulators(src, src, stride, dim, nthr);
+ turboq_wht_inverse(signs, src, dst, dim);
+ }
+}
+
template <typename T>
static void mha_reduce_typed(const PlainTensor& attn_score,
PlainTensor& output_emb,
bool has_out_transpose,
+ bool apply_inv_rotation,
size_t B,
size_t H,
size_t q_len,
size_t S,
int nthr,
const CpuParallelPtr& cpu_parallel,
- size_t q_offset) {
+ size_t q_offset,
+ const float* signs) {
const size_t thread_stride = attn_score.stride(0);
auto reduce_body = [&](size_t b, size_t h, size_t m) {
const size_t out_m = q_offset + m;
auto* dst = has_out_transpose ? output_emb.ptr<T>(b, out_m, h * S) : output_emb.ptr<T>(b, h, out_m);
auto* src0 = attn_score.ptr<float>(static_cast<size_t>(0), b, out_m, h);
- reduce_thread_accumulators(dst, src0, thread_stride, static_cast<int>(S), nthr);
+ reduce_head(static_cast<int>(S), dst, src0, nthr, thread_stride, apply_inv_rotation, signs);
};
if (q_len == 1) {
cpu_parallel->parallel_for2d(B, H, [&](size_t b, size_t h) {
@@ -65,23 +84,55 @@ static void mha_reduce_typed(const PlainTensor& attn_score,
static void mha_reduce(const PlainTensor& attn_score,
PlainTensor& output_emb,
bool has_out_transpose,
+ bool apply_inv_rotation,
size_t B,
size_t H,
size_t q_len,
size_t S,
int nthr,
const CpuParallelPtr& cpu_parallel,
+ const float* signs,
size_t q_offset = 0) {
const auto out_prec = output_emb.get_precision();
if (out_prec == ov::element::bf16) {
- mha_reduce_typed<
- ov::bfloat16>(attn_score, output_emb, has_out_transpose, B, H, q_len, S, nthr, cpu_parallel, q_offset);
+ mha_reduce_typed<ov::bfloat16>(attn_score,
+ output_emb,
+ has_out_transpose,
+ apply_inv_rotation,
+ B,
+ H,
+ q_len,
+ S,
+ nthr,
+ cpu_parallel,
+ q_offset,
+ signs);
} else if (out_prec == ov::element::f16) {
- mha_reduce_typed<
- ov::float16>(attn_score, output_emb, has_out_transpose, B, H, q_len, S, nthr, cpu_parallel, q_offset);
+ mha_reduce_typed<ov::float16>(attn_score,
+ output_emb,
+ has_out_transpose,
+ apply_inv_rotation,
+ B,
+ H,
+ q_len,
+ S,
+ nthr,
+ cpu_parallel,
+ q_offset,
+ signs);
} else {
- mha_reduce_typed<
- float>(attn_score, output_emb, has_out_transpose, B, H, q_len, S, nthr, cpu_parallel, q_offset);
+ mha_reduce_typed<float>(attn_score,
+ output_emb,
+ has_out_transpose,
+ apply_inv_rotation,
+ B,
+ H,
+ q_len,
+ S,
+ nthr,
+ cpu_parallel,
+ q_offset,
+ signs);
}
}
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_loop.hpp b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_loop.hpp
index 512a628178b..ff51198097d 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_loop.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_loop.hpp
@@ -28,13 +28,13 @@ namespace ov::Extensions::Cpu::XARCH::simd {
// Load: any source type (float, bf16, f16, u8) → vec<float, I>.
template <typename V, isa I, typename SrcT>
-inline V load(const SrcT* ptr, active_lanes<I>) {
+inline V load(const SrcT* ptr, active_lanes<I> /*lanes*/) {
return load(ptr, static_cast<V*>(nullptr));
}
// Store: vec<float, I> → any destination type (float, bf16, f16).
template <typename V, typename DstT, isa I>
-inline void store(V v, DstT* ptr, active_lanes<I>) {
+inline void store(V v, DstT* ptr, active_lanes<I> /*lanes*/) {
store(v, ptr);
}
@@ -42,7 +42,7 @@ inline void store(V v, DstT* ptr, active_lanes<I>) {
// For scalar ISA, just returns the value. For SIMD, reduces all lanes.
// Future: SVE/RVV will reduce only predicated/active lanes.
template <typename V, isa I>
-inline float reduce(V v, active_lanes<I>) {
+inline float reduce(V v, active_lanes<I> /*lanes*/) {
return reduce(v);
}
@@ -60,7 +60,7 @@ inline float reduce(V v, active_lanes<I>) {
// ---------------------------------------------------------------------------
template <isa I, typename Body>
-inline void for_each_chunk(int n, Body&& body) {
+inline void for_each_chunk(int n, Body& body) {
if constexpr (I == isa::scalar) {
for (int j = 0; j < n; j++) {
body(j, active_lanes<isa::scalar>{});
@@ -82,8 +82,8 @@ inline void for_each_chunk(int n, Body&& body) {
// ---------------------------------------------------------------------------
template <typename Body>
-inline void simd_loop(int n, Body&& body) {
- for_each_chunk<active_isa>(n, std::forward<Body>(body));
+inline void simd_loop(int n, Body body) {
+ for_each_chunk<active_isa>(n, body);
}
// ---------------------------------------------------------------------------
@@ -92,13 +92,13 @@ inline void simd_loop(int n, Body&& body) {
// ---------------------------------------------------------------------------
template <int N, typename Fn, int... Is>
-inline void unroll_impl(Fn&& fn, std::integer_sequence<int, Is...>) {
+inline void unroll_impl(Fn& fn, std::integer_sequence<int, Is...> /*seq*/) {
(fn(std::integral_constant<int, Is>{}), ...);
}
template <int N, typename Fn>
-inline void unroll(Fn&& fn) {
- unroll_impl<N>(std::forward<Fn>(fn), std::make_integer_sequence<int, N>{});
+inline void unroll(Fn fn) {
+ unroll_impl<N>(fn, std::make_integer_sequence<int, N>{});
}
// ---------------------------------------------------------------------------
@@ -116,7 +116,7 @@ inline void unroll(Fn&& fn) {
// ---------------------------------------------------------------------------
template <int Unroll = 4, typename MainBody, typename TailBody>
-inline float simd_loop_reduce(int n, MainBody&& main_body, TailBody&& tail_body) {
+inline float simd_loop_reduce(int n, MainBody main_body, TailBody tail_body) {
constexpr int W = f32::width;
f32 acc[Unroll]{};
diff --git a/src/plugins/intel_cpu/src/nodes/memory.cpp b/src/plugins/intel_cpu/src/nodes/memory.cpp
index c9aaa38ddeb..59f127584d4 100644
--- a/src/plugins/intel_cpu/src/nodes/memory.cpp
+++ b/src/plugins/intel_cpu/src/nodes/memory.cpp
@@ -23,6 +23,8 @@
#include "edge.h"
#include "graph.h"
#include "graph_context.h"
+#include "kernels/scaled_attn/cache_spec.hpp"
+#include "kernels/scaled_attn/mha_kv_cache_codec.hpp"
#include "memory_desc/cpu_memory_desc.h"
#include "memory_desc/cpu_memory_desc_utils.h"
#include "memory_state.h"
@@ -40,6 +42,7 @@
#include "openvino/core/type/element_type.hpp"
#include "openvino/op/assign.hpp"
#include "openvino/op/read_value.hpp"
+#include "openvino/runtime/internal_properties.hpp"
#include "openvino/util/common_util.hpp"
#include "proxy_mem_blk.h"
#include "scaled_attn.h"
@@ -1082,13 +1085,13 @@ MemStatePtr MemoryInputSDPA::makeState() const {
auto node = m_sdpaNode.lock();
// retrieve the internal precision and axis order from the SDPA node
CPU_NODE_ASSERT(node, "SDPA node is not available");
- auto kv_precision = node->getKVCachePrecision();
- ScaledDotProductAttention::SDPAQuantParam quant_param;
+ // SDPA port convention: K = inputNumber - 2, V = inputNumber - 1.
+ const auto sdpa_inputs = node->getOriginalInputsNumber();
+ const bool is_key = static_cast<size_t>(m_child_port_idx) == sdpa_inputs - 2;
+ auto kv_precision = is_key ? node->getKeyCachePrecision() : node->getValueCachePrecision();
+ ov::Extensions::Cpu::CacheSpec quant_param;
if (kv_precision == ov::element::u8 || kv_precision == ov::element::u4) {
- const auto& edges_to_past_key = node->getParentEdgeAt(node->getParentEdges().size() - 2);
- const auto& past_key = std::dynamic_pointer_cast<node::MemoryInputBase>(edges_to_past_key->getParent());
- OPENVINO_ASSERT(past_key);
- quant_param = past_key->getId() == state_name ? node->getKeyQuantParam() : node->getValueQuantParam();
+ quant_param = is_key ? node->getKeySpec() : node->getValueSpec();
}
VectorDims order = {2, 0, 1, 3};
@@ -1096,13 +1099,24 @@ MemStatePtr MemoryInputSDPA::makeState() const {
order = node->getKVCacheOrder();
}
- auto internal_desc = ArbitraryOrderDescCreator(order).createSharedDesc(kv_precision, outputShapes.at(0));
+ // For TurboQuant codecs, internal cache hidden dim is packed byte size per head record,
+ // not the original head_dim. Model-space output still uses head_dim.
+ auto internal_shape = outputShapes.at(0);
+ const auto& qp = is_key ? node->getKeySpec() : node->getValueSpec();
+ if (qp.alg == ov::internal::CacheQuantAlgorithm::TURBO) {
+ auto min_dims = internal_shape.getMinDims();
+ auto max_dims = internal_shape.getMaxDims();
+ const auto head_dim = static_cast<int>(max_dims.back());
+ const auto packed =
+ ov::Extensions::Cpu::XARCH::turboq_head_bytes(head_dim, static_cast<int>(qp.precision.bitwidth()));
+ min_dims.back() = packed;
+ max_dims.back() = packed;
+ internal_shape = Shape(min_dims, max_dims);
+ }
+
+ auto internal_desc = ArbitraryOrderDescCreator(order).createSharedDesc(kv_precision, internal_shape);
- return std::make_shared<VariableStateKVcache>(state_name,
- original_desc,
- internal_desc,
- quant_param.isByChannel,
- quant_param.groupSize);
+ return std::make_shared<VariableStateKVcache>(state_name, original_desc, internal_desc, quant_param);
}
void MemoryInputSDPA::runStatic(dnnl::stream strm) {
@@ -1111,9 +1125,16 @@ void MemoryInputSDPA::runStatic(dnnl::stream strm) {
void MemoryInputSDPA::runDynamic([[maybe_unused]] dnnl::stream strm) {
auto currentState = getAssignedState();
+ auto sdpaState = std::dynamic_pointer_cast<VariableStateKVcache>(currentState);
+ // For TBQ, internal cache has packed hidden dim but downstream shape inference
+ // expects the original model head_dim. Report model-space dims here; the SDPA executor
+ // reads the packed cache directly via m_k_state->internal_state_mem(), bypassing this output.
+ const auto& base_shape = getBaseMemDescAtOutputPort(0)->getShape();
+ const bool is_tbq = sdpaState && sdpaState->get_spec().alg == ov::internal::CacheQuantAlgorithm::TURBO;
+
if (currentState->is_reset_state()) {
if (getParentEdges().empty()) {
- auto newShape = MemoryDescUtils::makeDummyShape(getBaseMemDescAtOutputPort(0)->getShape(), 0);
+ auto newShape = MemoryDescUtils::makeDummyShape(base_shape, 0);
redefineOutputMemory({newShape.getStaticDims()});
} else {
auto inpMem = getSrcMemoryAtPort(0);
@@ -1127,7 +1148,13 @@ void MemoryInputSDPA::runDynamic([[maybe_unused]] dnnl::stream strm) {
" is empty, node name: ",
getName());
- redefineOutputMemory({stateMem->getStaticDims()});
+ if (is_tbq) {
+ auto dims = stateMem->getStaticDims();
+ dims.back() = base_shape.getDims().back();
+ redefineOutputMemory({dims});
+ } else {
+ redefineOutputMemory({stateMem->getStaticDims()});
+ }
}
}
diff --git a/src/plugins/intel_cpu/src/nodes/scaled_attn.cpp b/src/plugins/intel_cpu/src/nodes/scaled_attn.cpp
index 7e4be0f6b11..38fae7062b1 100644
--- a/src/plugins/intel_cpu/src/nodes/scaled_attn.cpp
+++ b/src/plugins/intel_cpu/src/nodes/scaled_attn.cpp
@@ -35,6 +35,7 @@
#include "openvino/core/type.hpp"
#include "openvino/core/type/element_type.hpp"
#include "openvino/op/scaled_dot_product_attention.hpp"
+#include "openvino/runtime/internal_properties.hpp"
#include "openvino/runtime/system_conf.hpp"
#include "shape_inference/custom/scaled_attn.hpp"
#include "transformations/cpu_opset/common/op/sdpa.hpp"
@@ -67,7 +68,10 @@
#include "kernels/scaled_attn/attn_memcpy.hpp"
#include "kernels/scaled_attn/attn_quant.hpp"
-#include "kernels/scaled_attn/codecs/cache_codec.hpp"
+#include "kernels/scaled_attn/cache_spec.hpp"
+#include "kernels/scaled_attn/codecs/codec_kernels.hpp"
+#include "kernels/scaled_attn/codecs/turboq_quantize.hpp"
+#include "kernels/scaled_attn/codecs/turboq_rotation.hpp"
#include "kernels/scaled_attn/mha_kv_cache_codec.hpp"
#include "kernels/scaled_attn/mha_single_token.hpp"
#include "kernels/scaled_attn/softmax.hpp"
@@ -86,20 +90,24 @@ static bool is_quantized_cache(ov::element::Type prec) {
}
// Compress and write cur tensor into the KV cache (dst) at position L0.
-// Handles u8/u4 quant (per-group or by-channel) and raw precision-matching copy.
+// Handles encoded (TurboQ), quantized (u8/u4 with scale/zp), or raw (f32/f16/bf16 memcpy).
+// ws: per-thread f32 scratch for the codec path.
static void compress_cache(const PlainTensor& cur,
PlainTensor& dst,
size_t L0,
- ov::element::Type quant_precision,
+ const ov::Extensions::Cpu::CacheSpec& spec,
PlainTensor& scale_zp,
- size_t group_size,
- bool quant_by_channel,
- const CpuParallelPtr& cpu_parallel) {
- if (is_quantized_cache(quant_precision)) {
- if (quant_by_channel) {
- attn_quant_by_channel(cur, dst, scale_zp, L0, group_size, cpu_parallel);
+ PlainTensor& meta_data,
+ const CpuParallelPtr& cpu_parallel,
+ ov::Extensions::Cpu::StridedData<float> ws = {nullptr, 0},
+ const PlainTensor& signs = {}) {
+ if (spec.alg == ov::internal::CacheQuantAlgorithm::TURBO) {
+ turboq_quantize(cur, dst, meta_data, L0, static_cast<int>(spec.precision.bitwidth()), cpu_parallel, ws, signs);
+ } else if (is_quantized_cache(spec.precision)) {
+ if (spec.by_channel) {
+ attn_quant_by_channel(cur, dst, scale_zp, L0, spec.group_size, cpu_parallel);
} else {
- attn_quant_by_token(cur, dst, scale_zp, L0, group_size, cpu_parallel);
+ attn_quant_by_token(cur, dst, scale_zp, L0, spec.group_size, cpu_parallel);
}
} else {
attn_memcpy2d(cur, dst, L0, cpu_parallel);
@@ -1384,13 +1392,18 @@ struct ScaledDotProductAttention::AttentionExecutor : public ScaledDotProductAtt
PlainTensor m_attn_w;
PlainTensor m_attn_score;
+ size_t m_key_group_size = 0;
+ size_t m_value_group_size = 0;
+
explicit AttentionExecutor(GraphContext::CPtr ctx,
size_t k_group_size,
size_t v_group_size,
bool quant_key_by_channel)
: context(std::move(ctx)),
kernel(context),
- kernel_single_token(k_group_size, v_group_size, quant_key_by_channel) {}
+ kernel_single_token(k_group_size, v_group_size, quant_key_by_channel),
+ m_key_group_size(k_group_size),
+ m_value_group_size(v_group_size) {}
[[nodiscard]] impl_desc_type implType() const override {
return kernel.getImplType();
@@ -1413,8 +1426,13 @@ struct ScaledDotProductAttention::AttentionExecutor : public ScaledDotProductAtt
const MemoryPtr beam_input,
const PlainTensor& k_scale_zp,
const PlainTensor& v_scale_zp,
- ov::Extensions::Cpu::CacheCodec k_codec,
- ov::Extensions::Cpu::CacheCodec v_codec) override {
+ const ov::Extensions::Cpu::CacheSpec& k_param,
+ const ov::Extensions::Cpu::CacheSpec& v_param,
+ float* per_thread_head_scratch,
+ size_t per_thread_head_stride,
+ const PlainTensor& k_quant_meta_data,
+ const PlainTensor& v_quant_meta_data,
+ const PlainTensor& wht_signs) override {
bool has_in_reshape = config.config.input_BLHxS;
bool has_out_transpose = config.config.output_BLHxS;
bool fuse_causal_attn = config.config.fuse_causal_attn;
@@ -1507,8 +1525,14 @@ struct ScaledDotProductAttention::AttentionExecutor : public ScaledDotProductAtt
k_input.assert_dims({B, Hk, L0 + L1, S});
v_input.assert_dims({B, Hk, L0 + L1, SV});
}
- present_key.assert_dims({B, Hk, L0 + L1, S});
- present_value.assert_dims({B, Hk, L0 + L1, SV});
+ const bool k_is_turboq = k_param.alg == ov::internal::CacheQuantAlgorithm::TURBO;
+ const bool v_is_turboq = v_param.alg == ov::internal::CacheQuantAlgorithm::TURBO;
+ if (!k_is_turboq) {
+ present_key.assert_dims({B, Hk, L0 + L1, S});
+ }
+ if (!v_is_turboq) {
+ present_value.assert_dims({B, Hk, L0 + L1, SV});
+ }
if (beam_table) {
beam_table.assert_dims({B, L0 + L1});
}
@@ -1589,17 +1613,20 @@ struct ScaledDotProductAttention::AttentionExecutor : public ScaledDotProductAtt
m_attn_score,
has_out_transpose,
scale_input,
- k_codec,
- v_codec,
+ k_param,
+ v_param,
auto_causal,
sink_input,
context->getCpuParallel(),
k_scale_zp,
- kernel_single_token.m_key_group_size,
v_scale_zp,
- kernel_single_token.m_value_group_size,
q_input.get_precision(),
- SV);
+ SV,
+ per_thread_head_scratch,
+ per_thread_head_stride,
+ k_quant_meta_data,
+ v_quant_meta_data,
+ wht_signs);
} else {
kernel_single_token(q_input,
present_key,
@@ -1820,23 +1847,49 @@ ScaledDotProductAttention::ScaledDotProductAttention(const std::shared_ptr<ov::N
const auto valueDims = getInputShapeAtPort(2).getDims();
const auto keyS = *(keyDims.end() - 1);
const auto valueS = *(valueDims.end() - 1);
- CPU_NODE_ASSERT(valueCachePrecision == keyCachePrecision, "supports same key/value cache precision");
- CPU_NODE_ASSERT(any_of(keyCachePrecision,
- ov::element::f32,
- ov::element::f16,
- ov::element::bf16,
- ov::element::u8,
- ov::element::u4),
- "supports key/value cache precision f32, f16, bf16, u8, u4 but gets ",
- keyCachePrecision);
- m_key_quant_param.groupSize = (cpuConfig.keyCacheGroupSize == 0 || keyS % cpuConfig.keyCacheGroupSize != 0)
- ? keyS
- : cpuConfig.keyCacheGroupSize;
- m_key_quant_param.precision = keyCachePrecision;
- m_value_quant_param.groupSize = (cpuConfig.valueCacheGroupSize == 0 || valueS % cpuConfig.valueCacheGroupSize != 0)
- ? valueS
- : cpuConfig.valueCacheGroupSize;
- m_value_quant_param.precision = valueCachePrecision;
+ const bool is_turbo_key = cpuConfig.keyCacheQuantAlg == ov::internal::CacheQuantAlgorithm::TURBO;
+ const bool is_turbo_value = cpuConfig.valueCacheQuantAlg == ov::internal::CacheQuantAlgorithm::TURBO;
+ if (is_turbo_key || is_turbo_value) {
+ if (is_turbo_key) {
+ CPU_NODE_ASSERT(any_of(keyCachePrecision, ov::element::u3, ov::element::u4),
+ "TURBO key cache requires KEY_CACHE_PRECISION = u3 or u4, got ",
+ keyCachePrecision);
+ CPU_NODE_ASSERT(keyS % 64 == 0, "TurboQuant requires key head_dim divisible by 64, got ", keyS);
+ }
+ if (is_turbo_value) {
+ CPU_NODE_ASSERT(any_of(valueCachePrecision, ov::element::u3, ov::element::u4),
+ "TURBO value cache requires VALUE_CACHE_PRECISION = u3 or u4, got ",
+ valueCachePrecision);
+ CPU_NODE_ASSERT(valueS % 64 == 0, "TurboQuant requires value head_dim divisible by 64, got ", valueS);
+ }
+ if (is_turbo_key && is_turbo_value) {
+ CPU_NODE_ASSERT(keyS == valueS,
+ "TurboQuant requires same head_dim for key and value, got key=",
+ keyS,
+ " value=",
+ valueS);
+ }
+ } else {
+ for (auto prec : {keyCachePrecision, valueCachePrecision}) {
+ CPU_NODE_ASSERT(any_of(prec,
+ ov::element::dynamic,
+ ov::element::f32,
+ ov::element::f16,
+ ov::element::bf16,
+ ov::element::u8,
+ ov::element::u4),
+ "supports key/value cache precision f32, f16, bf16, u8, u4 but gets ",
+ prec);
+ }
+ }
+ m_key_spec.group_size = (cpuConfig.keyCacheGroupSize == 0 || keyS % cpuConfig.keyCacheGroupSize != 0)
+ ? keyS
+ : cpuConfig.keyCacheGroupSize;
+ m_key_spec.precision = keyCachePrecision;
+ m_value_spec.group_size = (cpuConfig.valueCacheGroupSize == 0 || valueS % cpuConfig.valueCacheGroupSize != 0)
+ ? valueS
+ : cpuConfig.valueCacheGroupSize;
+ m_value_spec.precision = valueCachePrecision;
if (const auto node = ov::as_type_ptr<const ov::op::v13::ScaledDotProductAttention>(op)) {
m_config.config.is_causal = node->get_causal();
@@ -1845,6 +1898,10 @@ ScaledDotProductAttention::ScaledDotProductAttention(const std::shared_ptr<ov::N
} else if (const auto node = ov::as_type_ptr<const SDPAWithTransposeReshape>(op)) {
m_config.config = node->get_config();
}
+
+ m_key_spec.alg = cpuConfig.keyCacheQuantAlg;
+ m_value_spec.alg = cpuConfig.valueCacheQuantAlg;
+ m_key_spec.by_channel = cpuConfig.keyCacheQuantMode == ov::intel_cpu::Config::CacheQuantMode::BY_CHANNEL;
}
void ScaledDotProductAttention::initSupportedPrimitiveDescriptors() {
@@ -1946,48 +2003,31 @@ void ScaledDotProductAttention::createPrimitive() {
const auto keyS = *(keyDims.end() - 1);
const auto valueS = *(valueDims.end() - 1);
- m_key_quant_param.groupSize = cpuConfig.keyCacheGroupSize ? cpuConfig.keyCacheGroupSize : keyS;
- m_key_quant_param.isByChannel = false;
+ m_key_spec.group_size = cpuConfig.keyCacheGroupSize ? cpuConfig.keyCacheGroupSize : keyS;
+ m_key_spec.by_channel = false;
if (cpuConfig.keyCacheQuantMode == ov::intel_cpu::Config::CacheQuantMode::BY_CHANNEL) {
- m_key_quant_param.isByChannel = true;
+ m_key_spec.by_channel = true;
} else if (cpuConfig.keyCacheQuantMode == ov::intel_cpu::Config::CacheQuantMode::BY_TOKEN) {
- m_key_quant_param.isByChannel = false;
+ m_key_spec.by_channel = false;
}
- m_value_quant_param.groupSize = cpuConfig.valueCacheGroupSize ? cpuConfig.valueCacheGroupSize : valueS;
- OPENVINO_ASSERT(keyS % m_key_quant_param.groupSize == 0,
+ m_value_spec.group_size = cpuConfig.valueCacheGroupSize ? cpuConfig.valueCacheGroupSize : valueS;
+ OPENVINO_ASSERT(keyS % m_key_spec.group_size == 0,
"ScaledDotProductAttention AttentionExecutor creation fails key state " + std::to_string(keyS) +
- " cannot be divided by group size " + std::to_string(m_key_quant_param.groupSize));
+ " cannot be divided by group size " + std::to_string(m_key_spec.group_size));
- OPENVINO_ASSERT(valueS % m_value_quant_param.groupSize == 0,
+ OPENVINO_ASSERT(valueS % m_value_spec.group_size == 0,
"ScaledDotProductAttention AttentionExecutor creation fails value state " + std::to_string(keyS) +
- " cannot be divided by group size " + std::to_string(m_key_quant_param.groupSize));
- // Compute cache codecs — fixed for model lifetime.
+ " cannot be divided by group size " + std::to_string(m_key_spec.group_size));
+
// For fuse_concat=true the cache is the internal state with quantization per config.
- // Without fuse_concat the cache is the raw K/V input — use the input precision directly,
- // since config.keyCachePrecision/valueCachePrecision only describe the internal state.
- auto codec_from_precision = [](ov::element::Type prec, bool by_channel) {
- using ov::Extensions::Cpu::CacheCodec;
- if (prec == ov::element::u8) {
- return by_channel ? CacheCodec::U8_BY_CHANNEL : CacheCodec::U8;
- }
- if (prec == ov::element::u4) {
- return CacheCodec::U4;
- }
- if (prec == ov::element::f16) {
- return CacheCodec::RAW_F16;
- }
- if (prec == ov::element::bf16) {
- return CacheCodec::RAW_BF16;
- }
- return CacheCodec::RAW_F32;
- };
- // For fuse_concat the cache state precision is decided by getKVCachePrecision(),
- // which downgrades the f16 hint to rtPrecision when rtPrecision == bf16. Using
- // m_*_quant_param.precision here would pick the raw cpuConfig hint (f16) and
- // mismatch the actual cache layout, decoding bf16 bytes as f16.
- const auto cache_precision = m_config.config.fuse_concat ? getKVCachePrecision() : rtPrecision;
- m_k_codec = codec_from_precision(cache_precision, m_key_quant_param.isByChannel);
- m_v_codec = codec_from_precision(cache_precision, false);
+ // Without fuse_concat the cache is the raw K/V input — use rtPrecision to decode it,
+ // since cpuConfig.{key,value}CachePrecision only describes the internal state.
+ if (m_key_spec.alg != ov::internal::CacheQuantAlgorithm::TURBO) {
+ m_key_spec.precision = m_config.config.fuse_concat ? getKeyCachePrecision() : rtPrecision;
+ }
+ if (m_value_spec.alg != ov::internal::CacheQuantAlgorithm::TURBO) {
+ m_value_spec.precision = m_config.config.fuse_concat ? getValueCachePrecision() : rtPrecision;
+ }
ScaledDotProductAttentionKey key = {rtPrecision};
@@ -1997,64 +2037,64 @@ void ScaledDotProductAttention::createPrimitive() {
if (rtPrecision == ov::element::bf16) {
if (ov::with_cpu_x86_bfloat16()) {
executor = std::make_shared<AttentionExecutor<KT_ONEDNN, ov::bfloat16>>(context,
- m_key_quant_param.groupSize,
- m_value_quant_param.groupSize,
- m_key_quant_param.isByChannel);
+ m_key_spec.group_size,
+ m_value_spec.group_size,
+ m_key_spec.by_channel);
} else {
executor = std::make_shared<AttentionExecutor<KT_REF, ov::bfloat16>>(context,
- m_key_quant_param.groupSize,
- m_value_quant_param.groupSize,
- m_key_quant_param.isByChannel);
+ m_key_spec.group_size,
+ m_value_spec.group_size,
+ m_key_spec.by_channel);
}
} else if (rtPrecision == ov::element::f16) {
if (with_cpu_x86_avx512_core_fp16()) {
executor = std::make_shared<AttentionExecutor<KT_ONEDNN, ov::float16>>(context,
- m_key_quant_param.groupSize,
- m_value_quant_param.groupSize,
- m_key_quant_param.isByChannel);
+ m_key_spec.group_size,
+ m_value_spec.group_size,
+ m_key_spec.by_channel);
} else {
executor = std::make_shared<AttentionExecutor<KT_REF, ov::float16>>(context,
- m_key_quant_param.groupSize,
- m_value_quant_param.groupSize,
- m_key_quant_param.isByChannel);
+ m_key_spec.group_size,
+ m_value_spec.group_size,
+ m_key_spec.by_channel);
}
} else {
# ifdef OV_CPU_WITH_MLAS
executor = std::make_shared<AttentionExecutor<KT_MLAS, float>>(context,
- m_key_quant_param.groupSize,
- m_value_quant_param.groupSize,
- m_key_quant_param.isByChannel);
+ m_key_spec.group_size,
+ m_value_spec.group_size,
+ m_key_spec.by_channel);
# else
if (with_cpu_x86_avx512_core()) {
executor = std::make_shared<AttentionExecutor<KT_ONEDNN, float>>(context,
- m_key_quant_param.groupSize,
- m_value_quant_param.groupSize,
- m_key_quant_param.isByChannel);
+ m_key_spec.group_size,
+ m_value_spec.group_size,
+ m_key_spec.by_channel);
} else {
executor = std::make_shared<AttentionExecutor<KT_REF, float>>(context,
- m_key_quant_param.groupSize,
- m_value_quant_param.groupSize,
- m_key_quant_param.isByChannel);
+ m_key_spec.group_size,
+ m_value_spec.group_size,
+ m_key_spec.by_channel);
}
# endif
}
#elif defined(OV_CPU_WITH_ACL)
if (rtPrecision == ov::element::f16) {
executor = std::make_shared<AttentionExecutor<KT_ACL, ov::float16>>(context,
- m_key_quant_param.groupSize,
- m_value_quant_param.groupSize,
- m_key_quant_param.isByChannel);
+ m_key_spec.group_size,
+ m_value_spec.group_size,
+ m_key_spec.by_channel);
} else {
executor = std::make_shared<AttentionExecutor<KT_ACL, float>>(context,
- m_key_quant_param.groupSize,
- m_value_quant_param.groupSize,
- m_key_quant_param.isByChannel);
+ m_key_spec.group_size,
+ m_value_spec.group_size,
+ m_key_spec.by_channel);
}
#else
executor = std::make_shared<AttentionExecutor<KT_REF, float>>(context,
- m_key_quant_param.groupSize,
- m_value_quant_param.groupSize,
- m_key_quant_param.isByChannel);
+ m_key_spec.group_size,
+ m_value_spec.group_size,
+ m_key_spec.by_channel);
#endif
getSelectedPrimitiveDescriptor()->setImplementationType(executor->implType());
return executor;
@@ -2064,6 +2104,29 @@ void ScaledDotProductAttention::createPrimitive() {
auto result = cache->getOrCreate(key, builder);
CPU_NODE_ASSERT(result.first, "AttentionExecutor creation fails with precision " + rtPrecision.to_string());
m_executor = result.first;
+
+ // Per-thread f32 workspace of one head_dim row — reused across codec stages:
+ if (m_key_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO ||
+ m_value_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO) {
+ const auto nthr = static_cast<size_t>(context->getCpuParallel()->get_num_worker_threads());
+ const auto k_head_dim = *(keyDims.end() - 1);
+ const auto v_head_dim = *(valueDims.end() - 1);
+ const auto head_dim = std::max(k_head_dim, v_head_dim);
+ const auto desc = std::make_shared<CpuBlockedMemoryDesc>(ov::element::f32, Shape{VectorDims{nthr, head_dim}});
+ m_per_thread_head_scratch = getScratchPadMem(desc);
+
+ // Precompute WHT sign vector once. Hot path reads m_wht_signs.
+ m_wht_signs.resize<float>({head_dim});
+ const auto* src = ov::Extensions::Cpu::turboq_get_wht_signs(static_cast<int>(head_dim));
+ std::copy(src, src + head_dim, m_wht_signs.ptr<float>());
+ }
+}
+
+ov::Extensions::Cpu::StridedData<float> ScaledDotProductAttention::get_per_thread_scratch() const {
+ if (!m_per_thread_head_scratch) {
+ return {nullptr, 0};
+ }
+ return {m_per_thread_head_scratch->getDataAs<float>(), m_per_thread_head_scratch->getStaticDims().back()};
}
void ScaledDotProductAttention::execute(const dnnl::stream& strm) {
@@ -2093,6 +2156,7 @@ void ScaledDotProductAttention::execute(const dnnl::stream& strm) {
presentk_input = inputs[1];
presentv_input = inputs[2];
}
+ auto [per_thread_head_scratch, per_thread_head_stride] = get_per_thread_scratch();
m_executor->execute(strm,
m_config,
inputs,
@@ -2102,8 +2166,13 @@ void ScaledDotProductAttention::execute(const dnnl::stream& strm) {
beam_input,
k_scale_zp,
v_scale_zp,
- m_k_codec,
- m_v_codec);
+ m_key_spec,
+ m_value_spec,
+ per_thread_head_scratch,
+ per_thread_head_stride,
+ m_k_quant_meta_data,
+ m_v_quant_meta_data,
+ m_wht_signs);
}
bool ScaledDotProductAttention::isSupportedOperation(const std::shared_ptr<const ov::Node>& op,
@@ -2205,7 +2274,7 @@ static std::shared_ptr<CpuBlockedMemoryDesc> make_kv_cache_desc(ov::element::Typ
}
// Per-channel groups along L; per-token groups along inner. L_total is (L0+L1)*2.
-static std::vector<size_t> compute_scale_zp_shape(const ScaledDotProductAttention::SDPAQuantParam& quant_param,
+static std::vector<size_t> compute_scale_zp_shape(const ov::Extensions::Cpu::CacheSpec& quant_param,
size_t hidden_states,
size_t B,
size_t H,
@@ -2213,11 +2282,11 @@ static std::vector<size_t> compute_scale_zp_shape(const ScaledDotProductAttentio
const std::vector<size_t>& order,
const std::vector<size_t>& real_order) {
std::vector<size_t> bhls;
- if (quant_param.isByChannel) {
- const size_t group_nums = div_up(L_total, quant_param.groupSize) * 2;
+ if (quant_param.by_channel) {
+ const size_t group_nums = div_up(L_total, quant_param.group_size) * 2;
bhls = {B, H, group_nums, hidden_states};
} else {
- bhls = {B, H, L_total, hidden_states / quant_param.groupSize * 2};
+ bhls = {B, H, L_total, hidden_states / quant_param.group_size * 2};
}
return permute_axes(bhls_to_model_shape(bhls, order), real_order);
}
@@ -2276,14 +2345,30 @@ void ScaledDotProductAttention::resetBeamTablePastkv(const MemoryPtr& mem_cur_k,
}
// 2. resize pastkv
- ov::element::Type kvcache_precision = m_k_state->internal_desc()->getPrecision();
+ const ov::element::Type k_kvcache_precision = m_k_state->internal_desc()->getPrecision();
+ const ov::element::Type v_kvcache_precision = m_v_state->internal_desc()->getPrecision();
+ const bool is_k_turboq = m_key_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO;
+ const bool is_v_turboq = m_value_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO;
+ const int k_bits = is_k_turboq ? static_cast<int>(m_key_spec.precision.bitwidth()) : 0;
+ const int v_bits = is_v_turboq ? static_cast<int>(m_value_spec.precision.bitwidth()) : 0;
+ const size_t S_cache = is_k_turboq ? ov::Extensions::Cpu::XARCH::turboq_head_bytes(static_cast<int>(S), k_bits) : S;
+ const size_t SV_cache =
+ is_v_turboq ? ov::Extensions::Cpu::XARCH::turboq_head_bytes(static_cast<int>(SV), v_bits) : SV;
+ // Save old meta-data before resize so we can beam-reorder+copy into the new buffer.
+ PlainTensor old_k_meta_data = m_k_quant_meta_data;
+ PlainTensor old_v_meta_data = m_v_quant_meta_data;
+ if (is_k_turboq) {
+ m_k_quant_meta_data = PlainTensor{};
+ m_k_quant_meta_data.resize<float>({B, H, L0 + L1, 1});
+ }
+ if (is_v_turboq) {
+ m_v_quant_meta_data = PlainTensor{};
+ m_v_quant_meta_data.resize<float>({B, H, L0 + L1, 1});
+ }
{
- // shape is the shape used by the original model which maybe different from BHLS, reverse here is to permute
- // BHLS to original model shape. BHLS is the stated input shape of SDPA, however internally we use LBHS for
- // KV-cache storage. real_order is used to permute the original shape to LBHS
- auto mem_desc_k = make_kv_cache_desc(kvcache_precision, B, H, (L0 + L1) * 2, S, order, real_order);
+ auto mem_desc_k = make_kv_cache_desc(k_kvcache_precision, B, H, (L0 + L1) * 2, S_cache, order, real_order);
auto new_internal_mem_k = std::make_shared<Memory>(getEngine(), mem_desc_k);
- auto mem_desc_v = make_kv_cache_desc(kvcache_precision, B, H, (L0 + L1) * 2, SV, order, real_order);
+ auto mem_desc_v = make_kv_cache_desc(v_kvcache_precision, B, H, (L0 + L1) * 2, SV_cache, order, real_order);
auto new_internal_mem_v = std::make_shared<Memory>(getEngine(), mem_desc_v);
PlainTensor new_pastk;
@@ -2301,67 +2386,90 @@ void ScaledDotProductAttention::resetBeamTablePastkv(const MemoryPtr& mem_cur_k,
old_past_v.reset(old_internal_mem_v);
old_past_k = old_past_k.permute(order);
old_past_v = old_past_v.permute(order);
- const size_t k_row_bytes = S * old_past_k.m_element_size / old_past_k.m_sub_byte_multiplier;
- const size_t v_row_bytes = SV * old_past_v.m_element_size / old_past_v.m_sub_byte_multiplier;
+ const size_t k_row_bytes =
+ is_k_turboq ? S_cache : S * old_past_k.m_element_size / old_past_k.m_sub_byte_multiplier;
+ const size_t v_row_bytes =
+ is_v_turboq ? SV_cache : SV * old_past_v.m_element_size / old_past_v.m_sub_byte_multiplier;
cpu_parallel->parallel_for3d(B, H, L0, [&](size_t b, size_t h, size_t m) {
auto idx = static_cast<size_t>(table[b]);
auto b_kv = static_cast<size_t>(old_beam_table_k.at<int32_t>({idx, m}));
memcpy(&new_pastk.at<char>({b, h, m}), &old_past_k.at<char>({b_kv, h, m}), k_row_bytes);
memcpy(&new_pastv.at<char>({b, h, m}), &old_past_v.at<char>({b_kv, h, m}), v_row_bytes);
+ if (is_k_turboq) {
+ *m_k_quant_meta_data.ptr<float>(b, h, m) = *old_k_meta_data.ptr<float>(b_kv, h, m);
+ }
+ if (is_v_turboq) {
+ *m_v_quant_meta_data.ptr<float>(b, h, m) = *old_v_meta_data.ptr<float>(b_kv, h, m);
+ }
});
}
- if (is_quantized_cache(kvcache_precision)) {
+ const bool need_k_szp = is_quantized_cache(k_kvcache_precision) && !is_k_turboq;
+ const bool need_v_szp = is_quantized_cache(v_kvcache_precision) && !is_v_turboq;
+ if (need_k_szp || need_v_szp) {
auto& old_scale_zp_k = m_k_state->get_scale_zp();
auto& old_scale_zp_v = m_v_state->get_scale_zp();
PlainTensor new_scale_zp_k;
PlainTensor new_scale_zp_v;
- new_scale_zp_k.resize<float>(
- compute_scale_zp_shape(m_key_quant_param, S, B, H, (L0 + L1) * 2, order, real_order));
- new_scale_zp_v.resize<float>(
- compute_scale_zp_shape(m_value_quant_param, SV, B, H, (L0 + L1) * 2, order, real_order));
+ if (need_k_szp) {
+ new_scale_zp_k.resize<float>(
+ compute_scale_zp_shape(m_key_spec, S, B, H, (L0 + L1) * 2, order, real_order));
+ }
+ if (need_v_szp) {
+ new_scale_zp_v.resize<float>(
+ compute_scale_zp_shape(m_value_spec, SV, B, H, (L0 + L1) * 2, order, real_order));
+ }
if (L0 > 0) {
- auto update_scales_zp =
- [&](const SDPAQuantParam& quant_param, PlainTensor& new_scale_zp, PlainTensor& old_scale_zp) {
- if (quant_param.isByChannel) {
- cpu_parallel->parallel_for2d(L0, B, [&](size_t m, size_t b) {
- auto idx = static_cast<size_t>(table[b]);
+ auto update_scales_zp = [&](const ov::Extensions::Cpu::CacheSpec& quant_param,
+ PlainTensor& new_scale_zp,
+ PlainTensor& old_scale_zp) {
+ if (quant_param.by_channel) {
+ cpu_parallel->parallel_for2d(L0, B, [&](size_t m, size_t b) {
+ auto idx = static_cast<size_t>(table[b]);
+ auto b_kv = static_cast<size_t>(old_beam_table_k.at<int32_t>({idx, m}));
+ size_t group_id = m / quant_param.group_size;
+ for (size_t h = 0; h < H; h++) {
+ // scale
+ memcpy(new_scale_zp.ptr<float>(group_id * 2, b, h, 0),
+ old_scale_zp.ptr<float>(group_id * 2, b_kv, h, 0),
+ sizeof(float) * old_scale_zp.m_dims[3]);
+ // zp
+ memcpy(new_scale_zp.ptr<float>(group_id * 2 + 1, b, h, 0),
+ old_scale_zp.ptr<float>(group_id * 2 + 1, b_kv, h, 0),
+ sizeof(float) * old_scale_zp.m_dims[3]);
+ }
+ });
+ } else {
+ cpu_parallel->parallel_for2d(L0, B, [&](size_t m, size_t b) {
+ auto idx = static_cast<size_t>(table[b]);
+ for (size_t h = 0; h < H; h++) {
auto b_kv = static_cast<size_t>(old_beam_table_k.at<int32_t>({idx, m}));
- size_t group_id = m / quant_param.groupSize;
- for (size_t h = 0; h < H; h++) {
- // scale
- memcpy(new_scale_zp.ptr<float>(group_id * 2, b, h, 0),
- old_scale_zp.ptr<float>(group_id * 2, b_kv, h, 0),
- sizeof(float) * old_scale_zp.m_dims[3]);
- // zp
- memcpy(new_scale_zp.ptr<float>(group_id * 2 + 1, b, h, 0),
- old_scale_zp.ptr<float>(group_id * 2 + 1, b_kv, h, 0),
- sizeof(float) * old_scale_zp.m_dims[3]);
- }
- });
- } else {
- cpu_parallel->parallel_for2d(L0, B, [&](size_t m, size_t b) {
- auto idx = static_cast<size_t>(table[b]);
- for (size_t h = 0; h < H; h++) {
- auto b_kv = static_cast<size_t>(old_beam_table_k.at<int32_t>({idx, m}));
- std::memcpy(new_scale_zp.ptr<float>(m, b, h, 0),
- old_scale_zp.ptr<float>(m, b_kv, h, 0),
- old_scale_zp.m_dims[3] * sizeof(float));
- }
- });
- }
- };
- update_scales_zp(m_key_quant_param, new_scale_zp_k, old_scale_zp_k);
- update_scales_zp(m_value_quant_param, new_scale_zp_v, old_scale_zp_v);
+ std::memcpy(new_scale_zp.ptr<float>(m, b, h, 0),
+ old_scale_zp.ptr<float>(m, b_kv, h, 0),
+ old_scale_zp.m_dims[3] * sizeof(float));
+ }
+ });
+ }
+ };
+ if (need_k_szp) {
+ update_scales_zp(m_key_spec, new_scale_zp_k, old_scale_zp_k);
+ }
+ if (need_v_szp) {
+ update_scales_zp(m_value_spec, new_scale_zp_v, old_scale_zp_v);
+ }
}
- m_k_state->set_scale_zp(new_scale_zp_k);
- m_v_state->set_scale_zp(new_scale_zp_v);
+ if (need_k_szp) {
+ m_k_state->set_scale_zp(new_scale_zp_k);
+ }
+ if (need_v_szp) {
+ m_v_state->set_scale_zp(new_scale_zp_v);
+ }
}
std::vector<size_t> new_shape = reverse({B, H, (L0 + L1), S});
// Get the shape of physical layout using real order
auto strides = mem_desc_k->getStrides();
- mem_desc_k = std::make_shared<CpuBlockedMemoryDesc>(kvcache_precision,
+ mem_desc_k = std::make_shared<CpuBlockedMemoryDesc>(k_kvcache_precision,
Shape(new_shape),
permute_axes(new_shape, real_order),
real_order,
@@ -2372,7 +2480,7 @@ void ScaledDotProductAttention::resetBeamTablePastkv(const MemoryPtr& mem_cur_k,
new_shape = reverse({B, H, (L0 + L1), SV});
// Get the shape of physical layout using real order
strides = mem_desc_v->getStrides();
- mem_desc_v = std::make_shared<CpuBlockedMemoryDesc>(kvcache_precision,
+ mem_desc_v = std::make_shared<CpuBlockedMemoryDesc>(v_kvcache_precision,
Shape(new_shape),
permute_axes(new_shape, real_order),
real_order,
@@ -2382,22 +2490,25 @@ void ScaledDotProductAttention::resetBeamTablePastkv(const MemoryPtr& mem_cur_k,
new_internal_mem_v->redefineDesc(mem_desc_v);
auto k_scale_zp = m_k_state->get_scale_zp();
auto v_scale_zp = m_v_state->get_scale_zp();
+ auto ws = get_per_thread_scratch();
compress_cache(cur_k,
new_pastk,
L0,
- kvcache_precision,
+ m_key_spec,
k_scale_zp,
- m_key_quant_param.groupSize,
- m_key_quant_param.isByChannel,
- cpu_parallel);
+ m_k_quant_meta_data,
+ cpu_parallel,
+ ws,
+ m_wht_signs);
compress_cache(cur_v,
new_pastv,
L0,
- kvcache_precision,
+ m_value_spec,
v_scale_zp,
- m_value_quant_param.groupSize,
- false,
- cpu_parallel);
+ m_v_quant_meta_data,
+ cpu_parallel,
+ ws,
+ m_wht_signs);
m_k_state->assign_internal_state(new_internal_mem_k);
m_v_state->assign_internal_state(new_internal_mem_v);
@@ -2582,7 +2693,7 @@ void ScaledDotProductAttention::updateBeamTable(const MemoryPtr& mem_beam_idx, s
no_reorder = false;
}
}
- OPENVINO_ASSERT(no_reorder || !m_key_quant_param.isByChannel,
+ OPENVINO_ASSERT(no_reorder || !m_key_spec.by_channel,
this->getName(),
" SDPA only support bychannel quantization with greedy search!");
// reorder
@@ -2646,18 +2757,46 @@ void ScaledDotProductAttention::updatePastkv(const MemoryPtr& mem_cur_k, const M
CPU_NODE_ASSERT(B == B_state, "pastkv batch: ", B, " is not equal to batch of state: ", B_state);
CPU_NODE_ASSERT(B * (L0 + L1) > 0, "B or (L0+L1) is zero, B: ", B, ", L0: ", L0, ", L1: ", L1);
// resize buffer
- ov::element::Type kvcache_precision = m_k_state->internal_desc()->getPrecision();
+ const ov::element::Type k_kvcache_precision = m_k_state->internal_desc()->getPrecision();
+ const ov::element::Type v_kvcache_precision = m_v_state->internal_desc()->getPrecision();
+ const bool is_k_turboq = m_key_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO;
+ const bool is_v_turboq = m_value_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO;
+ const int k_bits = is_k_turboq ? static_cast<int>(m_key_spec.precision.bitwidth()) : 0;
+ const int v_bits = is_v_turboq ? static_cast<int>(m_value_spec.precision.bitwidth()) : 0;
+ const size_t S_cache = is_k_turboq ? ov::Extensions::Cpu::XARCH::turboq_head_bytes(static_cast<int>(S), k_bits) : S;
+ const size_t SV_cache =
+ is_v_turboq ? ov::Extensions::Cpu::XARCH::turboq_head_bytes(static_cast<int>(SV), v_bits) : SV;
+ // Grow the norm buffer if needed; preserve old content for L0 tokens so subsequent
+ // decodes see the correct norms (this path grows in place, no beam reorder).
+ auto grow_meta_data = [&](PlainTensor& meta_data) {
+ if (meta_data && meta_data.size(2) >= L0 + L1) {
+ return;
+ }
+ PlainTensor old = meta_data;
+ meta_data = PlainTensor{};
+ meta_data.resize<float>({B, H, L0 + L1, 1});
+ if (old && L0 > 0 && !is_reset) {
+ for (size_t b = 0; b < B; ++b) {
+ for (size_t h = 0; h < H; ++h) {
+ std::memcpy(meta_data.ptr<float>(b, h, 0), old.ptr<float>(b, h, 0), sizeof(float) * L0);
+ }
+ }
+ }
+ };
+ if (is_k_turboq) {
+ grow_meta_data(m_k_quant_meta_data);
+ }
+ if (is_v_turboq) {
+ grow_meta_data(m_v_quant_meta_data);
+ }
bool need_redefine = true;
- if (B * H * (L0 + L1) * S > m_k_state->internal_state_max_size()) {
- // new_shape is the shape used by the original model which maybe different from BHLS, reverse here is to permute
- // BHLS to original model shape. BHLS is the stated input shape of SDPA, however internally we use LBHS for
- // KV-cache storage. real_order is used to permute the original shape to LBHS
- auto new_internal_mem_k =
- std::make_shared<Memory>(getEngine(),
- make_kv_cache_desc(kvcache_precision, B, H, (L0 + L1) * 2, S, order, real_order));
- auto new_internal_mem_v =
- std::make_shared<Memory>(getEngine(),
- make_kv_cache_desc(kvcache_precision, B, H, (L0 + L1) * 2, SV, order, real_order));
+ if (B * H * (L0 + L1) * S_cache > m_k_state->internal_state_max_size()) {
+ auto new_internal_mem_k = std::make_shared<Memory>(
+ getEngine(),
+ make_kv_cache_desc(k_kvcache_precision, B, H, (L0 + L1) * 2, S_cache, order, real_order));
+ auto new_internal_mem_v = std::make_shared<Memory>(
+ getEngine(),
+ make_kv_cache_desc(v_kvcache_precision, B, H, (L0 + L1) * 2, SV_cache, order, real_order));
PlainTensor new_pastk;
PlainTensor new_pastv;
@@ -2678,42 +2817,57 @@ void ScaledDotProductAttention::updatePastkv(const MemoryPtr& mem_cur_k, const M
past_v = new_pastv;
m_k_state->assign_internal_state(new_internal_mem_k);
m_v_state->assign_internal_state(new_internal_mem_v);
- m_k_state->assign_internal_state_max_size(2 * (L0 + L1) * B * H * S);
- m_v_state->assign_internal_state_max_size(2 * (L0 + L1) * B * H * SV);
- if (is_quantized_cache(kvcache_precision)) {
+ m_k_state->assign_internal_state_max_size(2 * (L0 + L1) * B * H * S_cache);
+ m_v_state->assign_internal_state_max_size(2 * (L0 + L1) * B * H * SV_cache);
+ const bool need_k_szp = is_quantized_cache(k_kvcache_precision) && !is_k_turboq;
+ const bool need_v_szp = is_quantized_cache(v_kvcache_precision) && !is_v_turboq;
+ if (need_k_szp || need_v_szp) {
auto& old_scale_zp_k = m_k_state->get_scale_zp();
auto& old_scale_zp_v = m_v_state->get_scale_zp();
PlainTensor new_scale_zp_k;
PlainTensor new_scale_zp_v;
- new_scale_zp_k.resize<float>(
- compute_scale_zp_shape(m_key_quant_param, S, B, H, (L0 + L1) * 2, order, real_order));
- new_scale_zp_v.resize<float>(
- compute_scale_zp_shape(m_value_quant_param, SV, B, H, (L0 + L1) * 2, order, real_order));
+ if (need_k_szp) {
+ new_scale_zp_k.resize<float>(
+ compute_scale_zp_shape(m_key_spec, S, B, H, (L0 + L1) * 2, order, real_order));
+ }
+ if (need_v_szp) {
+ new_scale_zp_v.resize<float>(
+ compute_scale_zp_shape(m_value_spec, SV, B, H, (L0 + L1) * 2, order, real_order));
+ }
if (L0 > 0 && !is_reset) {
- auto update_scales_zp =
- [&](const SDPAQuantParam& quant_param, PlainTensor& new_scale_zp, PlainTensor& old_scale_zp) {
- if (quant_param.isByChannel) {
- size_t group_nums = div_up(L0, quant_param.groupSize) * 2;
- cpu_parallel->parallel_for(group_nums, [&](size_t m) {
- memcpy(new_scale_zp.ptr<float>(m),
- old_scale_zp.ptr<float>(m),
- sizeof(float) * old_scale_zp.m_dims[1] * old_scale_zp.m_dims[2] *
- old_scale_zp.m_dims[3]);
- });
- } else {
- cpu_parallel->parallel_for(L0, [&](size_t m) {
- memcpy(new_scale_zp.ptr<float>(m),
- old_scale_zp.ptr<float>(m),
- sizeof(float) * old_scale_zp.m_dims[1] * old_scale_zp.m_dims[2] *
- old_scale_zp.m_dims[3]);
- });
- }
- };
- update_scales_zp(m_key_quant_param, new_scale_zp_k, old_scale_zp_k);
- update_scales_zp(m_value_quant_param, new_scale_zp_v, old_scale_zp_v);
+ auto update_scales_zp = [&](const ov::Extensions::Cpu::CacheSpec& quant_param,
+ PlainTensor& new_scale_zp,
+ PlainTensor& old_scale_zp) {
+ if (quant_param.by_channel) {
+ size_t group_nums = div_up(L0, quant_param.group_size) * 2;
+ cpu_parallel->parallel_for(group_nums, [&](size_t m) {
+ memcpy(new_scale_zp.ptr<float>(m),
+ old_scale_zp.ptr<float>(m),
+ sizeof(float) * old_scale_zp.m_dims[1] * old_scale_zp.m_dims[2] *
+ old_scale_zp.m_dims[3]);
+ });
+ } else {
+ cpu_parallel->parallel_for(L0, [&](size_t m) {
+ memcpy(new_scale_zp.ptr<float>(m),
+ old_scale_zp.ptr<float>(m),
+ sizeof(float) * old_scale_zp.m_dims[1] * old_scale_zp.m_dims[2] *
+ old_scale_zp.m_dims[3]);
+ });
+ }
+ };
+ if (need_k_szp) {
+ update_scales_zp(m_key_spec, new_scale_zp_k, old_scale_zp_k);
+ }
+ if (need_v_szp) {
+ update_scales_zp(m_value_spec, new_scale_zp_v, old_scale_zp_v);
+ }
+ }
+ if (need_k_szp) {
+ m_k_state->set_scale_zp(new_scale_zp_k);
+ }
+ if (need_v_szp) {
+ m_v_state->set_scale_zp(new_scale_zp_v);
}
- m_k_state->set_scale_zp(new_scale_zp_k);
- m_v_state->set_scale_zp(new_scale_zp_v);
}
} else if (is_reset) {
// when reset and not resize, just reset the desc
@@ -2721,7 +2875,7 @@ void ScaledDotProductAttention::updatePastkv(const MemoryPtr& mem_cur_k, const M
// new_shape is the shape used by the original model which maybe different from BHLS, reverse here is to permute
// BHLS to original model shape. BHLS is the stated input shape of SDPA, however internally we use LBHS for
// KV-cache storage. real_order is used to permute the original shape to LBHS
- auto reset_desc = [&](size_t new_S) {
+ auto reset_desc = [&](ov::element::Type prec, size_t new_S) {
std::vector<size_t> new_shape = reverse({B, H, (L0 + L1), new_S});
VectorDims strides(new_shape.size(), 1);
auto real_shape = permute_axes(new_shape, real_order);
@@ -2729,7 +2883,7 @@ void ScaledDotProductAttention::updatePastkv(const MemoryPtr& mem_cur_k, const M
strides[real_shape.size() - i] =
strides[real_shape.size() - (i - 1)] * real_shape[real_shape.size() - (i - 1)];
}
- return std::make_shared<CpuBlockedMemoryDesc>(kvcache_precision,
+ return std::make_shared<CpuBlockedMemoryDesc>(prec,
Shape(new_shape),
real_shape,
real_order,
@@ -2737,31 +2891,29 @@ void ScaledDotProductAttention::updatePastkv(const MemoryPtr& mem_cur_k, const M
VectorDims{},
strides);
};
- internal_mem_k->redefineDesc(reset_desc(S));
- internal_mem_v->redefineDesc(reset_desc(SV));
- if (is_quantized_cache(kvcache_precision)) {
+ internal_mem_k->redefineDesc(reset_desc(k_kvcache_precision, S_cache));
+ internal_mem_v->redefineDesc(reset_desc(v_kvcache_precision, SV_cache));
+ if ((is_quantized_cache(k_kvcache_precision) || is_quantized_cache(v_kvcache_precision)) && !is_k_turboq &&
+ !is_v_turboq) {
auto& old_scale_zp_k = m_k_state->get_scale_zp();
auto& old_scale_zp_v = m_v_state->get_scale_zp();
// only dim0, dim1 need change
// LBHS
- old_scale_zp_k.m_strides[0] =
- m_key_quant_param.isByChannel ? H * B * S : H * B * S / m_key_quant_param.groupSize * 2;
- old_scale_zp_k.m_strides[1] =
- m_key_quant_param.isByChannel ? H * S : H * S / m_key_quant_param.groupSize * 2;
+ old_scale_zp_k.m_strides[0] = m_key_spec.by_channel ? H * B * S : H * B * S / m_key_spec.group_size * 2;
+ old_scale_zp_k.m_strides[1] = m_key_spec.by_channel ? H * S : H * S / m_key_spec.group_size * 2;
old_scale_zp_v.m_strides[0] =
- m_value_quant_param.isByChannel ? H * B * SV : H * B * SV / m_value_quant_param.groupSize * 2;
- old_scale_zp_v.m_strides[1] =
- m_value_quant_param.isByChannel ? H * SV : H * SV / m_value_quant_param.groupSize * 2;
+ m_value_spec.by_channel ? H * B * SV : H * B * SV / m_value_spec.group_size * 2;
+ old_scale_zp_v.m_strides[1] = m_value_spec.by_channel ? H * SV : H * SV / m_value_spec.group_size * 2;
}
}
if (need_redefine) {
// new_shape is the shape used by the original model which maybe different from BHLS, reverse here is to permute
// BHLS to original model shape. BHLS is the stated input shape of SDPA, however internally we use LBHS for
// KV-cache storage. real_order is used to permute the original shape to LBHS
- auto redefine_desc = [&](MemoryPtr& mem, size_t new_S) {
+ auto redefine_desc = [&](ov::element::Type prec, MemoryPtr& mem, size_t new_S) {
std::vector<size_t> new_shape = reverse({B, H, (L0 + L1), new_S});
auto real_shape = permute_axes(new_shape, real_order);
- return std::make_shared<CpuBlockedMemoryDesc>(kvcache_precision,
+ return std::make_shared<CpuBlockedMemoryDesc>(prec,
Shape(new_shape),
real_shape,
real_order,
@@ -2769,8 +2921,8 @@ void ScaledDotProductAttention::updatePastkv(const MemoryPtr& mem_cur_k, const M
VectorDims{},
mem->getDescWithType<BlockedMemoryDesc>()->getStrides());
};
- internal_mem_k->redefineDesc(redefine_desc(internal_mem_k, S));
- internal_mem_v->redefineDesc(redefine_desc(internal_mem_v, SV));
+ internal_mem_k->redefineDesc(redefine_desc(k_kvcache_precision, internal_mem_k, S_cache));
+ internal_mem_v->redefineDesc(redefine_desc(v_kvcache_precision, internal_mem_v, SV_cache));
}
if (!past_k) {
@@ -2795,74 +2947,71 @@ void ScaledDotProductAttention::updatePastkv(const MemoryPtr& mem_cur_k, const M
// L0 is set to 0 here because past_kv is reset by set_state API, re-initializing
auto k_scale_zp = m_k_state->get_scale_zp();
auto v_scale_zp = m_v_state->get_scale_zp();
+ auto ws0 = get_per_thread_scratch();
compress_cache(init_k,
past_k,
0,
- kvcache_precision,
+ m_key_spec,
k_scale_zp,
- m_key_quant_param.groupSize,
- m_key_quant_param.isByChannel,
- cpu_parallel);
+ m_k_quant_meta_data,
+ cpu_parallel,
+ ws0,
+ m_wht_signs);
compress_cache(init_v,
past_v,
0,
- kvcache_precision,
+ m_value_spec,
v_scale_zp,
- m_value_quant_param.groupSize,
- false,
- cpu_parallel);
+ m_v_quant_meta_data,
+ cpu_parallel,
+ ws0,
+ m_wht_signs);
}
}
auto k_scale_zp = m_k_state->get_scale_zp();
auto v_scale_zp = m_v_state->get_scale_zp();
- compress_cache(cur_k,
- past_k,
- L0,
- kvcache_precision,
- k_scale_zp,
- m_key_quant_param.groupSize,
- m_key_quant_param.isByChannel,
- cpu_parallel);
- compress_cache(cur_v,
- past_v,
- L0,
- kvcache_precision,
- v_scale_zp,
- m_value_quant_param.groupSize,
- false,
- cpu_parallel);
+ auto ws = get_per_thread_scratch();
+ compress_cache(cur_k, past_k, L0, m_key_spec, k_scale_zp, m_k_quant_meta_data, cpu_parallel, ws, m_wht_signs);
+ compress_cache(cur_v, past_v, L0, m_value_spec, v_scale_zp, m_v_quant_meta_data, cpu_parallel, ws, m_wht_signs);
}
-ov::element::Type ScaledDotProductAttention::getKVCachePrecision() {
- ov::element::Type kvcache_precision;
- // TODO: SDPA only supports same key/value cache precision.
- auto rtPrecision = getRuntimePrecision();
- auto keyCachePrecisionHint = context->getConfig().keyCachePrecision;
- auto valueCachePrecisionHint = context->getConfig().valueCachePrecision;
- bool enableKVCacheFP16 = m_config.config.fuse_concat && mayiuse(cpu_isa_t::avx2) &&
- rtPrecision != ov::element::bf16 &&
- (all_of(ov::element::f16, keyCachePrecisionHint, valueCachePrecisionHint));
- kvcache_precision = enableKVCacheFP16 ? ov::element::f16 : rtPrecision;
- bool use_int8_kv_cache = (all_of(ov::element::u8, keyCachePrecisionHint, valueCachePrecisionHint));
- bool use_u4_kv_cache = (all_of(ov::element::u4, keyCachePrecisionHint, valueCachePrecisionHint));
- if (use_int8_kv_cache) {
- kvcache_precision = ov::element::u8;
- } else if (use_u4_kv_cache) {
- kvcache_precision = ov::element::u4;
- } else {
- kvcache_precision = enableKVCacheFP16 ? ov::element::f16 : rtPrecision;
+static ov::element::Type side_cache_precision(bool is_turbo,
+ ov::element::Type side_hint,
+ ov::element::Type rtPrecision,
+ bool enableKVCacheFP16) {
+ if (is_turbo) {
+ // TBQ packed bytes live in a u8 buffer.
+ return ov::element::u8;
}
-
- return kvcache_precision;
+ if (side_hint == ov::element::u8 || side_hint == ov::element::u4 || side_hint == ov::element::f16) {
+ return side_hint == ov::element::f16 && !enableKVCacheFP16 ? rtPrecision : side_hint;
+ }
+ return enableKVCacheFP16 ? ov::element::f16 : rtPrecision;
}
-const ScaledDotProductAttention::SDPAQuantParam& ScaledDotProductAttention::getKeyQuantParam() {
- return m_key_quant_param;
+ov::element::Type ScaledDotProductAttention::getKeyCachePrecision() {
+ const auto rtPrecision = getRuntimePrecision();
+ const auto keyHint = context->getConfig().keyCachePrecision;
+ const auto valueHint = context->getConfig().valueCachePrecision;
+ const bool enableKVCacheFP16 = m_config.config.fuse_concat && mayiuse(cpu_isa_t::avx2) &&
+ rtPrecision != ov::element::bf16 && all_of(ov::element::f16, keyHint, valueHint);
+ return side_cache_precision(m_key_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO,
+ keyHint,
+ rtPrecision,
+ enableKVCacheFP16);
}
-const ScaledDotProductAttention::SDPAQuantParam& ScaledDotProductAttention::getValueQuantParam() {
- return m_value_quant_param;
+ov::element::Type ScaledDotProductAttention::getValueCachePrecision() {
+ const auto rtPrecision = getRuntimePrecision();
+ const auto keyHint = context->getConfig().keyCachePrecision;
+ const auto valueHint = context->getConfig().valueCachePrecision;
+ const bool enableKVCacheFP16 = m_config.config.fuse_concat && mayiuse(cpu_isa_t::avx2) &&
+ rtPrecision != ov::element::bf16 && all_of(ov::element::f16, keyHint, valueHint);
+ return side_cache_precision(m_value_spec.alg == ov::internal::CacheQuantAlgorithm::TURBO,
+ valueHint,
+ rtPrecision,
+ enableKVCacheFP16);
}
ov::element::Type ScaledDotProductAttention::getRuntimePrecision() const {
diff --git a/src/plugins/intel_cpu/src/nodes/scaled_attn.h b/src/plugins/intel_cpu/src/nodes/scaled_attn.h
index d5acf14c9d1..a5f084047da 100644
--- a/src/plugins/intel_cpu/src/nodes/scaled_attn.h
+++ b/src/plugins/intel_cpu/src/nodes/scaled_attn.h
@@ -13,7 +13,9 @@
#include "cpu_memory.h"
#include "cpu_types.h"
#include "graph_context.h"
-#include "kernels/scaled_attn/codecs/cache_codec.hpp"
+#include "kernels/scaled_attn/cache_spec.hpp"
+#include "kernels/scaled_attn/codecs/codec_kernels.hpp"
+#include "kernels/scaled_attn/mha_kv_cache_codec.hpp"
#include "memory_state.h"
#include "node.h"
#include "onednn/iml_type_mapper.h"
@@ -65,14 +67,18 @@ public:
}
return real_order;
}
- struct SDPAQuantParam {
- ov::element::Type precision = ov::element::dynamic;
- size_t groupSize = 0;
- bool isByChannel = false;
- };
- ov::element::Type getKVCachePrecision();
- const SDPAQuantParam& getKeyQuantParam();
- const SDPAQuantParam& getValueQuantParam();
+ ov::element::Type getKeyCachePrecision();
+ ov::element::Type getValueCachePrecision();
+ // Legacy: returns key-side precision. Kept for graph_dumper serialization.
+ ov::element::Type getKVCachePrecision() {
+ return getKeyCachePrecision();
+ }
+ const ov::Extensions::Cpu::CacheSpec& getKeySpec() const {
+ return m_key_spec;
+ }
+ const ov::Extensions::Cpu::CacheSpec& getValueSpec() const {
+ return m_value_spec;
+ }
private:
void gatherConcatPastkv(const MemoryPtr& mem_cur_k, const MemoryPtr& mem_cur_v, const MemoryPtr& mem_beam_idx);
@@ -80,6 +86,9 @@ private:
void updatePastkv(const MemoryPtr& mem_cur_k, const MemoryPtr& mem_cur_v);
ov::element::Type getRuntimePrecision() const override;
void resetBeamTablePastkv(const MemoryPtr& mem_cur_k, const MemoryPtr& mem_cur_v, const MemoryPtr& mem_beam_idx);
+ // Derive per-thread scratch {base, stride} (f32 slots) from m_per_thread_head_scratch.
+ // Indexed as ws[tid] to get per-thread buffer start. {nullptr, 0} when non-codec.
+ ov::Extensions::Cpu::StridedData<float> get_per_thread_scratch() const;
struct Config {
ScaledDotProductAttentionWithKVCache::Config config;
@@ -95,8 +104,13 @@ private:
MemoryPtr beam_input,
const PlainTensor& k_scale_zp,
const PlainTensor& v_scale_zp,
- ov::Extensions::Cpu::CacheCodec k_codec,
- ov::Extensions::Cpu::CacheCodec v_codec) = 0;
+ const ov::Extensions::Cpu::CacheSpec& k_spec,
+ const ov::Extensions::Cpu::CacheSpec& v_spec,
+ float* per_thread_head_scratch,
+ size_t per_thread_head_stride,
+ const PlainTensor& k_quant_meta_data,
+ const PlainTensor& v_quant_meta_data,
+ const PlainTensor& wht_signs) = 0;
[[nodiscard]] virtual impl_desc_type implType() const = 0;
virtual ~Executor() = default;
};
@@ -113,10 +127,14 @@ private:
// (0, 1, 2, 3) for BHLS
// (2, 0, 1, 3) for LBHS
std::vector<size_t> m_kvstate_layout = {2, 0, 1, 3};
- SDPAQuantParam m_key_quant_param;
- SDPAQuantParam m_value_quant_param;
- ov::Extensions::Cpu::CacheCodec m_k_codec{};
- ov::Extensions::Cpu::CacheCodec m_v_codec{};
+ ov::Extensions::Cpu::CacheSpec m_key_spec;
+ ov::Extensions::Cpu::CacheSpec m_value_spec;
+ MemoryPtr m_per_thread_head_scratch;
+ // Per-token TBQ norm. Populated only when a side has alg=TURBO; empty otherwise.
+ PlainTensor m_k_quant_meta_data;
+ PlainTensor m_v_quant_meta_data;
+ // Random ±1 sign vector for WHT rotation.
+ PlainTensor m_wht_signs;
};
} // namespace ov::intel_cpu::node
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/arm/concat_sdp.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/arm/concat_sdp.cpp
index a0178a8e586..b6a392a796d 100644
--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/arm/concat_sdp.cpp
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/arm/concat_sdp.cpp
@@ -1,66 +1,46 @@
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
-#include "openvino/pass/manager.hpp"
-#include "transformations/op_conversions/scaled_dot_product_attention_decomposition.hpp"
-
#include "custom/subgraph_tests/src/classes/concat_sdp.hpp"
-#include "shared_test_classes/base/ov_subgraph.hpp"
-#include "utils/cpu_test_utils.hpp"
-#include "common_test_utils/ov_tensor_utils.hpp"
-
-using namespace CPUTestUtils;
namespace ov {
namespace test {
-
namespace {
+
const std::vector<std::vector<InputShape>> inputShapes = {
// greedy search
{
- // B, H, L1, S
{{1, 8, -1, 64}, {{1, 8, 10, 64}, {1, 8, 1, 64}, {1, 8, 1, 64}, {1, 8, 20, 64}, {1, 8, 1, 64}}},
- // B, H, L0, S
{{1, 8, -1, 64}, {{1, 8, 0, 64}, {1, 8, 10, 64}, {1, 8, 11, 64}, {1, 8, 12, 64}, {1, 8, 32, 64}}},
},
// beam search
{
- // B, H, L1, S
{{-1, 8, -1, 64}, {{4, 8, 10, 64}, {4, 8, 1, 64}, {4, 8, 1, 64}, {4, 8, 1, 64}, {4, 8, 1, 64}}},
- // B, H, L0, S
{{-1, 8, -1, 64}, {{4, 8, 0, 64}, {4, 8, 10, 64}, {4, 8, 11, 64}, {4, 8, 12, 64}, {4, 8, 13, 64}}},
},
- // big batch to check cvt_copy fast-path inside mha_single_token_kernel
+ // big batch
{
- // B, H, L1, S
{{-1, 8, -1, 64}, {{129, 8, 10, 64}, {129, 8, 1, 64}, {129, 8, 1, 64}, {129, 8, 1, 64}, {129, 8, 1, 64}}},
- // B, H, L0, S
{{-1, 8, -1, 64}, {{129, 8, 0, 64}, {129, 8, 10, 64}, {129, 8, 11, 64}, {129, 8, 12, 64}, {129, 8, 13, 64}}},
},
};
-// @todo claude: enable asymmetric K/V cache precision combinations in a separate PR;
-// for now restrict to symmetric pairs so the SDPA assertion at scaled_attn.cpp:1823 holds.
+const ov::AnyMap cfg_none{};
+const ov::AnyMap cfg_u8_sym{
+ {"KEY_CACHE_PRECISION", "u8"},
+ {"VALUE_CACHE_PRECISION", "u8"},
+};
+
INSTANTIATE_TEST_SUITE_P(smoke_ConcatSDPTest,
- ConcatSDPTest,
- ::testing::Combine(::testing::Values(ElementType::f16),
- ::testing::ValuesIn(inputShapes),
- ::testing::Values("none"),
- ::testing::Values("none"),
- ::testing::Values(true, false),
- ::testing::Values(true, false)),
- ConcatSDPTest::getTestCaseName);
+ ConcatSDPTest,
+ ::testing::Combine(::testing::Values(ElementType::f16),
+ ::testing::ValuesIn(inputShapes),
+ ::testing::Values(cfg_none, cfg_u8_sym),
+ ::testing::Values(true, false),
+ ::testing::Values<int64_t>(8),
+ ::testing::Values<int64_t>(8)),
+ ConcatSDPTest::getTestCaseName);
-INSTANTIATE_TEST_SUITE_P(smoke_ConcatSDPTest_U8,
- ConcatSDPTest,
- ::testing::Combine(::testing::Values(ElementType::f16),
- ::testing::ValuesIn(inputShapes),
- ::testing::Values("u8"),
- ::testing::Values("u8"),
- ::testing::Values(true, false),
- ::testing::Values(true, false)),
- ConcatSDPTest::getTestCaseName);
} // namespace
-
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.cpp
index b76b3a2890f..fa4c49d741f 100644
--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.cpp
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.cpp
@@ -2,13 +2,23 @@
// SPDX-License-Identifier: Apache-2.0
//
#include "concat_sdp.hpp"
-#include "openvino/opsets/opset13_decl.hpp"
+
+#include "common_test_utils/ov_tensor_utils.hpp"
#include "openvino/op/add.hpp"
+#include "openvino/op/broadcast.hpp"
#include "openvino/op/concat.hpp"
+#include "openvino/op/constant.hpp"
#include "openvino/op/gather.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/read_value.hpp"
+#include "openvino/op/reshape.hpp"
+#include "openvino/op/scaled_dot_product_attention.hpp"
#include "openvino/op/shape_of.hpp"
-
-using namespace CPUTestUtils;
+#include "openvino/op/sink.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/pass/manager.hpp"
+#include "openvino/runtime/system_conf.hpp"
+#include "transformations/op_conversions/scaled_dot_product_attention_decomposition.hpp"
namespace ov {
namespace test {
@@ -31,7 +41,7 @@ namespace test {
* Result
*/
std::string ConcatSDPTest::getTestCaseName(const testing::TestParamInfo<ConcatSDPTestParams>& obj) {
- const auto& [inType, inputShapes, kCachePrec, vCachePrec, hasShapeOf, isDiffKVHeadSize] = obj.param;
+ const auto& [inType, inputShapes, cacheCfg, hasShapeOf, headNumQ, headNumKV] = obj.param;
std::ostringstream result;
result << "IS=";
for (const auto& shape : inputShapes) {
@@ -40,78 +50,101 @@ std::string ConcatSDPTest::getTestCaseName(const testing::TestParamInfo<ConcatSD
result << "TS=";
for (const auto& shape : inputShapes) {
result << "(";
- if (!shape.second.empty()) {
- for (const auto& itr : shape.second) {
- result << ov::test::utils::vec2str(itr);
- }
+ for (const auto& itr : shape.second) {
+ result << ov::test::utils::vec2str(itr);
}
result << ")_";
}
result << "Prc=" << inType << "_";
- result << "Kprec=" << kCachePrec << "_";
- result << "Vprec=" << vCachePrec << "_";
- result << "HasShapeOf=" << hasShapeOf << "_";
- result << "IsDiffKVHeadSize=" << isDiffKVHeadSize;
+ result << "Cfg=";
+ if (cacheCfg.empty()) {
+ result << "NONE";
+ } else {
+ for (const auto& [k, v] : cacheCfg) {
+ result << k << "=" << v.as<std::string>() << "/";
+ }
+ }
+ result << "_HasShapeOf=" << hasShapeOf;
+ result << "_Hq=" << headNumQ << "_Hkv=" << headNumKV;
return result.str();
}
void ConcatSDPTest::SetUp() {
- const auto& [inType, inputShapes, kCachePrec, vCachePrec, hasShapeOf, isDiffKVHeadSize] = this->GetParam();
- m_kCachePrec = kCachePrec;
- m_vCachePrec = vCachePrec;
+ const auto& [inType, inputShapes, cacheCfg, hasShapeOf, headNumQ, headNumKV] = this->GetParam();
+ m_cacheCfg = cacheCfg;
m_hasShapeOf = hasShapeOf;
- m_isDiffKVHeadSize = isDiffKVHeadSize;
- targetDevice = ov::test::utils::DEVICE_CPU;
- rel_threshold = 1e-2f;
- if (inType == ElementType::bf16 || inType == ElementType::f16) {
- configuration.insert({"INFERENCE_PRECISION_HINT", ov::element::Type(inType).get_type_name()});
- rel_threshold = 0.01f;
- }
+ m_headNumQ = headNumQ;
+ m_headNumKV = headNumKV;
+ OPENVINO_ASSERT(m_headNumQ % m_headNumKV == 0, "head_num_q must be divisible by head_num_kv");
- if (m_kCachePrec != "none") {
- configuration["KEY_CACHE_PRECISION"] = m_kCachePrec;
+ if (inType == ElementType::bf16 && !ov::with_cpu_x86_bfloat16()) {
+ GTEST_SKIP() << "Host has no native bf16 support.";
+ }
+ if (inType == ElementType::f16 && !ov::with_cpu_x86_avx512_core_fp16()) {
+ GTEST_SKIP() << "Host has no native f16 support.";
}
- if (m_vCachePrec != "none") {
- configuration["VALUE_CACHE_PRECISION"] = m_vCachePrec;
+
+ targetDevice = ov::test::utils::DEVICE_CPU;
+ configuration["INFERENCE_PRECISION_HINT"] = ov::element::Type(inType).get_type_name();
+ for (const auto& kv : m_cacheCfg) {
+ configuration[kv.first] = kv.second;
}
- // Wider tolerance for quantized cache (u4 has only 16 levels).
- if (m_kCachePrec == "u4" || m_vCachePrec == "u4") {
- abs_threshold = 0.3f;
+
+ // Reference: CPU plugin with codec keys stripped — same reduction order, isolates
+ // codec/quant noise. Loose abs for quant codecs covers near-zero values where rel
+ // explodes; tbq bias grows with accumulated state across iters.
+ auto has_value = [&](const std::string& key, const std::string& needle) {
+ auto it = m_cacheCfg.find(key);
+ return it != m_cacheCfg.end() && it->second.as<std::string>() == needle;
+ };
+ const bool is_u4 = has_value("KEY_CACHE_PRECISION", "u4") || has_value("VALUE_CACHE_PRECISION", "u4");
+ const bool is_u8 = has_value("KEY_CACHE_PRECISION", "u8") || has_value("VALUE_CACHE_PRECISION", "u8");
+ const bool is_tbq = has_value("KEY_CACHE_QUANT_ALG", "TURBO") ||
+ has_value("VALUE_CACHE_QUANT_ALG", "TURBO");
+ rel_threshold = 1e-2F;
+ abs_threshold = 1e-3F;
+ if (is_u4 && is_tbq) {
+ abs_threshold = 0.1F;
+ } else if (is_u4) {
+ abs_threshold = 0.08F;
+ } else if (is_tbq) {
+ abs_threshold = 0.09F;
+ } else if (is_u8) {
+ abs_threshold = 0.02F;
}
init_input_shapes(inputShapes);
+
+ auto q_ps = inputDynamicShapes[0];
+ auto kv_ps = q_ps;
+ kv_ps[1] = m_headNumKV;
+ auto past_ps = inputDynamicShapes[1];
+ past_ps[1] = m_headNumKV;
+
ov::ParameterVector inputParams;
- // q,k,v
- inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, inputDynamicShapes[0]));
- inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, inputDynamicShapes[0]));
- auto v_ps = inputDynamicShapes[0];
- if (m_isDiffKVHeadSize) {
- v_ps[3] += m_diffKVHeadSize;
- }
- inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, v_ps));
+ inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, q_ps));
+ inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, kv_ps));
+ inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, kv_ps));
inputParams[0]->set_friendly_name("q");
inputParams[1]->set_friendly_name("k");
inputParams[2]->set_friendly_name("v");
- // pastkv init_cost
- inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, inputDynamicShapes[1]));
- auto var_k = std::make_shared<ov::op::util::Variable>(
- ov::op::util::VariableInfo{inputDynamicShapes[1], inType, "pastk"});
+ inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, past_ps));
+ auto var_k = std::make_shared<ov::op::util::Variable>(ov::op::util::VariableInfo{past_ps, inType, "pastk"});
auto pastk = std::make_shared<ov::op::v6::ReadValue>(inputParams[3], var_k);
pastk->set_friendly_name("pastk_r");
- // pastv init_cost
- auto v_init_ps = inputDynamicShapes[1];
- if (m_isDiffKVHeadSize) {
- v_init_ps[3] += m_diffKVHeadSize;
- }
- inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, v_init_ps));
- auto var_v = std::make_shared<ov::op::util::Variable>(
- ov::op::util::VariableInfo{v_init_ps, inType, "pastv"});
+ inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, past_ps));
+ auto var_v = std::make_shared<ov::op::util::Variable>(ov::op::util::VariableInfo{past_ps, inType, "pastv"});
auto pastv = std::make_shared<ov::op::v6::ReadValue>(inputParams[4], var_v);
pastv->set_friendly_name("pastv_r");
+
auto beam_idx = std::make_shared<ov::op::v0::Parameter>(ElementType::i32, ov::PartialShape{-1});
beam_idx->set_friendly_name("beam_idx");
inputParams.push_back(beam_idx);
- auto gatherK = std::make_shared<ov::op::v8::Gather>(pastk, beam_idx, op::v0::Constant::create(ElementType::i32, {}, {0}));
- auto gatherV = std::make_shared<ov::op::v8::Gather>(pastv, beam_idx, op::v0::Constant::create(ElementType::i32, {}, {0}));
+
+ auto gatherK = std::make_shared<ov::op::v8::Gather>(
+ pastk, beam_idx, ov::op::v0::Constant::create(ElementType::i32, {}, {0}));
+ auto gatherV = std::make_shared<ov::op::v8::Gather>(
+ pastv, beam_idx, ov::op::v0::Constant::create(ElementType::i32, {}, {0}));
+
std::shared_ptr<Node> shapeof_k, shapeof_v;
// test special case:
// ReadValue->Gather->Concat->SDPA...
@@ -124,11 +157,37 @@ void ConcatSDPTest::SetUp() {
}
auto concatK = std::make_shared<ov::op::v0::Concat>(OutputVector{gatherK, inputParams[1]}, 2);
auto concatV = std::make_shared<ov::op::v0::Concat>(OutputVector{gatherV, inputParams[2]}, 2);
- auto sdp = std::make_shared<ov::opset13::ScaledDotProductAttention>(inputParams[0], concatK, concatV, false);
+
+ std::shared_ptr<ov::Node> k_for_sdp = concatK;
+ std::shared_ptr<ov::Node> v_for_sdp = concatV;
+ if (m_headNumQ != m_headNumKV) {
+ const auto group_size = static_cast<int32_t>(m_headNumQ / m_headNumKV);
+ const auto Hq = static_cast<int32_t>(m_headNumQ);
+ const auto head_size = static_cast<int32_t>(q_ps[3].get_length());
+ auto make_gqa_broadcast = [&](const std::shared_ptr<ov::Node>& node) {
+ auto unsqueezed = std::make_shared<ov::op::v0::Unsqueeze>(
+ node, ov::op::v0::Constant::create(ov::element::i32, {}, {2}));
+ auto broadcasted = std::make_shared<ov::op::v3::Broadcast>(
+ unsqueezed,
+ ov::op::v0::Constant::create(ov::element::i32, {5},
+ std::vector<int32_t>{1, 1, group_size, 1, 1}),
+ ov::op::BroadcastType::BIDIRECTIONAL);
+ return std::make_shared<ov::op::v1::Reshape>(
+ broadcasted,
+ ov::op::v0::Constant::create(ov::element::i32, {4},
+ std::vector<int32_t>{0, Hq, -1, head_size}),
+ true);
+ };
+ k_for_sdp = make_gqa_broadcast(concatK);
+ v_for_sdp = make_gqa_broadcast(concatV);
+ }
+
+ auto sdp = std::make_shared<ov::op::v13::ScaledDotProductAttention>(
+ inputParams[0], k_for_sdp, v_for_sdp, false);
sdp->set_friendly_name("mha");
- auto add = std::make_shared<ov::op::v1::Add>(sdp, op::v0::Constant::create(inType, {1}, {1.0f}));
- auto pastk_assign = std::make_shared<op::v6::Assign>(concatK, var_k);
- auto pastv_assign = std::make_shared<op::v6::Assign>(concatV, var_v);
+ auto add = std::make_shared<ov::op::v1::Add>(sdp, ov::op::v0::Constant::create(inType, {1}, {1.0f}));
+ auto pastk_assign = std::make_shared<ov::op::v6::Assign>(concatK, var_k);
+ auto pastv_assign = std::make_shared<ov::op::v6::Assign>(concatV, var_v);
pastk_assign->set_friendly_name("pastk_w");
pastv_assign->set_friendly_name("pastv_w");
@@ -139,130 +198,117 @@ void ConcatSDPTest::SetUp() {
}
SinkVector sinks{pastk_assign, pastv_assign};
function = std::make_shared<ov::Model>(results, sinks, inputParams, "ConcatSDP");
- targetDevice = ov::test::utils::DEVICE_CPU;
functionRefs = function->clone();
pass::Manager manager;
- // decompose ScaledDotProductAttention
manager.register_pass<ov::pass::ScaledDotProductAttentionDecomposition>();
manager.run_passes(functionRefs);
}
-template<typename IT, typename T>
-void strided_iota(IT first, size_t n, T value, T stride) {
- for (size_t i = 0; i < n; i++) {
- *first++ = value;
- value += stride;
- }
-}
-
-void ConcatSDPTest::generate(int idx, const std::vector<ov::Shape>& targetInputStaticShapes) {
+void ConcatSDPTest::generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) {
inputs.clear();
- auto create_input = [this] (std::shared_ptr<op::v0::Parameter> param, ov::Shape shape, float val) {
- if (param->get_element_type() == element::i32) {
- ov::Tensor t{ov::element::i32, shape};
- auto size = shape[0];
- auto* p = static_cast<int*>(t.data());
- auto start = static_cast<int>(val);
- for (size_t i = 0; i < size; i++) {
- p[i] = (start + i) % size;
- }
- inputs.insert({param, t});
- } else if (param->get_element_type() == element::f32) {
- ov::Tensor t{ov::element::f32, shape};
- strided_iota(static_cast<float*>(t.data()), t.get_size(), val, 0.1f);
- inputs.insert({param, t});
- } else if (param->get_element_type() == element::f16) {
- ov::Tensor t{ov::element::f16, shape};
- strided_iota(static_cast<ov::float16 *>(t.data()), t.get_size(), val, 0.0f);
- inputs.insert({param, t});
- } else {
- ASSERT_TRUE(param->get_element_type() == element::bf16);
- ov::Tensor t{ov::element::bf16, shape};
- strided_iota(static_cast<ov::bfloat16*>(t.data()), t.get_size(), val, 0.1f);
- inputs.insert({param, t});
+ const int idx = m_iter++;
+ const auto& params = function->get_parameters();
+ auto fill_gaussian = [](const std::shared_ptr<ov::op::v0::Parameter>& param, const ov::Shape& shape, int seed) {
+ return utils::create_and_fill_tensor_normal_distribution(param->get_element_type(),
+ shape,
+ /*mean=*/0.0F,
+ /*stddev=*/0.2F,
+ seed);
+ };
+ auto fill_beam_idx = [](const std::shared_ptr<ov::op::v0::Parameter>& param, const ov::Shape& shape, int start) {
+ ov::Tensor t{param->get_element_type(), shape};
+ auto* p = static_cast<int*>(t.data());
+ const auto size = shape[0];
+ for (size_t i = 0; i < size; i++) {
+ p[i] = (start + static_cast<int>(i)) % static_cast<int>(size);
}
+ return t;
};
- // q, k, v, pastkv
- auto v_shape = targetInputStaticShapes[0];
- auto v_init_shape = targetInputStaticShapes[1];
- if (m_isDiffKVHeadSize) {
- v_shape[3] += m_diffKVHeadSize;
- v_init_shape[3] += m_diffKVHeadSize;
- }
- create_input(function->get_parameters()[0], targetInputStaticShapes[0], idx + 1.0f);
- create_input(function->get_parameters()[1], targetInputStaticShapes[0], idx + 2.0f);
- create_input(function->get_parameters()[2], v_shape, idx + 3.0f);
- create_input(function->get_parameters()[3], targetInputStaticShapes[1], idx + 4.0f);
- create_input(function->get_parameters()[4], v_init_shape, idx + 4.0f);
- create_input(function->get_parameters()[5], ov::Shape{targetInputStaticShapes[0][0]}, idx + 0.0f);
-}
+ auto q_shape = targetInputStaticShapes[0];
+ auto kv_shape = q_shape;
+ kv_shape[1] = static_cast<size_t>(m_headNumKV);
+ auto past_shape = targetInputStaticShapes[1];
+ past_shape[1] = static_cast<size_t>(m_headNumKV);
+ past_shape[2] = (idx == 0) ? 0 : m_accum_L_q;
+ m_accum_L_q = past_shape[2] + q_shape[2];
-void ConcatSDPTest::prepare() {
- compile_model();
- inferRequest = compiledModel.create_infer_request();
- ASSERT_TRUE(inferRequest);
+ inputs.insert({params[0], fill_gaussian(params[0], q_shape, idx + 1)});
+ inputs.insert({params[1], fill_gaussian(params[1], kv_shape, idx + 2)});
+ inputs.insert({params[2], fill_gaussian(params[2], kv_shape, idx + 3)});
+ inputs.insert({params[3], fill_gaussian(params[3], past_shape, idx + 4)});
+ inputs.insert({params[4], fill_gaussian(params[4], past_shape, idx + 5)});
+ inputs.insert({params[5], fill_beam_idx(params[5], ov::Shape{q_shape[0]}, idx)});
}
-void ConcatSDPTest::reset() {
- for (auto&& state : inferRequest.query_state()) {
- state.reset();
+// Compile `model` with `cfg`, run all iters via generate_inputs, return per-iter
+// outputs. Updates `compiledModel` so TEST_P post-checks inspect the last run.
+// Inputs keyed by original Parameter pointers; match compiled ports by friendly
+// name. Deep-copy outputs.
+std::vector<std::vector<ov::Tensor>>
+ConcatSDPTest::run_test(const std::shared_ptr<ov::Model>& model, const ov::AnyMap& cfg) {
+ compiledModel = core->compile_model(model, targetDevice, cfg);
+ auto req = compiledModel.create_infer_request();
+ m_iter = 0;
+ m_accum_L_q = 0;
+ std::vector<std::vector<ov::Tensor>> all;
+ for (const auto& shapes : targetStaticShapes) {
+ generate_inputs(shapes);
+ for (const auto& port : compiledModel.inputs()) {
+ const auto& name = port.get_node()->get_friendly_name();
+ for (const auto& [node, tensor] : inputs) {
+ if (node->get_friendly_name() == name) {
+ req.set_tensor(port, tensor);
+ break;
+ }
+ }
+ }
+ req.infer();
+ std::vector<ov::Tensor> outs;
+ for (const auto& port : compiledModel.outputs()) {
+ const auto& src = req.get_tensor(port);
+ ov::Tensor c{src.get_element_type(), src.get_shape()};
+ src.copy_to(c);
+ outs.push_back(std::move(c));
+ }
+ all.push_back(std::move(outs));
}
+ return all;
}
-std::vector<ov::Tensor> ConcatSDPTest::run_test(std::shared_ptr<ov::Model> model) {
- function = model;
- prepare();
- std::vector<ov::Tensor> outputs;
- int idx = 0;
- for (auto&& shapes : targetStaticShapes) {
- generate(idx++, shapes);
- for (const auto& input : inputs) {
- inferRequest.set_tensor(input.first, input.second);
- }
- inferRequest.infer();
- auto outputTensor = inferRequest.get_output_tensor(0);
- ov::Tensor copy{outputTensor.get_element_type(), outputTensor.get_shape()};
- outputTensor.copy_to(copy);
- outputs.push_back(copy);
+void ConcatSDPTest::run() {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ // Reference: SDPA decomposed into matmul/softmax (no cache codec). Strip cache
+ // config keys so reference runs full-precision; keeps quant noise on actual side only.
+ auto ref_config = configuration;
+ for (const auto& key : {"KEY_CACHE_PRECISION", "VALUE_CACHE_PRECISION",
+ "KEY_CACHE_QUANT_ALG", "VALUE_CACHE_QUANT_ALG"}) {
+ ref_config.erase(key);
+ }
+ auto expected = run_test(functionRefs, ref_config);
+ auto actual = run_test(function, configuration);
+ for (size_t i = 0; i < actual.size(); ++i) {
+ compare(expected[i], actual[i]);
}
- reset();
-
- return outputs;
}
+
TEST_P(ConcatSDPTest, CompareWithRefs) {
SKIP_IF_CURRENT_TEST_IS_DISABLED();
- const auto& [inType, inputShapes, kCachePrec, vCachePrec, hasShapeOf, isDiffKVHeadSize] = this->GetParam();
- auto actualOutputs = run_test(function);
- if (!hasShapeOf) {
+ run();
+ if (!m_hasShapeOf) {
CheckNumberOfNodesWithType(compiledModel, "ScaledDotProductAttention", 1);
CheckNumberOfNodesWithType(compiledModel, "Concatenation", 0);
CheckNumberOfNodesWithType(compiledModel, "Reorder", 0);
CheckNumberOfNodesWithType(compiledModel, "Gather", 0);
} else {
- // SimplifyGatherShapeOf will generate subgraph which contains Gather/Concat/Reorder, so could not check the number to confirm it's expected.
- // W/ or w/o fusion the SDPA name is the same, but if fused the output number should be 3(data+pastk+pastv)
for (const auto& node : compiledModel.get_runtime_model()->get_ops()) {
- if (node->get_rt_info().find(ov::exec_model_info::LAYER_TYPE)->second.as<std::string>() == "ScaledDotProductAttention") {
+ if (node->get_rt_info().find(ov::exec_model_info::LAYER_TYPE)->second.as<std::string>() ==
+ "ScaledDotProductAttention") {
ASSERT_EQ(3, node->get_output_size()) << "ScaledDotProductAttention should be fused";
}
}
}
-
- // the range of our result will exceed f16 max value and there may be 'inf'. In softmax, there is a step:
- // v - max(v), if v is inf, the result of 'v-max(v)' will be nan
- // use f32 as reference
- if (inType == ElementType::f16) {
- configuration["INFERENCE_PRECISION_HINT"] = "f32";
- }
-
- auto expectedOutputs = run_test(functionRefs);
- CheckNumberOfNodesWithType(compiledModel, "ScaledDotProductAttention", 0);
- for (size_t i = 0; i < actualOutputs.size(); i++) {
- ov::test::utils::compare(expectedOutputs[i], actualOutputs[i], abs_threshold, rel_threshold);
- }
}
-
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.hpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.hpp
index 05f33cf91a8..5a43cdacc1f 100644
--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.hpp
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.hpp
@@ -1,12 +1,10 @@
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
-#include "openvino/pass/manager.hpp"
-#include "transformations/op_conversions/scaled_dot_product_attention_decomposition.hpp"
+#pragma once
#include "shared_test_classes/base/ov_subgraph.hpp"
#include "utils/cpu_test_utils.hpp"
-#include "common_test_utils/ov_tensor_utils.hpp"
using namespace CPUTestUtils;
@@ -30,35 +28,36 @@ namespace test {
* |
* Result
*/
-template<typename IT, typename T>
-void strided_iota(IT first, size_t n, T value, T stride);
-
+// (inType, inputShapes, cacheCfg, hasShapeOf, head_num_q, head_num_kv)
+// cacheCfg carries KEY_CACHE_* / VALUE_CACHE_* / KV_CACHE_* properties; empty = default.
typedef std::tuple<ElementType,
std::vector<InputShape>,
- std::string, // K cache precision: "none", "u8", "u4"
- std::string, // V cache precision: "none", "u8", "u4"
- bool, // hasShapeOf
- bool> // isDiffKVHeadSize
+ ov::AnyMap,
+ bool,
+ int64_t,
+ int64_t>
ConcatSDPTestParams;
-class ConcatSDPTest :
- public testing::WithParamInterface<ConcatSDPTestParams>,
- virtual public ov::test::SubgraphBaseTest,
- public CPUTestsBase {
+class ConcatSDPTest : public testing::WithParamInterface<ConcatSDPTestParams>,
+ virtual public ov::test::SubgraphBaseTest,
+ public CPUTestsBase {
public:
static std::string getTestCaseName(const testing::TestParamInfo<ConcatSDPTestParams>& obj);
- void generate(int idx, const std::vector<ov::Shape>& targetInputStaticShapes);
- void prepare();
- void reset();
- std::vector<ov::Tensor> run_test(std::shared_ptr<ov::Model> model);
- std::string m_kCachePrec;
- std::string m_vCachePrec;
- bool m_hasShapeOf;
- bool m_isDiffKVHeadSize;
+
protected:
void SetUp() override;
+ void run() override;
+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override;
+ // Compile+run all iters. Updates `compiledModel` so post-checks see last run.
+ std::vector<std::vector<ov::Tensor>>
+ run_test(const std::shared_ptr<ov::Model>& model, const ov::AnyMap& cfg);
- static constexpr size_t m_diffKVHeadSize = 16;
+ ov::AnyMap m_cacheCfg;
+ bool m_hasShapeOf = false;
+ int64_t m_headNumQ = 8;
+ int64_t m_headNumKV = 8;
+ int m_iter = 0;
+ size_t m_accum_L_q = 0;
};
} // namespace test
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/concat_sdp.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/concat_sdp.cpp
index 387bbead457..0a2c7cc8238 100644
--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/concat_sdp.cpp
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/concat_sdp.cpp
@@ -1,67 +1,46 @@
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
-#include "openvino/pass/manager.hpp"
-#include "transformations/op_conversions/scaled_dot_product_attention_decomposition.hpp"
-
#include "custom/subgraph_tests/src/classes/concat_sdp.hpp"
-#include "shared_test_classes/base/ov_subgraph.hpp"
-#include "utils/cpu_test_utils.hpp"
-#include "common_test_utils/ov_tensor_utils.hpp"
-
-using namespace CPUTestUtils;
namespace ov {
namespace test {
-
namespace {
+
const std::vector<std::vector<InputShape>> inputShapes = {
// greedy search
{
- // B, H, L1, S
{{1, 8, -1, 64}, {{1, 8, 10, 64}, {1, 8, 1, 64}, {1, 8, 1, 64}, {1, 8, 20, 64}, {1, 8, 1, 64}}},
- // B, H, L0, S
{{1, 8, -1, 64}, {{1, 8, 0, 64}, {1, 8, 10, 64}, {1, 8, 11, 64}, {1, 8, 12, 64}, {1, 8, 32, 64}}},
},
// beam search
{
- // B, H, L1, S
{{-1, 8, -1, 64}, {{4, 8, 10, 64}, {4, 8, 1, 64}, {4, 8, 1, 64}, {4, 8, 1, 64}, {4, 8, 1, 64}}},
- // B, H, L0, S
{{-1, 8, -1, 64}, {{4, 8, 0, 64}, {4, 8, 10, 64}, {4, 8, 11, 64}, {4, 8, 12, 64}, {4, 8, 13, 64}}},
},
// big batch to check cvt_copy fast-path inside mha_single_token_kernel
{
- // B, H, L1, S
{{-1, 8, -1, 64}, {{129, 8, 10, 64}, {129, 8, 1, 64}, {129, 8, 1, 64}, {129, 8, 1, 64}, {129, 8, 1, 64}}},
- // B, H, L0, S
{{-1, 8, -1, 64}, {{129, 8, 0, 64}, {129, 8, 10, 64}, {129, 8, 11, 64}, {129, 8, 12, 64}, {129, 8, 13, 64}}},
},
};
-// @todo claude: enable asymmetric K/V cache precision combinations in a separate PR;
-// for now restrict to symmetric pairs so the SDPA assertion at scaled_attn.cpp:1823 holds.
-INSTANTIATE_TEST_SUITE_P(smoke_ConcatSDPTest,
- ConcatSDPTest,
- ::testing::Combine(::testing::Values(ElementType::f32),
- ::testing::ValuesIn(inputShapes),
- ::testing::Values("none"),
- ::testing::Values("none"),
- ::testing::Values(true, false),
- ::testing::Values(true, false)),
- ConcatSDPTest::getTestCaseName);
+const ov::AnyMap cfg_none{};
+const ov::AnyMap cfg_u8_sym{
+ {"KEY_CACHE_PRECISION", "u8"},
+ {"VALUE_CACHE_PRECISION", "u8"},
+};
-INSTANTIATE_TEST_SUITE_P(smoke_ConcatSDPTest_U8,
- ConcatSDPTest,
- ::testing::Combine(::testing::Values(ElementType::f32),
- ::testing::ValuesIn(inputShapes),
- ::testing::Values("u8"),
- ::testing::Values("u8"),
- ::testing::Values(true, false),
- ::testing::Values(true, false)),
- ConcatSDPTest::getTestCaseName);
+INSTANTIATE_TEST_SUITE_P(smoke_ConcatSDPTest,
+ ConcatSDPTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(inputShapes),
+ ::testing::Values(cfg_none, cfg_u8_sym),
+ ::testing::Values(true, false),
+ ::testing::Values<int64_t>(8),
+ ::testing::Values<int64_t>(8)),
+ ConcatSDPTest::getTestCaseName);
} // namespace
-
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/concat_sdp.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/concat_sdp.cpp
index 05a8c30f71a..2aaceee9884 100644
--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/concat_sdp.cpp
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/concat_sdp.cpp
@@ -1,84 +1,66 @@
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
-#include "openvino/pass/manager.hpp"
-#include "transformations/op_conversions/scaled_dot_product_attention_decomposition.hpp"
-
#include "custom/subgraph_tests/src/classes/concat_sdp.hpp"
-#include "shared_test_classes/base/ov_subgraph.hpp"
-#include "utils/cpu_test_utils.hpp"
-#include "common_test_utils/ov_tensor_utils.hpp"
-
-using namespace CPUTestUtils;
namespace ov {
namespace test {
-
namespace {
+
const std::vector<std::vector<InputShape>> inputShapes = {
// greedy search
{
- // B, H, L1, S
{{1, 8, -1, 64}, {{1, 8, 10, 64}, {1, 8, 1, 64}, {1, 8, 1, 64}, {1, 8, 20, 64}, {1, 8, 1, 64}}},
- // B, H, L0, S
{{1, 8, -1, 64}, {{1, 8, 0, 64}, {1, 8, 10, 64}, {1, 8, 11, 64}, {1, 8, 12, 64}, {1, 8, 32, 64}}},
},
// beam search
{
- // B, H, L1, S
{{-1, 8, -1, 64}, {{4, 8, 10, 64}, {4, 8, 1, 64}, {4, 8, 1, 64}, {4, 8, 1, 64}, {4, 8, 1, 64}}},
- // B, H, L0, S
{{-1, 8, -1, 64}, {{4, 8, 0, 64}, {4, 8, 10, 64}, {4, 8, 11, 64}, {4, 8, 12, 64}, {4, 8, 13, 64}}},
},
// big batch to check cvt_copy fast-path inside mha_single_token_kernel
{
- // B, H, L1, S
{{-1, 8, -1, 64}, {{129, 8, 10, 64}, {129, 8, 1, 64}, {129, 8, 1, 64}, {129, 8, 1, 64}, {129, 8, 1, 64}}},
- // B, H, L0, S
{{-1, 8, -1, 64}, {{129, 8, 0, 64}, {129, 8, 10, 64}, {129, 8, 11, 64}, {129, 8, 12, 64}, {129, 8, 13, 64}}},
},
};
-// @todo claude: enable asymmetric K/V cache precision combinations in a separate PR;
-// for now restrict to symmetric pairs so the SDPA assertion at scaled_attn.cpp:1823 holds.
-INSTANTIATE_TEST_SUITE_P(smoke_ConcatSDPTest,
- ConcatSDPTest,
- ::testing::Combine(::testing::Values(ElementType::bf16, ElementType::f16),
- ::testing::ValuesIn(inputShapes),
- ::testing::Values("none"),
- ::testing::Values("none"),
- ::testing::Values(true, false),
- ::testing::Values(true, false)),
- ConcatSDPTest::getTestCaseName);
+// K×V codec matrix: {none, u8, u4 scalar, TBQ4 (u4+TURBO)}.
+enum class KvCodec { NONE, U8, U4, TBQ4 };
+static ov::AnyMap kv_cfg(KvCodec k, KvCodec v) {
+ ov::AnyMap m;
+ auto set = [&](KvCodec c, const char* prec_key, const char* alg_key) {
+ switch (c) {
+ case KvCodec::NONE: break;
+ case KvCodec::U8: m[prec_key] = "u8"; break;
+ case KvCodec::U4: m[prec_key] = "u4"; break;
+ case KvCodec::TBQ4: m[prec_key] = "u4"; m[alg_key] = "TURBO"; break;
+ }
+ };
+ set(k, "KEY_CACHE_PRECISION", "KEY_CACHE_QUANT_ALG");
+ set(v, "VALUE_CACHE_PRECISION", "VALUE_CACHE_QUANT_ALG");
+ return m;
+}
+static std::vector<ov::AnyMap> all_kv_cfgs() {
+ std::vector<ov::AnyMap> out;
+ for (auto k : {KvCodec::NONE, KvCodec::U8, KvCodec::U4, KvCodec::TBQ4}) {
+ for (auto v : {KvCodec::NONE, KvCodec::U8, KvCodec::U4, KvCodec::TBQ4}) {
+ out.push_back(kv_cfg(k, v));
+ }
+ }
+ return out;
+}
-INSTANTIATE_TEST_SUITE_P(smoke_ConcatSDPTest_U8,
- ConcatSDPTest,
- ::testing::Combine(::testing::Values(ElementType::bf16, ElementType::f16),
- ::testing::ValuesIn(inputShapes),
- ::testing::Values("u8"),
- ::testing::Values("u8"),
- ::testing::Values(true, false),
- ::testing::Values(true, false)),
- ConcatSDPTest::getTestCaseName);
-
-// u4 test shapes: first iteration must be single-token (L1=1) because the
-// multi-token kernel doesn't support sub-byte cache dequant.
-const std::vector<std::vector<InputShape>> u4Shapes = {{
- {{1, 8, -1, 64}, {{1, 8, 1, 64}, {1, 8, 1, 64}, {1, 8, 1, 64}, {1, 8, 1, 64}, {1, 8, 1, 64}}},
- {{1, 8, -1, 64}, {{1, 8, 0, 64}, {1, 8, 1, 64}, {1, 8, 2, 64}, {1, 8, 3, 64}, {1, 8, 4, 64}}},
-}};
-
-INSTANTIATE_TEST_SUITE_P(smoke_ConcatSDPU4Test,
- ConcatSDPTest,
- ::testing::Combine(::testing::Values(ElementType::f32),
- ::testing::ValuesIn(u4Shapes),
- ::testing::Values("u4"),
- ::testing::Values("u4"),
- ::testing::Values(false),
- ::testing::Values(false)),
- ConcatSDPTest::getTestCaseName);
+INSTANTIATE_TEST_SUITE_P(smoke_ConcatSDPTest,
+ ConcatSDPTest,
+ ::testing::Combine(::testing::Values(ElementType::f32, ElementType::bf16, ElementType::f16),
+ ::testing::ValuesIn(inputShapes),
+ ::testing::ValuesIn(all_kv_cfgs()),
+ ::testing::Values(true, false),
+ ::testing::Values<int64_t>(8),
+ ::testing::Values<int64_t>(8, 2, 1)),
+ ConcatSDPTest::getTestCaseName);
} // namespace
-
} // namespace test
} // namespace ov
diff --git a/src/tests/test_utils/common_test_utils/src/ov_tensor_utils.cpp b/src/tests/test_utils/common_test_utils/src/ov_tensor_utils.cpp
index 92f5c45570d..6d4a3645058 100644
--- a/src/tests/test_utils/common_test_utils/src/ov_tensor_utils.cpp
+++ b/src/tests/test_utils/common_test_utils/src/ov_tensor_utils.cpp
@@ -412,6 +412,11 @@ protected:
std::vector<IncorrectValue> incorrect_values_abs;
double abs_threshold, rel_threshold, mvn_threshold, topk_threshold, mvn_results, topk_results;
size_t tensor_size;
+ // Track the coord with the largest |actual - expected| so release builds (which only
+ // print one failing coord) surface the coord that actually drives the failure —
+ // otherwise the reader sees the first-in-tensor-order fail, which may be far from worst.
+ double worst_diff = -1.0;
+ IncorrectValue worst_value{0.0, 0.0, 0.0, 0};
void emplace_back(double in_actual_value, double in_expected_value, double in_threshold, size_t in_coordinate) {
incorrect_values_abs.push_back(IncorrectValue(in_actual_value, in_expected_value, in_threshold, in_coordinate));
@@ -438,6 +443,10 @@ public:
if (less_or_equal(diff, threshold)) {
return true;
}
+ if (diff > worst_diff) {
+ worst_diff = diff;
+ worst_value = IncorrectValue(actual, expected, threshold, coordinate);
+ }
emplace_back(actual, expected, threshold, coordinate);
return false;
}
@@ -463,12 +472,22 @@ public:
constexpr size_t max_num_to_print = 1;
#endif
size_t i = 0;
- for (; i < incorrect_values_abs.size() && i < max_num_to_print; ++i) {
- auto val = incorrect_values_abs[i];
- std::cout << "Coordinate: " << std::setw(2) << val.coordinate << " Expected: " << val.expected_value
- << " Actual: " << val.actual_value
- << " Diff: " << std::fabs(val.expected_value - val.actual_value)
- << " abs_threshold: " << val.threshold << "\n";
+ if constexpr (max_num_to_print == 1) {
+ if (worst_diff >= 0.0) {
+ std::cout << "Coordinate: " << std::setw(2) << worst_value.coordinate
+ << " Expected: " << worst_value.expected_value << " Actual: " << worst_value.actual_value
+ << " Diff: " << worst_diff << " abs_threshold: " << worst_value.threshold << " (worst of "
+ << incorrect_values_abs.size() << ")\n";
+ i = 1;
+ }
+ } else {
+ for (; i < incorrect_values_abs.size() && i < max_num_to_print; ++i) {
+ auto val = incorrect_values_abs[i];
+ std::cout << "Coordinate: " << std::setw(2) << val.coordinate << " Expected: " << val.expected_value
+ << " Actual: " << val.actual_value
+ << " Diff: " << std::fabs(val.expected_value - val.actual_value)
+ << " abs_threshold: " << val.threshold << "\n";
+ }
}
if constexpr (max_num_to_print > 1) {