OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[CPU] Introduced simd abstraction and use for SDPA kernel (#35414)
Egor Duplenskii02ee88812afe
diff --git a/src/plugins/intel_cpu/CMakeLists.txt b/src/plugins/intel_cpu/CMakeLists.txtindex 5c455a57951..cb27d7931ca 100644--- a/src/plugins/intel_cpu/CMakeLists.txt+++ b/src/plugins/intel_cpu/CMakeLists.txt@@ -319,6 +319,13 @@ cross_compiled_file(${TARGET_NAME}NAME paged_attn_quantkv attn_quant_u8 attn_dequant_u8 attn_quant_by_token attn_quant_by_channel attn_quant_by_channel_u8 attn_dequant_by_channel_u8NAMESPACE ov::Extensions::Cpu::XARCH)+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+ NAMESPACE ov::Extensions::Cpu::XARCH+)cross_compiled_file(${TARGET_NAME}ARCH AVX512F ANYdiff --git a/src/plugins/intel_cpu/src/config.cpp b/src/plugins/intel_cpu/src/config.cppindex 9b16b0d553c..0c63b0d3546 100644--- a/src/plugins/intel_cpu/src/config.cpp+++ b/src/plugins/intel_cpu/src/config.cpp@@ -330,7 +330,12 @@ void Config::readProperties(const ov::AnyMap& prop, const ModelType modelType) {try {kvCachePrecisionSetExplicitly = true;const auto prec = val.as<ov::element::Type>();- if (any_of(prec, ov::element::f32, ov::element::f16, ov::element::bf16, ov::element::u8)) {+ if (any_of(prec,+ ov::element::f32,+ ov::element::f16,+ ov::element::bf16,+ ov::element::u8,+ ov::element::u4)) {kvCachePrecision = prec;} else {OPENVINO_THROW("invalid value");@@ -340,7 +345,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, bf16, f16, f32");+ ". Supported values: u8, u4, bf16, f16, f32");}} else if (key == ov::key_cache_precision.name()) {try {diff --git a/src/plugins/intel_cpu/src/memory_state.cpp b/src/plugins/intel_cpu/src/memory_state.cppindex a4459f68833..df2308a166c 100644--- a/src/plugins/intel_cpu/src/memory_state.cpp+++ b/src/plugins/intel_cpu/src/memory_state.cpp@@ -322,7 +322,7 @@ void VariableStateKVcache::set_state_impl(const ov::SoPtr<ov::ITensor>& state) {m_internal_mem = std::make_shared<Memory>(get_engine(), dense_internal_desc);Memory external_mem(get_engine(), state_desc, m_state->data());- if (dense_internal_desc->getPrecision() == element::u8) {+ if (dense_internal_desc->getPrecision() == element::u8 || dense_internal_desc->getPrecision() == element::u4) {PlainTensor external;PlainTensor internal;auto&& actual_internal_order = m_dense_internal_desc->getOrder();diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/attn_quant.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/attn_quant.cppindex 38a4f5e1bcd..9daf4aab99e 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/attn_quant.cpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/attn_quant.cpp@@ -422,22 +422,27 @@ void attn_dequant_u8(const uint8_t* src, float* dst, size_t n, float* params) {attn_dequant_kernel<float, ov::element::u8>(src, dst, n, params);}-template <typename T>-static void attn_quant_by_token_typed(const ov::intel_cpu::PlainTensor& cur,- const ov::intel_cpu::PlainTensor& dst,- const ov::intel_cpu::PlainTensor& scale_zp,- size_t L0,- size_t group_size,- const ov::intel_cpu::CpuParallelPtr& cpu_parallel) {+template <typename SrcT, typename QuantFn>+static void attn_quant_by_token_impl(const ov::intel_cpu::PlainTensor& cur,+ const ov::intel_cpu::PlainTensor& dst,+ const ov::intel_cpu::PlainTensor& scale_zp,+ size_t L0,+ size_t group_size,+ const ov::intel_cpu::CpuParallelPtr& cpu_parallel,+ QuantFn quant_fn) {const auto B = cur.m_dims[0];const auto H = cur.m_dims[1];const auto L1 = cur.m_dims[2];const auto S = cur.m_dims[3];+ // dst_group_bytes: byte size of one group in dst. For u4: group_size/2. For u8: group_size.+ const size_t dst_group_bytes = group_size * dst.m_element_size / dst.m_sub_byte_multiplier;cpu_parallel->parallel_for3d(L1, B, H, [&](size_t m, size_t b, size_t h) {auto* p_szp = scale_zp.ptr<float>(L0 + m, b, h);+ auto* dst_row = static_cast<uint8_t*>(dst.ptr_v(b, h, L0 + m));for (size_t group_id = 0; group_id < S / group_size; group_id++) {- quant_u8(cur.ptr<T>(b, h, m, group_id * group_size),- dst.ptr<uint8_t>(b, h, L0 + m, group_id * group_size),+ const auto* src = cur.ptr<SrcT>(b, h, m, group_id * group_size);+ quant_fn(src,+ dst_row + group_id * dst_group_bytes,group_size,p_szp[group_id * 2],p_szp[group_id * 2 + 1]);@@ -451,15 +456,34 @@ void attn_quant_by_token(const ov::intel_cpu::PlainTensor& cur,size_t L0,size_t group_size,const ov::intel_cpu::CpuParallelPtr& cpu_parallel) {- const auto prec = cur.get_precision();- if (prec == ov::element::f32) {- attn_quant_by_token_typed<float>(cur, dst, scale_zp, L0, group_size, cpu_parallel);- } else if (prec == ov::element::bf16) {- attn_quant_by_token_typed<ov::bfloat16>(cur, dst, scale_zp, L0, group_size, cpu_parallel);- } else if (prec == ov::element::f16) {- attn_quant_by_token_typed<ov::float16>(cur, dst, scale_zp, L0, group_size, cpu_parallel);- } else {- OPENVINO_THROW("unsupported src precision ", prec, " in attn_quant_by_token");+ auto dispatch_src = [&](auto quant_fn) {+ switch (cur.get_precision()) {+ case ov::element::f32:+ attn_quant_by_token_impl<float>(cur, dst, scale_zp, L0, group_size, cpu_parallel, quant_fn);+ break;+ case ov::element::bf16:+ attn_quant_by_token_impl<ov::bfloat16>(cur, dst, scale_zp, L0, group_size, cpu_parallel, quant_fn);+ break;+ case ov::element::f16:+ attn_quant_by_token_impl<ov::float16>(cur, dst, scale_zp, L0, group_size, cpu_parallel, quant_fn);+ break;+ default:+ OPENVINO_THROW("unsupported src precision ", cur.get_precision(), " in attn_quant_by_token");+ }+ };+ switch (dst.get_precision()) {+ case ov::element::u4:+ dispatch_src([](const auto* src, void* d, size_t n, float& s, float& z) {+ quant_u4(src, d, n, s, z);+ });+ break;+ case ov::element::u8:+ dispatch_src([](const auto* src, void* d, size_t n, float& s, float& z) {+ quant_u8(src, static_cast<uint8_t*>(d), n, s, z);+ });+ break;+ default:+ OPENVINO_THROW("unsupported dst precision ", dst.get_precision(), " in attn_quant_by_token");}}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.hppnew file mode 100644index 00000000000..b431d2fbc6c--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/cache_codec.hpp@@ -0,0 +1,22 @@+// 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::Cpudiff --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.hppnew file mode 100644index 00000000000..13478712b87--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/codec_kernels.hpp@@ -0,0 +1,90 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Shared inner SIMD kernels consuming DecodePlan objects:+// - decode_at: element-index -> plan.decoder.decode at correct bit offset+// - codec_dot: generic QK dot product over dim elements+// - codec_weighted_accum: generic V weighted accumulation into n_heads outputs+//+// These templates are header-only so each decoder-specific TU can+// instantiate them without cross-TU function calls.++#pragma once++#include <cstddef>+#include <cstdint>++#include "nodes/kernels/simd/simd_loop.hpp"++namespace ov::Extensions::Cpu::XARCH {++// Lightweight strided pointer — wraps (base, stride) for head-strided arrays.+// Usage: data[head][offset]+template <typename T>+struct StridedData {+ T* data;+ size_t stride;++ T* operator[](size_t i) const {+ return data + i * stride;+ }+};++// 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.+template <typename Plan, simd::isa I>+auto decode_at(const uint8_t* data, int j, const Plan& plan, simd::active_lanes<I> a) {+ using Dec = std::decay_t<decltype(plan.decoder)>;+ constexpr int bits = Dec::bits;+ int b = j * bits;+ return plan.decoder.decode(data + b / 8, b % 8, plan.params, a);+}++// Attention QK dot product: sum(plan.decode(k[j]) * q[j]) for j in [0, dim).+// Returns raw dot product — caller applies outer scale.+// QT: query element type (float, float16, bfloat16). simd::load handles conversion.+// PlanFor: plan provider — plan_for(j, active_lanes<I>) returns a DecodePlan for position j.+// 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) {+ return simd::simd_loop_reduce<4>(+ dim,+ [&](int j, simd::f32& acc) {+ simd::active_lanes<simd::active_isa> a{};+ auto plan = plan_for(j, a);+ acc = simd::fmadd(simd::load<simd::f32>(q + j), decode_at(k, j, plan, a), acc);+ },+ [&](int j, float& tail) {+ simd::active_lanes<simd::isa::scalar> a{};+ auto plan = plan_for(j, a);+ using Vs = simd::f32_t<simd::isa::scalar>;+ tail += reduce(simd::load<Vs>(q + j) * decode_at(k, j, plan, a));+ });+}++// Attention V weighted accumulation: for each element j, decode v[j] once and+// accumulate into all n_heads output buffers with weight * outer_scale.+// PlanFor: plan provider — plan_for(j, active_lanes<I>) returns a DecodePlan for position j.+template <typename PlanFor>+void codec_weighted_accum(const uint8_t* v,+ int dim,+ PlanFor&& plan_for,+ float outer_scale,+ StridedData<const float> weights,+ StridedData<float> accum,+ int n_heads) {+ simd::simd_loop(dim, [&](int j, auto a) {+ auto plan = plan_for(j, a);+ auto v_dec = decode_at(v, j, plan, a);+ using V = std::decay_t<decltype(v_dec)>;+ for (int h = 0; h < n_heads; h++) {+ V vw(weights[h][0] * outer_scale);+ float* out = accum[h] + j;+ simd::store(simd::fmadd(vw, v_dec, simd::load<V>(out, a)), out, a);+ }+ });+}++} // namespace ov::Extensions::Cpu::XARCHdiff --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.hppnew file mode 100644index 00000000000..1bf98145c7f--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/codecs.hpp@@ -0,0 +1,341 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Quantization decoders, params, and views for KV cache scoring and accumulation.+//+// Three-layer architecture (see codec_refactoring.md):+//+// Params: GroupedScaleZpParams, ByChannelScaleZpParams, NoParams —+// carry per-position dequant parameters. Views resolve params;+// decoders consume them. j drives span resolution in the view,+// NOT in the decoder.+//+// Decoders: U8Decoder, U4Decoder, RawDecoder —+// stateless, ISA-agnostic decode math via templated+// decode(base, bit_offset, params, active_lanes).+//+// Views: RecordView, GroupedView, ByChannelView, AffineView, etc. —+// resolve per-token/per-group metadata and produce params.+//+// Detection traits: is_head_grouped, is_token_indexed, is_raw_decoder,+// is_affine, has_params_for — dispatch on view interface.++#pragma once++#include <cstddef>+#include <cstdint>+#include <type_traits>++#include "nodes/kernels/simd/simd.hpp"+#include "utils/plain_tensor.hpp"++namespace ov::Extensions::Cpu::XARCH {++// ---------------------------------------------------------------------------+// Params — carry per-position dequantization parameters.+//+// Views resolve params from metadata; decoders consume them via get_zp/get_scale.+// This separation keeps j (element position) in the view/params layer,+// not in the decoder — j drives span resolution, not decode math.+// ---------------------------------------------------------------------------++// Grouped quantization: one scale/zp pair per group. Broadcast to SIMD width.+struct GroupedScaleZpParams {+ float v_scale;+ float v_zp;++ template <simd::isa I>+ simd::f32_t<I> get_scale(simd::active_lanes<I> /*unused*/) const {+ return simd::f32_t<I>(v_scale);+ }+ template <simd::isa I>+ simd::f32_t<I> get_zp(simd::active_lanes<I> /*unused*/) const {+ return simd::f32_t<I>(v_zp);+ }+};++// By-channel quantization: span-relative pointers. Vector load at current width.+// scalar: load(scale_ptr) reads one element+// SIMD: load(scale_ptr) reads a contiguous lane block+struct ByChannelScaleZpParams {+ const float* scale_ptr;+ const float* zp_ptr;++ template <simd::isa I>+ simd::f32_t<I> get_scale(simd::active_lanes<I> /*unused*/) const {+ return simd::load<simd::f32_t<I>>(scale_ptr);+ }+ template <simd::isa I>+ simd::f32_t<I> get_zp(simd::active_lanes<I> /*unused*/) const {+ return simd::load<simd::f32_t<I>>(zp_ptr);+ }+};++// Raw / affine: no per-element scale/zp. Decoder ignores params entirely.+struct NoParams {};++// ---------------------------------------------------------------------------+// DecodePlan — bound decoder + resolved params, ready for execution.+//+// Views resolve navigation (token, head, group, element position) and+// produce a DecodePlan. Inner kernels consume the plan via decode_at().+// This keeps view resolution and decode execution cleanly separated.+// ---------------------------------------------------------------------------++template <typename Decoder, typename Params>+struct DecodePlan {+ Decoder decoder;+ Params params;+};++template <typename D, typename P>+DecodePlan(D, P) -> DecodePlan<D, P>;++// ---------------------------------------------------------------------------+// Decoders — stateless, ISA-agnostic element-level dequantization.+//+// decode() is templated on ISA via active_lanes<I> and on Params.+// ISA width is NOT part of the decoder type. Decoders are stateless —+// dequant parameters come from Params, resolved by the view layer.+// ---------------------------------------------------------------------------++// U8 decoder: load W consecutive u8 values, convert to float, dequantize.+// Works with any Params that provide get_zp(a) and get_scale(a).+struct U8Decoder {+ static constexpr int bits = 8;++ template <simd::isa I, typename Params>+ simd::f32_t<I> decode(const uint8_t* base, int /*bit_offset*/, const Params& p, simd::active_lanes<I> a) const {+ return (simd::load<simd::f32_t<I>>(base) - p.get_zp(a)) * p.get_scale(a);+ }+};++// U4 decoder: load W nibbles, convert to float, dequantize.+struct U4Decoder {+ static constexpr int bits = 4;++ template <simd::isa I, typename Params>+ simd::f32_t<I> decode(const uint8_t* base, int bit_offset, const Params& p, simd::active_lanes<I> a) const {+ return (simd::load_u4<simd::f32_t<I>>(base, bit_offset) - p.get_zp(a)) * p.get_scale(a);+ }+};++// Raw decoder: typed load + convert for uncompressed cache (f32/f16/bf16). Stateless.+// Ignores params — raw data needs no dequantization.+template <typename KT>+struct RawDecoder {+ static constexpr int bits = static_cast<int>(sizeof(KT)) * 8;++ template <simd::isa I, typename Params>+ simd::f32_t<I> decode(const uint8_t* base,+ int /*bit_offset*/,+ const Params& /*p*/,+ simd::active_lanes<I> /*unused*/) const {+ return simd::load<simd::f32_t<I>>(reinterpret_cast<const KT*>(base));+ }+};++// ---------------------------------------------------------------------------+// Detection traits — dispatch on interface, not tags.+// ---------------------------------------------------------------------------++// is_head_grouped: view splits head_dim into sub-groups, each with its own decoder+params.+template <typename T, typename = void>+struct is_head_grouped_t : std::false_type {};+template <typename T>+struct is_head_grouped_t<T, std::void_t<decltype(std::declval<const T>().group_decoder(0))>> : std::true_type {};+template <typename T>+inline constexpr bool is_head_grouped_v = is_head_grouped_t<T>::value;++// is_token_indexed: record view has external scale/zp tensor indexed by token position.+template <typename T, typename = void>+struct is_token_indexed_t : std::false_type {};+template <typename T>+struct is_token_indexed_t<+ T,+ std::void_t<decltype(std::declval<const T>().for_token(size_t{}, size_t{}, size_t{}, size_t{}))>> : std::true_type {+};+template <typename T>+inline constexpr bool is_token_indexed_v = is_token_indexed_t<T>::value;++// is_raw_decoder: matches RawDecoder<T> for any T.+template <typename T>+struct is_raw_decoder_t : std::false_type {};+template <typename KT>+struct is_raw_decoder_t<RawDecoder<KT>> : std::true_type {};+template <typename T>+inline constexpr bool is_raw_decoder_v = is_raw_decoder_t<T>::value;++// is_affine: view applies deferred dequant correction after dot product.+template <typename T, typename = void>+struct is_affine_t : std::false_type {};+template <typename T>+struct is_affine_t<T, std::void_t<decltype(std::declval<const T>().correct_dot(0.0F, 0))>> : std::true_type {};+template <typename T>+inline constexpr bool is_affine_v = is_affine_t<T>::value;++// has_for_head: record view supports per-head resolution.+template <typename T, typename = void>+struct has_for_head_t : std::false_type {};+template <typename T>+struct has_for_head_t<T, std::void_t<decltype(std::declval<const T>().for_head(0))>> : std::true_type {};+template <typename T>+inline constexpr bool has_for_head_v = has_for_head_t<T>::value;++// has_params_for: view resolves per-element params via params_for(j, active_lanes).+template <typename T, typename = void>+struct has_params_for_t : std::false_type {};+template <typename T>+struct has_params_for_t<+ T,+ std::void_t<decltype(std::declval<const T>().params_for(0, simd::active_lanes<simd::isa::scalar>{}))>>+ : std::true_type {};+template <typename T>+inline constexpr bool has_params_for_v = has_params_for_t<T>::value;++// ---------------------------------------------------------------------------+// Record views — hold cache tensor metadata, produce per-token views/decoders.+// ---------------------------------------------------------------------------++// Non-grouped record view: one decoder for the whole record (used for raw cache).+template <typename Decoder>+struct RecordView {+ using decoder_t = Decoder;+ Decoder decoder;+};++// ---------------------------------------------------------------------------+// Affine view — deferred dequantization for u8 QK dot product.+// Inner decoder does raw type conversion (no scale/zp per element).+// Post-dot correction applies: scale * (raw_dot - zp * q_group_sum).+// ---------------------------------------------------------------------------++// Per-token resolved view for affine deferred dequant.+struct AffineView {+ const float* szp;+ const float* q_group_sums;+ size_t group_size;++ [[nodiscard]] int group_dim() const {+ return static_cast<int>(group_size);+ }+ [[nodiscard]] int n_groups(int head_dim) const {+ return head_dim / static_cast<int>(group_size);+ }++ [[nodiscard]] static RawDecoder<uint8_t> group_decoder(int /*group*/) {+ return {};+ }+ [[nodiscard]] static NoParams group_params(int /*group*/) {+ return {};+ }++ [[nodiscard]] float correct_dot(float raw_dot, int group) const {+ float scale = szp[group * 2];+ float zp = szp[group * 2 + 1];+ return scale * (raw_dot - zp * q_group_sums[group]);+ }+};++// Factory: holds scale_zp tensor + precomputed q_group_sums base+stride.+// select_head(g) sets q_group_sums for query head g within the KV group.+// for_token() resolves per-token scale/zp and returns AffineView.+struct AffineRecordView {+ using decoder_t = RawDecoder<uint8_t>;+ const ov::intel_cpu::PlainTensor& scale_zp;+ size_t group_size = 0UL;+ const float* q_group_sums = nullptr; // q_group_sums for first head in group+ size_t q_sums_head_stride = 0; // stride between query heads++ // Resolve q_group_sums for query head g within the KV group.+ [[nodiscard]] AffineRecordView for_head(int g) const {+ return {scale_zp, group_size, q_group_sums + g * q_sums_head_stride, q_sums_head_stride};+ }++ [[nodiscard]] AffineView for_token(size_t start_pos, size_t h_group, size_t t, size_t b_kv) const {+ // scale_zp is a float tensor (one [scale, zp] pair per group).+ // Must use ptr<float>: ptr<uint8_t> on a float tensor returns base + off bytes+ // instead of base + off*sizeof(float) bytes.+ const auto* base = scale_zp.ptr<float>(start_pos + t, b_kv, h_group);+ return {base, q_group_sums, group_size};+ }+};++// ---------------------------------------------------------------------------+// Grouped views — head_dim split into sub-groups with per-group scale/zp.+// ---------------------------------------------------------------------------++// Grouped view: per-token resolved with szp pointer.+// group_decoder() returns a stateless decoder; group_params() returns+// per-group GroupedScaleZpParams that the decoder consumes.+template <typename Decoder>+struct GroupedView {+ const float* szp;+ size_t group_size;++ [[nodiscard]] int group_dim() const {+ return static_cast<int>(group_size);+ }+ [[nodiscard]] int n_groups(int head_dim) const {+ return head_dim / static_cast<int>(group_size);+ }+ // Stateless decoder — dequant params come from group_params().+ static Decoder group_decoder(int /*group*/) {+ return {};+ }+ // Per-group scale/zp.+ [[nodiscard]] GroupedScaleZpParams group_params(int group) const {+ return {szp[group * 2], szp[group * 2 + 1]};+ }+};++// Grouped record view: holds the side tensor for per-token scale/zp resolution.+// for_token() resolves addressing and returns a lightweight GroupedView.+// scale_zp is laid out as [L, B, H, n_groups*2] in tensor-native (post-permute) order.+template <typename Decoder>+struct GroupedRecordView {+ using decoder_t = Decoder;+ const ov::intel_cpu::PlainTensor& scale_zp;+ size_t group_size = 0UL;++ [[nodiscard]] GroupedView<Decoder> for_token(size_t start_pos, size_t h_group, size_t t, size_t b_kv) const {+ return {scale_zp.ptr<float>(start_pos + t, b_kv, h_group), group_size};+ }+};++// ---------------------------------------------------------------------------+// By-channel views — per-element scale/zp across head_dim.+//+// params_for(j, active_lanes) resolves span-relative ByChannelScaleZpParams:+// scalar: {scale + j, zp + j} → load reads one element+// SIMD: {scale + j, zp + j} → load reads a contiguous lane block+// j drives span resolution in the view, not in the decoder.+// ---------------------------------------------------------------------------++// By-channel view: per-token resolved. Non-grouped — params resolved per-j.+struct ByChannelView {+ using decoder_t = U8Decoder;+ const float* scale;+ const float* zp;++ template <simd::isa I>+ ByChannelScaleZpParams params_for(int j, simd::active_lanes<I> /*unused*/) const {+ return {scale + j, zp + j};+ }+};++// By-channel record view: holds the scale_zp tensor for per-channel resolution.+// scale_zp layout: [group_id*2, B, H, S] — scale at even indices, zp at odd.+// for_token() resolves to a ByChannelView with base pointers.+struct ByChannelRecordView {+ using decoder_t = U8Decoder;+ const ov::intel_cpu::PlainTensor& scale_zp;+ size_t group_size = 0UL; // number of tokens sharing the same per-channel stats++ [[nodiscard]] ByChannelView for_token(size_t start_pos, size_t h_group, size_t t, size_t b_kv) const {+ size_t group_id = (start_pos + t) / group_size;+ return {scale_zp.ptr<float>(group_id * 2, b_kv, h_group), scale_zp.ptr<float>(group_id * 2 + 1, b_kv, h_group)};+ }+};++} // namespace ov::Extensions::Cpu::XARCHdiff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/common_quantize.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/common_quantize.hppnew file mode 100644index 00000000000..17f6ae8e113--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/codecs/common_quantize.hpp@@ -0,0 +1,75 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Shared encode helpers: L2 norm + unit-vector normalization,+// branchless scalar quantize via boundary linear-scan.+// These are used by TurboQ, TurboQ-QJL, and PolarQuant encoders.+//+// Header-only: included by per-codec `*_quantize.hpp` headers, which in turn+// are included by the cross-compiled mha_kv_cache_codec.cpp TU, so SIMD code+// compiles for the active ISA without requiring a separate TU.++#pragma once++#include <cmath>+#include <cstdint>+#include <cstring>++#include "nodes/kernels/simd/simd.hpp"+#include "nodes/kernels/simd/simd_loop.hpp"+#include "openvino/core/type/bfloat16.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/core/type/float16.hpp"++namespace ov::Extensions::Cpu::XARCH {++// Compute L2 norm and normalize src to unit vector in f32. Returns the norm.+// Dispatches on src_precision to handle bf16/f16→f32 conversion during the load.+template <typename T>+float normalize_to_unit(const void* src_raw, float* unit, int dim) {+ const auto* src = static_cast<const T*>(src_raw);++ float norm_sq = simd::simd_loop_reduce<2>(+ dim,+ [&](int i, simd::f32& acc) {+ auto v = simd::load<simd::f32>(src + i);+ acc = simd::fmadd(v, v, acc);+ },+ [&](int i, float& tail) {+ auto v = static_cast<float>(src[i]);+ tail += v * v;+ });+ const float norm = std::sqrt(norm_sq);++ if (norm < 1e-30F) {+ std::memset(unit, 0, dim * sizeof(float));+ } else {+ const float inv_norm = 1.0F / norm;+ simd::simd_loop(dim, [&](int i, auto a) {+ using V = simd::vec<float, decltype(a)::isa_tag::value>;+ simd::store(simd::load<V>(src + i, a) * V(inv_norm), unit + i, a);+ });+ }+ return norm;+}++inline float dispatch_normalize(const void* src, float* unit, int dim, ov::element::Type precision) {+ if (precision == ov::element::bf16) {+ return normalize_to_unit<ov::bfloat16>(src, unit, dim);+ }+ if (precision == ov::element::f16) {+ return normalize_to_unit<ov::float16>(src, unit, dim);+ }+ return normalize_to_unit<float>(src, unit, dim);+}++// Branchless linear scan over boundaries — shared by TBQ / QJL / Polar.+inline uint8_t scalar_quantize(float x, const float* boundaries, int n_boundaries) {+ int idx = 0;+ for (int i = 0; i < n_boundaries; i++) {+ idx += (x > boundaries[i]) ? 1 : 0;+ }+ return static_cast<uint8_t>(idx);+}++} // namespace ov::Extensions::Cpu::XARCHdiff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hppindex 58bee1b10ea..bedfb13479c 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hpp@@ -19,6 +19,17 @@# include <immintrin.h>#endif+#if defined(HAVE_AVX2) || defined(HAVE_AVX512F)+# define prefetch_bytes(bytes, sel, advance, src) \+ { \+ auto* _pf = reinterpret_cast<const char*>(src); \+ for (size_t _i = 0; _i < (bytes); _i += 64) \+ _mm_prefetch(_pf + _i + (advance), sel); \+ }+#else+# define prefetch_bytes(bytes, sel, advance, src)+#endif+#if defined(OPENVINO_ARCH_ARM64)# if defined(HAVE_SVE)# include "arm_sve.h"@@ -165,8 +176,8 @@ inline void mm512_uni_storeu_tail_ps(ov::float16* addr, __m512 v, size_t count)_mm256_mask_storeu_epi16(reinterpret_cast<__m256i*>(addr), mask_addr, vec_f16);}-inline void mm512_loadu_u4_to_f32(uint8_t* src_data, __m512& first_half, __m512& second_half) {- auto data = _mm_loadu_si128(reinterpret_cast<__m128i*>(src_data));+inline void mm512_loadu_u4_to_f32(const uint8_t* src_data, __m512& first_half, __m512& second_half) {+ auto data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(src_data));auto v_i32 = _mm512_cvtepu8_epi32(data);auto v_512_low_half = _mm512_srli_epi32(v_i32, 4);@@ -307,8 +318,8 @@ inline void mm256_uni_storeu_tail_ps(ov::bfloat16* addr, __m256 v, size_t count)return _mm_maskmoveu_si128(bf16_o, mask, reinterpret_cast<char*>(addr));}-inline void mm256_loadu_u4_to_f32(uint8_t* src, __m256& first_half, __m256& second_half) {- auto data = _mm_loadl_epi64(reinterpret_cast<__m128i*>(src));+inline void mm256_loadu_u4_to_f32(const uint8_t* src, __m256& first_half, __m256& second_half) {+ auto data = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(src));auto v_i32 = _mm256_cvtepu8_epi32(data);auto v_256_low_half = _mm256_srli_epi32(v_i32, 4);diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cppindex 87af45e8c09..66a3cc3ff0f 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp@@ -56,21 +56,6 @@ using namespace ov::intel_cpu;// currently depends on brgemm which only support x64 or ARM SVE#if defined(OPENVINO_ARCH_X86_64) || (defined(OPENVINO_ARCH_ARM64) && defined(HAVE_SVE))-# if defined(HAVE_AVX2) || defined(HAVE_AVX512F)--# define prefetch_bytes(bytes, sel, advance, src) \- { \- auto* p = reinterpret_cast<char*>(src); \- for (size_t i = 0; i < bytes; i += 64) \- _mm_prefetch(p + i + advance, sel); \- }--# else--# define prefetch_bytes(bytes, sel, advance, src)--# endif-// dequant f16/u8 to floattemplate <typename T,ov::element::Type_t SRC_PREC,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.cppnew file mode 100644index 00000000000..7b116814c1d--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_codec.cpp@@ -0,0 +1,653 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "mha_kv_cache_codec.hpp"++#include <algorithm>+#include <cstring>++#include "codecs/codec_kernels.hpp"+#include "codecs/codecs.hpp"+#include "common.hpp"+#include "mha_kv_cache_reduce.hpp"+#include "nodes/kernels/simd/simd.hpp"+#include "openvino/core/parallel.hpp"+#include "softmax_kernel.hpp"++namespace ov::Extensions::Cpu::XARCH {++// 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;++// ---------------------------------------------------------------------------+// 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;++struct NoOpInit {+ void operator()(size_t /*unused*/) const {}+};++struct MhaKvTraversal {+ size_t batch_size = 0;+ size_t num_kv_heads = 0;+ size_t kv_len = 0;+ size_t heads_per_kv_group = 0;+ int nthr = 0;+};++// Generic parallel loop over KV cache tokens.+// Covers both Q·K scoring and V accumulation — both traverse the same [B, num_kv_heads, kv_len]+// cache structure with identical parallelization and work splitting.+//+// direct_fn(run_len, num_group_heads, head_dim, b, h_group, start_pos, ithr)+// Processes all tokens in a contiguous run. Computes pointers, handles prefetching,+// and accesses data via captures.+// per_thread_init(ithr)+// Called once per thread before work (e.g. memset accumulators). Default: no-op.+template <typename DirectFn, typename InitFn = NoOpInit>+static void mha_foreach_kv(const MhaKvTraversal& traversal,+ size_t head_dim,+ DirectFn&& direct_fn,+ InitFn per_thread_init = {}) {+ parallel_nt_static(traversal.nthr, [&](const size_t ithr, const size_t nthr) {+ const auto [B, num_kv_heads, kv_len, heads_per_kv_group, traversal_nthr] = traversal;+ (void)traversal_nthr;+ per_thread_init(ithr);++ size_t start{0}, end{0};+ splitter(B * num_kv_heads * kv_len, nthr, ithr, start, end);+ if (start >= end) {+ return;+ }++ size_t pos = 0, b = 0, h_group = 0;+ parallel_it_init(start, h_group, num_kv_heads, b, B, pos, kv_len);++ size_t iwork = start;+ while (iwork < end) {+ size_t run_len = std::min(kv_len - pos, end - iwork);++ direct_fn(run_len, static_cast<int>(heads_per_kv_group), static_cast<int>(head_dim), b, h_group, pos, ithr);++ for (size_t r = 0; r < run_len; r++) {+ parallel_it_step(h_group, num_kv_heads, b, B, pos, kv_len);+ }+ iwork += run_len;+ }+ });+}++static void mha_softmax(const PlainTensor& attn_w,+ const PlainTensor& alibi_mask,+ const PlainTensor& attention_mask,+ const PlainTensor& sink_input,+ size_t B,+ size_t num_q_heads,+ size_t q_len,+ size_t kv_len,+ bool auto_causal,+ float d_scale,+ const CpuParallelPtr& cpu_parallel) {+ auto precision = ov::element::f32;+ auto softmax_body = [&](size_t b, size_t h, size_t m) {+ auto ncausal = auto_causal ? (kv_len - q_len + m + 1) : kv_len;+ float* alibi_ptr = alibi_mask ? &alibi_mask.at<float>({b, h, m, 0}, true) : nullptr;+ uint8_t* attn_mask_ptr = nullptr;+ auto attn_mask_prec = attention_mask.get_precision();+ if (attention_mask) {+ attn_mask_ptr = &attention_mask.at<uint8_t>({b, h, m, 0}, true);+ }+ float* sink = nullptr;+ if (sink_input) {+ sink = &sink_input.at<float>({b, h, m, 0}, true);+ }+ attn_softmax_kernel<float>(attn_w.ptr<float>(b, h, m),+ attn_w.ptr<float>(b, h, m),+ d_scale,+ alibi_ptr,+ attn_mask_ptr,+ nullptr,+ false,+ ncausal,+ kv_len,+ attn_mask_prec,+ precision,+ sink);+ };+ if (q_len == 1) {+ cpu_parallel->parallel_for2d(B, num_q_heads, [&](size_t b, size_t h) {+ softmax_body(b, h, 0);+ });+ } else {+ cpu_parallel->parallel_for3d(B, num_q_heads, q_len, softmax_body);+ }+}++// ---------------------------------------------------------------------------+// QK dot product and V accumulation through record codecs.+// ---------------------------------------------------------------------------++template <typename QT, typename View>+static inline float record_qk_dot(const uint8_t* k, const QT* q, int head_dim, const View& view) {+ if constexpr (is_affine_v<View>) {+ // Deferred dequant: raw dot per group, then affine correction.+ const int gd = view.group_dim();+ const int ng = view.n_groups(head_dim);+ float sum = 0.0F;+ for (int g = 0; g < ng; g++) {+ auto plan = DecodePlan{view.group_decoder(g), view.group_params(g)};+ constexpr int bpe = decltype(plan.decoder)::bits;+ const auto* gk = k + static_cast<size_t>(g * gd) * bpe / 8;+ float raw = codec_dot<QT>(gk, q + g * gd, gd, [&](int, auto) {+ return plan;+ });+ sum += view.correct_dot(raw, g);+ }+ return sum;+ } else if constexpr (is_head_grouped_v<View>) {+ const int gd = view.group_dim();+ const int ng = view.n_groups(head_dim);+ float sum = 0.0F;+ for (int g = 0; g < ng; g++) {+ auto plan = DecodePlan{view.group_decoder(g), view.group_params(g)};+ constexpr int bpe = decltype(plan.decoder)::bits;+ const auto* gk = k + static_cast<size_t>(g * gd) * bpe / 8;+ sum += codec_dot<QT>(gk, q + g * gd, gd, [&](int, auto) {+ return plan;+ });+ }+ return sum;+ } else if constexpr (has_params_for_v<View>) {+ // By-channel: plan resolved per-j by the view.+ using D = typename View::decoder_t;+ return codec_dot<QT>(k, q, head_dim, [&view](int j, auto a) {+ return DecodePlan{D{}, view.params_for(j, a)};+ });+ } else {+ // RecordView<RawDecoder<T>>: constant plan, no dequant params.+ auto plan = DecodePlan{view.decoder, NoParams{}};+ return codec_dot<QT>(k, q, head_dim, [&](int, auto) {+ return plan;+ });+ }+}++// Unified per-token V weighted accumulation through record view.+template <typename View>+static inline void record_v_accum(const uint8_t* v,+ StridedData<const float> weights,+ StridedData<float> accum,+ int num_group_heads,+ int head_dim,+ const View& view) {+ if constexpr (is_head_grouped_v<View>) {+ const int gd = view.group_dim();+ const int ng = view.n_groups(head_dim);+ for (int g = 0; g < ng; g++) {+ auto plan = DecodePlan{view.group_decoder(g), view.group_params(g)};+ constexpr int bpe = decltype(plan.decoder)::bits;+ const auto* gv = v + static_cast<size_t>(g * gd) * bpe / 8;+ StridedData<float> ga{accum.data + g * gd, accum.stride};+ codec_weighted_accum(+ gv,+ gd,+ [&](int, auto) {+ return plan;+ },+ 1.0F,+ weights,+ ga,+ num_group_heads);+ }+ } else if constexpr (has_params_for_v<View>) {+ // By-channel: plan resolved per-j by the view.+ using D = typename View::decoder_t;+ codec_weighted_accum(+ v,+ head_dim,+ [&view](int j, auto a) {+ return DecodePlan{D{}, view.params_for(j, a)};+ },+ 1.0F,+ weights,+ accum,+ num_group_heads);+ } else {+ // RecordView<RawDecoder<T>>: constant plan, no dequant params.+ auto plan = DecodePlan{view.decoder, NoParams{}};+ codec_weighted_accum(+ v,+ head_dim,+ [&](int, auto) {+ return plan;+ },+ 1.0F,+ weights,+ accum,+ num_group_heads);+ }+}++// ---------------------------------------------------------------------------+// QKScorer — bound QK scorer for Phase 1.+// Owns query head access, view resolution, and the call to record_qk_dot.+// Constructed once per (q_precision, codec) dispatch, passed to score_tokens.+// ---------------------------------------------------------------------------++struct KVEntryContext {+ size_t start_pos;+ size_t h_group;+ int head_dim;+};++template <typename Q, typename RecordView>+struct QKScorer {+ Q q;+ RecordView record_view;+ KVEntryContext ctx;++ 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];+ 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);+ } 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);+ } else {+ return record_qk_dot<QT>(k, q_head, ctx.head_dim, record_view);+ }+ }+};++template <typename Q, typename RecordView>+QKScorer(Q, RecordView, KVEntryContext) -> QKScorer<Q, RecordView>;++// ---------------------------------------------------------------------------+// VAccumulator — bound V accumulator for Phase 3.+// Owns view resolution and the call to record_v_accum.+// Constructed once per codec dispatch, passed to accum_tokens.+// ---------------------------------------------------------------------------++template <typename RecordView>+struct VAccumulator {+ RecordView record_view;+ KVEntryContext ctx;++ void operator()(const uint8_t* v,+ StridedData<const float> w,+ StridedData<float> a,+ int num_group_heads,+ size_t t,+ size_t b_kv) const {+ 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);+ } else {+ record_v_accum(v, w, a, num_group_heads, ctx.head_dim, record_view);+ }+ }+};++template <typename RecordView>+VAccumulator(RecordView, KVEntryContext) -> VAccumulator<RecordView>;++// Unified per-token QK scoring loop.+// Handles beam table resolution, prefetching, and multi-head scoring.+template <typename TokenScoreFn>+static void score_tokens(const uint8_t* kv_base,+ size_t stride_batch,+ size_t stride_pos,+ const int32_t* beam_tbl,+ size_t b,+ StridedData<float> scores,+ size_t run_len,+ int num_group_heads,+ 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;+ const uint8_t* k_record = kv_base + b_kv * stride_batch + t * stride_pos;+ if (t + PREFETCH_AHEAD < run_len) {+ [[maybe_unused]] const size_t prefetch_t = t + PREFETCH_AHEAD;+ [[maybe_unused]] const size_t prefetch_b = beam_tbl ? static_cast<size_t>(beam_tbl[prefetch_t]) : b;+ [[maybe_unused]] const uint8_t* prefetch_record =+ kv_base + prefetch_b * stride_batch + prefetch_t * stride_pos;+ prefetch_bytes(pf_bytes, _MM_HINT_T0, 0, prefetch_record);+ }+ for (int g = 0; g < num_group_heads; g++) {+ scores[g][t] = score_fn(k_record, g, t, b_kv);+ }+ }+}++// Unified per-token V accumulation loop.+template <typename TokenAccumFn>+static void accum_tokens(const uint8_t* kv_base,+ size_t stride_batch,+ size_t stride_pos,+ const int32_t* beam_tbl,+ size_t b,+ StridedData<const float> weights,+ StridedData<float> accum,+ int num_group_heads,+ size_t run_len,+ 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;+ const uint8_t* v_record = kv_base + b_kv * stride_batch + t * stride_pos;+ if (t + PREFETCH_AHEAD < run_len) {+ [[maybe_unused]] const size_t prefetch_t = t + PREFETCH_AHEAD;+ [[maybe_unused]] const size_t prefetch_b = beam_tbl ? static_cast<size_t>(beam_tbl[prefetch_t]) : b;+ [[maybe_unused]] const uint8_t* prefetch_record =+ kv_base + prefetch_b * stride_batch + prefetch_t * stride_pos;+ prefetch_bytes(pf_bytes, _MM_HINT_T0, 0, prefetch_record);+ }+ // Offset weights by t: weights[h][t] is the weight for head h at token t.+ StridedData<const float> weights_at_t{weights.data + t, weights.stride};+ accum_fn(v_record, weights_at_t, accum, num_group_heads, t, b_kv);+ }+}++// ---------------------------------------------------------------------------+// Q precision dispatch helper: resolves runtime Q element type to typed pointer.+// ---------------------------------------------------------------------------+template <typename Fn>+static void dispatch_q_precision(const PlainTensor& q_input,+ size_t b,+ size_t h_start,+ ov::element::Type q_precision,+ Fn&& fn,+ size_t q_idx = 0) {+ const size_t q_stride = q_input.stride(1);+ if (q_precision == ov::element::f16) {+ fn(StridedData<const ov::float16>{q_input.ptr<ov::float16>(b, h_start, q_idx), q_stride});+ } else if (q_precision == ov::element::bf16) {+ fn(StridedData<const ov::bfloat16>{q_input.ptr<ov::bfloat16>(b, h_start, q_idx), q_stride});+ } else {+ fn(StridedData<const float>{q_input.ptr<float>(b, h_start, q_idx), q_stride});+ }+}++// ---------------------------------------------------------------------------+// Total byte size of one cache record for `codec` at head_dim `head_dim`.+// Used for prefetch sizing.+// ---------------------------------------------------------------------------+template <typename View>+static inline size_t codec_record_bytes(const View& view, int head_dim) {+ (void)view;+ return static_cast<size_t>(head_dim) * View::decoder_t::bits / 8;+}++// ---------------------------------------------------------------------------+// Codec dispatch: maps runtime CacheCodec to concrete HeadCodec type.+// ---------------------------------------------------------------------------+template <typename Fn>+static void dispatch_codec(CacheCodec codec,+ int head_dim,+ size_t group_size,+ const PlainTensor& scale_zp,+ Fn&& fn,+ 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});+ }+ 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>>{{}});+ break;+ }+}++// ---------------------------------------------------------------------------++void mha_kv_cache(PlainTensor& q_input,+ const PlainTensor& key_cache,+ const PlainTensor& packed_value,+ const PlainTensor& alibi_mask,+ const PlainTensor& attention_mask,+ const PlainTensor& beams,+ PlainTensor& output_emb,+ PlainTensor& buf_attn_w,+ PlainTensor& buf_attn_score,+ bool has_out_transpose,+ float d_scale,+ CacheCodec k_codec,+ CacheCodec v_codec,+ 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) {+ // ---------------------------------------------------------------------------+ // Setup: dimensions, scratch buffers, precomputed constants.+ // ---------------------------------------------------------------------------+ const auto B = q_input.size(0);+ const auto num_q_heads = q_input.size(1);+ const auto q_len = q_input.size(2);+ const auto S = q_input.size(3); // K head dimension (= Q head dimension)+ const auto SV = value_head_dim; // V head dimension (may differ from S)+ const auto num_kv_heads = key_cache.size(1);+ const auto kv_len = key_cache.size(2);+ const size_t heads_per_kv_group = num_q_heads / num_kv_heads;+ const auto nthr = parallel_get_max_threads();+ const MhaKvTraversal kv_traversal{B, num_kv_heads, kv_len, heads_per_kv_group, nthr};++ if (d_scale == 0.0F) {+ d_scale = 1.0F / std::sqrt(static_cast<float>(S));+ }++ 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});++ // Precompute per-group Q sums for affine u8 deferred dequant optimization.+ // q_group_sums[b, h, m, group] = sum(q[b, h, m, group*gs .. (group+1)*gs]).+ // 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;+ PlainTensor q_group_sums_buf;+ if (use_affine_k) {+ q_group_sums_buf.resize<float>({B, num_q_heads, q_len, n_key_groups});+ cpu_parallel->parallel_for3d(B, num_q_heads, q_len, [&](size_t b, size_t h, size_t m_idx) {+ auto* sums = q_group_sums_buf.ptr<float>(b, h, m_idx);+ dispatch_q_precision(+ q_input,+ b,+ h,+ q_precision,+ [&](auto q) {+ using QT = std::remove_const_t<std::remove_pointer_t<decltype(q.data)>>;+ const QT* q_head = q[0]; // single head at (b, h)+ 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;+ size_t i = 0;+ for (; i + W <= key_group_size; i += W) {+ acc = acc + simd::load<simd::f32>(q_head + offset + i);+ }+ sums[g] = reduce(acc);+ for (; i < key_group_size; i++) {+ sums[g] += static_cast<float>(q_head[offset + i]);+ }+ }+ },+ m_idx);+ });+ }++ // For each query position m, phases 1-4 run independently. When q_len=1+ // (single-token decode) these loops execute once. When q_len>1 (fuse_concat+ // prompt), each position gets its own scores, softmax, and accumulation.++ // ---------------------------------------------------------------------------+ // Phase 1: Q·K scores for all query positions.+ // ---------------------------------------------------------------------------+ for (size_t m = 0; m < q_len; m++) {+ 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*/) {+ 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);+ const size_t stride_pos = key_cache.stride_bytes(2);+ const bool use_beams = beams && B > 1;+ 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};++ // 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;+ dispatch_q_precision(+ q_input,+ b,+ h_start,+ q_precision,+ [&](auto q) {+ dispatch_codec(+ k_codec,+ head_dim,+ key_group_size,+ k_scale_zp,+ [&](auto record_view) {+ auto scorer = QKScorer{q, record_view, entry_ctx};+ score_tokens(kv_base,+ stride_batch,+ stride_pos,+ beam_tbl_ptr,+ b,+ scores,+ run_len,+ num_group_heads,+ codec_record_bytes(record_view, head_dim),+ scorer);+ },+ q_group_sums,+ q_group_sums_stride);+ },+ m);+ });+ }++ // ---------------------------------------------------------------------------+ // Phase 2: Softmax — runs over all query positions at once.+ // ---------------------------------------------------------------------------+ mha_softmax(buf_attn_w,+ alibi_mask,+ attention_mask,+ sink_input,+ B,+ num_q_heads,+ q_len,+ kv_len,+ auto_causal,+ d_scale,+ cpu_parallel);++ // ---------------------------------------------------------------------------+ // Phases 3+4: V accumulation + reduce, per query position.+ // ---------------------------------------------------------------------------+ 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) {+ 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);+ const size_t stride_pos = packed_value.stride_bytes(2);+ const bool use_beams = beams && B > 1;+ const int32_t* beam_tbl_ptr = use_beams ? beams.ptr<int32_t>(b) + start_pos : nullptr;+ const float* weights_row_base = buf_attn_w.ptr<float>(b, h_start, m) + start_pos;+ 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};++ dispatch_codec(v_codec, head_dim, value_group_size, v_scale_zp, [&](auto record_view) {+ auto vaccum = VAccumulator{record_view, entry_ctx};+ accum_tokens(kv_base,+ stride_batch,+ stride_pos,+ beam_tbl_ptr,+ b,+ weights,+ accum,+ num_group_heads,+ run_len,+ codec_record_bytes(record_view, head_dim),+ vaccum);+ });+ },+ [&](size_t ithr) {+ for (size_t b = 0; b < B; ++b) {+ std::memset(buf_attn_score.ptr<float>(ithr, b, m, 0, 0),+ 0,+ buf_attn_score.stride(2) * sizeof(float));+ }+ });++ // Phase 4: Reduce for query position m.+ mha_reduce(buf_attn_score,+ output_emb,+ has_out_transpose,+ B,+ num_q_heads,+ 1, // reduce one query position at a time+ SV,+ nthr,+ cpu_parallel,+ m);+ }+}++} // namespace ov::Extensions::Cpu::XARCHdiff --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.hppnew file mode 100644index 00000000000..2feb3215baa--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_codec.hpp@@ -0,0 +1,45 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Generic codec-aware multi-head attention pipeline entry point.++#pragma once++#include <cstddef>++#include "codecs/cache_codec.hpp"+#include "cpu_parallel.hpp"+#include "openvino/core/type/element_type.hpp"+#include "utils/plain_tensor.hpp"++namespace ov::Extensions::Cpu::XARCH {++// Generic codec-aware fused multi-head attention pipeline.+// k_codec / v_codec: identify the encoding scheme of cached K/V.+// 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,+ const ov::intel_cpu::PlainTensor& packed_value,+ const ov::intel_cpu::PlainTensor& alibi_mask,+ const ov::intel_cpu::PlainTensor& attention_mask,+ const ov::intel_cpu::PlainTensor& beams,+ ov::intel_cpu::PlainTensor& output_emb,+ ov::intel_cpu::PlainTensor& buf_attn_w,+ 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,+ 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);++} // namespace ov::Extensions::Cpu::XARCHdiff --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.hppnew file mode 100644index 00000000000..467cd76afcd--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_kv_cache_reduce.hpp@@ -0,0 +1,88 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>++#include "cpu_parallel.hpp"+#include "nodes/kernels/simd/simd_loop.hpp"+#include "openvino/core/type/bfloat16.hpp"+#include "openvino/core/type/float16.hpp"+#include "utils/plain_tensor.hpp"++namespace ov::Extensions::Cpu::XARCH {++using ov::intel_cpu::CpuParallelPtr;+using ov::intel_cpu::PlainTensor;++// Sum per-thread accumulators: dst[i] = sum_t(src[i + t * stride]) for i in [0, dim).+// When T != float, converts f32 accumulator result to T on store.+// Uses simd_loop for automatic SIMD main loop + scalar tail handling.+template <typename T>+static void reduce_thread_accumulators(T* dst, const float* src, size_t stride, int dim, int nthr) {+ simd::simd_loop(dim, [&](int i, auto a) {+ using V = simd::vec<float, decltype(a)::isa_tag::value>;+ auto acc = simd::load<V>(src + i, a);+ const float* p = src + i + stride;+ for (int t = 1; t < nthr; t++) {+ acc = acc + simd::load<V>(p, a);+ p += stride;+ }+ simd::store(acc, dst + i, a);+ });+}++template <typename T>+static void mha_reduce_typed(const PlainTensor& attn_score,+ PlainTensor& output_emb,+ bool has_out_transpose,+ size_t B,+ size_t H,+ size_t q_len,+ size_t S,+ int nthr,+ const CpuParallelPtr& cpu_parallel,+ size_t q_offset) {+ 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);+ };+ if (q_len == 1) {+ cpu_parallel->parallel_for2d(B, H, [&](size_t b, size_t h) {+ reduce_body(b, h, 0);+ });+ } else {+ cpu_parallel->parallel_for3d(B, H, q_len, reduce_body);+ }+}++static void mha_reduce(const PlainTensor& attn_score,+ PlainTensor& output_emb,+ bool has_out_transpose,+ size_t B,+ size_t H,+ size_t q_len,+ size_t S,+ int nthr,+ const CpuParallelPtr& cpu_parallel,+ 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);+ } 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);+ } else {+ mha_reduce_typed<+ float>(attn_score, output_emb, has_out_transpose, B, H, q_len, S, nthr, cpu_parallel, q_offset);+ }+}++} // namespace ov::Extensions::Cpu::XARCHdiff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_single_token.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_single_token.cppindex 19e7411b228..d4c155db260 100644--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_single_token.cpp+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/mha_single_token.cpp@@ -31,21 +31,6 @@ namespace ov::Extensions::Cpu::XARCH {using namespace ov;-#if defined(HAVE_AVX2)--# define prefetch_bytes(bytes, sel, advance, src) \- { \- auto* p = reinterpret_cast<char*>(src); \- for (size_t i = 0; i < bytes; i += 64) \- _mm_prefetch(p + i + advance, sel); \- }--#else--# define prefetch_bytes(bytes, sel, advance, src)--#endif-template <typename TA, typename TB>static void cvt_copy(TA* dst, TB* src, size_t n) {size_t i = 0;diff --git a/src/plugins/intel_cpu/src/nodes/kernels/simd/README.md b/src/plugins/intel_cpu/src/nodes/kernels/simd/README.mdnew file mode 100644index 00000000000..37f8b42e4de--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/simd/README.md@@ -0,0 +1,229 @@+# SIMD Abstraction Layer++Namespace: `ov::Extensions::Cpu::XARCH::simd`++(`XARCH` is a macro set by OpenVINO's cross-compilation framework — it+resolves to `AVX2`, `AVX512F`, or `ANY` depending on the target ISA of each+translation unit.)++Compile-time abstraction over AVX-512 / AVX2 / scalar.+`vec<T, i>` wraps the native register. Operators are members, everything+else is a free function found via ADL.++## Files++| File | Contents |+|------|----------|+| `simd_common.hpp` | `isa` enum, `active_isa`, primary templates for `vec`/`mask` |+| `simd_scalar.hpp` | Scalar specializations (always available, no `#ifdef`) |+| `simd_avx2.hpp` | AVX2 specializations (no `#ifdef` inside) |+| `simd_avx512.hpp` | AVX-512 specializations (no `#ifdef` inside) |+| `simd.hpp` | Aggregator: includes above + aliases (`f32`, `i32`), load API, `table` |+| `simd_loop.hpp` | Unified loop/reduction frontend: `simd_loop`, `simd_loop_reduce`, active-aware wrappers |++Each per-ISA header includes `simd_common.hpp` and is self-contained. The+only `#ifdef` is in `simd.hpp` — one conditional include per ISA.++### Known dependency++`simd_avx2.hpp` and `simd_avx512.hpp` depend on `scaled_attn/common.hpp`+for `mm256_loadu_u4_to_f32` / `mm512_loadu_u4_to_f32` (used in+`load_u4_pair`). Moving this logic into simd would make the directory+fully self-contained.++## Usage++```cpp+#include "nodes/kernels/simd/simd.hpp"++using namespace ov::Extensions::Cpu::XARCH;++simd::f32 a(1.0f); // broadcast+auto b = simd::load<simd::f32>(ptr); // load (same-type or converting)+auto c = fmadd(a, b, simd::f32(0.0f)); // FMA (ADL from vec args)+store(c, out_ptr); // store (ADL)+float sum = reduce(c); // horizontal sum (ADL)++simd::table<16> cb(codebook_data); // 16-entry LUT in registers+auto decoded = cb.lookup(indices); // parallel LUT lookup+```++## simd_loop++`simd_loop.hpp` provides a higher-level frontend on top of `vec<T, i>` for+elementwise traversal and reduction kernels.++Elementwise traversal:++```cpp+simd::simd_loop(n, [&](int j, auto a) {+ auto v = simd::load<simd::f32>(ptr + j, a);+ ...+});+```++Reduction kernels:++```cpp+float sum = simd::simd_loop_reduce<4>(+ n,+ [&](int j, simd::f32& acc) { ... },+ [&](int j, float& tail) { ... });+```++The intent is:++- write the loop body once+- keep tail handling in one place+- preserve explicit vector accumulators for hot reductions++### Current status++The current backend lowering is still simple:++- `scalar`+ - scalar loop+- `AVX2`+ - SIMD main loop + scalar tail+- `AVX-512`+ - SIMD main loop + scalar tail++So the frontend abstraction is in place, but per-ISA tail strategies are+not fully implemented yet.++### Evolution direction++The intended evolution is:++- `AVX2`+ - SIMD main loop + scalar tail+- `AVX-512`+ - SIMD main loop + masked tail chunk+- future `SVE`+ - predicated loop+- future `RVV`+ - VL-driven loop++That requires evolution in four places:++- `for_each_chunk<I>()`+ - from generic non-scalar path to real per-ISA loop drivers+- `active_lanes<I>`+ - from compile-time tag to a real active-lane context where needed+- `load/store/reduce(..., active_lanes<I>)`+ - from thin wrappers to tail-aware operations+- `simd_loop_reduce`+ - from fixed scalar tail to ISA-specific tail handling++## Adding a New ISA++### Step 1: Add the enum value++In `simd_common.hpp`, add to the enum:++```cpp+enum class isa { scalar, avx2, avx512, neon /* new */ };+```++### Step 2: Create the per-ISA header++Create `simd_<name>.hpp` (e.g. `simd_neon.hpp`). Use any existing file as+template. The file must:++1. Include `simd_common.hpp`+2. Open `namespace ov::Extensions::Cpu::XARCH::simd`+3. Specialize `vec<float, isa::neon>` and `vec<int32_t, isa::neon>` with:+ - `using element_type = ...;`+ - `static constexpr int width = ...;`+ - `static constexpr isa isa_value = ...;`+ - Zero constructor, broadcast constructor, raw register constructor+ - `operator+`, `-`, `*` (float) and `operator&` (int32)+4. Provide all required free functions (see checklist below)+5. Close the namespace++No `#ifdef` guards inside the file.++### Step 3: Include from simd.hpp++Add one conditional include in `simd.hpp`:++```cpp+#if defined(HAVE_NEON)+#include "simd_neon.hpp"+#endif+```++### Step 4: Set active_isa++In `simd_common.hpp`, add the preprocessor branch:++```cpp+#if defined(HAVE_AVX512F)+inline constexpr isa active_isa = isa::avx512;+#elif defined(HAVE_AVX2)+inline constexpr isa active_isa = isa::avx2;+#elif defined(HAVE_NEON) // new+inline constexpr isa active_isa = isa::neon;+#else+inline constexpr isa active_isa = isa::scalar;+#endif+```++### Free function checklist++Every per-ISA header must provide these free functions for `vec<float, isa::X>`:++**Required** (used by codec infrastructure):++| Function | Signature |+|----------|-----------|+| `store` | `void store(vec<float, I> v, float* p)` |+| `store` | `void store(vec<int32_t, I> v, int32_t* p)` |+| `reduce` | `float reduce(vec<float, I> v)` |+| `fmadd` | `vec<float, I> fmadd(vec<float, I> a, b, c)` |+| `load` (float) | `vec<float, I> load(const float* p, vec<float, I>*)` |+| `load` (f16) | `vec<float, I> load(const ov::float16* p, vec<float, I>*)` |+| `load` (bf16) | `vec<float, I> load(const ov::bfloat16* p, vec<float, I>*)` |+| `load` (u8→f32) | `vec<float, I> load(const uint8_t* p, vec<float, I>*)` |+| `load` (i32) | `vec<int32_t, I> load(const int32_t* p, vec<int32_t, I>*)` |+| `load` (u8→i32) | `vec<int32_t, I> load(const uint8_t* p, vec<int32_t, I>*)` |+| `partial_load` | `vec<float, I> partial_load(uint32_t k, const float* p, vec<float, I>*)` |+| `load_u4` | `vec<float, I> load_u4(const uint8_t* p, int bit_offset, vec<float, I>*)` |+| `load_u4_pair` | `void load_u4_pair(const uint8_t* p, vec<float, I>& lo, vec<float, I>& hi)` |+| `load_u8_pair` | `void load_u8_pair(const uint8_t* p, vec<float, I>& lo, vec<float, I>& hi)` |+| `permute` | `vec<float, I> permute(vec<float, I> table, vec<int32_t, I> idx)` |+| `srlv` | `vec<int32_t, I> srlv(vec<int32_t, I> val, vec<int32_t, I> shift)` |+| `select` | `vec<float, I> select(mask<I> m, vec<float, I> if_false, vec<float, I> if_true)` |+| comparisons | `mask<I> operator>(vec<int32_t, I>, vec<int32_t, I>)` (all 6) |++**Optional** (only needed for specific code paths):++| Function | Used by |+|----------|---------|+| `permute2` | `table::lookup` (N > W, AVX-512 path) |+| `unpack_lo/hi` | Polar interleave/deinterleave |+| `unpack_lo/hi_64` | AVX2 deinterleave |+| `shuffle<imm>` | AVX2 deinterleave |+| `permute_lanes<ctrl>` | AVX2 interleave |+| `permute_64<ctrl>` | AVX2 deinterleave |+| `broadcast_halves` | 3-bit unpack (AVX-512 only) |+| `select` (4-arg) | AVX2 compare+blend convenience |++Scalar stubs (assert-false or static_assert) are acceptable for optional+functions that are guarded by `if constexpr(i != isa::scalar)` at call sites.++### No changes needed in vec consumers++The codec infrastructure (`codecs.hpp`, `turboq_codecs.hpp`, `polar_codecs.hpp`,+`mha_kv_cache_codec.cpp`) is generic over `vec<T, i>`.++If a new ISA only needs `vec<T, i>` support, that often requires no+consumer changes outside this directory.++If the ISA is also meant to participate in `simd_loop`, then adding a new+per-ISA header is not enough. You should also consider:++- `active_lanes<I>`+- `for_each_chunk<I>()`+- active-aware `load/store/reduce`+- whether the ISA should use scalar tail, masked tail, or predicated/VL loopdiff --git a/src/plugins/intel_cpu/src/nodes/kernels/simd/simd.hpp b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd.hppnew file mode 100644index 00000000000..061d563c602--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd.hpp@@ -0,0 +1,109 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// simd::vec<T, i> — compile-time abstraction over AVX-512 / AVX2 / scalar.+//+// vec<T, i> wraps the native register. Operators (+, -, *, &) are members.+// Everything else is a free function: load, store, reduce, fmadd, select,+// permute, shuffle, etc. — found via ADL from vec/mask arguments.+//+// File layout:+// simd_common.hpp — isa enum, active_isa, primary templates+// simd_scalar.hpp — scalar specializations (always available)+// simd_avx2.hpp — AVX2 specializations (no #ifdef inside)+// simd_avx512.hpp — AVX-512 specializations (no #ifdef inside)+// simd.hpp (this) — aggregator: includes above + aliases, load API, table++#pragma once++#include "simd_common.hpp"+#include "simd_scalar.hpp"+#if defined(HAVE_AVX2)+# include "simd_avx2.hpp"+#endif+#if defined(HAVE_AVX512F)+# include "simd_avx512.hpp"+#endif++namespace ov::Extensions::Cpu::XARCH::simd {++// ===== Convenience aliases ================================================++// Templated aliases: f32_t<I> / i32_t<I> pick an explicit ISA.+template <isa I = active_isa>+using f32_t = vec<float, I>;+template <isa I = active_isa>+using i32_t = vec<int32_t, I>;++// Shorthand for active ISA — used everywhere except where a specific ISA is needed.+using f32 = f32_t<>;+using i32 = i32_t<>;++// ===== Public load API ====================================================++template <typename V, typename SrcT>+inline V load(const SrcT* ptr) {+ return load(ptr, static_cast<V*>(nullptr));+}++template <typename V>+inline V partial_load(uint32_t k, const typename V::element_type* ptr) {+ return partial_load(k, ptr, static_cast<V*>(nullptr));+}++template <typename V>+inline V load_u4(const uint8_t* ptr, int bit_offset) {+ return load_u4(ptr, bit_offset, static_cast<V*>(nullptr));+}++// ===== table: fixed-size SIMD look-up table ===============================++template <int N, isa i = active_isa>+struct table {+ using V = vec<float, i>;+ using VI = vec<int32_t, i>;+ static constexpr int W = V::width;+ static constexpr int n_regs = (N + W - 1) / W;+ static_assert(n_regs <= 4, "table supports up to 4 * vec::width entries");+ V regs[n_regs];++ explicit table(const float* data) {+ for (int r = 0; r < n_regs; r++) {+ int remaining = N - r * W;+ if (remaining >= W) {+ regs[r] = load<V>(data + r * W);+ } else {+ regs[r] = partial_load<V>((1U << remaining) - 1, data + r * W);+ }+ }+ }++ [[nodiscard]] V lookup(VI idx) const {+ if constexpr (n_regs == 1) {+ return permute(regs[0], idx);+ } else if constexpr (n_regs == 2 && i == isa::avx512) {+ return permute2(regs[0], idx, regs[1]);+ } else {+ auto lane = idx & VI{W - 1};+ auto res = select(idx > VI{W - 1}, permute(regs[0], lane), permute(regs[1], lane));+ if constexpr (n_regs >= 3) {+ res = select(idx > VI{2 * W - 1}, res, permute(regs[2], lane));+ }+ if constexpr (n_regs >= 4) {+ res = select(idx > VI{3 * W - 1}, res, permute(regs[3], lane));+ }+ return res;+ }+ }+};++template <int N>+struct table<N, isa::scalar> {+ const float* data;+ explicit table(const float* p) : data(p) {}+ [[nodiscard]] vec<float, isa::scalar> lookup(vec<int32_t, isa::scalar> idx) const {+ return {data[idx.v]};+ }+};++} // namespace ov::Extensions::Cpu::XARCH::simddiff --git a/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_avx2.hpp b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_avx2.hppnew file mode 100644index 00000000000..056cc911df7--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_avx2.hpp@@ -0,0 +1,215 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// AVX2 ISA specializations for simd::vec, simd::mask, and free functions.+// Included only when HAVE_AVX2 is defined — no #ifdef guards inside.++#pragma once++#include <immintrin.h>++#include "nodes/kernels/scaled_attn/common.hpp"+#include "simd_common.hpp"++namespace ov::Extensions::Cpu::XARCH::simd {++// --- vec<float> ------------------------------------------------------------++template <>+struct vec<float, isa::avx2> {+ using element_type = float;+ static constexpr int width = 8;+ static constexpr isa isa_value = isa::avx2;+ __m256 v;++ vec() : v(_mm256_setzero_ps()) {}+ vec(float val) : v(_mm256_set1_ps(val)) {} // NOLINT(google-explicit-constructor)+ vec(__m256 val) : v(val) {} // NOLINT(google-explicit-constructor)++ vec operator+(vec b) const {+ return {_mm256_add_ps(v, b.v)};+ }+ vec operator-(vec b) const {+ return {_mm256_sub_ps(v, b.v)};+ }+ vec operator*(vec b) const {+ return {_mm256_mul_ps(v, b.v)};+ }+};++inline void store(vec<float, isa::avx2> v, float* p) {+ _mm256_storeu_ps(p, v.v);+}+inline void store(vec<float, isa::avx2> v, ov::bfloat16* p) {+ // f32 → bf16: round-to-nearest-even, keep upper 16 bits.+ auto i32 = _mm256_castps_si256(v.v);+ auto lsb = _mm256_and_si256(_mm256_srli_epi32(i32, 16), _mm256_set1_epi32(1));+ auto rounded = _mm256_srli_epi32(_mm256_add_epi32(i32, _mm256_add_epi32(_mm256_set1_epi32(0x00007FFF), lsb)), 16);+ // Extract low 16 bits from each 32-bit lane without saturation via pshufb.+ const auto pack_mask = _mm_setr_epi8(0, 1, 4, 5, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1);+ auto lo = _mm_shuffle_epi8(_mm256_castsi256_si128(rounded), pack_mask);+ auto hi = _mm_shuffle_epi8(_mm256_extracti128_si256(rounded, 1), pack_mask);+ _mm_storeu_si128(reinterpret_cast<__m128i*>(p), _mm_unpacklo_epi64(lo, hi));+}+inline void store(vec<float, isa::avx2> v, ov::float16* p) {+ _mm_storeu_si128(reinterpret_cast<__m128i*>(p), _mm256_cvtps_ph(v.v, _MM_FROUND_TO_NEAREST_INT));+}+inline float reduce(vec<float, isa::avx2> v) {+ __m128 hi = _mm256_extractf128_ps(v.v, 1);+ __m128 lo = _mm256_castps256_ps128(v.v);+ lo = _mm_add_ps(lo, hi);+ lo = _mm_hadd_ps(lo, lo);+ lo = _mm_hadd_ps(lo, lo);+ return _mm_cvtss_f32(lo);+}+inline vec<float, isa::avx2> fmadd(vec<float, isa::avx2> a, vec<float, isa::avx2> b, vec<float, isa::avx2> c) {+ return {_mm256_fmadd_ps(a.v, b.v, c.v)};+}++// --- vec<int32_t> ----------------------------------------------------------++template <>+struct vec<int32_t, isa::avx2> {+ using element_type = int32_t;+ static constexpr int width = 8;+ static constexpr isa isa_value = isa::avx2;+ __m256i v;++ vec() : v(_mm256_setzero_si256()) {}+ vec(__m256i val) : v(val) {} // NOLINT(google-explicit-constructor)+ vec(int32_t val) : v(_mm256_set1_epi32(val)) {} // NOLINT(google-explicit-constructor)++ static vec widen_u8(__m128i bytes) {+ return {_mm256_cvtepu8_epi32(bytes)};+ }+ vec operator&(vec b) const {+ return {_mm256_and_si256(v, b.v)};+ }+};++inline void store(vec<int32_t, isa::avx2> v, int32_t* p) {+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(p), v.v);+}++// --- loads -----------------------------------------------------------------++inline vec<float, isa::avx2> load(const float* p, vec<float, isa::avx2>* /*tag*/) {+ return {_mm256_loadu_ps(p)};+}+inline vec<float, isa::avx2> load(const ov::float16* p, vec<float, isa::avx2>* /*tag*/) {+ return {_mm256_cvtph_ps(_mm_loadu_si128(reinterpret_cast<const __m128i*>(p)))};+}+inline vec<float, isa::avx2> load(const ov::bfloat16* p, vec<float, isa::avx2>* /*tag*/) {+ auto raw = _mm_loadu_si128(reinterpret_cast<const __m128i*>(p));+ return {_mm256_castsi256_ps(_mm256_slli_epi32(_mm256_cvtepu16_epi32(raw), 16))};+}+inline vec<float, isa::avx2> load(const uint8_t* p, vec<float, isa::avx2>* /*tag*/) {+ return {_mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(_mm_loadl_epi64(reinterpret_cast<const __m128i*>(p))))};+}+inline vec<float, isa::avx2> partial_load(uint32_t k, const float* p, vec<float, isa::avx2>* /*tag*/) {+ const __m256i bit_masks = _mm256_setr_epi32(1, 2, 4, 8, 16, 32, 64, 128);+ __m256i kmask =+ _mm256_cmpeq_epi32(_mm256_and_si256(_mm256_set1_epi32(static_cast<int32_t>(k)), bit_masks), bit_masks);+ return {_mm256_maskload_ps(p, kmask)};+}+inline vec<float, isa::avx2> load_u4(const uint8_t* p, int /*bit_offset*/, vec<float, isa::avx2>* /*tag*/) {+ const __m128i nibble_mask = _mm_set1_epi8(0x0F);+ __m128i raw = _mm_cvtsi32_si128(*reinterpret_cast<const int32_t*>(p));+ __m128i unpacked =+ _mm_unpacklo_epi8(_mm_and_si128(_mm_srli_epi16(raw, 4), nibble_mask), _mm_and_si128(raw, nibble_mask));+ return {_mm256_cvtepi32_ps(_mm256_cvtepu8_epi32(unpacked))};+}+inline void load_u4_pair(const uint8_t* p, vec<float, isa::avx2>& lo, vec<float, isa::avx2>& hi) {+ mm256_loadu_u4_to_f32(p, lo.v, hi.v);+}+inline void load_u8_pair(const uint8_t* p, vec<float, isa::avx2>& lo, vec<float, isa::avx2>& hi) {+ lo = load(p, static_cast<vec<float, isa::avx2>*>(nullptr));+ hi = load(p + 8, static_cast<vec<float, isa::avx2>*>(nullptr));+}++inline vec<int32_t, isa::avx2> load(const int32_t* p, vec<int32_t, isa::avx2>* /*tag*/) {+ return {_mm256_loadu_si256(reinterpret_cast<const __m256i*>(p))};+}+inline vec<int32_t, isa::avx2> load(const uint8_t* p, vec<int32_t, isa::avx2>* /*tag*/) {+ return {_mm256_cvtepu8_epi32(_mm_loadl_epi64(reinterpret_cast<const __m128i*>(p)))};+}++// --- arithmetic / permute --------------------------------------------------++inline vec<int32_t, isa::avx2> srlv(vec<int32_t, isa::avx2> val, vec<int32_t, isa::avx2> shift) {+ return {_mm256_srlv_epi32(val.v, shift.v)};+}++inline vec<float, isa::avx2> permute(vec<float, isa::avx2> table, vec<int32_t, isa::avx2> idx) {+ return {_mm256_permutevar8x32_ps(table.v, idx.v)};+}++inline vec<float, isa::avx2> unpack_lo(vec<float, isa::avx2> a, vec<float, isa::avx2> b) {+ return {_mm256_unpacklo_ps(a.v, b.v)};+}+inline vec<float, isa::avx2> unpack_hi(vec<float, isa::avx2> a, vec<float, isa::avx2> b) {+ return {_mm256_unpackhi_ps(a.v, b.v)};+}++template <int imm>+inline vec<float, isa::avx2> shuffle(vec<float, isa::avx2> a, vec<float, isa::avx2> b) {+ return {_mm256_shuffle_ps(a.v, b.v, imm)};+}++inline vec<float, isa::avx2> unpack_lo_64(vec<float, isa::avx2> a, vec<float, isa::avx2> b) {+ return {_mm256_castpd_ps(_mm256_unpacklo_pd(_mm256_castps_pd(a.v), _mm256_castps_pd(b.v)))};+}+inline vec<float, isa::avx2> unpack_hi_64(vec<float, isa::avx2> a, vec<float, isa::avx2> b) {+ return {_mm256_castpd_ps(_mm256_unpackhi_pd(_mm256_castps_pd(a.v), _mm256_castps_pd(b.v)))};+}++template <int ctrl>+inline vec<float, isa::avx2> permute_64(vec<float, isa::avx2> a) {+ return {_mm256_castpd_ps(_mm256_permute4x64_pd(_mm256_castps_pd(a.v), ctrl))};+}++template <int ctrl>+inline vec<float, isa::avx2> permute_lanes(vec<float, isa::avx2> a, vec<float, isa::avx2> b) {+ return {_mm256_permute2f128_ps(a.v, b.v, ctrl)};+}++// --- mask ------------------------------------------------------------------++template <>+struct mask<isa::avx2> {+ __m256i v;+ mask() : v(_mm256_setzero_si256()) {}+ mask(__m256i val) : v(val) {} // NOLINT(google-explicit-constructor)+};++inline mask<isa::avx2> operator>(vec<int32_t, isa::avx2> a, vec<int32_t, isa::avx2> b) {+ return {_mm256_cmpgt_epi32(a.v, b.v)};+}+inline mask<isa::avx2> operator<(vec<int32_t, isa::avx2> a, vec<int32_t, isa::avx2> b) {+ return b > a;+}+inline mask<isa::avx2> operator>=(vec<int32_t, isa::avx2> a, vec<int32_t, isa::avx2> b) {+ return {_mm256_or_si256(_mm256_cmpgt_epi32(a.v, b.v), _mm256_cmpeq_epi32(a.v, b.v))};+}+inline mask<isa::avx2> operator<=(vec<int32_t, isa::avx2> a, vec<int32_t, isa::avx2> b) {+ return b >= a;+}+inline mask<isa::avx2> operator==(vec<int32_t, isa::avx2> a, vec<int32_t, isa::avx2> b) {+ return {_mm256_cmpeq_epi32(a.v, b.v)};+}+inline mask<isa::avx2> operator!=(vec<int32_t, isa::avx2> a, vec<int32_t, isa::avx2> b) {+ return {_mm256_xor_si256(_mm256_cmpeq_epi32(a.v, b.v), _mm256_set1_epi32(-1))};+}++inline vec<float, isa::avx2> select(mask<isa::avx2> m, vec<float, isa::avx2> if_false, vec<float, isa::avx2> if_true) {+ return {_mm256_blendv_ps(if_false.v, if_true.v, _mm256_castsi256_ps(m.v))};+}++inline vec<float, isa::avx2> select(vec<int32_t, isa::avx2> val,+ vec<int32_t, isa::avx2> threshold,+ vec<float, isa::avx2> if_false,+ vec<float, isa::avx2> if_true) {+ return select(val > threshold, if_false, if_true);+}++} // namespace ov::Extensions::Cpu::XARCH::simddiff --git a/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_avx512.hpp b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_avx512.hppnew file mode 100644index 00000000000..a30a568a9d2--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_avx512.hpp@@ -0,0 +1,193 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// AVX-512 ISA specializations for simd::vec, simd::mask, and free functions.+// Included only when HAVE_AVX512F is defined — no #ifdef guards inside.++#pragma once++#include <immintrin.h>++// @todo get rid of this dependency by moving logic from common.hpp to simd and use simd everywhere+// this will also make simd selfcontained and allow to write perfect unit tests+#include "nodes/kernels/scaled_attn/common.hpp"+#include "simd_common.hpp"++namespace ov::Extensions::Cpu::XARCH::simd {++// --- vec<float> ------------------------------------------------------------++template <>+struct vec<float, isa::avx512> {+ using element_type = float;+ static constexpr int width = 16;+ static constexpr isa isa_value = isa::avx512;+ __m512 v;++ vec() : v(_mm512_setzero_ps()) {}+ vec(float val) : v(_mm512_set1_ps(val)) {} // NOLINT(google-explicit-constructor)+ vec(__m512 val) : v(val) {} // NOLINT(google-explicit-constructor)++ vec operator+(vec b) const {+ return {_mm512_add_ps(v, b.v)};+ }+ vec operator-(vec b) const {+ return {_mm512_sub_ps(v, b.v)};+ }+ vec operator*(vec b) const {+ return {_mm512_mul_ps(v, b.v)};+ }+};++inline void store(vec<float, isa::avx512> v, float* p) {+ _mm512_storeu_ps(p, v.v);+}+inline void store(vec<float, isa::avx512> v, ov::bfloat16* p) {+ // f32 → bf16: round-to-nearest-even, keep upper 16 bits.+ auto i32 = _mm512_castps_si512(v.v);+ auto lsb = _mm512_and_epi32(_mm512_srli_epi32(i32, 16), _mm512_set1_epi32(1));+ auto rounded = _mm512_srli_epi32(_mm512_add_epi32(i32, _mm512_add_epi32(_mm512_set1_epi32(0x00007FFF), lsb)), 16);+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(p), _mm512_cvtepi32_epi16(rounded));+}+inline void store(vec<float, isa::avx512> v, ov::float16* p) {+ _mm256_storeu_si256(reinterpret_cast<__m256i*>(p), _mm512_cvtps_ph(v.v, _MM_FROUND_TO_NEAREST_INT));+}+inline float reduce(vec<float, isa::avx512> v) {+ return _mm512_reduce_add_ps(v.v);+}+inline vec<float, isa::avx512> fmadd(vec<float, isa::avx512> a, vec<float, isa::avx512> b, vec<float, isa::avx512> c) {+ return {_mm512_fmadd_ps(a.v, b.v, c.v)};+}++// --- vec<int32_t> ----------------------------------------------------------++template <>+struct vec<int32_t, isa::avx512> {+ using element_type = int32_t;+ static constexpr int width = 16;+ static constexpr isa isa_value = isa::avx512;+ __m512i v;++ vec() : v(_mm512_setzero_si512()) {}+ vec(__m512i val) : v(val) {} // NOLINT(google-explicit-constructor)+ vec(int32_t val) : v(_mm512_set1_epi32(val)) {} // NOLINT(google-explicit-constructor)++ static vec widen_u8(__m128i bytes) {+ return {_mm512_cvtepu8_epi32(bytes)};+ }+ vec operator&(vec b) const {+ return {_mm512_and_epi32(v, b.v)};+ }++ static vec broadcast_halves(int32_t lo, int32_t hi) {+ return {_mm512_mask_set1_epi32(_mm512_set1_epi32(lo), 0xFF00, hi)};+ }+};++inline void store(vec<int32_t, isa::avx512> v, int32_t* p) {+ _mm512_storeu_si512(reinterpret_cast<__m512i*>(p), v.v);+}++// --- loads -----------------------------------------------------------------++inline vec<float, isa::avx512> load(const float* p, vec<float, isa::avx512>* /*tag*/) {+ return {_mm512_loadu_ps(p)};+}+inline vec<float, isa::avx512> load(const ov::float16* p, vec<float, isa::avx512>* /*tag*/) {+ return {_mm512_cvtph_ps(_mm256_loadu_si256(reinterpret_cast<const __m256i*>(p)))};+}+inline vec<float, isa::avx512> load(const ov::bfloat16* p, vec<float, isa::avx512>* /*tag*/) {+ auto raw = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(p));+ return {_mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu16_epi32(raw), 16))};+}+inline vec<float, isa::avx512> load(const uint8_t* p, vec<float, isa::avx512>* /*tag*/) {+ return {_mm512_cvtepi32_ps(_mm512_cvtepu8_epi32(_mm_loadu_si128(reinterpret_cast<const __m128i*>(p))))};+}+inline vec<float, isa::avx512> partial_load(uint32_t k, const float* p, vec<float, isa::avx512>* /*tag*/) {+ return {_mm512_maskz_loadu_ps(static_cast<__mmask16>(k), p)};+}+inline vec<float, isa::avx512> load_u4(const uint8_t* p, int /*bit_offset*/, vec<float, isa::avx512>* /*tag*/) {+ const __m128i nibble_mask = _mm_set1_epi8(0x0F);+ __m128i raw = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(p));+ __m128i unpacked =+ _mm_unpacklo_epi8(_mm_and_si128(_mm_srli_epi16(raw, 4), nibble_mask), _mm_and_si128(raw, nibble_mask));+ return {_mm512_cvtepi32_ps(_mm512_cvtepu8_epi32(unpacked))};+}+inline void load_u4_pair(const uint8_t* p, vec<float, isa::avx512>& lo, vec<float, isa::avx512>& hi) {+ mm512_loadu_u4_to_f32(p, lo.v, hi.v);+}+inline void load_u8_pair(const uint8_t* p, vec<float, isa::avx512>& lo, vec<float, isa::avx512>& hi) {+ lo = load(p, static_cast<vec<float, isa::avx512>*>(nullptr));+ hi = load(p + 16, static_cast<vec<float, isa::avx512>*>(nullptr));+}++inline vec<int32_t, isa::avx512> load(const int32_t* p, vec<int32_t, isa::avx512>* /*tag*/) {+ return {_mm512_loadu_si512(reinterpret_cast<const __m512i*>(p))};+}+inline vec<int32_t, isa::avx512> load(const uint8_t* p, vec<int32_t, isa::avx512>* /*tag*/) {+ return {_mm512_cvtepu8_epi32(_mm_loadu_si128(reinterpret_cast<const __m128i*>(p)))};+}++// --- arithmetic / permute --------------------------------------------------++inline vec<int32_t, isa::avx512> srlv(vec<int32_t, isa::avx512> val, vec<int32_t, isa::avx512> shift) {+ return {_mm512_srlv_epi32(val.v, shift.v)};+}++inline vec<float, isa::avx512> permute(vec<float, isa::avx512> table, vec<int32_t, isa::avx512> idx) {+ return {_mm512_permutexvar_ps(idx.v, table.v)};+}++inline vec<float, isa::avx512> permute2(vec<float, isa::avx512> table_lo,+ vec<int32_t, isa::avx512> idx,+ vec<float, isa::avx512> table_hi) {+ return {_mm512_permutex2var_ps(table_lo.v, idx.v, table_hi.v)};+}++template <int imm>+inline vec<float, isa::avx512> shuffle(vec<float, isa::avx512> a, vec<float, isa::avx512> b) {+ return {_mm512_shuffle_ps(a.v, b.v, imm)};+}++inline vec<float, isa::avx512> unpack_lo(vec<float, isa::avx512> a, vec<float, isa::avx512> b) {+ return {_mm512_unpacklo_ps(a.v, b.v)};+}+inline vec<float, isa::avx512> unpack_hi(vec<float, isa::avx512> a, vec<float, isa::avx512> b) {+ return {_mm512_unpackhi_ps(a.v, b.v)};+}++// --- mask ------------------------------------------------------------------++template <>+struct mask<isa::avx512> {+ __mmask16 v;+ mask() : v(0) {}+ mask(__mmask16 val) : v(val) {} // NOLINT(google-explicit-constructor)+};++inline mask<isa::avx512> operator>(vec<int32_t, isa::avx512> a, vec<int32_t, isa::avx512> b) {+ return {_mm512_cmpgt_epi32_mask(a.v, b.v)};+}+inline mask<isa::avx512> operator<(vec<int32_t, isa::avx512> a, vec<int32_t, isa::avx512> b) {+ return {_mm512_cmplt_epi32_mask(a.v, b.v)};+}+inline mask<isa::avx512> operator>=(vec<int32_t, isa::avx512> a, vec<int32_t, isa::avx512> b) {+ return {_mm512_cmpge_epi32_mask(a.v, b.v)};+}+inline mask<isa::avx512> operator<=(vec<int32_t, isa::avx512> a, vec<int32_t, isa::avx512> b) {+ return {_mm512_cmple_epi32_mask(a.v, b.v)};+}+inline mask<isa::avx512> operator==(vec<int32_t, isa::avx512> a, vec<int32_t, isa::avx512> b) {+ return {_mm512_cmpeq_epi32_mask(a.v, b.v)};+}+inline mask<isa::avx512> operator!=(vec<int32_t, isa::avx512> a, vec<int32_t, isa::avx512> b) {+ return {_mm512_cmpneq_epi32_mask(a.v, b.v)};+}++inline vec<float, isa::avx512> select(mask<isa::avx512> m,+ vec<float, isa::avx512> if_false,+ vec<float, isa::avx512> if_true) {+ return {_mm512_mask_blend_ps(m.v, if_false.v, if_true.v)};+}++} // namespace ov::Extensions::Cpu::XARCH::simddiff --git a/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_common.hpp b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_common.hppnew file mode 100644index 00000000000..f0055dc4a93--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_common.hpp@@ -0,0 +1,51 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Common declarations for the simd namespace: isa enum, active_isa,+// active_lanes execution context, primary templates for vec and mask,+// and utility constexpr functions.+// No ISA-specific code — included by all per-ISA headers.++#pragma once++#include <cstdint>+#include <type_traits>++namespace ov::Extensions::Cpu::XARCH::simd {++enum class isa : uint8_t { scalar, avx2, avx512 };++#if defined(HAVE_AVX512F)+inline constexpr isa active_isa = isa::avx512;+#elif defined(HAVE_AVX2)+inline constexpr isa active_isa = isa::avx2;+#else+inline constexpr isa active_isa = isa::scalar;+#endif++constexpr int shuffle_ctrl(int d3, int d2, int d1, int d0) {+ return (d3 << 6) | (d2 << 4) | (d1 << 2) | d0;+}++constexpr int lane_ctrl(int out0, int out1) {+ return out0 | (out1 << 4);+}++template <typename T = float, isa i = active_isa>+struct vec;++template <isa i>+struct mask;++// ---------------------------------------------------------------------------+// active_lanes<I>: execution context for one SIMD iteration.+// Carries the ISA at compile time. Bodies receive this to determine width.+// Future: SVE/RVV overloads will carry predicate/VL state.+// ---------------------------------------------------------------------------++template <isa I>+struct active_lanes {+ using isa_tag = std::integral_constant<isa, I>;+};++} // namespace ov::Extensions::Cpu::XARCH::simddiff --git a/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_loop.hpp b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_loop.hppnew file mode 100644index 00000000000..512a628178b--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_loop.hpp@@ -0,0 +1,149 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// simd_loop: unified SIMD iteration with automatic tail handling.+//+// The loop body is written once, generic over ISA. The loop driver+// instantiates it at the active ISA for the main loop and at scalar+// ISA for the tail (x86/NEON) or with a predicate (SVE/RVV, future).+//+// See simd_loop.md (RFC) for design rationale.++#pragma once++#include <type_traits>+#include <utility>++#include "simd.hpp"++namespace ov::Extensions::Cpu::XARCH::simd {++// active_lanes<I> is defined in simd_common.hpp — available here via simd.hpp.++// ---------------------------------------------------------------------------+// Active-aware load/store: thin wrappers that delegate to existing per-ISA+// free functions. The active_lanes parameter selects the ISA at compile time.+// Future: SVE/RVV overloads will use the predicate/vl from active_lanes.+// ---------------------------------------------------------------------------++// 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>) {+ 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>) {+ store(v, ptr);+}++// Reduce: horizontal sum of active lanes → scalar float.+// 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>) {+ return reduce(v);+}++// ---------------------------------------------------------------------------+// for_each_chunk<I>: ISA-specific loop driver.+//+// x86 (AVX2/AVX512) and NEON: SIMD main loop + scalar tail.+// Scalar: element-by-element.+// Future SVE: single predicated loop.+// Future RVV: single VL-adaptive loop.+//+// Body signature: body(int offset, active_lanes<I> a)+// Body is called with active_lanes<I> for full-width iterations and+// active_lanes<isa::scalar> for tail elements.+// ---------------------------------------------------------------------------++template <isa I, typename 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>{});+ }+ } else {+ constexpr int W = vec<float, I>::width;+ int j = 0;+ for (; j + W - 1 < n; j += W) {+ body(j, active_lanes<I>{});+ }+ for (; j < n; j++) {+ body(j, active_lanes<isa::scalar>{});+ }+ }+}++// ---------------------------------------------------------------------------+// simd_loop: public frontend — dispatches to the active ISA loop driver.+// ---------------------------------------------------------------------------++template <typename Body>+inline void simd_loop(int n, Body&& body) {+ for_each_chunk<active_isa>(n, std::forward<Body>(body));+}++// ---------------------------------------------------------------------------+// Compile-time unroll helper.+// Calls fn(integral_constant<int, 0>{}), fn(integral_constant<int, 1>{}), ...+// ---------------------------------------------------------------------------++template <int N, typename Fn, int... Is>+inline void unroll_impl(Fn&& fn, std::integer_sequence<int, Is...>) {+ (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>{});+}++// ---------------------------------------------------------------------------+// simd_loop_reduce: reduction-oriented SIMD loop with explicit vector+// accumulators, compile-time unrolling, and scalar tail.+//+// Maintains Unroll independent vector accumulators for FMA latency hiding.+// main_body(int offset, f32& acc): called per W-wide SIMD chunk.+// Driver handles unrolling — body sees one chunk at a time.+// tail_body(int offset, float& tail): called per scalar tail element.+// Returns: reduce(acc[0] + acc[1] + ... + acc[Unroll-1]) + tail.+//+// For hot reduction kernels (dot product, norm, score accumulation) where+// per-iteration reduce in simd_loop would be too expensive.+// ---------------------------------------------------------------------------++template <int Unroll = 4, typename MainBody, typename TailBody>+inline float simd_loop_reduce(int n, MainBody&& main_body, TailBody&& tail_body) {+ constexpr int W = f32::width;++ f32 acc[Unroll]{};+ float tail_acc = 0.0F;+ int j = 0;++ // Unrolled main loop: Unroll × W elements per outer iteration.+ for (; j + Unroll * W - 1 < n; j += Unroll * W) {+ unroll<Unroll>([&](auto U) {+ main_body(j + int(U) * W, acc[int(U)]);+ });+ }+ // Single-width cleanup: remaining full W-wide chunks.+ for (; j + W - 1 < n; j += W) {+ main_body(j, acc[0]);+ }+ // Scalar tail.+ for (; j < n; j++) {+ tail_body(j, tail_acc);+ }++ // Final reduction: combine all vector accumulators + scalar tail.+ f32 combined = acc[0];+ for (int u = 1; u < Unroll; u++) {+ combined = combined + acc[u];+ }+ return reduce(combined) + tail_acc;+}++} // namespace ov::Extensions::Cpu::XARCH::simddiff --git a/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_scalar.hpp b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_scalar.hppnew file mode 100644index 00000000000..ed3a718cc84--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/kernels/simd/simd_scalar.hpp@@ -0,0 +1,203 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+// Scalar ISA specializations for simd::vec, simd::mask, and free functions.+// No intrinsics — pure C++. Always available as fallback.++#pragma once++#include <cassert>+#include <type_traits>++#include "openvino/core/type/bfloat16.hpp"+#include "openvino/core/type/float16.hpp"+#include "simd_common.hpp"++namespace ov::Extensions::Cpu::XARCH::simd {++// --- vec<float> ------------------------------------------------------------++template <>+struct vec<float, isa::scalar> {+ using element_type = float;+ static constexpr int width = 1;+ static constexpr isa isa_value = isa::scalar;+ float v;++ vec() : v(0.0F) {}+ vec(float val) : v(val) {} // NOLINT(google-explicit-constructor)++ vec operator+(vec b) const {+ return {v + b.v};+ }+ vec operator-(vec b) const {+ return {v - b.v};+ }+ vec operator*(vec b) const {+ return {v * b.v};+ }+};++inline void store(vec<float, isa::scalar> v, float* p) {+ *p = v.v;+}+inline void store(vec<float, isa::scalar> v, ov::bfloat16* p) {+ *p = ov::bfloat16(v.v);+}+inline void store(vec<float, isa::scalar> v, ov::float16* p) {+ *p = ov::float16(v.v);+}+inline float reduce(vec<float, isa::scalar> v) {+ return v.v;+}+inline vec<float, isa::scalar> fmadd(vec<float, isa::scalar> a, vec<float, isa::scalar> b, vec<float, isa::scalar> c) {+ return {a.v * b.v + c.v};+}++// --- vec<int32_t> ----------------------------------------------------------++template <>+struct vec<int32_t, isa::scalar> {+ using element_type = int32_t;+ static constexpr int width = 1;+ static constexpr isa isa_value = isa::scalar;+ int32_t v;++ vec() : v(0) {}+ vec(int32_t val) : v(val) {} // NOLINT(google-explicit-constructor)++ vec operator&(vec b) const {+ return {v & b.v};+ }+};++inline void store(vec<int32_t, isa::scalar> v, int32_t* p) {+ *p = v.v;+}++// --- loads -----------------------------------------------------------------++inline vec<float, isa::scalar> load(const float* p, vec<float, isa::scalar>* /*tag*/) {+ return {*p};+}+inline vec<float, isa::scalar> load(const ov::float16* p, vec<float, isa::scalar>* /*tag*/) {+ return {static_cast<float>(*p)};+}+inline vec<float, isa::scalar> load(const ov::bfloat16* p, vec<float, isa::scalar>* /*tag*/) {+ return {static_cast<float>(*p)};+}+inline vec<float, isa::scalar> load(const uint8_t* p, vec<float, isa::scalar>* /*tag*/) {+ return {static_cast<float>(*p)};+}+inline vec<float, isa::scalar> partial_load(uint32_t k, const float* p, vec<float, isa::scalar>* /*tag*/) {+ return {(k & 1) ? *p : 0.0F};+}+inline vec<float, isa::scalar> load_u4(const uint8_t* p, int bit_offset, vec<float, isa::scalar>* /*tag*/) {+ return {static_cast<float>((*p >> (4 - bit_offset)) & 0x0F)};+}+inline void load_u4_pair(const uint8_t* p, vec<float, isa::scalar>& lo, vec<float, isa::scalar>& hi) {+ lo.v = static_cast<float>(*p & 0x0F);+ hi.v = static_cast<float>((*p >> 4) & 0x0F);+}+inline void load_u8_pair(const uint8_t* p, vec<float, isa::scalar>& lo, vec<float, isa::scalar>& hi) {+ lo = load(p, static_cast<vec<float, isa::scalar>*>(nullptr));+ hi = load(p + 1, static_cast<vec<float, isa::scalar>*>(nullptr));+}++inline vec<int32_t, isa::scalar> load(const int32_t* p, vec<int32_t, isa::scalar>* /*tag*/) {+ return {*p};+}+inline vec<int32_t, isa::scalar> load(const uint8_t* p, vec<int32_t, isa::scalar>* /*tag*/) {+ return {static_cast<int32_t>(*p)};+}++// --- arithmetic / permute --------------------------------------------------++inline vec<int32_t, isa::scalar> srlv(vec<int32_t, isa::scalar> val, vec<int32_t, isa::scalar> shift) {+ return {static_cast<int32_t>(static_cast<uint32_t>(val.v) >> shift.v)};+}++inline vec<float, isa::scalar> permute(vec<float, isa::scalar> table, vec<int32_t, isa::scalar> idx) {+ (void)idx;+ return table;+}++inline vec<float, isa::scalar> permute2(vec<float, isa::scalar> table_lo,+ vec<int32_t, isa::scalar> idx,+ vec<float, isa::scalar> table_hi) {+ return (idx.v & 1) == 0 ? table_lo : table_hi;+}++// Scalar stubs for shuffle operations — satisfy template name lookup only.+inline vec<float, isa::scalar> unpack_lo(vec<float, isa::scalar> /*a*/, vec<float, isa::scalar> /*b*/) {+ assert(false && "unpack_lo: scalar stub"); // NOLINT+ return {};+}+inline vec<float, isa::scalar> unpack_hi(vec<float, isa::scalar> /*a*/, vec<float, isa::scalar> /*b*/) {+ assert(false && "unpack_hi: scalar stub"); // NOLINT+ return {};+}+inline vec<float, isa::scalar> unpack_lo_64(vec<float, isa::scalar> /*a*/, vec<float, isa::scalar> /*b*/) {+ assert(false && "unpack_lo_64: scalar stub"); // NOLINT+ return {};+}+inline vec<float, isa::scalar> unpack_hi_64(vec<float, isa::scalar> /*a*/, vec<float, isa::scalar> /*b*/) {+ assert(false && "unpack_hi_64: scalar stub"); // NOLINT+ return {};+}+// Always-false-when-instantiated helper (depends on template param so it's only+// evaluated at instantiation, not at template definition).+template <int>+struct scalar_always_false : std::false_type {};++template <int ctrl>+inline vec<float, isa::scalar> shuffle(vec<float, isa::scalar> /*a*/, vec<float, isa::scalar> /*b*/) {+ static_assert(scalar_always_false<ctrl>::value, "shuffle: not available for scalar ISA");+ return {};+}+template <int ctrl>+inline vec<float, isa::scalar> permute_lanes(vec<float, isa::scalar> /*a*/, vec<float, isa::scalar> /*b*/) {+ static_assert(scalar_always_false<ctrl>::value, "permute_lanes: not available for scalar ISA");+ return {};+}+template <int ctrl>+inline vec<float, isa::scalar> permute_64(vec<float, isa::scalar> /*a*/) {+ static_assert(scalar_always_false<ctrl>::value, "permute_64: not available for scalar ISA");+ return {};+}++// --- mask ------------------------------------------------------------------++template <>+struct mask<isa::scalar> {+ bool v;+ mask() : v(false) {}+ mask(bool val) : v(val) {} // NOLINT(google-explicit-constructor)+};++inline mask<isa::scalar> operator>(vec<int32_t, isa::scalar> a, vec<int32_t, isa::scalar> b) {+ return {a.v > b.v};+}+inline mask<isa::scalar> operator<(vec<int32_t, isa::scalar> a, vec<int32_t, isa::scalar> b) {+ return {a.v < b.v};+}+inline mask<isa::scalar> operator>=(vec<int32_t, isa::scalar> a, vec<int32_t, isa::scalar> b) {+ return {a.v >= b.v};+}+inline mask<isa::scalar> operator<=(vec<int32_t, isa::scalar> a, vec<int32_t, isa::scalar> b) {+ return {a.v <= b.v};+}+inline mask<isa::scalar> operator==(vec<int32_t, isa::scalar> a, vec<int32_t, isa::scalar> b) {+ return {a.v == b.v};+}+inline mask<isa::scalar> operator!=(vec<int32_t, isa::scalar> a, vec<int32_t, isa::scalar> b) {+ return {a.v != b.v};+}++inline vec<float, isa::scalar> select(mask<isa::scalar> m,+ vec<float, isa::scalar> if_false,+ vec<float, isa::scalar> if_true) {+ return m.v ? if_true : if_false;+}++} // namespace ov::Extensions::Cpu::XARCH::simddiff --git a/src/plugins/intel_cpu/src/nodes/memory.cpp b/src/plugins/intel_cpu/src/nodes/memory.cppindex 1a620d84fcd..be1571d52fa 100644--- a/src/plugins/intel_cpu/src/nodes/memory.cpp+++ b/src/plugins/intel_cpu/src/nodes/memory.cpp@@ -996,7 +996,7 @@ MemStatePtr MemoryInputSDPA::makeState() const {CPU_NODE_ASSERT(node, "SDPA node is not available");auto kv_precision = node->getKVCachePrecision();ScaledDotProductAttention::SDPAQuantParam quant_param;- if (kv_precision == ov::element::u8) {+ 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);diff --git a/src/plugins/intel_cpu/src/nodes/scaled_attn.cpp b/src/plugins/intel_cpu/src/nodes/scaled_attn.cppindex b8fc43314c6..7e4be0f6b11 100644--- a/src/plugins/intel_cpu/src/nodes/scaled_attn.cpp+++ b/src/plugins/intel_cpu/src/nodes/scaled_attn.cpp@@ -67,6 +67,8 @@#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/mha_kv_cache_codec.hpp"#include "kernels/scaled_attn/mha_single_token.hpp"#include "kernels/scaled_attn/softmax.hpp"#include "kernels/x64/brgemm_kernel.hpp"@@ -79,8 +81,12 @@ using namespace dnnl::impl::cpu::x64;namespace ov::intel_cpu::node {+static bool is_quantized_cache(ov::element::Type prec) {+ return prec == ov::element::u8 || prec == ov::element::u4;+}+// Compress and write cur tensor into the KV cache (dst) at position L0.-// Handles u8 quant (per-group or by-channel) and raw precision-matching copy.+// Handles u8/u4 quant (per-group or by-channel) and raw precision-matching copy.static void compress_cache(const PlainTensor& cur,PlainTensor& dst,size_t L0,@@ -89,7 +95,7 @@ static void compress_cache(const PlainTensor& cur,size_t group_size,bool quant_by_channel,const CpuParallelPtr& cpu_parallel) {- if (quant_precision == ov::element::u8) {+ if (is_quantized_cache(quant_precision)) {if (quant_by_channel) {attn_quant_by_channel(cur, dst, scale_zp, L0, group_size, cpu_parallel);} else {@@ -1373,7 +1379,10 @@ struct ScaledDotProductAttention::AttentionExecutor : public ScaledDotProductAttPlainTensor attn_buf; // f32[[B|1],[H|1], L1|1, L0+L1]MHAKernel<KType, T> kernel;+ // @todo replace with mha_kv_cache when ARM is supportedMHASingleToken kernel_single_token;+ PlainTensor m_attn_w;+ PlainTensor m_attn_score;explicit AttentionExecutor(GraphContext::CPtr ctx,size_t k_group_size,@@ -1403,7 +1412,9 @@ struct ScaledDotProductAttention::AttentionExecutor : public ScaledDotProductAttconst MemoryPtr presentv_input,const MemoryPtr beam_input,const PlainTensor& k_scale_zp,- const PlainTensor& v_scale_zp) override {+ const PlainTensor& v_scale_zp,+ ov::Extensions::Cpu::CacheCodec k_codec,+ ov::Extensions::Cpu::CacheCodec v_codec) 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;@@ -1555,20 +1566,56 @@ struct ScaledDotProductAttention::AttentionExecutor : public ScaledDotProductAtt// 1, in matrix mutiply, using AMX is not efficency because the M dimension of A will alway be 1// 2, using float will save the repack cost which typically is required for bf16/int8 opt// 3, using dot product can leverage the SIMD while easily adapt to indirect kv cache- kernel_single_token(q_input,- present_key,- present_value,- alibi_mask,- use_attn_mask ? attn_mask : PlainTensor(),- output_emb,- beam_table,- has_out_transpose,- auto_causal,- scale_input,- k_scale_zp,- v_scale_zp,- sink_input,- context->getCpuParallel());++ // Use mha_kv_cache pipeline for all single-token decoding.+ // This unifies quantized (u8/u4) and raw paths through a single codec-generic pipeline.+ // temporary OV_TURBOQ_LEGACY_ATTN=1 reverts to the old per-type dispatch.+ // ARM SIMD abstraction not yet wired through mha_kv_cache — fall back to legacy.+#if defined(OPENVINO_ARCH_ARM) || defined(OPENVINO_ARCH_ARM64)+ const bool use_new_pipeline = false;+#else+ static const bool force_legacy = std::getenv("OV_CPU_LEGACY_ATTN") != nullptr;+ const bool use_new_pipeline = !force_legacy;+#endif+ if (use_new_pipeline) {+ mha_kv_cache(q_input,+ present_key,+ present_value,+ alibi_mask,+ use_attn_mask ? attn_mask : PlainTensor(),+ beam_table,+ output_emb,+ m_attn_w,+ m_attn_score,+ has_out_transpose,+ scale_input,+ k_codec,+ v_codec,+ 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);+ } else {+ kernel_single_token(q_input,+ present_key,+ present_value,+ alibi_mask,+ use_attn_mask ? attn_mask : PlainTensor(),+ output_emb,+ beam_table,+ has_out_transpose,+ auto_causal,+ scale_input,+ k_scale_zp,+ v_scale_zp,+ sink_input,+ context->getCpuParallel());+ }}#if defined(OPENVINO_ARCH_ARM64)@@ -1774,8 +1821,13 @@ ScaledDotProductAttention::ScaledDotProductAttention(const std::shared_ptr<ov::Nconst 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),- "supports key/value cache precision f32, f16, bf16, u8 but gets ",+ 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@@ -1909,6 +1961,34 @@ void ScaledDotProductAttention::createPrimitive() {OPENVINO_ASSERT(valueS % m_value_quant_param.groupSize == 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.+ // 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);+ScaledDotProductAttentionKey key = {rtPrecision};auto builder = [&]([[maybe_unused]] const ScaledDotProductAttentionKey& key) -> std::shared_ptr<Executor> {@@ -2013,8 +2093,17 @@ void ScaledDotProductAttention::execute(const dnnl::stream& strm) {presentk_input = inputs[1];presentv_input = inputs[2];}- m_executor- ->execute(strm, m_config, inputs, output, presentk_input, presentv_input, beam_input, k_scale_zp, v_scale_zp);+ m_executor->execute(strm,+ m_config,+ inputs,+ output,+ presentk_input,+ presentv_input,+ beam_input,+ k_scale_zp,+ v_scale_zp,+ m_k_codec,+ m_v_codec);}bool ScaledDotProductAttention::isSupportedOperation(const std::shared_ptr<const ov::Node>& op,@@ -2092,6 +2181,47 @@ std::vector<T> permute_axes(const std::vector<T>& shape, const std::vector<size_return results;}+// BHLS dims -> original-model dim order via the inverse of `order`.+// SDPA states inputs as BHLS; the model may permute axes, so the cache is+// allocated in the model's native order and then laid out as LBHS via real_order.+static std::vector<size_t> bhls_to_model_shape(const std::vector<size_t>& bhls, const std::vector<size_t>& order) {+ std::vector<size_t> shape(bhls.size());+ for (size_t i = 0; i < bhls.size(); i++) {+ shape[order[i]] = bhls[i];+ }+ return shape;+}++// Build the KV-cache memory desc with logical BHLS dims and LBHS physical layout.+static std::shared_ptr<CpuBlockedMemoryDesc> make_kv_cache_desc(ov::element::Type prec,+ size_t B,+ size_t H,+ size_t L_total,+ size_t inner,+ const std::vector<size_t>& order,+ const std::vector<size_t>& real_order) {+ const auto shape = bhls_to_model_shape({B, H, L_total, inner}, order);+ return std::make_shared<CpuBlockedMemoryDesc>(prec, Shape(shape), permute_axes(shape, real_order), real_order);+}++// 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,+ size_t hidden_states,+ size_t B,+ size_t H,+ size_t L_total,+ 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;+ bhls = {B, H, group_nums, hidden_states};+ } else {+ bhls = {B, H, L_total, hidden_states / quant_param.groupSize * 2};+ }+ return permute_axes(bhls_to_model_shape(bhls, order), real_order);+}+void ScaledDotProductAttention::resetBeamTablePastkv(const MemoryPtr& mem_cur_k,const MemoryPtr& mem_cur_v,const MemoryPtr& mem_beam_idx) {@@ -2151,17 +2281,9 @@ void ScaledDotProductAttention::resetBeamTablePastkv(const MemoryPtr& mem_cur_k,// 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- std::vector<size_t> shape = reverse({B, H, (L0 + L1) * 2, S});- auto mem_desc_k = std::make_shared<CpuBlockedMemoryDesc>(kvcache_precision,- Shape(shape),- permute_axes(shape, real_order),- real_order);+ auto mem_desc_k = make_kv_cache_desc(kvcache_precision, B, H, (L0 + L1) * 2, S, order, real_order);auto new_internal_mem_k = std::make_shared<Memory>(getEngine(), mem_desc_k);- shape = reverse({B, H, (L0 + L1) * 2, SV});- auto mem_desc_v = std::make_shared<CpuBlockedMemoryDesc>(kvcache_precision,- Shape(shape),- permute_axes(shape, real_order),- real_order);+ auto mem_desc_v = make_kv_cache_desc(kvcache_precision, B, H, (L0 + L1) * 2, SV, order, real_order);auto new_internal_mem_v = std::make_shared<Memory>(getEngine(), mem_desc_v);PlainTensor new_pastk;@@ -2179,37 +2301,24 @@ 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;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}),- S * old_past_k.m_element_size);- memcpy(&new_pastv.at<char>({b, h, m}),- &old_past_v.at<char>({b_kv, h, m}),- SV * old_past_v.m_element_size);+ 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 (kvcache_precision == ov::element::u8) {+ if (is_quantized_cache(kvcache_precision)) {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;- auto get_scale_zp_shape = [&](const SDPAQuantParam& quant_param, const size_t hidden_states) {- std::vector<size_t> shape;- if (quant_param.isByChannel) {- // round_up to group_size- size_t group_nums = div_up((L0 + L1) * 2, quant_param.groupSize) * 2;- shape = reverse({B, H, group_nums, hidden_states});- } else {- shape = reverse({B, H, (L0 + L1) * 2, hidden_states / quant_param.groupSize * 2});- }- return permute_axes(shape, real_order);- };- std::vector<size_t> real_shape = get_scale_zp_shape(m_key_quant_param, S);- new_scale_zp_k.resize<float>(real_shape);- real_shape = get_scale_zp_shape(m_value_quant_param, SV);- new_scale_zp_v.resize<float>(real_shape);+ 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 (L0 > 0) {auto update_scales_zp =[&](const SDPAQuantParam& quant_param, PlainTensor& new_scale_zp, PlainTensor& old_scale_zp) {@@ -2543,16 +2652,12 @@ 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 new_memory = [&](size_t new_S) {- std::vector<size_t> new_shape = reverse({B, H, (L0 + L1) * 2, new_S});- auto real_shape = permute_axes(new_shape, real_order);- auto mem_desc =- std::make_shared<CpuBlockedMemoryDesc>(kvcache_precision, Shape(new_shape), real_shape, real_order);- return std::make_shared<Memory>(getEngine(), mem_desc);- };-- auto new_internal_mem_k = new_memory(S);- auto new_internal_mem_v = new_memory(SV);+ 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));PlainTensor new_pastk;PlainTensor new_pastv;@@ -2575,26 +2680,15 @@ void ScaledDotProductAttention::updatePastkv(const MemoryPtr& mem_cur_k, const Mm_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 (kvcache_precision == ov::element::u8) {+ if (is_quantized_cache(kvcache_precision)) {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;- auto get_scale_zp_shape = [&](const SDPAQuantParam& quant_param, const size_t hidden_states) {- std::vector<size_t> shape;- if (quant_param.isByChannel) {- // round_up to group_size- size_t group_nums = div_up((L0 + L1) * 2, quant_param.groupSize) * 2;- shape = reverse({B, H, group_nums, hidden_states});- } else {- shape = reverse({B, H, (L0 + L1) * 2, hidden_states / quant_param.groupSize * 2});- }- return permute_axes(shape, real_order);- };- std::vector<size_t> real_shape = get_scale_zp_shape(m_key_quant_param, S);- new_scale_zp_k.resize<float>(real_shape);- real_shape = get_scale_zp_shape(m_value_quant_param, SV);- new_scale_zp_v.resize<float>(real_shape);+ 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 (L0 > 0 && !is_reset) {auto update_scales_zp =[&](const SDPAQuantParam& quant_param, PlainTensor& new_scale_zp, PlainTensor& old_scale_zp) {@@ -2645,7 +2739,7 @@ void ScaledDotProductAttention::updatePastkv(const MemoryPtr& mem_cur_k, const M};internal_mem_k->redefineDesc(reset_desc(S));internal_mem_v->redefineDesc(reset_desc(SV));- if (kvcache_precision == ov::element::u8) {+ if (is_quantized_cache(kvcache_precision)) {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@@ -2750,9 +2844,12 @@ ov::element::Type ScaledDotProductAttention::getKVCachePrecision() {rtPrecision != ov::element::bf16 &&(all_of(ov::element::f16, keyCachePrecisionHint, valueCachePrecisionHint));kvcache_precision = enableKVCacheFP16 ? ov::element::f16 : rtPrecision;- bool use_int8_kv_cache_precision = (all_of(ov::element::u8, keyCachePrecisionHint, valueCachePrecisionHint));- if (use_int8_kv_cache_precision) {+ 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;}diff --git a/src/plugins/intel_cpu/src/nodes/scaled_attn.h b/src/plugins/intel_cpu/src/nodes/scaled_attn.hindex 39f12af6194..d5acf14c9d1 100644--- a/src/plugins/intel_cpu/src/nodes/scaled_attn.h+++ b/src/plugins/intel_cpu/src/nodes/scaled_attn.h@@ -13,6 +13,7 @@#include "cpu_memory.h"#include "cpu_types.h"#include "graph_context.h"+#include "kernels/scaled_attn/codecs/cache_codec.hpp"#include "memory_state.h"#include "node.h"#include "onednn/iml_type_mapper.h"@@ -93,7 +94,9 @@ private:MemoryPtr presentv_input,MemoryPtr beam_input,const PlainTensor& k_scale_zp,- const PlainTensor& v_scale_zp) = 0;+ const PlainTensor& v_scale_zp,+ ov::Extensions::Cpu::CacheCodec k_codec,+ ov::Extensions::Cpu::CacheCodec v_codec) = 0;[[nodiscard]] virtual impl_desc_type implType() const = 0;virtual ~Executor() = default;};@@ -112,6 +115,8 @@ private: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{};};} // namespace ov::intel_cpu::nodediff --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.cppindex 23b95eb9314..a0178a8e586 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@@ -39,11 +39,24 @@ const std::vector<std::vector<InputShape>> inputShapes = {},};+// @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::f16),::testing::ValuesIn(inputShapes),+ ::testing::Values("none"),+ ::testing::Values("none"),::testing::Values(true, false),+ ::testing::Values(true, false)),+ 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);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.cppindex db32fca6827..b76b3a2890f 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@@ -31,7 +31,7 @@ namespace test {* Result*/std::string ConcatSDPTest::getTestCaseName(const testing::TestParamInfo<ConcatSDPTestParams>& obj) {- const auto& [inType, inputShapes, forceKVU8, hasShapeOf, isDiffKVHeadSize] = obj.param;+ const auto& [inType, inputShapes, kCachePrec, vCachePrec, hasShapeOf, isDiffKVHeadSize] = obj.param;std::ostringstream result;result << "IS=";for (const auto& shape : inputShapes) {@@ -48,17 +48,19 @@ std::string ConcatSDPTest::getTestCaseName(const testing::TestParamInfo<ConcatSDresult << ")_";}result << "Prc=" << inType << "_";- result << "ForceKVU8=" << forceKVU8 << "_";+ result << "Kprec=" << kCachePrec << "_";+ result << "Vprec=" << vCachePrec << "_";result << "HasShapeOf=" << hasShapeOf << "_";result << "IsDiffKVHeadSize=" << isDiffKVHeadSize;return result.str();}void ConcatSDPTest::SetUp() {- const auto& [inType, inputShapes, _m_forceKVU8, _m_hasShapeOf, _m_isDiffKVHeadSize] = this->GetParam();- m_forceKVU8 = _m_forceKVU8;- m_hasShapeOf = _m_hasShapeOf;- m_isDiffKVHeadSize = _m_isDiffKVHeadSize;+ const auto& [inType, inputShapes, kCachePrec, vCachePrec, hasShapeOf, isDiffKVHeadSize] = this->GetParam();+ m_kCachePrec = kCachePrec;+ m_vCachePrec = vCachePrec;+ m_hasShapeOf = hasShapeOf;+ m_isDiffKVHeadSize = isDiffKVHeadSize;targetDevice = ov::test::utils::DEVICE_CPU;rel_threshold = 1e-2f;if (inType == ElementType::bf16 || inType == ElementType::f16) {@@ -66,8 +68,15 @@ void ConcatSDPTest::SetUp() {rel_threshold = 0.01f;}- if (m_forceKVU8) {- configuration["KV_CACHE_PRECISION"] = "u8";+ if (m_kCachePrec != "none") {+ configuration["KEY_CACHE_PRECISION"] = m_kCachePrec;+ }+ if (m_vCachePrec != "none") {+ configuration["VALUE_CACHE_PRECISION"] = m_vCachePrec;+ }+ // Wider tolerance for quantized cache (u4 has only 16 levels).+ if (m_kCachePrec == "u4" || m_vCachePrec == "u4") {+ abs_threshold = 0.3f;}init_input_shapes(inputShapes);ov::ParameterVector inputParams;@@ -223,7 +232,7 @@ std::vector<ov::Tensor> ConcatSDPTest::run_test(std::shared_ptr<ov::Model> model}TEST_P(ConcatSDPTest, CompareWithRefs) {SKIP_IF_CURRENT_TEST_IS_DISABLED();- const auto& [inType, inputShapes, forceKVU8, hasShapeOf, isDiffKVHeadSize] = this->GetParam();+ const auto& [inType, inputShapes, kCachePrec, vCachePrec, hasShapeOf, isDiffKVHeadSize] = this->GetParam();auto actualOutputs = run_test(function);if (!hasShapeOf) {CheckNumberOfNodesWithType(compiledModel, "ScaledDotProductAttention", 1);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.hppindex 7dc7ba17f33..05f33cf91a8 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@@ -33,7 +33,13 @@ namespace test {template<typename IT, typename T>void strided_iota(IT first, size_t n, T value, T stride);-typedef std::tuple<ElementType, std::vector<InputShape>, bool, bool, bool> ConcatSDPTestParams;+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+ ConcatSDPTestParams;class ConcatSDPTest :public testing::WithParamInterface<ConcatSDPTestParams>,@@ -45,7 +51,8 @@ public:void prepare();void reset();std::vector<ov::Tensor> run_test(std::shared_ptr<ov::Model> model);- bool m_forceKVU8;+ std::string m_kCachePrec;+ std::string m_vCachePrec;bool m_hasShapeOf;bool m_isDiffKVHeadSize;protected: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.cppindex d6221ee37d1..387bbead457 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@@ -39,11 +39,24 @@ const std::vector<std::vector<InputShape>> inputShapes = {},};+// @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);++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);diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/concat_transpose_sdp_transpose.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/concat_transpose_sdp_transpose.cppindex ee21c86039a..04a267b4d98 100644--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/concat_transpose_sdp_transpose.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/concat_transpose_sdp_transpose.cpp@@ -386,6 +386,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_ConcatSDPTransposeByChannelTest,::testing::Values(true),::testing::Values(8)),ConcatSDPTransposeTest::getTestCaseName);+} // namespaceclass ConcatSDPTransposeTestSetState : public ConcatSDPTransposeTestBase {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.cppindex 8f15bdd080d..05a8c30f71a 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@@ -39,15 +39,45 @@ const std::vector<std::vector<InputShape>> inputShapes = {},};+// @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);++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);+} // namespace} // namespace test