Skip to content

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

[GSOC][CPU][ARM] Add fp16 support for SDPA (#25918)

Mb354be87d1e2
diff --git a/cmake/developer_package/compile_flags/os_flags.cmake b/cmake/developer_package/compile_flags/os_flags.cmake
index 6c531d3db72..fdfd7211c8e 100644
--- a/cmake/developer_package/compile_flags/os_flags.cmake
+++ b/cmake/developer_package/compile_flags/os_flags.cmake
@@ -184,6 +184,30 @@ macro(ov_arm_neon_optimization_flags flags)
endif()
endmacro()
+#
+# ov_arm_neon_fp16_optimization_flags(<output flags>)
+#
+macro(ov_arm_neon_fp16_optimization_flags flags)
+ if(CMAKE_CXX_COMPILER_ID STREQUAL "Intel" OR CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
+ message(WARNING "Unsupported CXX compiler ${CMAKE_CXX_COMPILER_ID}")
+ elseif(ANDROID)
+ if(ANDROID_ABI STREQUAL "arm64-v8a")
+ set(${flags} -march=armv8.2-a+fp16 -Wno-unused-command-line-argument)
+ else()
+ message(WARNING "fp16 is not supported by Android armv7")
+ endif()
+ elseif(AARCH64)
+ set(${flags} -O2 -march=armv8.2-a+fp16)
+ if(NOT CMAKE_CL_64)
+ list(APPEND ${flags} -ftree-vectorize)
+ endif()
+ elseif(ARM)
+ message(WARNING "fp16 is not supported by 32-bit ARM")
+ else()
+ message(WARNING "fp16 is not supported by architecture ${CMAKE_SYSTEM_PROCESSOR}")
+ endif()
+endmacro()
+
#
# ov_disable_all_warnings(<target1 [target2 target3 ...]>)
#
diff --git a/cmake/developer_package/cross_compile/cross_compiled_disp_gen.cmake b/cmake/developer_package/cross_compile/cross_compiled_disp_gen.cmake
index 0132f940ef7..c33d64635eb 100644
--- a/cmake/developer_package/cross_compile/cross_compiled_disp_gen.cmake
+++ b/cmake/developer_package/cross_compile/cross_compiled_disp_gen.cmake
@@ -14,11 +14,12 @@
#
# =================================================================
-set(_CPU_CHECK_ANY "true")
-set(_CPU_CHECK_SSE42 "with_cpu_x86_sse42()")
-set(_CPU_CHECK_AVX "with_cpu_x86_avx()")
-set(_CPU_CHECK_AVX2 "with_cpu_x86_avx2()")
-set(_CPU_CHECK_AVX512F "with_cpu_x86_avx512f()")
+set(_CPU_CHECK_ANY "true")
+set(_CPU_CHECK_SSE42 "with_cpu_x86_sse42()")
+set(_CPU_CHECK_AVX "with_cpu_x86_avx()")
+set(_CPU_CHECK_NEON_FP16 "with_cpu_neon_fp16()")
+set(_CPU_CHECK_AVX2 "with_cpu_x86_avx2()")
+set(_CPU_CHECK_AVX512F "with_cpu_x86_avx512f()")
function(_generate_dispatcher)
string(REPLACE "::" ";" XARCH_NAMESPACES "${XARCH_NAMESPACES}")
diff --git a/cmake/developer_package/cross_compile/cross_compiled_func.cmake b/cmake/developer_package/cross_compile/cross_compiled_func.cmake
index 5f7b72ff47e..1e92fe3bfda 100644
--- a/cmake/developer_package/cross_compile/cross_compiled_func.cmake
+++ b/cmake/developer_package/cross_compile/cross_compiled_func.cmake
@@ -3,25 +3,28 @@
#
## list of available instruction sets
-set(_ARCH_LIST ANY SSE42 AVX AVX2 AVX512F)
+set(_ARCH_LIST ANY SSE42 AVX AVX2 AVX512F NEON_FP16)
set(_ACCEPTED_ARCHS_ANY "^(ANY)$")
set(_ACCEPTED_ARCHS_SSE42 "^(ANY|SSE42)$")
set(_ACCEPTED_ARCHS_AVX "^(ANY|SSE42|AVX)$")
set(_ACCEPTED_ARCHS_AVX2 "^(ANY|SSE42|AVX|AVX2)$")
set(_ACCEPTED_ARCHS_AVX512F "^(ANY|SSE42|AVX|AVX2|AVX512F)$")
+set(_ACCEPTED_ARCHS_NEON_FP16 "^(ANY|NEON_FP16)$")
## Arch specific definitions
-set(_DEFINE_ANY "")
-set(_DEFINE_SSE42 "HAVE_SSE42" ${_DEFINE_ANY})
-set(_DEFINE_AVX "HAVE_AVX" ${_DEFINE_SSE42})
-set(_DEFINE_AVX2 "HAVE_AVX2" ${_DEFINE_AVX})
-set(_DEFINE_AVX512F "HAVE_AVX512F" ${_DEFINE_AVX2})
+set(_DEFINE_ANY "")
+set(_DEFINE_SSE42 "HAVE_SSE42" ${_DEFINE_ANY})
+set(_DEFINE_AVX "HAVE_AVX" ${_DEFINE_SSE42})
+set(_DEFINE_AVX2 "HAVE_AVX2" ${_DEFINE_AVX})
+set(_DEFINE_AVX512F "HAVE_AVX512F" ${_DEFINE_AVX2})
+set(_DEFINE_NEON_FP16 "HAVE_NEON_FP16" ${_DEFINE_ANY})
## Arch specific compile options
ov_avx512_optimization_flags(_FLAGS_AVX512F)
ov_avx2_optimization_flags (_FLAGS_AVX2)
ov_sse42_optimization_flags (_FLAGS_SSE42)
+ov_arm_neon_fp16_optimization_flags(_FLAGS_NEON_FP16)
set(_FLAGS_AVX "") ## TBD is not defined for OV project yet
set(_FLAGS_ANY "") ##
@@ -180,7 +183,9 @@ endfunction()
# Return currently requested ARCH id
#
function(_currently_requested_top_arch VAR)
- if(ENABLE_AVX512F)
+ if(ENABLE_NEON_FP16)
+ set(RES NEON_FP16)
+ elseif(ENABLE_AVX512F)
set(RES AVX512F)
elseif(ENABLE_AVX2)
set(RES AVX2)
diff --git a/cmake/developer_package/features.cmake b/cmake/developer_package/features.cmake
index 99e99145d30..8d1f3696c67 100644
--- a/cmake/developer_package/features.cmake
+++ b/cmake/developer_package/features.cmake
@@ -49,6 +49,8 @@ ov_dependent_option (ENABLE_AVX2 "Enable AVX2 optimizations" ON "X86_64 OR (X86
ov_dependent_option (ENABLE_AVX512F "Enable AVX512 optimizations" ON "X86_64 OR (X86 AND NOT EMSCRIPTEN)" OFF)
+ov_dependent_option(ENABLE_NEON_FP16 "Enable ARM FP16 optimizations" ON "AARCH64" OFF)
+
# Type of build, we add this as an explicit option to default it to ON
get_property(BUILD_SHARED_LIBS_DEFAULT GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS)
ov_option (BUILD_SHARED_LIBS "Build as a shared library" ${BUILD_SHARED_LIBS_DEFAULT})
diff --git a/src/inference/dev_api/openvino/runtime/system_conf.hpp b/src/inference/dev_api/openvino/runtime/system_conf.hpp
index b6f22ad4f8d..59d56dfdd49 100644
--- a/src/inference/dev_api/openvino/runtime/system_conf.hpp
+++ b/src/inference/dev_api/openvino/runtime/system_conf.hpp
@@ -76,6 +76,13 @@ OPENVINO_RUNTIME_API int get_number_of_blocked_cores();
*/
OPENVINO_RUNTIME_API bool with_cpu_x86_sse42();
+/**
+ * @brief Checks whether CPU supports ARM NEON FP16 capability
+ * @ingroup ov_dev_api_system_conf
+ * @return `True` is ARM NEON FP16 instructions are available, `false` otherwise
+ */
+OPENVINO_RUNTIME_API bool with_cpu_neon_fp16();
+
/**
* @brief Checks whether CPU supports AVX capability
* @ingroup ov_dev_api_system_conf
diff --git a/src/inference/src/system_conf.cpp b/src/inference/src/system_conf.cpp
index 9de1eeb78e1..27c671d07ad 100644
--- a/src/inference/src/system_conf.cpp
+++ b/src/inference/src/system_conf.cpp
@@ -17,6 +17,16 @@
# include <sched.h>
#endif
+#if !defined(BARE_METAL) && !defined(__APPLE__) && !defined(__OpenBSD__) && (defined(__arm__) || defined(__aarch64__))
+# include <asm/hwcap.h> /* Get HWCAP bits from asm/hwcap.h */
+# include <sys/auxv.h>
+# define ARM_COMPUTE_CPU_FEATURE_HWCAP_FPHP (1 << 9)
+# define ARM_COMPUTE_CPU_FEATURE_HWCAP_ASIMDHP (1 << 10)
+#elif defined(__APPLE__) && defined(__aarch64__)
+# include <sys/sysctl.h>
+# include <sys/types.h>
+#endif
+
#include "dev/threading/parallel_custom_arena.hpp"
#include "openvino/core/except.hpp"
#include "openvino/core/visibility.hpp"
@@ -100,6 +110,10 @@ bool with_cpu_x86_avx512_core_amx() {
return with_cpu_x86_avx512_core_amx_int8() || with_cpu_x86_avx512_core_amx_bf16();
}
+bool with_cpu_neon_fp16() {
+ return false;
+}
+
#else // OPENVINO_ARCH_X86 || OPENVINO_ARCH_X86_64
bool with_cpu_x86_sse42() {
@@ -141,7 +155,24 @@ bool with_cpu_x86_avx512_core_amx_fp16() {
bool with_cpu_x86_avx512_core_amx() {
return false;
}
-
+bool with_cpu_neon_fp16() {
+# if !defined(_WIN64) && !defined(BARE_METAL) && !defined(__APPLE__) && !defined(__OpenBSD__) && \
+ !defined(__arm__) && defined(__aarch64__)
+ const uint32_t hwcaps = getauxval(AT_HWCAP);
+ return hwcaps & (ARM_COMPUTE_CPU_FEATURE_HWCAP_FPHP | ARM_COMPUTE_CPU_FEATURE_HWCAP_ASIMDHP);
+# elif !defined(_WIN64) && !defined(BARE_METAL) && !defined(__APPLE__) && !defined(__OpenBSD__) && \
+ !defined(__aarch64__) && defined(__arm__)
+ return false;
+# elif defined(__aarch64__) && defined(__APPLE__)
+ int64_t result(0);
+ size_t size = sizeof(result);
+ const std::string& cap = "hw.optional.neon_fp16";
+ sysctlbyname(cap.c_str(), &result, &size, NULL, 0);
+ return result > 0;
+# else
+ return false;
+# endif
+}
#endif // OPENVINO_ARCH_X86 || OPENVINO_ARCH_X86_64
bool check_open_mp_env_vars(bool include_omp_num_threads) {
diff --git a/src/plugins/intel_cpu/CMakeLists.txt b/src/plugins/intel_cpu/CMakeLists.txt
index ddf0648f58a..3f349bebb4d 100644
--- a/src/plugins/intel_cpu/CMakeLists.txt
+++ b/src/plugins/intel_cpu/CMakeLists.txt
@@ -287,14 +287,14 @@ cross_compiled_file(${TARGET_NAME}
NAMESPACE ov::Extensions::Cpu::XARCH
)
cross_compiled_file(${TARGET_NAME}
- ARCH AVX512F AVX2 ANY
+ ARCH AVX512F AVX2 NEON_FP16 ANY
src/nodes/kernels/scaled_attn/softmax.cpp
API src/nodes/kernels/scaled_attn/softmax.hpp
NAME attn_softmax
NAMESPACE ov::Extensions::Cpu::XARCH
)
cross_compiled_file(${TARGET_NAME}
- ARCH AVX512F AVX2 ANY
+ ARCH AVX512F AVX2 NEON_FP16 ANY
src/nodes/kernels/scaled_attn/mha_single_token.cpp
API src/nodes/kernels/scaled_attn/mha_single_token.hpp
NAME mha_single_token
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/acl/gemm_kernel.cpp b/src/plugins/intel_cpu/src/nodes/kernels/acl/gemm_kernel.cpp
index afaae43850b..0ae6a4ad2c4 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/acl/gemm_kernel.cpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/acl/gemm_kernel.cpp
@@ -18,12 +18,13 @@ namespace intel_cpu {
if (!one_of(inType, ov::element::f32, ov::element::f16, ov::element::bf16))
THROW_ERROR("brgemm kernel only supports bf16, f16 and f32");
- if (inType == ov::element::f32)
+ if (inType == ov::element::f32) {
format = arm_compute::Format::F32;
- else if (inType == ov::element::f16)
+ } else if (inType == ov::element::f16) {
format = arm_compute::Format::F16;
- else if (inType == ov::element::bf16)
+ } else if (inType == ov::element::bf16) {
format = arm_compute::Format::BFLOAT16;
+ }
aclGemmKernel = std::make_unique<arm_compute::NEGEMM>();
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/common.hpp
index c1e35335509..3341f6f6082 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
@@ -29,6 +29,7 @@ static constexpr size_t vec_len_neon = 16lu;
static constexpr size_t vec_len_f32_avx512 = vec_len_avx512 / sizeof(float);
static constexpr size_t vec_len_f32_avx2 = vec_len_avx2 / sizeof(float);
static constexpr size_t vec_len_f32_neon = vec_len_neon / sizeof(float);
+static constexpr size_t vec_len_f16_neon = vec_len_neon / sizeof(ov::float16);
#ifdef HAVE_AVX512F
inline __m512 cvt_bf16_to_fp32(const __m256i src) {
@@ -200,7 +201,7 @@ static constexpr size_t vec_len_f32_neon = vec_len_neon / sizeof(float);
#endif
#ifdef OPENVINO_ARCH_ARM64
- inline float32x4_t exp_ps_neon(float32x4_t& src) {
+ inline float32x4_t exp_ps_neon_f32(const float32x4_t& src) {
const auto c1 = vreinterpretq_f32_u32(vdupq_n_u32(0x3f7ffff6));
const auto c2 = vreinterpretq_f32_u32(vdupq_n_u32(0x3efffedb));
const auto c3 = vreinterpretq_f32_u32(vdupq_n_u32(0x3e2aaf33));
@@ -252,8 +253,42 @@ static constexpr size_t vec_len_f32_neon = vec_len_neon / sizeof(float);
inline float32x4_t __vld1q_f32(const float* a) {
return vld1q_f32(a);
}
+ inline float32x4_t __vld1q_f32(const ov::float16* a) {
+ auto _a = reinterpret_cast<const float16_t*>(a);
+ return vcvt_f32_f16(vld1_f16(_a));
+ }
+ inline void __vst1q_f32(float* a, float32x4_t b) {
+ vst1q_f32(a, b);
+ }
+ inline void __vst1q_f32(ov::float16* a, float32x4_t b) {
+ float16x4_t v_f16 = vcvt_f16_f32(b);
+ vst1_f16(reinterpret_cast<float16_t*>(a), v_f16);
+ }
+ inline void __vst1q_f32(ov::bfloat16* a, float32x4_t b) {
+ uint32x4_t v_int32 = vreinterpretq_u32_f32(b);
+ uint16x4_t v_bf16 = vshrn_n_u32(v_int32, 16);
+
+ vst1_u16(reinterpret_cast<uint16_t*>(a), v_bf16);
+ }
+
#endif
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+ inline float16x8_t exp_ps_neon_f16(float16x8_t x) {
+ const float32x4_t x_high = vcvt_f32_f16(vget_high_f16(x));
+ const float32x4_t x_low = vcvt_f32_f16(vget_low_f16(x));
+
+ // We use f32 to maintain accuracy
+ const float16x8_t res = vcombine_f16(vcvt_f16_f32(exp_ps_neon_f32(x_low)), vcvt_f16_f32(exp_ps_neon_f32(x_high)));
+ return res;
+ }
+ inline float16_t hsum(float16x8_t vec) {
+ float16x4_t sum1 = vpadd_f16(vget_low_f16(vec), vget_high_f16(vec));
+ float16x4_t sum2 = vpadd_f16(sum1, sum1);
+ float16x4_t sum3 = vpadd_f16(sum2, sum2);
+ return vget_lane_f16(sum3, 0);
+ }
+#endif
} // namespace XARCH
} // namespace Cpu
} // namespace Extensions
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/executor_pa.cpp
index e302e0f25c8..1fe7b811b92 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
@@ -932,21 +932,22 @@ struct MHAHelper {
if (_sliding_window) {
size_t start_idx = 0;
auto new_causal = ncausal;
+ float* alibi_lookup = nullptr;
if (ncausal > _sliding_window) {
start_idx = ncausal - static_cast<size_t>(_sliding_window);
new_causal = _sliding_window;
}
- attn_softmax_kernel(score + start_idx,
- reinterpret_cast<DATA_TYPE*>(score) + start_idx,
- _d_scale,
- nullptr,
- nullptr,
- nullptr,
- false,
- new_causal,
- rnd_up(cur_kv_len, _block_size) - start_idx,
- precision_of<DATA_TYPE>::value,
- precision_of<DATA_TYPE>::value);
+ attn_softmax_kernel<float>(score + start_idx,
+ reinterpret_cast<DATA_TYPE*>(score) + start_idx,
+ _d_scale,
+ alibi_lookup,
+ nullptr,
+ nullptr,
+ false,
+ new_causal,
+ rnd_up(cur_kv_len, _block_size) - start_idx,
+ precision_of<DATA_TYPE>::value,
+ precision_of<DATA_TYPE>::value);
memset(score, 0, sizeof(DATA_TYPE) * start_idx);
} else {
@@ -957,18 +958,18 @@ struct MHAHelper {
alibi_slope = alibi_slopes.ptr<float>()[h];
alibi_lookup = _alibi_lookup.ptr<float>() + _alibi_lookup.m_dims[0] - ncausal;
}
- attn_softmax_kernel(score,
- reinterpret_cast<DATA_TYPE*>(score),
- _d_scale,
- alibi_lookup,
- nullptr,
- nullptr,
- false,
- ncausal,
- rnd_up(cur_kv_len, _block_size),
- precision_of<DATA_TYPE>::value,
- precision_of<DATA_TYPE>::value,
- alibi_slope);
+ attn_softmax_kernel<float>(score,
+ reinterpret_cast<DATA_TYPE*>(score),
+ _d_scale,
+ alibi_lookup,
+ nullptr,
+ nullptr,
+ false,
+ ncausal,
+ rnd_up(cur_kv_len, _block_size),
+ precision_of<DATA_TYPE>::value,
+ precision_of<DATA_TYPE>::value,
+ alibi_slope);
}
if (score_output) {
cvt_copy(score_output + h * rnd_up(cur_kv_len, 16), reinterpret_cast<DATA_TYPE*>(score), cur_kv_len);
@@ -1058,18 +1059,18 @@ struct MHAHelper {
alibi_slope = alibi_slopes.ptr<float>()[h];
alibi_lookup = _alibi_lookup.ptr<float>() + _alibi_lookup.m_dims[0] - cur_kv_len;
}
- attn_softmax_kernel(_weight.ptr<float>(ithr, h, pq),
- _weight.ptr<float>(ithr, h, pq),
- _d_scale,
- alibi_lookup,
- nullptr,
- nullptr,
- false,
- cur_kv_len,
- cur_kv_len,
- ov::element::f32,
- ov::element::f32,
- alibi_slope);
+ attn_softmax_kernel<float>(_weight.ptr<float>(ithr, h, pq),
+ _weight.ptr<float>(ithr, h, pq),
+ _d_scale,
+ alibi_lookup,
+ nullptr,
+ nullptr,
+ false,
+ cur_kv_len,
+ cur_kv_len,
+ ov::element::f32,
+ ov::element::f32,
+ alibi_slope);
if (score_output) {
memcpy(score_output + h * rnd_up(cur_kv_len, 16), _weight.ptr<float>(ithr, h, pq), cur_kv_len * sizeof(float));
}
@@ -1157,18 +1158,18 @@ struct MHAHelper {
alibi_slope = alibi_slopes.ptr<float>()[h];
alibi_lookup = _alibi_lookup.ptr<float>() + _alibi_lookup.m_dims[0] - cur_kv_len;
}
- attn_softmax_kernel(_weight_bhl.ptr<float>(b, h, pq),
- _weight_bhl.ptr<float>(b, h, pq),
- _d_scale,
- alibi_lookup,
- nullptr,
- nullptr,
- false,
- ncausal,
- cur_kv_len,
- ov::element::f32,
- ov::element::f32,
- alibi_slope);
+ attn_softmax_kernel<float>(_weight_bhl.ptr<float>(b, h, pq),
+ _weight_bhl.ptr<float>(b, h, pq),
+ _d_scale,
+ alibi_lookup,
+ nullptr,
+ nullptr,
+ false,
+ ncausal,
+ cur_kv_len,
+ ov::element::f32,
+ ov::element::f32,
+ alibi_slope);
});
if (output_score) {
diff --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.cpp
index 5177f401331..3ce275d47e3 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
@@ -59,12 +59,20 @@ void cvt_copy(TA* dst, TB* src, size_t n) {
mm256_uni_storeu_ps(dst + i, vb);
}
#elif defined(OPENVINO_ARCH_ARM64)
- int vec_len_f32_neon = 4;
- auto _dst = reinterpret_cast<float32_t*>(dst);
- for (; i + vec_len_f32_neon <= n; i += vec_len_f32_neon) {
- float32x4_t vb1 = vld1q_f32(src + i);
- vst1q_f32(_dst + i, vb1);
+ if (std::is_same<TA, float>::value && std::is_same<TB, float>::value) {
+ for (; i + vec_len_f32_neon <= n; i += vec_len_f32_neon) {
+ float32x4_t vb1 = __vld1q_f32(src + i);
+ __vst1q_f32(dst + i, vb1);
+ }
+ }
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+ if (std::is_same<TA, ov::float16>::value && std::is_same<TB, ov::float16>::value) {
+ for (; i + vec_len_f16_neon <= n; i += vec_len_f16_neon) {
+ auto vb1 = vld1q_f16(reinterpret_cast<const float16_t*>(src + i));
+ vst1q_f16(reinterpret_cast<float16_t*>(dst + i), vb1);
+ }
}
+#endif
#endif
for (; i < n; i++) {
dst[i] = src[i];
@@ -92,12 +100,11 @@ static void attn_acc_value(float* out, float weight, T* v, size_t S, float* scal
}
#elif defined(OPENVINO_ARCH_ARM64)
float32x4_t attn_w_vec_fp32 = vdupq_n_f32(weight);
- auto _v = reinterpret_cast<float32_t *>(v);
for (; i + vec_len_f32_neon <= S; i += vec_len_f32_neon) {
- float32x4_t v_value = vld1q_f32(_v + i);
- float32x4_t v_out = vld1q_f32(out + i);
+ float32x4_t v_value = __vld1q_f32(v + i);
+ float32x4_t v_out = __vld1q_f32(out + i);
v_out = vmlaq_f32(v_out, attn_w_vec_fp32, v_value);
- vst1q_f32(out + i, v_out);
+ __vst1q_f32(out + i, v_out);
}
#endif
for (; i < S; i++) {
@@ -105,6 +112,26 @@ static void attn_acc_value(float* out, float weight, T* v, size_t S, float* scal
}
}
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+template<typename T>
+static void attn_acc_value(ov::float16* out, ov::float16 weight, T* v, size_t S, float* scale, float* zp) {
+ size_t i = 0;
+ auto attn_w_vec_fp16 = vdupq_n_f16(weight);
+ auto _v = reinterpret_cast<float16_t *>(v);
+ auto _out = reinterpret_cast<float16_t *>(out);
+ for (; i + vec_len_f16_neon <= S; i += vec_len_f16_neon) {
+ auto v_value = vld1q_f16(_v + i);
+ auto v_out = vld1q_f16(_out + i);
+ v_out = vfmaq_f16(v_out, attn_w_vec_fp16, v_value);
+ vst1q_f16(_out + i, v_out);
+ }
+ for (; i < S; i++) {
+ out[i] += weight * v[i];
+ }
+}
+#endif
+
+
static void attn_acc_value(float* out, float weight, uint8_t* v, size_t S, float* scale, float* zp) {
size_t i = 0;
weight *= *scale;
@@ -475,19 +502,16 @@ static float dot_product(TA* a, TB* b, size_t n, float* scale, float* zp, float*
float32x4_t vsum2 = vdupq_n_f32(0.0f);
float32x4_t vsum3 = vdupq_n_f32(0.0f);
- auto _a = reinterpret_cast<float32_t*>(a);
- auto _b = reinterpret_cast<float32_t*>(b);
-
for (; i + 4 * vec_len_f32_neon <= n; i += vec_len_f32_neon * 4) {
- float32x4_t va0 = vld1q_f32(_a + i);
- float32x4_t va1 = vld1q_f32(_a + i + vec_len_f32_neon);
- float32x4_t va2 = vld1q_f32(_a + i + vec_len_f32_neon * 2);
- float32x4_t va3 = vld1q_f32(_a + i + vec_len_f32_neon * 3);
+ float32x4_t va0 = __vld1q_f32(a + i);
+ float32x4_t va1 = __vld1q_f32(a + i + vec_len_f32_neon);
+ float32x4_t va2 = __vld1q_f32(a + i + vec_len_f32_neon * 2);
+ float32x4_t va3 = __vld1q_f32(a + i + vec_len_f32_neon * 3);
- float32x4_t vb0 = vld1q_f32(_b + i);
- float32x4_t vb1 = vld1q_f32(_b + i + vec_len_f32_neon);
- float32x4_t vb2 = vld1q_f32(_b + i + vec_len_f32_neon * 2);
- float32x4_t vb3 = vld1q_f32(_b + i + vec_len_f32_neon * 3);
+ float32x4_t vb0 = __vld1q_f32(b + i);
+ float32x4_t vb1 = __vld1q_f32(b + i + vec_len_f32_neon);
+ float32x4_t vb2 = __vld1q_f32(b + i + vec_len_f32_neon * 2);
+ float32x4_t vb3 = __vld1q_f32(b + i + vec_len_f32_neon * 3);
vsum0 = vmlaq_f32(vsum0, va0, vb0);
vsum1 = vmlaq_f32(vsum1, va1, vb1);
@@ -495,19 +519,19 @@ static float dot_product(TA* a, TB* b, size_t n, float* scale, float* zp, float*
vsum3 = vmlaq_f32(vsum3, va3, vb3);
}
if (i + 2 * vec_len_f32_neon <= n) {
- float32x4_t va0 = vld1q_f32(_a + i);
- float32x4_t va1 = vld1q_f32(_a + i + vec_len_f32_neon);
+ float32x4_t va0 = __vld1q_f32(a + i);
+ float32x4_t va1 = __vld1q_f32(a + i + vec_len_f32_neon);
- float32x4_t vb0 = vld1q_f32(_b + i);
- float32x4_t vb1 = vld1q_f32(_b + i + vec_len_f32_neon);
+ float32x4_t vb0 = __vld1q_f32(b + i);
+ float32x4_t vb1 = __vld1q_f32(b + i + vec_len_f32_neon);
vsum0 = vmlaq_f32(vsum0, va0, vb0);
vsum1 = vmlaq_f32(vsum1, va1, vb1);
i += 2 * vec_len_f32_neon;
}
if (i + vec_len_f32_neon <= n) {
- float32x4_t va0 = vld1q_f32(_a + i);
- float32x4_t vb0 = vld1q_f32(_b + i);
+ float32x4_t va0 = __vld1q_f32(a + i);
+ float32x4_t vb0 = __vld1q_f32(b + i);
vsum0 = vmlaq_f32(vsum0, va0, vb0);
i += vec_len_f32_neon;
}
@@ -527,6 +551,64 @@ static float dot_product(TA* a, TB* b, size_t n, float* scale, float* zp, float*
return sum;
}
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+static ov::float16 dot_product_fp16(ov::float16* a, ov::float16* b, size_t n, float* scale, float* zp, float* head_sum) {
+ size_t i = 0;
+ ov::float16 sum = 0.0f;
+ auto vsum0 = vdupq_n_f16(0.0f);
+ auto vsum1 = vdupq_n_f16(0.0f);
+ auto vsum2 = vdupq_n_f16(0.0f);
+ auto vsum3 = vdupq_n_f16(0.0f);
+ auto _a = reinterpret_cast<float16_t*>(a);
+ auto _b = reinterpret_cast<float16_t*>(b);
+
+ for (; i + 4 * vec_len_f16_neon <= n; i += vec_len_f16_neon * 4) {
+ auto va0 = vld1q_f16(_a + i);
+ auto va1 = vld1q_f16(_a + i + vec_len_f16_neon);
+ auto va2 = vld1q_f16(_a + i + vec_len_f16_neon * 2);
+ auto va3 = vld1q_f16(_a + i + vec_len_f16_neon * 3);
+
+ auto vb0 = vld1q_f16(_b + i);
+ auto vb1 = vld1q_f16(_b + i + vec_len_f16_neon);
+ auto vb2 = vld1q_f16(_b + i + vec_len_f16_neon * 2);
+ auto vb3 = vld1q_f16(_b + i + vec_len_f16_neon * 3);
+
+ vsum0 = vfmaq_f16(vsum0, va0, vb0);
+ vsum1 = vfmaq_f16(vsum1, va1, vb1);
+ vsum2 = vfmaq_f16(vsum2, va2, vb2);
+ vsum3 = vfmaq_f16(vsum3, va3, vb3);
+ }
+ if (i + 2 * vec_len_f16_neon <= n) {
+ auto va0 = vld1q_f16(_a + i);
+ auto va1 = vld1q_f16(_a + i + vec_len_f16_neon);
+
+ auto vb0 = vld1q_f16(_b + i);
+ auto vb1 = vld1q_f16(_b + i + vec_len_f16_neon);
+
+ vsum0 = vfmaq_f16(vsum0, va0, vb0);
+ vsum1 = vfmaq_f16(vsum1, va1, vb1);
+ i += 2 * vec_len_f16_neon;
+ }
+ if (i + vec_len_f16_neon <= n) {
+ auto va0 = vld1q_f16(_a + i);
+ auto vb0 = vld1q_f16(_b + i);
+ vsum0 = vfmaq_f16(vsum0, va0, vb0);
+ i += vec_len_f16_neon;
+ }
+
+ vsum0 = vaddq_f16(vsum0, vsum1);
+ vsum2 = vaddq_f16(vsum2, vsum3);
+ vsum0 = vaddq_f16(vsum0, vsum2);
+
+ sum = hsum(vsum0);
+
+ for (; i < n; i++) {
+ sum += a[i] * b[i];
+ }
+ return sum;
+}
+#endif
+
template<typename TA>
static float dot_product(TA* a, uint8_t* b, size_t n, float* scale, float* zp, float* head_sum) {
size_t i = 0;
@@ -708,16 +790,15 @@ static void attn_reduce(T* dst, float* temp, size_t M, size_t S, size_t temp_str
mm256_uni_storeu_ps(dst + i, result_vec_fp32);
}
#elif defined(OPENVINO_ARCH_ARM64)
- auto _dst = reinterpret_cast<float32_t*>(dst);
for (; i + vec_len_f32_neon <= S; i += vec_len_f32_neon) {
auto* src = temp + i;
auto result_vec_fp32 = vdupq_n_f32(0.0f);
for (size_t m = 0; m < M; m++) {
- auto o_vec_fp32 = vld1q_f32(src);
+ auto o_vec_fp32 = __vld1q_f32(src);
result_vec_fp32 = vaddq_f32(result_vec_fp32, o_vec_fp32);
src += temp_stride;
}
- vst1q_f32(_dst + i, result_vec_fp32);
+ __vst1q_f32(dst + i, result_vec_fp32);
}
#endif
for (; i < S; i++) {
@@ -732,7 +813,33 @@ static void attn_reduce(T* dst, float* temp, size_t M, size_t S, size_t temp_str
}
}
-template <typename T, typename T2>
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+static void attn_reduce(ov::float16* dst, ov::float16* temp, size_t M, size_t S, size_t temp_stride) {
+ size_t i = 0;
+ for (; i + vec_len_f16_neon <= S; i += vec_len_f16_neon) {
+ auto* src = temp + i;
+ auto result_vec_fp16 = vdupq_n_f16(0.0f);
+ for (size_t m = 0; m < M; m++) {
+ auto o_vec_fp16 = vld1q_f16(reinterpret_cast<float16_t*>(src));
+ result_vec_fp16 = vaddq_f16(result_vec_fp16, o_vec_fp16);
+ src += temp_stride;
+ }
+ vst1q_f16(reinterpret_cast<float16_t*>(dst + i), result_vec_fp16);
+ }
+ for (; i < S; i++) {
+ auto* src = temp + i;
+ float sum = 0.0f;
+ // sum result from all threads partition
+ for (size_t m = 0; m < M; m++) {
+ sum += src[0];
+ src += temp_stride;
+ }
+ dst[i] = sum;
+ }
+}
+#endif
+
+template <typename T, typename T2, typename T3>
static void mha_single_token_kernel(const ov::intel_cpu::PlainTensor& query,
const ov::intel_cpu::PlainTensor& present_key,
const ov::intel_cpu::PlainTensor& present_value,
@@ -755,6 +862,10 @@ static void mha_single_token_kernel(const ov::intel_cpu::PlainTensor& query,
auto q_len = query.size(2);
auto S = query.size(3);
auto h_group_num = present_value.size(1);
+ auto precision = ov::element::f32;
+ if (std::is_same<T3, ov::float16>::value) {
+ precision = ov::element::f16;
+ }
size_t h_each_group_len = 1;
if (h_group_num != H) {
h_each_group_len = H / h_group_num;
@@ -790,19 +901,39 @@ static void mha_single_token_kernel(const ov::intel_cpu::PlainTensor& query,
// the memory will be continuous when b==1
for (size_t iwork = start; iwork < end; ++iwork) {
auto p = past_k_scale_zp.ptr<float>(pk, 0, h_group);
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+ if (std::is_same<T3, ov::float16>::value && std::is_same<T, ov::float16>::value && std::is_same<T2, ov::float16>::value) {
+ auto p_k = present_key.ptr<ov::float16>(0, h_group, pk);
+ prefetch_bytes(S, _MM_HINT_T0, 4096, p_k);
+ auto _qk = dot_product_fp16(query.ptr<ov::float16>(0, h_group), p_k,
+ S, p, p + 1, head_sum.ptr<float>(0, h_group));
+ buf_attn_w.ptr<T3>(0, h_group, 0)[pk] = _qk;
+ parallel_it_step(pk, kv_len, b, B, h_group, h_group_num);
+ continue;
+ }
+#endif
auto p_k = present_key.ptr<T2>(0, h_group, pk);
prefetch_bytes(S, _MM_HINT_T0, 4096, p_k);
- buf_attn_w.ptr<float>(0, h_group, 0)[pk] =
- dot_product(query.ptr<T>(0, h_group), p_k,
- S, p, p + 1, head_sum.ptr<float>(0, h_group));
+ buf_attn_w.ptr<T3>(0, h_group, 0)[pk] = dot_product(query.ptr<T>(0, h_group), p_k,
+ S, p, p + 1, head_sum.ptr<float>(0, h_group));;
parallel_it_step(pk, kv_len, b, B, h_group, h_group_num);
}
} else {
for (size_t iwork = start; iwork < end; ++iwork) {
auto b_kv = beams ? beams.ptr<int32_t>(b)[pk] : b;
auto p = past_k_scale_zp.ptr<float>(pk, b_kv, h_group);
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+ if (std::is_same<T3, ov::float16>::value && std::is_same<T, ov::float16>::value && std::is_same<T2, ov::float16>::value) {
+ auto p_k = present_key.ptr<ov::float16>(b_kv, h_group, pk);
+ auto _qk = dot_product_fp16(query.ptr<ov::float16>(b, h_group), p_k,
+ S, p, p + 1, head_sum.ptr<float>(b, h_group));
+ buf_attn_w.ptr<T3>(b, h_group, 0)[pk] = _qk;
+ parallel_it_step(pk, kv_len, b, B, h_group, h_group_num);
+ continue;
+ }
+#endif
auto p_k = present_key.ptr<T2>(b_kv, h_group, pk);
- buf_attn_w.ptr<float>(b, h_group, 0)[pk] =
+ buf_attn_w.ptr<T3>(b, h_group, 0)[pk] =
dot_product(query.ptr<T>(b, h_group), p_k,
S, p, p + 1, head_sum.ptr<float>(b, h_group));
parallel_it_step(pk, kv_len, b, B, h_group, h_group_num);
@@ -814,7 +945,16 @@ static void mha_single_token_kernel(const ov::intel_cpu::PlainTensor& query,
for (size_t pq = 0; pq < q_len; pq++) {
auto p = past_k_scale_zp.ptr<float>(pk, b_kv, h_group);
for (size_t h = h_group * h_each_group_len; h < (h_group + 1) * h_each_group_len; h++) {
- buf_attn_w.ptr<float>(b, h, pq)[pk] =
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+ if (std::is_same<T3, ov::float16>::value && std::is_same<T, ov::float16>::value && std::is_same<T2, ov::float16>::value) {
+ auto p_k = present_key.ptr<ov::float16>(b_kv, h_group, pk);
+ auto _qk = dot_product_fp16(query.ptr<ov::float16>(b, h, pq), p_k,
+ S, p, p + 1, head_sum.ptr<float>(b, h, pq));
+ buf_attn_w.ptr<T3>(b, h, pq)[pk] = _qk;
+ continue;
+ }
+#endif
+ buf_attn_w.ptr<T3>(b, h, pq)[pk] =
dot_product(query.ptr<T>(b, h, pq), present_key.ptr<T2>(b_kv, h_group, pk),
S, p, p + 1, head_sum.ptr<float>(b, h, pq));
}
@@ -829,44 +969,44 @@ static void mha_single_token_kernel(const ov::intel_cpu::PlainTensor& query,
auto cur_kv_len = kv_len;
auto ncausal = auto_causal ? (cur_kv_len - q_len + pq + 1) : cur_kv_len;
// apply attention mask & sofmax
- float* alibi_ptr = alibi_mask ? &alibi_mask.at<float>({b, h, pq, 0}, true) : nullptr;
+ T3* alibi_ptr = alibi_mask ? &alibi_mask.at<T3>({b, h, pq, 0}, true) : nullptr;
uint8_t* attn_mask_ptr = nullptr;
auto attn_mask_prec = attention_mask.get_precision();
if (attention_mask)
attn_mask_ptr = reinterpret_cast<uint8_t*>(&attention_mask.at<T>({b, h, pq, 0}, true));
uint8_t* cmask_ptr = causal_mask ? &causal_mask.at<uint8_t>({b, h, pq, 0}, true) : nullptr;
- attn_softmax_kernel(buf_attn_w.ptr<float>(b, h, pq),
- buf_attn_w.ptr<float>(b, h, pq),
- d_scale,
- alibi_ptr,
- attn_mask_ptr,
- cmask_ptr,
- select_nfltmax_at_0,
- ncausal,
- cur_kv_len,
- attn_mask_prec,
- ov::element::f32);
+ attn_softmax_kernel<T3>(buf_attn_w.ptr<T3>(b, h, pq),
+ buf_attn_w.ptr<T3>(b, h, pq),
+ d_scale,
+ alibi_ptr,
+ attn_mask_ptr,
+ cmask_ptr,
+ select_nfltmax_at_0,
+ ncausal,
+ cur_kv_len,
+ attn_mask_prec,
+ precision);
});
// attn_w * V
// Fast Path if there are enough works for each thread
if (B >= static_cast<size_t>(nthr)) {
- buf_attn_score.resize<float>({static_cast<size_t>(nthr), q_len, h_each_group_len, S});
+ buf_attn_score.resize<T3>({static_cast<size_t>(nthr), q_len, h_each_group_len, S});
parallel_for2d(B, h_group_num, [&](size_t b, size_t h_group) {
auto ithr = parallel_get_thread_num();
- memset(buf_attn_score.ptr<float>(ithr), 0, q_len * h_each_group_len * S * sizeof(float));
+ memset(buf_attn_score.ptr<T3>(ithr), 0, q_len * h_each_group_len * S * sizeof(T3));
for (size_t pv = 0; pv < kv_len; pv++) {
auto b_kv = beams ? beams.ptr<int32_t>(b)[pv] : b;
auto* v = present_value.ptr<T2>(b_kv, h_group, pv);
auto p = past_v_scale_zp.ptr<float>(pv, b_kv, h_group);
for (size_t pq = 0; pq < q_len; pq++) {
for (size_t h = h_group * h_each_group_len, group_idx = 0; h < (h_group + 1) * h_each_group_len; h++, group_idx++) {
- attn_acc_value(buf_attn_score.ptr<float>(ithr, pq, group_idx),
- buf_attn_w.ptr<float>(b, h, pq)[pv],
- v,
- S,
- p + 0,
- p + 1);
+ attn_acc_value(buf_attn_score.ptr<T3>(ithr, pq, group_idx),
+ buf_attn_w.ptr<T3>(b, h, pq)[pv],
+ v,
+ S,
+ p + 0,
+ p + 1);
}
}
}
@@ -875,20 +1015,20 @@ static void mha_single_token_kernel(const ov::intel_cpu::PlainTensor& query,
for (size_t h = h_group * h_each_group_len, group_idx = 0; h < (h_group + 1) * h_each_group_len;
h++, group_idx++) {
auto* dst = has_out_transpose ? output_emb.ptr<T>(b, pq, h * S) : output_emb.ptr<T>(b, h, pq);
- cvt_copy(dst, buf_attn_score.ptr<float>(ithr, pq, group_idx), S);
+ cvt_copy(dst, buf_attn_score.ptr<T3>(ithr, pq, group_idx), S);
}
}
});
return;
}
- buf_attn_score.resize<float>({static_cast<size_t>(nthr), B, q_len, H, S});
+ buf_attn_score.resize<T3>({static_cast<size_t>(nthr), B, q_len, H, S});
// buf_attn_w {B, H, q_len, kv_len}
parallel_nt_static(nthr, [&](const size_t ithr, const size_t nthr) {
size_t start{0}, end{0};
splitter(B * h_group_num * kv_len, nthr, ithr, start, end);
- memset(buf_attn_score.ptr<float>(ithr, 0, 0, 0, 0), 0, buf_attn_score.stride(0) * sizeof(float));
+ memset(buf_attn_score.ptr<T3>(ithr, 0, 0, 0, 0), 0, buf_attn_score.stride(0) * sizeof(T3));
size_t b, h_group, pv;
if (start < end) {
@@ -898,12 +1038,12 @@ static void mha_single_token_kernel(const ov::intel_cpu::PlainTensor& query,
auto b_kv = beams ? beams.ptr<int32_t>(b)[pv] : b;
auto* v = present_value.ptr<T2>(b_kv, h_group, pv);
auto p = past_v_scale_zp.ptr<float>(pv, b_kv, h_group);
- attn_acc_value(buf_attn_score.ptr<float>(ithr, b, 0, h_group),
- buf_attn_w.ptr<float>(b, h_group, 0, pv)[0],
- v,
- S,
- p + 0,
- p + 1);
+ attn_acc_value(buf_attn_score.ptr<T3>(ithr, b, 0, h_group),
+ buf_attn_w.ptr<T3>(b, h_group, 0, pv)[0],
+ v,
+ S,
+ p + 0,
+ p + 1);
parallel_it_step(pv, kv_len, b, B, h_group, h_group_num);
}
} else {
@@ -913,8 +1053,8 @@ static void mha_single_token_kernel(const ov::intel_cpu::PlainTensor& query,
auto p = past_v_scale_zp.ptr<float>(pv, b_kv, h_group);
for (size_t pq = 0; pq < q_len; pq++) {
for (size_t h = h_group * h_each_group_len; h < (h_group + 1) * h_each_group_len; h++) {
- attn_acc_value(buf_attn_score.ptr<float>(ithr, b, pq, h),
- buf_attn_w.ptr<float>(b, h, pq)[pv],
+ attn_acc_value(buf_attn_score.ptr<T3>(ithr, b, pq, h),
+ buf_attn_w.ptr<T3>(b, h, pq)[pv],
v,
S,
p + 0,
@@ -928,7 +1068,7 @@ static void mha_single_token_kernel(const ov::intel_cpu::PlainTensor& query,
});
parallel_for3d(B, H, q_len, [&](size_t b, size_t h, size_t pq) {
- auto* temp = buf_attn_score.ptr<float>(0, b, pq, h);
+ auto* temp = buf_attn_score.ptr<T3>(0, b, pq, h);
size_t temp_stride = buf_attn_score.stride(0);
auto* dst = has_out_transpose ? output_emb.ptr<T>(b, pq, h * S) : output_emb.ptr<T>(b, h, pq);
attn_reduce(dst, temp, nthr, S, temp_stride);
@@ -952,7 +1092,7 @@ void mha_single_token(const ov::intel_cpu::PlainTensor& query,
ov::intel_cpu::PlainTensor& head_sum) {
if (query.get_precision() == ov::element::bf16) {
if (present_key.get_precision() == ov::element::u8) {
- mha_single_token_kernel<ov::bfloat16, uint8_t>(query,
+ mha_single_token_kernel<ov::bfloat16, uint8_t, float>(query,
present_key,
present_value,
alibi_mask,
@@ -968,7 +1108,7 @@ void mha_single_token(const ov::intel_cpu::PlainTensor& query,
past_v_scale_zp,
head_sum);
} else {
- mha_single_token_kernel<ov::bfloat16, ov::bfloat16>(query,
+ mha_single_token_kernel<ov::bfloat16, ov::bfloat16, float>(query,
present_key,
present_value,
alibi_mask,
@@ -986,7 +1126,7 @@ void mha_single_token(const ov::intel_cpu::PlainTensor& query,
}
} else if (query.get_precision() == ov::element::f32) {
if (present_key.get_precision() == ov::element::u8) {
- mha_single_token_kernel<float, uint8_t>(query,
+ mha_single_token_kernel<float, uint8_t, float>(query,
present_key,
present_value,
alibi_mask,
@@ -1002,7 +1142,7 @@ void mha_single_token(const ov::intel_cpu::PlainTensor& query,
past_v_scale_zp,
head_sum);
} else if (present_key.get_precision() == ov::element::f16) {
- mha_single_token_kernel<float, ov::float16>(query,
+ mha_single_token_kernel<float, ov::float16, float>(query,
present_key,
present_value,
alibi_mask,
@@ -1018,7 +1158,7 @@ void mha_single_token(const ov::intel_cpu::PlainTensor& query,
past_v_scale_zp,
head_sum);
} else {
- mha_single_token_kernel<float, float>(query,
+ mha_single_token_kernel<float, float, float>(query,
present_key,
present_value,
alibi_mask,
@@ -1034,6 +1174,30 @@ void mha_single_token(const ov::intel_cpu::PlainTensor& query,
past_v_scale_zp,
head_sum);
}
+ } else if (query.get_precision() == ov::element::f16) {
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+ if (present_key.get_precision() == ov::element::f16) {
+ mha_single_token_kernel<ov::float16, ov::float16, ov::float16>(query,
+ present_key,
+ present_value,
+ alibi_mask,
+ attention_mask,
+ beams,
+ output_emb,
+ buf_attn_w,
+ buf_attn_score,
+ has_out_transpose,
+ auto_causal,
+ d_scale,
+ past_k_scale_zp,
+ past_v_scale_zp,
+ head_sum);
+ } else {
+ OPENVINO_THROW("Unsupported precision: ", query.get_precision());
+ }
+#else
+ OPENVINO_THROW("Unsupported precision: ", query.get_precision());
+#endif
} else {
OPENVINO_THROW("Unsupported precision: ", query.get_precision());
}
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax.cpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax.cpp
index d91db322a94..28755e69eaf 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax.cpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax.cpp
@@ -23,21 +23,32 @@ namespace Extensions {
namespace Cpu {
namespace XARCH {
-void attn_softmax(float* a,
+void attn_softmax(void* a,
void* a_dst,
float scale,
- float* alibi,
+ void* alibi,
void* attn_mask,
uint8_t* causal_mask,
bool select_nfltmax_at_0,
size_t len,
size_t total_size,
+ ov::element::Type precision,
ov::element::Type attn_mask_prec,
ov::element::Type dst_precision) {
- attn_softmax_kernel(a, a_dst, scale, alibi, attn_mask, causal_mask, select_nfltmax_at_0, len, total_size, attn_mask_prec, dst_precision);
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+ if (precision == ov::element::f16) {
+ auto _a = reinterpret_cast<ov::float16*>(a);
+ auto _alibi = reinterpret_cast<ov::float16*>(alibi);
+ attn_softmax_kernel<ov::float16>(_a, a_dst, scale, _alibi, attn_mask, causal_mask, select_nfltmax_at_0, len, total_size, attn_mask_prec, dst_precision);
+ return;
+ }
+#endif
+ auto _a = reinterpret_cast<float*>(a);
+ auto _alibi = reinterpret_cast<float*>(alibi);
+ attn_softmax_kernel<float>(_a, a_dst, scale, _alibi, attn_mask, causal_mask, select_nfltmax_at_0, len, total_size, attn_mask_prec, dst_precision);
}
} // namespace XARCH
} // namespace Cpu
} // namespace Extensions
-} // namespace ov
\ No newline at end of file
+} // namespace ov
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax.hpp
index 8528d3d35a7..ee264924e8f 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax.hpp
@@ -14,17 +14,19 @@ namespace Extensions {
namespace Cpu {
namespace XARCH {
-void attn_softmax(float* a,
+void attn_softmax(void* a,
void* a_dst,
float scale,
- float* alibi,
+ void* alibi,
void* attn_mask,
uint8_t* causal_mask,
bool select_nfltmax_at_0,
size_t len,
size_t total_size,
+ ov::element::Type precision,
ov::element::Type attn_mask_prec,
ov::element::Type dst_precision);
+
} // namespace XARCH
} // namespace Cpu
} // namespace Extensions
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax_kernel.hpp
index 6b08c4dc10e..bffe0ee3761 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax_kernel.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/scaled_attn/softmax_kernel.hpp
@@ -449,6 +449,76 @@ inline void scale_add2_reduce_max(float* a,
}
}
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+template <bool has_alibi, bool has_attn_mask, bool has_causal_mask, typename T>
+inline void scale_add2_reduce_max(ov::float16* a,
+ float scale,
+ const ov::float16* alibi_lookup,
+ const T* attn_mask,
+ const uint8_t* causal_mask,
+ bool select_nfltmax_at_0, // true: 0 in mask set -FLT_MAX
+ size_t size,
+ float alibi_slope,
+ ov::float16& max) {
+ float16x8_t v_max = vdupq_n_f16(static_cast<float16_t>(-FLT_MAX));
+ float16x8_t v_scale = vdupq_n_f16(static_cast<float16_t>(scale));
+ float16x8_t v_a;
+ size_t i = 0;
+ uint16x8_t v_zeroi16 = vdupq_n_u16(0);
+ float16x8_t v_nfltmax = vdupq_n_f16(static_cast<float16_t>(-FLT_MAX));
+ uint16x8_t mask_xor = vdupq_n_u16(select_nfltmax_at_0 ? 0xFFFF : 0);
+ float16x8_t v_alibi_slope = vdupq_n_f16(static_cast<float16_t>(alibi_slope));
+
+ // process vector body
+ for (; i + vec_len_f16_neon <= size; i += vec_len_f16_neon) {
+ v_a = vld1q_f16(reinterpret_cast<const float16_t*>(a + i));
+ v_a = vmulq_f16(v_a, v_scale);
+
+ if (has_alibi) {
+ float16x8_t v_lookup = vld1q_f16(reinterpret_cast<const float16_t*>(alibi_lookup + i));
+ v_a = vfmaq_f16(v_a, v_lookup, v_alibi_slope);
+ }
+
+ if (has_attn_mask) {
+ float16x8_t v_mask = vld1q_f16(reinterpret_cast<const float16_t*>(attn_mask + i));
+ v_a = vaddq_f16(v_a, v_mask);
+ }
+
+ if (has_causal_mask) {
+ uint8x8_t v_maski8 = vld1_u8(causal_mask + i);
+ uint16x8_t v_maski16 = vmovl_u8(v_maski8);
+ uint16x8_t kmask = vceqq_u16(v_maski16, v_zeroi16);
+ kmask = veorq_u16(kmask, mask_xor);
+ v_a = vbslq_f16(kmask, v_nfltmax, v_a);
+ }
+
+ v_max = vmaxq_f16(v_max, v_a);
+ vst1q_f16(reinterpret_cast<float16_t*>(a + i), v_a);
+ }
+ max = vmaxvq_f16(v_max);
+ // process tails
+ for (; i < size; i++) {
+ a[i] *= scale;
+ if (has_alibi) {
+ a[i] += alibi_lookup[i] * alibi_slope;
+ }
+
+ if (has_attn_mask)
+ a[i] += attn_mask[i];
+ if (has_causal_mask) {
+ if (select_nfltmax_at_0) {
+ if (causal_mask[i] == 0)
+ a[i] = -FLT_MAX;
+ } else {
+ if (causal_mask[i] != 0)
+ a[i] = -FLT_MAX;
+ }
+ }
+ max = a[i] > max ? a[i] : max;
+ }
+}
+#endif
+
#if defined(HAVE_AVX512F)
static inline void exp_ps_avx512(__m512& src) {
#define REPEAT16(x) x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x
@@ -593,7 +663,7 @@ inline void exp_reduce_sum(float* a, const float max, const size_t size, float&
while (i + vec_len_f32_neon <= size) {
v_a = vld1q_f32(a + i);
v_a = vsubq_f32(v_a, v_max);
- v_a = exp_ps_neon(v_a);
+ v_a = exp_ps_neon_f32(v_a);
v_sum = vaddq_f32(v_sum, v_a);
vst1q_f32(a + i, v_a);
i += vec_len_f32_neon;
@@ -607,6 +677,72 @@ inline void exp_reduce_sum(float* a, const float max, const size_t size, float&
}
}
+#if defined(OPENVINO_ARCH_ARM64)
+inline void exp_reduce_sum_f32(ov::float16* a, const ov::float16 max, const size_t size, ov::float16& sum) {
+ float32x4_t v_a;
+ float32x4_t v_max = vdupq_n_f32(static_cast<float>(max));
+ float32x4_t v_sum = vdupq_n_f32(0.0f);
+ size_t i = 0;
+
+ // Process 4 FP32 elements at a time
+ for (; i + vec_len_f32_neon <= size; i += vec_len_f32_neon) {
+ // Load FP16 and convert to FP32
+ float16x4_t v_a_f16 = vld1_f16(reinterpret_cast<const float16_t*>(a + i));
+ v_a = vcvt_f32_f16(v_a_f16);
+
+ // Compute in FP32
+ v_a = vsubq_f32(v_a, v_max);
+ v_a = exp_ps_neon_f32(v_a);
+ v_sum = vaddq_f32(v_sum, v_a);
+
+ // Convert back to FP16 and store
+ float16x4_t v_result_f16 = vcvt_f16_f32(v_a);
+ vst1_f16(reinterpret_cast<float16_t*>(a + i), v_result_f16);
+ }
+
+ // Reduce sum
+ float total_sum = vaddvq_f32(v_sum);
+
+ // Handle remaining elements
+ for (; i < size; ++i) {
+ float val = exp(static_cast<float>(a[i] - max));
+ a[i] = static_cast<ov::float16>(val);
+ total_sum += val;
+ }
+
+ sum += static_cast<ov::float16>(total_sum);
+}
+#endif
+
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+inline void exp_reduce_sum(ov::float16* a, const ov::float16 max, const size_t size, ov::float16& sum) {
+ const size_t vec_len_f16_neon = 8;
+ float16x8_t v_a;
+ float16x8_t v_max = vdupq_n_f16(max);
+ float16x8_t v_sum = vdupq_n_f16(0.0f);
+ size_t i = 0;
+
+ for (; i + vec_len_f16_neon <= size; i += vec_len_f16_neon) {
+ v_a = vld1q_f16(reinterpret_cast<const float16_t*>(a + i));
+ v_a = vsubq_f16(v_a, v_max);
+ v_a = exp_ps_neon_f16(v_a);
+ v_sum = vaddq_f16(v_sum, v_a);
+ vst1q_f16(reinterpret_cast<float16_t*>(a + i), v_a);
+ }
+
+ float16x4_t v_sum_low = vadd_f16(vget_low_f16(v_sum), vget_high_f16(v_sum));
+ float16x4_t v_sum_pair = vpadd_f16(v_sum_low, v_sum_low);
+ float16x4_t v_sum_final = vpadd_f16(v_sum_pair, v_sum_pair);
+
+ sum += vget_lane_f16(v_sum_final, 0);
+
+ for (; i < size; ++i) {
+ a[i] = static_cast<ov::float16>(exp(static_cast<float>(a[i] - max)));
+ sum += a[i];
+ }
+}
+#endif
+
inline void multiply_scalar(float* a, float* a_dst, const float val, const size_t size) {
size_t i = 0;
#if defined(HAVE_AVX512F)
@@ -680,11 +816,64 @@ inline void multiply_scalar(float* a, ov::bfloat16* a_dst, const float val, cons
}
#endif
}
+#if defined(OPENVINO_ARCH_ARM64)
+inline void multiply_scalar(ov::float16* a, float* a_dst, const ov::float16 val, const size_t size) {
+ float16x4_t v_a_f16;
+ float32x4_t v_a, v_res;
+ float32x4_t v_val = vdupq_n_f32(static_cast<float>(val));
+ size_t i = 0;
+
+ for (; i + vec_len_f16_neon <= size; i += vec_len_f16_neon) {
+ v_a_f16 = vld1_f16(reinterpret_cast<const float16_t*>(a + i));
+ v_a = vcvt_f32_f16(v_a_f16);
+
+ v_res = vmulq_f32(v_a, v_val);
-inline void attn_softmax_kernel(float* a,
+ vst1q_f32(reinterpret_cast<float*>(a_dst + i), v_res);
+ }
+
+ for (; i < size; ++i) {
+ float a_f32 = static_cast<float>(a[i]);
+ a_dst[i] = a_f32 * static_cast<float>(val);
+ }
+}
+inline void multiply_scalar_f32(ov::float16* a, ov::float16* a_dst, const ov::float16 val, const size_t size) {
+ float32x4_t v_a, v_res;
+ float32x4_t v_val = vdupq_n_f32(val);
+ size_t i = 0;
+ for (; i + vec_len_f32_neon <= size; i += vec_len_f32_neon) {
+ v_a = __vld1q_f32((a + i));
+ v_res = vmulq_f32(v_a, v_val);
+ __vst1q_f32(a_dst + i, v_res);
+ }
+ auto val_f32 = static_cast<float>(val);
+ for (; i < size; ++i) {
+ auto _a_f32 = static_cast<float>(a_dst[i]);
+ auto _a_dst_f32 = val_f32 * _a_f32;
+ a_dst[i] = static_cast<ov::float16>(_a_dst_f32);
+ }
+}
+#endif
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+inline void multiply_scalar(ov::float16* a, ov::float16* a_dst, const ov::float16 val, const size_t size) {
+ float16x8_t v_a, v_res;
+ float16x8_t v_val = vdupq_n_f16(val);
+ size_t i = 0;
+ for (; i + vec_len_f16_neon <= size; i += vec_len_f16_neon) {
+ v_a = vld1q_f16(reinterpret_cast<const float16_t*>(a + i));
+ v_res = vmulq_f16(v_a, v_val);
+ vst1q_f16(reinterpret_cast<float16_t*>(a_dst + i), v_res);
+ }
+ for (; i < size; ++i) {
+ a_dst[i] = a[i] * val;
+ }
+}
+#endif
+template <typename T>
+inline void attn_softmax_kernel(T* a,
void* a_dst,
float scale,
- float* alibi,
+ T* alibi,
void* attn_mask,
uint8_t* causal_mask,
bool select_nfltmax_at_0,
@@ -692,7 +881,21 @@ inline void attn_softmax_kernel(float* a,
size_t total_size,
ov::element::Type attn_mask_prec,
ov::element::Type dst_precision,
- float alibi_slope = 0) {
+ float alibi_slope = 0);
+
+template <>
+inline void attn_softmax_kernel<float>(float* a,
+ void* a_dst,
+ float scale,
+ float* alibi,
+ void* attn_mask,
+ uint8_t* causal_mask,
+ bool select_nfltmax_at_0,
+ size_t len,
+ size_t total_size,
+ ov::element::Type attn_mask_prec,
+ ov::element::Type dst_precision,
+ float alibi_slope) {
using func_fp32_type = void (*)(float*, float, const float*, const float*, const uint8_t*, bool, size_t, float, float&);
using func_bf16_type = void (*)(float*, float, const float*, const ov::bfloat16*, const uint8_t*, bool, size_t, float, float&);
static constexpr func_fp32_type funcs_fp32[] = {
@@ -740,6 +943,81 @@ inline void attn_softmax_kernel(float* a,
memset(static_cast<ov::bfloat16*>(a_dst) + len, 0, sizeof(ov::bfloat16) * (total_size - len));
}
}
+#if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC)
+template <>
+inline void attn_softmax_kernel<ov::float16>(ov::float16* a,
+ void* a_dst,
+ float scale,
+ ov::float16* alibi,
+ void* attn_mask,
+ uint8_t* causal_mask,
+ bool select_nfltmax_at_0,
+ size_t len,
+ size_t total_size,
+ ov::element::Type attn_mask_prec,
+ ov::element::Type dst_precision,
+ float alibi_slope) {
+ using func_fp32_type = void (*)(ov::float16*, float, const ov::float16*, const float*, const uint8_t*, bool, size_t, float, ov::float16&);
+ using func_bf16_type = void (*)(ov::float16*, float, const ov::float16*, const ov::bfloat16*, const uint8_t*, bool, size_t, float, ov::float16&);
+ using func_fp16_type = void (*)(ov::float16*, float, const ov::float16*, const ov::float16*, const uint8_t*, bool, size_t, float, ov::float16&);
+ static constexpr func_fp32_type funcs_fp32[] = {
+ scale_add2_reduce_max<false, false, false>,
+ scale_add2_reduce_max<false, false, true>,
+ scale_add2_reduce_max<false, true, false>,
+ scale_add2_reduce_max<false, true, true>,
+ scale_add2_reduce_max<true, false, false>,
+ scale_add2_reduce_max<true, false, true>,
+ scale_add2_reduce_max<true, true, false>,
+ scale_add2_reduce_max<true, true, true>
+ };
+ static constexpr func_bf16_type funcs_bf16[] = {
+ scale_add2_reduce_max<false, false, false>,
+ scale_add2_reduce_max<false, false, true>,
+ scale_add2_reduce_max<false, true, false>,
+ scale_add2_reduce_max<false, true, true>,
+ scale_add2_reduce_max<true, false, false>,
+ scale_add2_reduce_max<true, false, true>,
+ scale_add2_reduce_max<true, true, false>,
+ scale_add2_reduce_max<true, true, true>
+ };
+ static constexpr func_fp16_type funcs_fp16[] = {
+ scale_add2_reduce_max<false, false, false>,
+ scale_add2_reduce_max<false, false, true>,
+ scale_add2_reduce_max<false, true, false>,
+ scale_add2_reduce_max<false, true, true>,
+ scale_add2_reduce_max<true, false, false>,
+ scale_add2_reduce_max<true, false, true>,
+ scale_add2_reduce_max<true, true, false>,
+ scale_add2_reduce_max<true, true, true>
+ };
+ int dispatch = (alibi ? 0b100 : 0) | (attn_mask ? 0b010 : 0) | (causal_mask ? 0b001 : 0);
+ ov::float16 max = std::numeric_limits<ov::float16>::lowest();
+ if (attn_mask_prec == ov::element::f32) {
+ funcs_fp32[dispatch](a, scale, alibi, static_cast<const float*>(attn_mask), causal_mask, select_nfltmax_at_0, len, alibi_slope, max);
+ } else if (attn_mask_prec == ov::element::f16) {
+ funcs_fp16[dispatch](a, scale, alibi, static_cast<const ov::float16*>(attn_mask), causal_mask, select_nfltmax_at_0, len, alibi_slope, max);
+ } else {
+ funcs_bf16[dispatch](a, scale, alibi, static_cast<const ov::bfloat16*>(attn_mask), causal_mask, select_nfltmax_at_0, len, alibi_slope, max);
+ }
+
+ ov::float16 sum = 0.0f;
+ if (dst_precision == ov::element::f32) {
+ exp_reduce_sum_f32(a, max, len, sum);
+ ov::float16 scalar = 1.0f / sum;
+ multiply_scalar(a, static_cast<float*>(a_dst), scalar, len);
+ // apply causual mask to final result instead of attn_score
+ if (total_size > len)
+ memset(static_cast<float*>(a_dst) + len, 0, sizeof(float) * (total_size - len));
+ } else {
+ exp_reduce_sum_f32(a, max, len, sum);
+ ov::float16 scalar = 1.0f / sum;
+ multiply_scalar_f32(a, static_cast<ov::float16*>(a_dst), scalar, len);
+ // apply causual mask to final result instead of attn_score
+ if (total_size > len)
+ memset(static_cast<ov::float16*>(a_dst) + len, 0, sizeof(ov::float16) * (total_size - len));
+ }
+}
+#endif
} // namespace XARCH
} // namespace Cpu
diff --git a/src/plugins/intel_cpu/src/nodes/scaled_attn.cpp b/src/plugins/intel_cpu/src/nodes/scaled_attn.cpp
index 72c9bf4b0a7..016fa90398a 100644
--- a/src/plugins/intel_cpu/src/nodes/scaled_attn.cpp
+++ b/src/plugins/intel_cpu/src/nodes/scaled_attn.cpp
@@ -34,6 +34,7 @@
#include "kernels/scaled_attn/attn_quant.hpp"
#include "kernels/x64/brgemm_kernel.hpp"
#include "nodes/common/cpu_convert.h"
+#include "utils/precision_support.h"
#include <algorithm>
#include <string>
@@ -404,16 +405,17 @@ struct MHAKernel<ScaledDotProductAttention::KT_ONEDNN, T> {
// apply attention mask & sofmax
auto ncausal = auto_causal ? (kv_len - q_len + m + 1) : kv_len;
auto score = weight_score.ptr<float>(ithr, h, m - m_start);
- attn_softmax(score,
+ attn_softmax(reinterpret_cast<void*>(score),
reinterpret_cast<T*>(score),
d_scale,
- alibi_ptr + m * alibi_stride,
+ reinterpret_cast<void*>(alibi_ptr + m * alibi_stride),
attn_mask_ptr + m * attn_mask_stride,
cmask_ptr + m * cmask_stride,
select_nfltmax_at_0,
ncausal,
kv_len,
precision_of<T>::value,
+ precision_of<T>::value,
precision_of<T>::value);
}
auto* w_ptr = reinterpret_cast<T*>(weight_score.ptr<float>(ithr, h, 0, 0));
@@ -497,15 +499,17 @@ struct MHAKernel<ScaledDotProductAttention::KT_ONEDNN, T> {
};
#ifdef OV_CPU_WITH_ACL
-template <>
-struct MHAKernel<ScaledDotProductAttention::KT_ACL, float> {
+template <typename T>
+struct MHAKernel<ScaledDotProductAttention::KT_ACL, T> {
const GraphContext::CPtr context;
size_t m_block_size;
+ ov::element::Type precision;
MHAKernel() = delete;
explicit MHAKernel(GraphContext::CPtr ctx): context(ctx) {
m_block_size = 512;
select_nfltmax_at_0 = false;
+ precision = ov::element::from<T>();
}
PlainTensor causal_mask;
@@ -551,23 +555,23 @@ struct MHAKernel<ScaledDotProductAttention::KT_ACL, float> {
auto m_end = std::min(m_start + m_block_size, q_len);
auto m_cnt = m_end - m_start;
- float* q_ptr = &query.at<float>({b, h, m_start, 0});
- float* k_ptr = &present_key.at<float>({b, h / h_each_group_len, 0, 0});
- float* v_ptr = &present_value.at<float>({b, h / h_each_group_len, 0, 0});
+ auto q_ptr = &query.at<T>({b, h, m_start, 0});
+ auto k_ptr = &present_key.at<T>({b, h / h_each_group_len, 0, 0});
+ auto v_ptr = &present_value.at<T>({b, h / h_each_group_len, 0, 0});
- float* alibi_ptr = nullptr;
+ T* alibi_ptr = nullptr;
auto alibi_stride = 0;
if (alibi_mask) {
- alibi_ptr = &alibi_mask.at<float>({b, h, 0, 0}, true);
+ alibi_ptr = &alibi_mask.at<T>({b, h, 0, 0}, true);
if (alibi_mask.size(2) > 1)
alibi_stride = alibi_mask.stride(2);
}
uint8_t* attn_mask_ptr = nullptr;
auto attn_mask_stride = 0;
if (attention_mask) {
- attn_mask_ptr = reinterpret_cast<uint8_t*>(&attention_mask.at<float>({b, h, 0, 0}, true));
+ attn_mask_ptr = reinterpret_cast<uint8_t*>(&attention_mask.at<T>({b, h, 0, 0}, true));
if (attention_mask.size(2) > 1)
- attn_mask_stride = attention_mask.stride(2) * sizeof(float);
+ attn_mask_stride = attention_mask.stride(2) * sizeof(T);
}
uint8_t* cmask_ptr = nullptr;
auto cmask_stride = 0;
@@ -583,7 +587,7 @@ struct MHAKernel<ScaledDotProductAttention::KT_ACL, float> {
bool b_transpose = false;
if (k_stride_s == 1)
b_transpose = true;
- GemmKernel qk_gemm(m_cnt, head_size, kv_len, b_transpose);
+ GemmKernel qk_gemm(m_cnt, head_size, kv_len, b_transpose, precision);
arm_compute::Strides qStrides({query.stride_bytes(3), query.stride_bytes(2)});
arm_compute::Strides kStrides({present_key.stride_bytes(3), present_key.stride_bytes(2)});
@@ -594,30 +598,31 @@ struct MHAKernel<ScaledDotProductAttention::KT_ACL, float> {
qStrides,
kStrides);
- auto qk = reinterpret_cast<float*>(qkTensor.buffer());
+ auto qk = reinterpret_cast<T*>(qkTensor.buffer());
for (size_t m = m_start; m < m_end; m++) {
// apply attention mask & sofmax
auto ncausal = auto_causal ? (kv_len - q_len + m + 1) : kv_len;
- attn_softmax(qk + (m - m_start) * kv_len,
+ attn_softmax(reinterpret_cast<void*>(qk + (m - m_start) * kv_len),
qk + (m - m_start) * kv_len,
d_scale,
- alibi_ptr + m * alibi_stride,
+ reinterpret_cast<void*>(alibi_ptr + m * alibi_stride),
attn_mask_ptr + m * attn_mask_stride,
cmask_ptr + m * cmask_stride,
select_nfltmax_at_0,
ncausal,
kv_len,
- ov::element::f32,
- ov::element::f32);
+ precision,
+ precision,
+ precision);
}
arm_compute::TensorInfo outInfo;
arm_compute::Tensor outTensor;
- auto out = has_out_transpose ? &output_emb.at<float>({b, m_start, h * head_size}) : &output_emb.at<float>({b, h, m_start});
+ auto out = has_out_transpose ? &output_emb.at<T>({b, m_start, h * head_size}) : &output_emb.at<T>({b, h, m_start});
auto strides = arm_compute::Strides({output_emb.stride_bytes(1), output_emb.stride_bytes(2)});
- GemmKernel out_gemm(m_cnt, kv_len, head_size);
+ GemmKernel out_gemm(m_cnt, kv_len, head_size, false, precision);
arm_compute::Strides vStrides({present_value.stride_bytes(3), present_value.stride_bytes(2)});
out_gemm.executeGemm(qkTensor.buffer(),
@@ -765,16 +770,17 @@ struct MHAKernel<ScaledDotProductAttention::KT_MLAS, float> {
for (size_t m = m_start; m < m_end; m++) {
// apply attention mask & sofmax
auto ncausal = auto_causal ? (kv_len - q_len + m + 1) : kv_len;
- attn_softmax(qk + (m - m_start) * qk_m_stride,
+ attn_softmax(reinterpret_cast<void*>(qk + (m - m_start) * qk_m_stride),
qk + (m - m_start) * qk_m_stride,
d_scale,
- alibi_ptr + m * alibi_stride,
+ reinterpret_cast<void*>(alibi_ptr + m * alibi_stride),
attn_mask_ptr + m * attn_mask_stride,
cmask_ptr + m * cmask_stride,
select_nfltmax_at_0,
ncausal,
kv_len,
ov::element::f32,
+ ov::element::f32,
ov::element::f32);
}
mlas_sgemm("N",
@@ -1067,8 +1073,11 @@ void ScaledDotProductAttention::createPrimitive() {
executor = std::make_shared<AttentionExecutor<KT_ONEDNN, ov::bfloat16>>(context);
#endif
} else {
-#ifdef OV_CPU_WITH_ACL
- executor = std::make_shared<AttentionExecutor<KT_ACL, float>>(context);
+#if defined(OV_CPU_WITH_ACL)
+ if (rtPrecision == ov::element::f16)
+ executor = std::make_shared<AttentionExecutor<KT_ACL, ov::float16>>(context);
+ else
+ executor = std::make_shared<AttentionExecutor<KT_ACL, float>>(context);
#elif defined(OV_CPU_WITH_MLAS)
executor = std::make_shared<AttentionExecutor<KT_MLAS, float>>(context);
#elif defined(OPENVINO_ARCH_X86_64)
@@ -1696,6 +1705,8 @@ ov::element::Type ScaledDotProductAttention::getRuntimePrecision() const {
// bf16 should be enabled only when platform supports
if (rtPrecision == ov::element::bf16 && ov::with_cpu_x86_bfloat16()) {
rtPrecision = ov::element::bf16;
+ } else if (rtPrecision == ov::element::f16 && ov::intel_cpu::hasHardwareSupport(ov::element::f16)) {
+ rtPrecision = ov::element::f16;
} else {
rtPrecision = ov::element::f32;
}
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/arm/concat_sdp.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/arm/concat_sdp.cpp
new file mode 100644
index 00000000000..eb6fdc2a6bf
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/arm/concat_sdp.cpp
@@ -0,0 +1,45 @@
+// Copyright (C) 2023 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#include "openvino/opsets/opset13.hpp"
+#include "openvino/pass/manager.hpp"
+#include "transformations/op_conversions/scaled_dot_product_attention_decomposition.hpp"
+
+#include "custom/subgraph_tests/src/classes/concat_sdp.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+#include "utils/cpu_test_utils.hpp"
+#include "common_test_utils/ov_tensor_utils.hpp"
+
+using namespace CPUTestUtils;
+
+namespace ov {
+namespace test {
+
+namespace {
+const std::vector<std::vector<InputShape>> inputShapes = {
+ // greedy search
+ {
+ // B, H, L1, S
+ {{1, 8, -1, 64}, {{1, 8, 10, 64}, {1, 8, 1, 64}, {1, 8, 1, 64}, {1, 8, 20, 64}, {1, 8, 1, 64}}},
+ // B, H, L0, S
+ {{1, 8, -1, 64}, {{1, 8, 0, 64}, {1, 8, 10, 64}, {1, 8, 11, 64}, {1, 8, 12, 64}, {1, 8, 32, 64}}},
+ },
+ // beam search
+ {
+ // B, H, L1, S
+ {{-1, 8, -1, 64}, {{4, 8, 10, 64}, {4, 8, 1, 64}, {4, 8, 1, 64}, {4, 8, 1, 64}, {4, 8, 1, 64}}},
+ // B, H, L0, S
+ {{-1, 8, -1, 64}, {{4, 8, 0, 64}, {4, 8, 10, 64}, {4, 8, 11, 64}, {4, 8, 12, 64}, {4, 8, 13, 64}}},
+ },
+};
+
+INSTANTIATE_TEST_SUITE_P(smoke_ConcatSDPTest,
+ ConcatSDPTest,
+ ::testing::Combine(::testing::Values(ElementType::f16),
+ ::testing::ValuesIn(inputShapes),
+ ::testing::Values(true, false)),
+ ConcatSDPTest::getTestCaseName);
+} // namespace
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.cpp
new file mode 100644
index 00000000000..f4abaa03b7c
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.cpp
@@ -0,0 +1,231 @@
+// Copyright (C) 2023 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#include "concat_sdp.hpp"
+
+using namespace CPUTestUtils;
+
+namespace ov {
+namespace test {
+
+// Subgraph:
+/* Parameter
+ * |
+ * Parameter ReadValue | ReadValue Parameter
+ * \ / | \ /
+ * Gather / Gather /
+ * \ / | \ /
+ * Concat | Concat
+ * / \ | / \
+ * / \ | / \
+ * / \ | / \
+ * Assign ScaledDotProductAttention Assign
+ * |
+ * Add
+ * |
+ * Result
+ */
+std::string ConcatSDPTest::getTestCaseName(const testing::TestParamInfo<ConcatSDPTestParams>& obj) {
+ ElementType inType;
+ std::vector<InputShape> inputShapes;
+ bool hasShapeof;
+ std::tie(inType, inputShapes, hasShapeof) = obj.param;
+ std::ostringstream result;
+ result << "IS=";
+ for (const auto& shape : inputShapes) {
+ result << ov::test::utils::partialShape2str({shape.first}) << "_";
+ }
+ result << "TS=";
+ for (const auto& shape : inputShapes) {
+ result << "(";
+ if (!shape.second.empty()) {
+ for (const auto& itr : shape.second) {
+ result << ov::test::utils::vec2str(itr);
+ }
+ }
+ result << ")_";
+ }
+ result << "Prc=" << inType << "_";
+ result << "HasShapeOf=" << hasShapeof;
+ return result.str();
+}
+
+void ConcatSDPTest::SetUp() {
+ ElementType inType;
+ std::vector<InputShape> inputShapes;
+ std::tie(inType, inputShapes, hasShapeOf) = this->GetParam();
+ targetDevice = ov::test::utils::DEVICE_CPU;
+ rel_threshold = 1e-2f;
+ if (inType == ElementType::bf16) {
+ configuration.insert({"ENFORCE_BF16", "YES"});
+ rel_threshold = 0.01f;
+ } else if (inType == ElementType::f16) {
+ configuration.insert({"INFERENCE_PRECISION_HINT", ov::element::Type(inType).get_type_name()});
+ }
+ init_input_shapes(inputShapes);
+ ov::ParameterVector inputParams;
+ // q,k,v
+ inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, inputDynamicShapes[0]));
+ inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, inputDynamicShapes[0]));
+ inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, inputDynamicShapes[0]));
+ inputParams[0]->set_friendly_name("q");
+ inputParams[1]->set_friendly_name("k");
+ inputParams[2]->set_friendly_name("v");
+ // pastkv init_cost
+ inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, inputDynamicShapes[1]));
+ auto var_k = std::make_shared<ov::op::util::Variable>(
+ ov::op::util::VariableInfo{inputDynamicShapes[1], inType, "pastk"});
+ auto pastk = std::make_shared<ov::op::v6::ReadValue>(inputParams[3], var_k);
+ pastk->set_friendly_name("pastk_r");
+ auto var_v = std::make_shared<ov::op::util::Variable>(
+ ov::op::util::VariableInfo{inputDynamicShapes[1], inType, "pastv"});
+ auto pastv = std::make_shared<ov::op::v6::ReadValue>(inputParams[3], var_v);
+ pastv->set_friendly_name("pastv_r");
+ auto beam_idx = std::make_shared<ov::op::v0::Parameter>(ElementType::i32, ov::PartialShape{-1});
+ beam_idx->set_friendly_name("beam_idx");
+ inputParams.push_back(beam_idx);
+ auto gatherK = std::make_shared<ov::op::v8::Gather>(pastk, beam_idx, op::v0::Constant::create(ElementType::i32, {}, {0}));
+ auto gatherV = std::make_shared<ov::op::v8::Gather>(pastv, beam_idx, op::v0::Constant::create(ElementType::i32, {}, {0}));
+ std::shared_ptr<Node> shapeof_k, shapeof_v;
+ // test special case:
+ // ReadValue->Gather->Concat->SDPA...
+ // |
+ // ShapeOf...
+ // The transformation 'SimplifyGatherShapeOf' will move ShapeOf to be the child of ReadValue
+ if (hasShapeOf) {
+ shapeof_k = std::make_shared<ov::op::v0::ShapeOf>(gatherK);
+ shapeof_v = std::make_shared<ov::op::v0::ShapeOf>(gatherV);
+ }
+ auto concatK = std::make_shared<ov::op::v0::Concat>(OutputVector{gatherK, inputParams[1]}, 2);
+ auto concatV = std::make_shared<ov::op::v0::Concat>(OutputVector{gatherV, inputParams[2]}, 2);
+ auto sdp = std::make_shared<ov::opset13::ScaledDotProductAttention>(inputParams[0], concatK, concatV, false);
+ sdp->set_friendly_name("mha");
+ auto add = std::make_shared<ov::op::v1::Add>(sdp, op::v0::Constant::create(inType, {1}, {1.0f}));
+ auto pastk_assign = std::make_shared<op::v6::Assign>(concatK, var_k);
+ auto pastv_assign = std::make_shared<op::v6::Assign>(concatV, var_v);
+ pastk_assign->set_friendly_name("pastk_w");
+ pastv_assign->set_friendly_name("pastv_w");
+
+ ResultVector results{std::make_shared<ov::op::v0::Result>(add)};
+ if (hasShapeOf) {
+ results.push_back(std::make_shared<ov::op::v0::Result>(shapeof_k));
+ results.push_back(std::make_shared<ov::op::v0::Result>(shapeof_v));
+ }
+ SinkVector sinks{pastk_assign, pastv_assign};
+ function = std::make_shared<ov::Model>(results, sinks, inputParams, "ConcatSDP");
+ targetDevice = ov::test::utils::DEVICE_CPU;
+
+ functionRefs = function->clone();
+ pass::Manager manager;
+ // decompose ScaledDotProductAttention
+ manager.register_pass<ov::pass::ScaledDotProductAttentionDecomposition>();
+ manager.run_passes(functionRefs);
+}
+void ConcatSDPTest::generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) {
+ std::vector<ov::Shape> shapes(4);
+ shapes[0] = targetInputStaticShapes[0];
+ shapes[1] = targetInputStaticShapes[0];
+ shapes[2] = targetInputStaticShapes[0];
+ shapes[3] = targetInputStaticShapes[1];
+ SubgraphBaseTest::generate_inputs(shapes);
+}
+template<typename IT, typename T>
+void strided_iota(IT first, size_t n, T value, T stride) {
+ for (size_t i = 0; i < n; i++) {
+ *first++ = value;
+ value += stride;
+ }
+}
+void ConcatSDPTest::generate(int idx, const std::vector<ov::Shape>& targetInputStaticShapes) {
+ inputs.clear();
+ auto create_input = [this] (std::shared_ptr<op::v0::Parameter> param, ov::Shape shape, float val) {
+ if (param->get_element_type() == element::i32) {
+ ov::Tensor t{ov::element::i32, shape};
+ auto size = shape[0];
+ auto* p = static_cast<int*>(t.data());
+ auto start = static_cast<int>(val);
+ for (size_t i = 0; i < size; i++) {
+ p[i] = (start + i) % size;
+ }
+ inputs.insert({param, t});
+ } else if (param->get_element_type() == element::f32) {
+ ov::Tensor t{ov::element::f32, shape};
+ strided_iota(static_cast<float*>(t.data()), t.get_size(), val, 0.1f);
+ inputs.insert({param, t});
+ } else if (param->get_element_type() == element::f16) {
+ ov::Tensor t{ov::element::f16, shape};
+ strided_iota(static_cast<ov::float16 *>(t.data()), t.get_size(), val, 0.0f);
+ inputs.insert({param, t});
+ } else {
+ ov::Tensor t{ov::element::bf16, shape};
+ strided_iota(static_cast<ov::bfloat16*>(t.data()), t.get_size(), val, 0.1f);
+ inputs.insert({param, t});
+ }
+ };
+ // q, k, v, pastkv
+ create_input(function->get_parameters()[0], targetInputStaticShapes[0], idx + 1.0f);
+ create_input(function->get_parameters()[1], targetInputStaticShapes[0], idx + 2.0f);
+ create_input(function->get_parameters()[2], targetInputStaticShapes[0], idx + 3.0f);
+ create_input(function->get_parameters()[3], targetInputStaticShapes[1], idx + 4.0f);
+ create_input(function->get_parameters()[4], ov::Shape{targetInputStaticShapes[0][0]}, idx + 0.0f);
+}
+void ConcatSDPTest::prepare() {
+ compile_model();
+ inferRequest = compiledModel.create_infer_request();
+ ASSERT_TRUE(inferRequest);
+}
+void ConcatSDPTest::reset() {
+ for (auto&& state : inferRequest.query_state()) {
+ state.reset();
+ }
+}
+std::vector<ov::Tensor> ConcatSDPTest::run_test(std::shared_ptr<ov::Model> model) {
+ function = model;
+ prepare();
+ std::vector<ov::Tensor> outputs;
+ int idx = 0;
+ for (auto&& shapes : targetStaticShapes) {
+ generate(idx++, shapes);
+ for (const auto& input : inputs) {
+ inferRequest.set_tensor(input.first, input.second);
+ }
+ inferRequest.infer();
+ auto outputTensor = inferRequest.get_output_tensor(0);
+ ov::Tensor copy{outputTensor.get_element_type(), outputTensor.get_shape()};
+ outputTensor.copy_to(copy);
+ outputs.push_back(copy);
+ }
+ reset();
+
+ return outputs;
+}
+TEST_P(ConcatSDPTest, CompareWithRefs) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED();
+ auto actualOutputs = run_test(function);
+ if (!hasShapeOf) {
+ CheckNumberOfNodesWithType(compiledModel, "ScaledDotProductAttention", 1);
+ CheckNumberOfNodesWithType(compiledModel, "Concatenation", 0);
+ CheckNumberOfNodesWithType(compiledModel, "Reorder", 0);
+ CheckNumberOfNodesWithType(compiledModel, "Gather", 0);
+ } else {
+ // SimplifyGatherShapeOf will generate subgraph which contains Gather/Concat/Reorder, so could not check the number to confirm it's expected.
+ // W/ or w/o fusion the SDPA name is the same, but if fused the output number should be 3(data+pastk+pastv)
+ for (const auto& node : compiledModel.get_runtime_model()->get_ops()) {
+ if (node->get_rt_info().find(ov::exec_model_info::LAYER_TYPE)->second.as<std::string>() == "ScaledDotProductAttention") {
+ ASSERT_EQ(3, node->get_output_size()) << "ScaledDotProductAttention should be fused";
+ }
+ }
+ }
+ if (inType == ElementType::f16) {
+ configuration["INFERENCE_PRECISION_HINT"] = "f32";
+ }
+ auto expectedOutputs = run_test(functionRefs);
+ CheckNumberOfNodesWithType(compiledModel, "ScaledDotProductAttention", 0);
+ for (size_t i = 0; i < actualOutputs.size(); i++) {
+ ov::test::utils::compare(expectedOutputs[i], actualOutputs[i], abs_threshold, rel_threshold);
+ }
+}
+
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.hpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.hpp
new file mode 100644
index 00000000000..56fad11f53e
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/concat_sdp.hpp
@@ -0,0 +1,56 @@
+// Copyright (C) 2023 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#include "openvino/opsets/opset13.hpp"
+#include "openvino/pass/manager.hpp"
+#include "transformations/op_conversions/scaled_dot_product_attention_decomposition.hpp"
+
+#include "shared_test_classes/base/ov_subgraph.hpp"
+#include "utils/cpu_test_utils.hpp"
+#include "common_test_utils/ov_tensor_utils.hpp"
+
+using namespace CPUTestUtils;
+
+namespace ov {
+namespace test {
+
+// Subgraph:
+/* Parameter
+ * |
+ * Parameter ReadValue | ReadValue Parameter
+ * \ / | \ /
+ * Gather / Gather /
+ * \ / | \ /
+ * Concat | Concat
+ * / \ | / \
+ * / \ | / \
+ * / \ | / \
+ * Assign ScaledDotProductAttention Assign
+ * |
+ * Add
+ * |
+ * Result
+ */
+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> ConcatSDPTestParams;
+
+class ConcatSDPTest :
+ public testing::WithParamInterface<ConcatSDPTestParams>,
+ virtual public ov::test::SubgraphBaseTest,
+ public CPUTestsBase {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<ConcatSDPTestParams>& obj);
+ void generate(int idx, const std::vector<ov::Shape>& targetInputStaticShapes);
+ void prepare();
+ void reset();
+ std::vector<ov::Tensor> run_test(std::shared_ptr<ov::Model> model);
+ bool hasShapeOf;
+protected:
+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override;
+ void SetUp() override;
+};
+
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/concat_sdp.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/common/concat_sdp.cpp
index c522e0bc7ca..f9971a7fe9c 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
@@ -5,6 +5,7 @@
#include "openvino/pass/manager.hpp"
#include "transformations/op_conversions/scaled_dot_product_attention_decomposition.hpp"
+#include "custom/subgraph_tests/src/classes/concat_sdp.hpp"
#include "shared_test_classes/base/ov_subgraph.hpp"
#include "utils/cpu_test_utils.hpp"
#include "common_test_utils/ov_tensor_utils.hpp"
@@ -14,226 +15,6 @@ using namespace CPUTestUtils;
namespace ov {
namespace test {
-using ConcatSDPTestParams = std::tuple<ElementType,
- std::vector<InputShape>,
- bool // has ShapeOf
- >;
-// Subgraph:
-/* Parameter
- * |
- * Parameter ReadValue | ReadValue Parameter
- * \ / | \ /
- * Gather / Gather /
- * \ / | \ /
- * Concat | Concat
- * / \ | / \
- * / \ | / \
- * / \ | / \
- * Assign ScaledDotProductAttention Assign
- * |
- * Add
- * |
- * Result
- */
-
-class ConcatSDPTest : public testing::WithParamInterface<ConcatSDPTestParams>, virtual public ov::test::SubgraphBaseTest, public CPUTestsBase {
-public:
- static std::string getTestCaseName(const testing::TestParamInfo<ConcatSDPTestParams>& obj) {
- ElementType inType;
- std::vector<InputShape> inputShapes;
- bool hasShapeof;
- std::tie(inType, inputShapes, hasShapeof) = obj.param;
- std::ostringstream result;
- result << "IS=";
- for (const auto& shape : inputShapes) {
- result << ov::test::utils::partialShape2str({shape.first}) << "_";
- }
- result << "TS=";
- for (const auto& shape : inputShapes) {
- result << "(";
- if (!shape.second.empty()) {
- for (const auto& itr : shape.second) {
- result << ov::test::utils::vec2str(itr);
- }
- }
- result << ")_";
- }
- result << "Prc=" << inType << "_";
- result << "HasShapeOf=" << hasShapeof;
- return result.str();
- }
-
- void SetUp() override {
- ElementType inType;
- std::vector<InputShape> inputShapes;
- std::tie(inType, inputShapes, hasShapeOf) = this->GetParam();
- targetDevice = ov::test::utils::DEVICE_CPU;
- rel_threshold = 1e-2f;
- if (inType == ElementType::bf16) {
- configuration.insert({"ENFORCE_BF16", "YES"});
- rel_threshold = 0.01f;
- }
- init_input_shapes(inputShapes);
- ov::ParameterVector inputParams;
- // q,k,v
- inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, inputDynamicShapes[0]));
- inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, inputDynamicShapes[0]));
- inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, inputDynamicShapes[0]));
- inputParams[0]->set_friendly_name("q");
- inputParams[1]->set_friendly_name("k");
- inputParams[2]->set_friendly_name("v");
- // pastkv init_cost
- inputParams.push_back(std::make_shared<ov::op::v0::Parameter>(inType, inputDynamicShapes[1]));
- auto var_k = std::make_shared<ov::op::util::Variable>(
- ov::op::util::VariableInfo{inputDynamicShapes[1], inType, "pastk"});
- auto pastk = std::make_shared<ov::op::v6::ReadValue>(inputParams[3], var_k);
- pastk->set_friendly_name("pastk_r");
- auto var_v = std::make_shared<ov::op::util::Variable>(
- ov::op::util::VariableInfo{inputDynamicShapes[1], inType, "pastv"});
- auto pastv = std::make_shared<ov::op::v6::ReadValue>(inputParams[3], var_v);
- pastv->set_friendly_name("pastv_r");
- auto beam_idx = std::make_shared<ov::op::v0::Parameter>(ElementType::i32, ov::PartialShape{-1});
- beam_idx->set_friendly_name("beam_idx");
- inputParams.push_back(beam_idx);
- auto gatherK = std::make_shared<ov::op::v8::Gather>(pastk, beam_idx, op::v0::Constant::create(ElementType::i32, {}, {0}));
- auto gatherV = std::make_shared<ov::op::v8::Gather>(pastv, beam_idx, op::v0::Constant::create(ElementType::i32, {}, {0}));
- std::shared_ptr<Node> shapeof_k, shapeof_v;
- // test special case:
- // ReadValue->Gather->Concat->SDPA...
- // |
- // ShapeOf...
- // The transformation 'SimplifyGatherShapeOf' will move ShapeOf to be the child of ReadValue
- if (hasShapeOf) {
- shapeof_k = std::make_shared<ov::op::v0::ShapeOf>(gatherK);
- shapeof_v = std::make_shared<ov::op::v0::ShapeOf>(gatherV);
- }
- auto concatK = std::make_shared<ov::op::v0::Concat>(OutputVector{gatherK, inputParams[1]}, 2);
- auto concatV = std::make_shared<ov::op::v0::Concat>(OutputVector{gatherV, inputParams[2]}, 2);
- auto sdp = std::make_shared<ov::opset13::ScaledDotProductAttention>(inputParams[0], concatK, concatV, false);
- sdp->set_friendly_name("mha");
- auto add = std::make_shared<ov::op::v1::Add>(sdp, op::v0::Constant::create(inType, {1}, {1.0f}));
- auto pastk_assign = std::make_shared<op::v6::Assign>(concatK, var_k);
- auto pastv_assign = std::make_shared<op::v6::Assign>(concatV, var_v);
- pastk_assign->set_friendly_name("pastk_w");
- pastv_assign->set_friendly_name("pastv_w");
-
- ResultVector results{std::make_shared<ov::op::v0::Result>(add)};
- if (hasShapeOf) {
- results.push_back(std::make_shared<ov::op::v0::Result>(shapeof_k));
- results.push_back(std::make_shared<ov::op::v0::Result>(shapeof_v));
- }
- SinkVector sinks{pastk_assign, pastv_assign};
- function = std::make_shared<ov::Model>(results, sinks, inputParams, "ConcatSDP");
- targetDevice = ov::test::utils::DEVICE_CPU;
-
- functionRefs = function->clone();
- pass::Manager manager;
- // decompose ScaledDotProductAttention
- manager.register_pass<ov::pass::ScaledDotProductAttentionDecomposition>();
- manager.run_passes(functionRefs);
- }
- void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override {
- std::vector<ov::Shape> shapes(4);
- shapes[0] = targetInputStaticShapes[0];
- shapes[1] = targetInputStaticShapes[0];
- shapes[2] = targetInputStaticShapes[0];
- shapes[3] = targetInputStaticShapes[1];
- SubgraphBaseTest::generate_inputs(shapes);
- }
- template<typename IT, typename T>
- void strided_iota(IT first, size_t n, T value, T stride) {
- for (size_t i = 0; i < n; i++) {
- *first++ = value;
- value += stride;
- }
- }
- void generate(int idx, const std::vector<ov::Shape>& targetInputStaticShapes) {
- inputs.clear();
- auto create_input = [this] (std::shared_ptr<op::v0::Parameter> param, ov::Shape shape, float val) {
- if (param->get_element_type() == element::i32) {
- ov::Tensor t{ov::element::i32, shape};
- auto size = shape[0];
- auto* p = static_cast<int*>(t.data());
- auto start = static_cast<int>(val);
- for (size_t i = 0; i < size; i++) {
- p[i] = (start + i) % size;
- }
- inputs.insert({param, t});
- } else if (param->get_element_type() == element::f32) {
- ov::Tensor t{ov::element::f32, shape};
- strided_iota(static_cast<float*>(t.data()), t.get_size(), val, 0.1f);
- inputs.insert({param, t});
- } else {
- ov::Tensor t{ov::element::bf16, shape};
- strided_iota(static_cast<ov::bfloat16*>(t.data()), t.get_size(), val, 0.1f);
- inputs.insert({param, t});
- }
- };
- // q, k, v, pastkv
- create_input(function->get_parameters()[0], targetInputStaticShapes[0], idx + 1.0f);
- create_input(function->get_parameters()[1], targetInputStaticShapes[0], idx + 2.0f);
- create_input(function->get_parameters()[2], targetInputStaticShapes[0], idx + 3.0f);
- create_input(function->get_parameters()[3], targetInputStaticShapes[1], idx + 4.0f);
- create_input(function->get_parameters()[4], ov::Shape{targetInputStaticShapes[0][0]}, idx + 0.0f);
- }
- void prepare() {
- compile_model();
- inferRequest = compiledModel.create_infer_request();
- ASSERT_TRUE(inferRequest);
- }
- void reset() {
- for (auto&& state : inferRequest.query_state()) {
- state.reset();
- }
- }
- std::vector<ov::Tensor> run_test(std::shared_ptr<ov::Model> model) {
- function = model;
- prepare();
- std::vector<ov::Tensor> outputs;
- int idx = 0;
- for (auto&& shapes : targetStaticShapes) {
- generate(idx++, shapes);
- for (const auto& input : inputs) {
- inferRequest.set_tensor(input.first, input.second);
- }
- inferRequest.infer();
- auto outputTensor = inferRequest.get_output_tensor(0);
- ov::Tensor copy{outputTensor.get_element_type(), outputTensor.get_shape()};
- outputTensor.copy_to(copy);
- outputs.push_back(copy);
- }
- reset();
-
- return outputs;
- }
-
- bool hasShapeOf;
-};
-
-TEST_P(ConcatSDPTest, CompareWithRefs) {
- SKIP_IF_CURRENT_TEST_IS_DISABLED();
- auto actualOutputs = run_test(function);
- if (!hasShapeOf) {
- CheckNumberOfNodesWithType(compiledModel, "ScaledDotProductAttention", 1);
- CheckNumberOfNodesWithType(compiledModel, "Concatenation", 0);
- CheckNumberOfNodesWithType(compiledModel, "Reorder", 0);
- CheckNumberOfNodesWithType(compiledModel, "Gather", 0);
- } else {
- // SimplifyGatherShapeOf will generate subgraph which contains Gather/Concat/Reorder, so could not check the number to confirm it's expected.
- // W/ or w/o fusion the SDPA name is the same, but if fused the output number should be 3(data+pastk+pastv)
- for (const auto& node : compiledModel.get_runtime_model()->get_ops()) {
- if (node->get_rt_info().find(ov::exec_model_info::LAYER_TYPE)->second.as<std::string>() == "ScaledDotProductAttention") {
- ASSERT_EQ(3, node->get_output_size()) << "ScaledDotProductAttention should be fused";
- }
- }
- }
- auto expectedOutputs = run_test(functionRefs);
- CheckNumberOfNodesWithType(compiledModel, "ScaledDotProductAttention", 0);
- for (size_t i = 0; i < actualOutputs.size(); i++) {
- ov::test::utils::compare(expectedOutputs[i], actualOutputs[i], abs_threshold, rel_threshold);
- }
-}
-
namespace {
const std::vector<std::vector<InputShape>> inputShapes = {
// greedy search
@@ -253,12 +34,12 @@ const std::vector<std::vector<InputShape>> inputShapes = {
};
INSTANTIATE_TEST_SUITE_P(smoke_ConcatSDPTest,
- ConcatSDPTest,
- ::testing::Combine(::testing::Values(ElementType::f32),
- ::testing::ValuesIn(inputShapes),
- ::testing::Values(true, false)),
- ConcatSDPTest::getTestCaseName);
-
+ ConcatSDPTest,
+ ::testing::Combine(::testing::Values(ElementType::f32),
+ ::testing::ValuesIn(inputShapes),
+ ::testing::Values(true, false)),
+ ConcatSDPTest::getTestCaseName);
} // namespace
+
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/skip_tests_config.cpp b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/skip_tests_config.cpp
index 2502efe4db2..2a8f49b5dcf 100644
--- a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/skip_tests_config.cpp
+++ b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/skip_tests_config.cpp
@@ -534,6 +534,7 @@ std::vector<std::string> disabledTestPatterns() {
if (!ov::intel_cpu::hasHardwareSupport(ov::element::f16)) {
// Skip fp16 tests for paltforms that don't support fp16 precision
retVector.emplace_back(R"(.*INFERENCE_PRECISION_HINT=(F|f)16.*)");
+ retVector.emplace_back(R"(.*Prc=f16.*)");
} else {
// Issue 117407
retVector.emplace_back(