Skip to content

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

[CPU] enable MLP & QKV on non-PA case and minor fixes (#26103)

Tingqian Lif7435e4ff830
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_kernel.cpp b/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_kernel.cpp
index 2564c25ade1..24528e7c5af 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_kernel.cpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_kernel.cpp
@@ -168,11 +168,38 @@ void MKernel::tile_config_M(TileConfig& tile_cfg, int M) {
});
}
+class FP16ToBF16Kernel : public dnnl::impl::cpu::x64::jit_generator {
+public:
+ DECLARE_CPU_JIT_AUX_FUNCTIONS(FP16ToBF16Kernel)
+ FP16ToBF16Kernel() : jit_generator("FP16ToBF16Kernel") {
+ create_kernel();
+ }
+
+ void generate() override {
+ Xbyak::Label loop_begin;
+ Xbyak::Reg64 src = abi_param1;
+ for (int i = 0; i < 16; i++) {
+ vcvtph2ps(zmm0, ptr[src]);
+ vcvtph2ps(zmm1, ptr[src + 32]);
+ vcvtne2ps2bf16(zmm2, zmm1, zmm0);
+ vmovups(ptr[src], zmm2);
+ lea(src, ptr[src + 64]);
+ }
+
+ ret();
+ }
+};
+
template <typename T>
void MKernel::repackB(ov::bfloat16* dst, T* src, int N_stride, int N, int K) {
- if (N == 16 && K == 32 && std::is_same<T, ov::bfloat16>::value) {
+ static FP16ToBF16Kernel fp16_to_bf16;
+
+ if (N == 16 && K == 32 && (std::is_same<T, ov::bfloat16>::value || std::is_same<T, ov::float16>::value)) {
// SIMD optimized version
ov::Extensions::Cpu::XARCH::llm_mlp_transpose_epi32_16x16(dst, src, N_stride * sizeof(T));
+ if (std::is_same<T, ov::float16>::value) {
+ fp16_to_bf16(dst);
+ }
return;
}
@@ -197,17 +224,18 @@ void MKernel::repackB(ov::bfloat16* dst, T* src, int N_stride, int N, int K) {
}
template <typename T>
-void MKernel::prepareB(PlainTensor& ret, T* p_weight, int stride, int N, int K) {
+void MKernel::prepareB(PlainTensor& ret, ov::bfloat16* dst, T* p_weight, int stride, int N, int K) {
OPENVINO_ASSERT((N % 32) == 0);
OPENVINO_ASSERT((K % 32) == 0);
// weight matrix is in unit of [N/32, Kx32]
- ret.resize<ov::bfloat16>({static_cast<size_t>(N / 32), static_cast<size_t>(K * 32)});
+ ret.resize<ov::bfloat16>({static_cast<size_t>(N / 32), static_cast<size_t>(K * 32)}, dst);
auto N_stride = stride / sizeof(T);
for (int n = 0, blkn = 0; n < N; n += 32, blkn++) {
- for (int k = 0, blkk = 0; k < K; k += 32, blkk++) {
+ auto* dst_base = ret.ptr<ov::bfloat16>(blkn, 0);
+ for (int k = 0, blkk = 0; k < K; k += 32, blkk++, dst_base += 1024) {
// two adjacent 32x16 (512) block of weight: dst0 & dst1
- auto* dst0 = ret.ptr<ov::bfloat16>(blkn, blkk * 1024);
+ auto* dst0 = dst_base;
auto* dst1 = dst0 + 16 * 32;
auto valid_k = (K - k) < 32 ? (K - k) : 32;
@@ -222,7 +250,35 @@ void MKernel::prepareB(PlainTensor& ret, T* p_weight, int stride, int N, int K)
}
}
-template void MKernel::prepareB<ov::bfloat16>(PlainTensor& ret, ov::bfloat16* p_weight, int stride, int N, int K);
+// interleaving two weights into one in unit of 16-column
+template <typename T>
+void MKernel::prepareB(PlainTensor& ret, ov::bfloat16* dst, T* p_weight1, T* p_weight2, int stride, int N, int K) {
+ OPENVINO_ASSERT((N % 32) == 0);
+ OPENVINO_ASSERT((K % 32) == 0);
+ // weight matrix is in unit of [N/32, Kx32]
+ ret.resize<ov::bfloat16>({static_cast<size_t>(N / 32), static_cast<size_t>(K * 32)}, dst);
+
+ auto N_stride = stride / sizeof(T);
+ auto N2 = N / 2;
+ for (int n = 0, blkn = 0; n < N2; n += 16, blkn++) {
+ for (int k = 0, blkk = 0; k < K; k += 32, blkk++) {
+ // two adjacent 32x16 (512) block of weight: dst0 & dst1
+ auto* dst0 = ret.ptr<ov::bfloat16>(blkn, blkk * 1024);
+ auto* dst1 = dst0 + 16 * 32;
+ auto valid_k = (K - k) < 32 ? (K - k) : 32;
+
+ auto* src0 = p_weight1 + n * N_stride + k;
+ auto valid_n0 = (N2 - n) < 16 ? (N2 - n) : 16;
+ repackB<T>(dst0, src0, N_stride, valid_n0, valid_k);
+
+ auto* src1 = p_weight2 + n * N_stride + k;
+ repackB<T>(dst1, src1, N_stride, valid_n0, valid_k);
+ }
+ }
+}
+
+template void MKernel::prepareB<ov::float16>(PlainTensor& ret, ov::bfloat16* dst, ov::float16* p_weight, int stride, int N, int K);
+template void MKernel::prepareB<ov::float16>(PlainTensor& ret, ov::bfloat16* dst, ov::float16* p_weight1, ov::float16* p_weight2, int stride, int N, int K);
// run L2 cache blocking kernel with size:
// [BM, BK]*[BK, BN] => [BM, BN]
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_kernel.hpp b/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_kernel.hpp
index 5c969fb7837..1e9634b0d56 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_kernel.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_kernel.hpp
@@ -9,6 +9,18 @@
#include "../scaled_attn/executor_pa_common.hpp"
#include "utils/plain_tensor.hpp"
+// register blocking size for K dimension (1x2 AMX B-tiles)
+#define REG_BLK_K_SIZE 32
+
+// register blocking size for N dimension (1x2 AMX B-tiles)
+#define REG_BLK_N_SIZE 32
+
+// cache blocking sie for K dimension
+#define CACHE_BLK_K_SIZE 256
+
+// cache blocking sie for M dimension
+#define CACHE_BLK_M_SIZE 256
+
namespace ov {
namespace intel_cpu {
@@ -65,7 +77,11 @@ public:
// weight is supposed to be of shape[N, K], stride in unit of bytes
template <typename T>
- void prepareB(PlainTensor& ret, T* p_weight, int stride, int N, int K);
+ void prepareB(PlainTensor& ret, ov::bfloat16* dst, T* p_weight, int stride, int N, int K);
+
+ // interleaving two weights into one in unit of 16-column
+ template <typename T>
+ void prepareB(PlainTensor& ret, ov::bfloat16* dst, T* p_weight1, T* p_weight2, int stride, int N, int K);
// to save push/pop: do not use `abi_save_gpr_regs`
uint8_t* prefetch_next_A_addr;
@@ -111,7 +127,7 @@ struct Work {
int BN = 0;
int blk_K_size = 0;
int output_id;
- ov::bfloat16* p_raw_weights;
+ ov::float16* p_raw_weights;
operator bool() {
return BN > 0;
}
@@ -124,14 +140,41 @@ struct Work {
// input : weight [N, K], setup repacks range of N [n_start, n_end)
template <typename T>
- void setup(T* p_weight, int stride) {
+ void setup(ov::bfloat16* dst, T* p_weight, int stride) {
auto& mkernel = get_MKernel();
- auto num_blk_K = (k1 - k0) / blk_K_size;
- auto* pw = p_weight + n0 * stride / sizeof(T) + k0;
+ auto num_blk_K = (k1 - k0 + blk_K_size - 1) / blk_K_size;
+ auto* pw = p_weight + n0 * stride / sizeof(T);
+ // weight is divided along K dimension into equal size blk_K_size, except last block.
weights.resize(num_blk_K);
- for (int k = 0; k < num_blk_K; k++) {
- mkernel.prepareB(weights[k], pw + k * blk_K_size, stride, BN, blk_K_size);
+ for (int k = k0, ki = 0; k < k1;) {
+ auto subK = std::min(blk_K_size, k1 - k);
+ mkernel.prepareB(weights[ki], dst, pw + k, stride, BN, subK);
+ dst += BN*subK;
+ k += subK;
+ ki++;
+ }
+
+ for (int Mtails = 0; Mtails < 32; Mtails++) {
+ mkernel.tile_config_M(m_tcfg[Mtails], Mtails == 0 ? 32 : Mtails);
+ }
+ }
+
+ template <typename T>
+ void setup(ov::bfloat16* dst, T* p_weight1, T* p_weight2, int stride) {
+ auto& mkernel = get_MKernel();
+ auto num_blk_K = (k1 - k0 + blk_K_size - 1) / blk_K_size;
+ auto* pw1 = p_weight1 + (n0/2) * stride / sizeof(T);
+ auto* pw2 = p_weight2 + (n0/2) * stride / sizeof(T);
+
+ // weight is divided along K dimension into equal size blk_K_size, except last block.
+ weights.resize(num_blk_K);
+ for (int k = k0, ki = 0; k < k1;) {
+ auto subK = std::min(blk_K_size, k1 - k);
+ mkernel.prepareB(weights[ki], dst, pw1 + k, pw2 + k, stride, BN, subK);
+ dst += BN*subK;
+ k += subK;
+ ki++;
}
for (int Mtails = 0; Mtails < 32; Mtails++) {
@@ -142,24 +185,28 @@ struct Work {
ov::Extensions::Cpu::TileConfig m_tcfg[32];
AutoTileConfiger m_tile_configer;
- size_t get_C_size(int M) {
+ PlainTensor m_C;
+
+ size_t set_C(int M, float * ext_buff) {
auto Mtails = M % 32;
auto Mbody = M - Mtails;
auto C_M = Mbody + (Mtails ? 32 : 0);
- return C_M * BN;
+ m_C.resize<float>({static_cast<size_t>(C_M), static_cast<size_t>(BN)}, ext_buff);
+ return C_M * BN * sizeof(float);
}
- void run(int M, uint8_t* pA, int strideA, PlainTensor& C) {
+ void run(int M, uint8_t* pA, int strideA) {
auto& mkernel = get_MKernel();
- int num_blk_K = (k1 - k0) / blk_K_size;
+ int num_blk_K = weights.size();
auto Mtails = M % 32;
auto Mbody = M - Mtails;
-
auto C_M = Mbody + (Mtails ? 32 : 0);
- C.resize<float>({static_cast<size_t>(C_M), static_cast<size_t>(BN)});
- auto pC = reinterpret_cast<uint8_t*>(C.ptr_v());
+
+ auto C_stride_bytes = BN * sizeof(float);
+ OPENVINO_ASSERT(C_M * C_stride_bytes <= m_C.stride_bytes(0) * m_C.size(0));
+ auto pC = reinterpret_cast<uint8_t*>(m_C.ptr_v());
pA += k0 * sizeof(ov::bfloat16);
bool do_accumulation = false;
@@ -174,7 +221,7 @@ struct Work {
strideA,
blockB,
pC,
- C.stride_bytes(0),
+ C_stride_bytes,
reinterpret_cast<uint8_t*>(blockB1.ptr_v()),
do_accumulation);
}
@@ -185,8 +232,8 @@ struct Work {
pA + ki * blk_K_size * sizeof(ov::bfloat16) + Mbody * strideA,
strideA,
blockB,
- pC + Mbody * C.stride_bytes(0),
- C.stride_bytes(0),
+ pC + Mbody * C_stride_bytes,
+ C_stride_bytes,
reinterpret_cast<uint8_t*>(blockB1.ptr_v()),
do_accumulation);
}
@@ -196,6 +243,23 @@ struct Work {
}
};
+// allocate weight memory in bigger trunck can benefit from HugePage (with much less page-fault effort)
+struct WeightBuffer {
+ PlainTensor buffer;
+ std::vector<size_t> offsets;
+ void alloc(std::vector<Work>& works) {
+ size_t weight_cnt = 0;
+ for (auto& work : works) {
+ offsets.push_back(weight_cnt);
+ weight_cnt += (work.n1 - work.n0) * (work.k1 - work.k0);
+ }
+ buffer.resize<ov::bfloat16>({weight_cnt});
+ }
+ ov::bfloat16* get(int work_id) {
+ return buffer.ptr<ov::bfloat16>() + offsets[work_id];
+ }
+};
+
// combine gate_proj & up_proj using activation algo, then convert to bf16
// ConvertFP32toBF16(act_fn(gate) * up)
class GateUpCombine : public dnnl::impl::cpu::x64::jit_generator {
diff --git a/src/plugins/intel_cpu/src/nodes/llm_mlp.cpp b/src/plugins/intel_cpu/src/nodes/llm_mlp.cpp
index f6ba63357e6..72f9ca87200 100644
--- a/src/plugins/intel_cpu/src/nodes/llm_mlp.cpp
+++ b/src/plugins/intel_cpu/src/nodes/llm_mlp.cpp
@@ -24,40 +24,40 @@ namespace node {
#if defined(OPENVINO_ARCH_X86_64)
-class Linear {
+class LinearKsplit2 {
public:
std::vector<Work> works;
int used_nthr = 0;
- bool do_splitK = false;
- Linear() {}
+ WeightBuffer wbuffer;
+ LinearKsplit2() {}
+
+ ReduceAdd2bh * p_jit_reduce2bh;
// weight [N, K]
// Gate & Up are interleaved in N dimension: 16-gate / 16-up
// and post-ops will compute silu(gate)*up in unit of 16 elements
// and store out as bfloat16.
template <typename T>
- void setup(T* p_weight, int stride, int N, int K, bool _do_splitK = false) {
- const int blk_K_size = 256;
- // prepare weights, split N among threads
- // in unit of 32
- OPENVINO_ASSERT((N % 32) == 0);
- OPENVINO_ASSERT((K % blk_K_size) == 0);
+ void setup(T* p_weight, int stride, int N, int K) {
+ static ReduceAdd2bh jit_reduce2bh_2(true);
+
+ OPENVINO_ASSERT((N % REG_BLK_N_SIZE) == 0);
+ OPENVINO_ASSERT((K % REG_BLK_K_SIZE) == 0);
auto nthr = parallel_get_max_threads();
- auto num_blk_N = N / 32;
- auto num_blk_K = K / blk_K_size;
+ auto num_blk_N = N / REG_BLK_N_SIZE;
works.resize(nthr);
- do_splitK = _do_splitK;
- auto K_splits = do_splitK ? 2 : 1;
+ p_jit_reduce2bh = &jit_reduce2bh_2;
+
+ auto K_splits = 2;
// split task on more cores is better on TBB
- auto valid_nthr = nthr / K_splits;
+ auto valid_nthr = nthr / 2;
auto blkN_per_thread = (num_blk_N) / valid_nthr;
auto blkN_leftover = num_blk_N - (blkN_per_thread * valid_nthr);
auto start_blkN = 0;
used_nthr = 0;
- auto blkK_per_thread = (num_blk_K + K_splits - 1) / K_splits;
for (int ithr = 0; ithr < nthr; ithr += K_splits) {
auto blkN = std::min(num_blk_N - start_blkN, blkN_per_thread);
@@ -67,20 +67,24 @@ public:
}
if (blkN) {
auto shared_atomic = std::make_shared<std::atomic_int>(0);
+
+ // split K dimension in unit of 32 evenly among 2 worker-threads
auto start_blkK = 0;
+ auto num_blk_K = K / REG_BLK_K_SIZE;
+ auto blkK_per_thread = (num_blk_K + 1) / 2;
for (int ik = 0; ik < K_splits; ik++) {
auto blk_K = std::min(num_blk_K - start_blkK, blkK_per_thread);
auto& work = works[ithr + ik];
work.sync_flag = shared_atomic;
- work.blk_K_size = blk_K_size;
+ work.blk_K_size = CACHE_BLK_K_SIZE;
- work.n0 = (start_blkN)*32;
- work.n1 = (start_blkN + blkN) * 32;
- work.BN = blkN * 32;
- work.k0 = start_blkK * blk_K_size;
- work.k1 = (start_blkK + blk_K) * blk_K_size;
+ work.n0 = (start_blkN) * REG_BLK_N_SIZE;
+ work.n1 = (start_blkN + blkN) * REG_BLK_N_SIZE;
+ work.BN = blkN * REG_BLK_N_SIZE;
+ work.k0 = start_blkK * REG_BLK_K_SIZE;
+ work.k1 = (start_blkK + blk_K) * REG_BLK_K_SIZE;
start_blkK += blk_K;
used_nthr++;
@@ -90,56 +94,62 @@ public:
start_blkN += blkN;
}
- DEBUG_LOG("Linear N,K=", N, ",", K, " used_nthr=", used_nthr, " do_splitK=", do_splitK);
+ DEBUG_LOG("Linear N,K=", N, ",", K, " used_nthr=", used_nthr);
+
+ wbuffer.alloc(works);
ov::parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
auto& work = works[ithr];
if (work) {
- work.setup(p_weight, stride);
+ work.setup(wbuffer.get(ithr), p_weight, stride);
}
});
DEBUG_LOG(" setup is done. weight @ ", static_cast<void*>(p_weight));
}
- void run(uint8_t* pA, int strideA, int M, ov::bfloat16* dstC, int strideC, std::vector<PlainTensor>& m_tempC) {
- static ReduceAdd2bh jit_reduce2bh_1(false);
- static ReduceAdd2bh jit_reduce2bh_2(true);
-
+ void run(uint8_t* pA, int strideA, int M, ov::bfloat16* dstC, int strideC) {
ov::parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
auto& work = works[ithr];
- auto& workC = m_tempC[ithr];
+ auto& workC = work.m_C;
if (work) {
- work.run(M, pA, strideA, workC);
-
- if (do_splitK) {
- auto sync_id = work.sync_flag->fetch_add(1);
- // (0,1) (2,3)
- if (sync_id & 1) {
- auto peer_ithr = (ithr & 1) ? (ithr - 1) : (ithr + 1);
- auto& peerC = m_tempC[peer_ithr];
- // the other one has finished, we can do the reduce sum
- jit_reduce2bh_2.call(workC.ptr<float>(), peerC.ptr<float>(), workC.stride(0),
- dstC + work.n0, strideC / sizeof(*dstC),
- M, work.BN);
- }
- } else {
- jit_reduce2bh_2.call(workC.ptr<float>(), workC.stride(0),
- dstC + work.n0, strideC / sizeof(*dstC),
- M, work.BN);
+ work.run(M, pA, strideA);
+
+ auto sync_id = work.sync_flag->fetch_add(1);
+ // (0,1) (2,3)
+ if (sync_id & 1) {
+ auto peer_ithr = (ithr & 1) ? (ithr - 1) : (ithr + 1);
+ auto& peerC = works[peer_ithr].m_C;
+ // the other one has finished, we can do the reduce sum
+ p_jit_reduce2bh->call(workC.ptr<float>(), peerC.ptr<float>(), workC.stride(0),
+ dstC + work.n0, strideC / sizeof(*dstC),
+ M, work.BN);
}
}
});
}
+};
- // gate & up are interleaved: 16 gates + 16 up
- void runGateUp(uint8_t* pA, int strideA, int M,
- ov::bfloat16* dstC, int strideC,
- const LLMMLPNode::Config& config,
- std::vector<PlainTensor>& m_tempC) {
+class LinearGateUp {
+public:
+ std::vector<Work> works;
+
+ int used_nthr = 0;
+
+ LinearGateUp() {}
+
+ WeightBuffer wbuffer;
+
+ GateUpCombine* jit_gateup;
+
+ // weight [N, K]
+ // Gate & Up are interleaved in N dimension: 16-gate / 16-up
+ // and post-ops will compute silu(gate)*up in unit of 16 elements
+ // and store out as bfloat16.
+ template <typename T>
+ void setup(T* p_weight_gate, T* p_weight_up, int stride, int N, int K, const LLMMLPNode::Config& config) {
static GateUpCombine jit_gateup_silu(dnnl_eltwise_swish);
static GateUpCombine jit_gateup_gelu(dnnl_eltwise_gelu_tanh);
- GateUpCombine* jit_gateup;
if (config.act == LLMMLPNode::ACT_FN::GELU)
jit_gateup = &jit_gateup_gelu;
else if (config.act == LLMMLPNode::ACT_FN::SILU)
@@ -147,14 +157,66 @@ public:
else
OPENVINO_THROW("unsupported act in GateUpCombine");
+ // prepare weights, split N among threads
+ // in unit of 32
+ OPENVINO_ASSERT((N % REG_BLK_N_SIZE) == 0);
+ OPENVINO_ASSERT((K % REG_BLK_K_SIZE) == 0);
+ auto nthr = parallel_get_max_threads();
+ auto num_blk_N = N / REG_BLK_N_SIZE;
+ works.resize(nthr);
+
+ // split task on more cores is better on TBB
+ auto valid_nthr = nthr;
+ auto blkN_per_thread = (num_blk_N) / valid_nthr;
+ auto blkN_leftover = num_blk_N - (blkN_per_thread * valid_nthr);
+ auto start_blkN = 0;
+ used_nthr = 0;
+
+ for (int ithr = 0; ithr < nthr; ithr ++) {
+ auto blkN = std::min(num_blk_N - start_blkN, blkN_per_thread);
+ if (blkN_leftover > 0) {
+ blkN_leftover--;
+ blkN++;
+ }
+ if (blkN) {
+ auto shared_atomic = std::make_shared<std::atomic_int>(0);
+ auto& work = works[ithr];
+ work.sync_flag = shared_atomic;
+ work.blk_K_size = CACHE_BLK_K_SIZE;
+
+ work.n0 = (start_blkN) * REG_BLK_N_SIZE;
+ work.n1 = (start_blkN + blkN) * REG_BLK_N_SIZE;
+ work.BN = blkN * REG_BLK_N_SIZE;
+ work.k0 = 0;
+ work.k1 = K;
+ used_nthr++;
+ }
+
+ start_blkN += blkN;
+ }
+ wbuffer.alloc(works);
+
+ DEBUG_LOG("Linear N,K=", N, ",", K, " used_nthr=", used_nthr);
ov::parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
auto& work = works[ithr];
- auto& workC = m_tempC[ithr];
- if (work.BN > 0) {
- work.run(M, pA, strideA, workC);
+ if (work) {
+ work.setup(wbuffer.get(ithr), p_weight_gate, p_weight_up, stride);
+ }
+ });
+ DEBUG_LOG(" setup is done. weight @ ", static_cast<void*>(p_weight_gate));
+ }
+
+ // gate & up are interleaved: 16 gates + 16 up
+ void runGateUp(uint8_t* pA, int strideA, int M,
+ ov::bfloat16* dstC, int strideC,
+ const LLMMLPNode::Config& config) {
+ ov::parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
+ auto& work = works[ithr];
+ if (work) {
+ work.run(M, pA, strideA);
// K reduce is done, results of [M, BN] sub-block is ready in L2.
// combine Gate & Up
- jit_gateup->call(workC.ptr<float>(), workC.stride(0),
+ jit_gateup->call(work.m_C.ptr<float>(), work.m_C.stride(0),
dstC + (work.n0 / 2), strideC / sizeof(*dstC),
M, work.BN);
}
@@ -168,14 +230,13 @@ struct LLMMLP::Impl {
MemoryPtr m_scratchMem;
uint8_t* m_scratch_base = nullptr;
- Linear gate_up;
- Linear down;
+ LinearGateUp gate_up;
+ LinearKsplit2 down;
int m_N;
int m_M = 0;
// MLP is not supposed to run in parallel
PlainTensor m_actUp;
- std::vector<PlainTensor> m_tempC;
// [M, K] x [N, K] => [M, N] x [K, N] => [M, K]
// w_gate/w_up : [N, K]
@@ -185,18 +246,10 @@ struct LLMMLP::Impl {
// [N, K] [N, K] interleave (16-16-...) into [2*N, K]
auto K = w_gate.size(1);
auto N = w_gate.size(0);
- static PlainTensor w_gate_up;
- w_gate_up.resize<ov::bfloat16>({static_cast<size_t>(2 * N), static_cast<size_t>(K)});
- for (size_t n = 0; n < N; n += 16) {
- for (size_t i = 0; i < 16; i++)
- memcpy(w_gate_up.ptr_v(2 * n + i, 0), w_gate.ptr_v(n + i, 0), K * sizeof(ov::bfloat16));
- for (size_t i = 0; i < 16; i++)
- memcpy(w_gate_up.ptr_v(2 * n + 16 + i, 0), w_up.ptr_v(n + i, 0), K * sizeof(ov::bfloat16));
- }
- gate_up.setup(w_gate_up.ptr<ov::bfloat16>(), w_gate_up.stride_bytes(0), N * 2, K);
- down.setup(w_down.ptr<ov::bfloat16>(), w_down.stride_bytes(0), K, N, true);
+ OPENVINO_ASSERT(w_gate.stride_bytes(0) == w_up.stride_bytes(0));
+ gate_up.setup(w_gate.ptr<ov::float16>(), w_up.ptr<ov::float16>(), w_up.stride_bytes(0), N * 2, K, config);
+ down.setup(w_down.ptr<ov::float16>(), w_down.stride_bytes(0), K, N);
- m_tempC.resize(parallel_get_max_threads());
m_N = N;
}
@@ -208,12 +261,13 @@ struct LLMMLP::Impl {
if (m_M < M || cur_scratch_base != m_scratch_base) {
size_t total_scratch_size = M * m_N * sizeof(ov::bfloat16);
std::vector<size_t> scratch_offsets;
- std::vector<size_t> scratch_C_sizes;
- for (size_t ithr = 0; ithr < m_tempC.size(); ithr++) {
+ auto nthr = parallel_get_max_threads();
+ for (int ithr = 0; ithr < nthr; ithr++) {
scratch_offsets.push_back(total_scratch_size);
- auto max_C_size = std::max(gate_up.works[ithr].get_C_size(M), down.works[ithr].get_C_size(M));
- scratch_C_sizes.push_back(max_C_size);
- total_scratch_size += max_C_size * sizeof(float);
+ auto C1_size = gate_up.works[ithr].set_C(M, reinterpret_cast<float*>(cur_scratch_base));
+ auto C2_size = down.works[ithr].set_C(M, reinterpret_cast<float*>(cur_scratch_base));
+ auto max_C_size = std::max(C1_size, C2_size);
+ total_scratch_size += max_C_size;
}
auto newMemDesc = std::make_shared<CpuBlockedMemoryDesc>(ov::element::u8, Shape{total_scratch_size});
@@ -222,8 +276,10 @@ struct LLMMLP::Impl {
m_scratch_base = m_scratchMem->getDataAs<uint8_t>();
m_actUp.resize<ov::bfloat16>({static_cast<size_t>(M), static_cast<size_t>(m_N)}, reinterpret_cast<ov::bfloat16*>(m_scratch_base));
- for (size_t ithr = 0; ithr < m_tempC.size(); ithr++) {
- m_tempC[ithr].resize<float>({1, scratch_C_sizes[ithr]}, reinterpret_cast<float*>(m_scratch_base + scratch_offsets[ithr]));
+ for (int ithr = 0; ithr < nthr; ithr++) {
+ auto C_base = reinterpret_cast<float*>(m_scratch_base + scratch_offsets[ithr]);
+ gate_up.works[ithr].set_C(M, C_base);
+ down.works[ithr].set_C(M, C_base);
}
m_M = M;
}
@@ -244,11 +300,10 @@ struct LLMMLP::Impl {
int strideC = dstStrides[dstStrides.size() - 2] * sizeof(ov::bfloat16);
for (int m = 0; m < M;) {
- int BM = std::min(M - m, 512);
+ int BM = std::min(M - m, CACHE_BLK_M_SIZE);
setM(BM);
-
- gate_up.runGateUp(pA, strideA, BM, m_actUp.ptr<ov::bfloat16>(), m_actUp.stride_bytes(0), m_config, m_tempC);
- down.run(reinterpret_cast<uint8_t*>(m_actUp.ptr<ov::bfloat16>()), m_actUp.stride_bytes(0), BM, dstC, strideC, m_tempC);
+ gate_up.runGateUp(pA, strideA, BM, m_actUp.ptr<ov::bfloat16>(), m_actUp.stride_bytes(0), m_config);
+ down.run(reinterpret_cast<uint8_t*>(m_actUp.ptr<ov::bfloat16>()), m_actUp.stride_bytes(0), BM, dstC, strideC);
m += BM;
pA += BM * strideA;
@@ -278,7 +333,7 @@ void LLMMLP::initSupportedPrimitiveDescriptors() {
return;
auto rtPrecision = ov::element::bf16;
- auto weightPrecision = ov::element::bf16;
+ auto weightPrecision = ov::element::f16;
// initialize input ports
std::vector<PortConfigurator> inPortConfigs;
@@ -310,6 +365,7 @@ void LLMMLP::execute(dnnl::stream strm) {
}
bool LLMMLP::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept {
+#if defined(OPENVINO_ARCH_X86_64)
try {
const auto node_mlp = std::dynamic_pointer_cast<const LLMMLPNode>(op);
if (node_mlp) {
@@ -321,12 +377,12 @@ bool LLMMLP::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std
}
auto down_size = down_proj_w_pshape[0].get_length();
auto up_size = down_proj_w_pshape[1].get_length();
- if ((down_size % 256) != 0) {
- errorMessage = "LLMMLPNode down_proj size is not multiple of 256";
+ if (down_size % REG_BLK_K_SIZE) {
+ errorMessage = "LLMMLPNode down_proj size is not multiple of register blocking size";
return false;
}
- if (up_size % 256) {
- errorMessage = "LLMMLPNode up_proj size is not multiple of 256";
+ if (up_size % REG_BLK_N_SIZE) {
+ errorMessage = "LLMMLPNode up_proj size is not multiple of register blocking size";
return false;
}
} else {
@@ -337,6 +393,9 @@ bool LLMMLP::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std
return false;
}
return true;
+#else
+ return false;
+#endif
}
} // namespace node
diff --git a/src/plugins/intel_cpu/src/nodes/qkv_proj.cpp b/src/plugins/intel_cpu/src/nodes/qkv_proj.cpp
index bc3c20d860c..27ed49b2301 100644
--- a/src/plugins/intel_cpu/src/nodes/qkv_proj.cpp
+++ b/src/plugins/intel_cpu/src/nodes/qkv_proj.cpp
@@ -44,32 +44,32 @@ static std::vector<int> allocate_workers(const std::vector<int>& grouped_works,
struct QKVProjection::Impl {
std::vector<Work> works;
- std::vector<PlainTensor> m_tempC;
QKVProjection * m_node;
DnnlScratchPadPtr m_scrachPad;
MemoryPtr m_scratchMem;
uint8_t* m_scratch_base = nullptr;
- int m_M;
+ int m_M = 0;
+
+ WeightBuffer wbuffer;
Impl(QKVProjection * pnode, DnnlScratchPadPtr scrachPad) : m_node(pnode), m_scrachPad(scrachPad) {
PlainTensor w0(pnode->getSrcMemoryAtPort(1));
PlainTensor w1(pnode->getSrcMemoryAtPort(2));
PlainTensor w2(pnode->getSrcMemoryAtPort(3));
- const int blk_K_size = 256;
auto K = w0.size(1);
- OPENVINO_ASSERT((K % blk_K_size) == 0);
+ OPENVINO_ASSERT((K % CACHE_BLK_K_SIZE) == 0);
auto nthr = parallel_get_max_threads();
- auto num_blk_K = K / blk_K_size;
- int stride = K * sizeof(ov::bfloat16);
+ auto num_blk_K = K / CACHE_BLK_K_SIZE;
+ int stride = K * sizeof(ov::float16);
works.resize(nthr);
int cur_work_id = 0;
- auto create_works = [&](ov::bfloat16* pw, int output_id, int N, int valid_nthr) {
+ auto create_works = [&](ov::float16* pw, int output_id, int N, int valid_nthr) {
// split task on more cores is better on TBB
- OPENVINO_ASSERT((N % 32) == 0);
- auto num_blk_N = N / 32;
+ OPENVINO_ASSERT((N % REG_BLK_N_SIZE) == 0);
+ auto num_blk_N = N / REG_BLK_N_SIZE;
auto blkN_per_thread = (num_blk_N) / valid_nthr;
auto blkN_leftover = num_blk_N - (blkN_per_thread * valid_nthr);
auto start_blkN = 0;
@@ -82,12 +82,12 @@ struct QKVProjection::Impl {
}
if (blkN) {
auto& work = works[cur_work_id++];
- work.blk_K_size = blk_K_size;
- work.n0 = (start_blkN)*32;
- work.n1 = (start_blkN + blkN) * 32;
- work.BN = blkN * 32;
+ work.blk_K_size = CACHE_BLK_K_SIZE;
+ work.n0 = (start_blkN) * REG_BLK_N_SIZE;
+ work.n1 = (start_blkN + blkN) * REG_BLK_N_SIZE;
+ work.BN = blkN * REG_BLK_N_SIZE;
work.k0 = 0;
- work.k1 = blk_K_size * num_blk_K;
+ work.k1 = CACHE_BLK_K_SIZE * num_blk_K;
work.output_id = output_id;
work.p_raw_weights = pw;
}
@@ -99,21 +99,22 @@ struct QKVProjection::Impl {
auto proj_size2 = static_cast<int>(w2.size(0));
auto n_group_workers = allocate_workers({proj_size0, proj_size1, proj_size2}, nthr);
- create_works(w0.ptr<ov::bfloat16>(), 0, proj_size0, n_group_workers[0]);
- create_works(w1.ptr<ov::bfloat16>(), 1, proj_size1, n_group_workers[1]);
- create_works(w2.ptr<ov::bfloat16>(), 2, proj_size2, n_group_workers[2]);
+ create_works(w0.ptr<ov::float16>(), 0, proj_size0, n_group_workers[0]);
+ create_works(w1.ptr<ov::float16>(), 1, proj_size1, n_group_workers[1]);
+ create_works(w2.ptr<ov::float16>(), 2, proj_size2, n_group_workers[2]);
DEBUG_LOG("QKVProj hidden_size=", K, " proj_sizes=",
proj_size0, ",", proj_size1, ",", proj_size2,
" used_nthr=", cur_work_id);
+
+ wbuffer.alloc(works);
+
ov::parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
auto& work = works[ithr];
if (work) {
- work.setup(work.p_raw_weights, stride);
+ work.setup(wbuffer.get(ithr), work.p_raw_weights, stride);
}
});
-
- m_tempC.resize(nthr);
}
void setM(int M) {
@@ -124,20 +125,23 @@ struct QKVProjection::Impl {
if (m_M < M || cur_scratch_base != m_scratch_base) {
size_t total_scratch_size = 0;
std::vector<size_t> scratch_offsets;
- std::vector<size_t> scratch_C_sizes;
- for (size_t ithr = 0; ithr < m_tempC.size(); ithr++) {
- scratch_offsets.push_back(total_scratch_size);
- auto max_C_size = works[ithr].get_C_size(M);
- scratch_C_sizes.push_back(max_C_size);
- total_scratch_size += max_C_size * sizeof(float);
+ for (auto& work : works) {
+ if (work) {
+ scratch_offsets.push_back(total_scratch_size);
+ auto C_size = work.set_C(M, reinterpret_cast<float*>(cur_scratch_base));
+ total_scratch_size += C_size;
+ }
}
auto newMemDesc = std::make_shared<CpuBlockedMemoryDesc>(ov::element::u8, Shape{total_scratch_size});
m_scratchMem = m_scrachPad->createScratchPadMem(newMemDesc);
m_scratch_base = m_scratchMem->getDataAs<uint8_t>();
- for (size_t ithr = 0; ithr < m_tempC.size(); ithr++) {
- m_tempC[ithr].resize<float>({1, scratch_C_sizes[ithr]}, reinterpret_cast<float*>(m_scratch_base + scratch_offsets[ithr]));
+ for (size_t ithr = 0; ithr < works.size(); ithr++) {
+ auto& work = works[ithr];
+ if (work) {
+ work.set_C(M, reinterpret_cast<float*>(m_scratch_base + scratch_offsets[ithr]));
+ }
}
m_M = M;
@@ -165,19 +169,18 @@ struct QKVProjection::Impl {
auto stride_2 = dstStrides2[1];
for (int m = 0; m < M;) {
- int BM = std::min(M - m, 256);
+ int BM = std::min(M - m, CACHE_BLK_M_SIZE);
setM(BM);
ov::parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
auto& work = works[ithr];
- auto& C = m_tempC[ithr];
- if (work.BN > 0) {
- work.run(BM, pA, strideA, C);
+ if (work) {
+ work.run(BM, pA, strideA);
// compress accumulation result into target
- auto* src = C.ptr<float>();
- auto stride_src = C.stride(0);
+ auto* src = work.m_C.ptr<float>();
+ auto stride_src = work.m_C.stride(0);
ov::bfloat16* dst = nullptr;
int stride_dst = 0;
if (work.output_id == 0) {
@@ -203,9 +206,9 @@ struct QKVProjection::Impl {
});
m += BM;
pA += BM * strideA;
- dst0 += BM * stride_0 / sizeof(ov::bfloat16);
- dst1 += BM * stride_1 / sizeof(ov::bfloat16);
- dst2 += BM * stride_2 / sizeof(ov::bfloat16);
+ dst0 += BM * stride_0;
+ dst1 += BM * stride_1;
+ dst2 += BM * stride_2;
}
}
};
@@ -240,14 +243,14 @@ void QKVProjection::initSupportedPrimitiveDescriptors() {
return;
auto rtPrecision = ov::element::bf16;
- auto weightPrecision = ov::element::bf16;
+ auto weightPrecision = ov::element::f16;
// initialize input ports
std::vector<PortConfigurator> inPortConfigs;
inPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getInputShapeAtPort(0), false, -1); // input
- inPortConfigs.emplace_back(LayoutType::ncsp, weightPrecision, getInputShapeAtPort(1), false, -1); // gate
- inPortConfigs.emplace_back(LayoutType::ncsp, weightPrecision, getInputShapeAtPort(2), false, -1); // up
- inPortConfigs.emplace_back(LayoutType::ncsp, weightPrecision, getInputShapeAtPort(3), false, -1); // down
+ inPortConfigs.emplace_back(LayoutType::ncsp, weightPrecision, getInputShapeAtPort(1), false, -1); // q_proj
+ inPortConfigs.emplace_back(LayoutType::ncsp, weightPrecision, getInputShapeAtPort(2), false, -1); // k_proj
+ inPortConfigs.emplace_back(LayoutType::ncsp, weightPrecision, getInputShapeAtPort(3), false, -1); // v_proj
// initialize output port
std::vector<PortConfigurator> outPortConfigs;
@@ -258,27 +261,39 @@ void QKVProjection::initSupportedPrimitiveDescriptors() {
addSupportedPrimDesc(inPortConfigs, outPortConfigs, impl_desc_type::ref_any);
}
-bool QKVProjection::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept {
+bool QKVProjection::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage, int concurrency) noexcept {
+#if defined(OPENVINO_ARCH_X86_64)
try {
const auto node_qkv = std::dynamic_pointer_cast<const QKVProjectionNode>(op);
if (node_qkv) {
+ if (concurrency > 0) {
+ if (concurrency < 3) {
+ errorMessage = "QKVProjection needs at least 3 cores to work";
+ return false;
+ }
+ float unbalance_ratio = static_cast<float>(concurrency % 3)/static_cast<float>(concurrency / 3);
+ if (unbalance_ratio > 0.2f) {
+ errorMessage = "QKVProjection needs number of cores to be nearly multiple of 3";
+ return false;
+ }
+ }
auto proj_pshape1 = op->input_value(1).get_shape();
auto proj_pshape2 = op->input_value(2).get_shape();
auto proj_pshape3 = op->input_value(3).get_shape();
- if ((proj_pshape1[1] % 256) != 0) {
- errorMessage = "QKVProjection input channel size is not multiple of 256";
+ if ((proj_pshape1[1] % CACHE_BLK_K_SIZE) != 0) {
+ errorMessage = "QKVProjection input channel size is not multiple of cache blocking size";
return false;
}
- if ((proj_pshape1[0] % 32) != 0) {
- errorMessage = "QKVProjection 1st proj output channel size is not multiple of 32";
+ if ((proj_pshape1[0] % REG_BLK_K_SIZE) != 0) {
+ errorMessage = "QKVProjection 1st proj output channel size is not multiple of register blocking size";
return false;
}
- if ((proj_pshape2[0] % 32) != 0) {
- errorMessage = "QKVProjection 2nd proj output channel size is not multiple of 32";
+ if ((proj_pshape2[0] % REG_BLK_K_SIZE) != 0) {
+ errorMessage = "QKVProjection 2nd proj output channel size is not multiple of register blocking size";
return false;
}
- if ((proj_pshape3[0] % 32) != 0) {
- errorMessage = "QKVProjection 3rd proj output channel size is not multiple of 32";
+ if ((proj_pshape3[0] % REG_BLK_K_SIZE) != 0) {
+ errorMessage = "QKVProjection 3rd proj output channel size is not multiple of register blocking size";
return false;
}
} else {
@@ -289,6 +304,9 @@ bool QKVProjection::isSupportedOperation(const std::shared_ptr<const ov::Node>&
return false;
}
return true;
+#else
+ return false;
+#endif
}
} // namespace node
diff --git a/src/plugins/intel_cpu/src/nodes/qkv_proj.h b/src/plugins/intel_cpu/src/nodes/qkv_proj.h
index 2d235a30505..7717d00e5de 100644
--- a/src/plugins/intel_cpu/src/nodes/qkv_proj.h
+++ b/src/plugins/intel_cpu/src/nodes/qkv_proj.h
@@ -29,7 +29,7 @@ public:
}
void initSupportedPrimitiveDescriptors() override;
void execute(dnnl::stream strm) override;
- static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;
+ static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage, int concurrency = 0) noexcept;
private:
struct Impl;
diff --git a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
index afb30574142..0ff024f4356 100644
--- a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
+++ b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
@@ -828,33 +828,26 @@ void Transformations::PostLpt() {
// MLP & QKV fusion optimizations is focused on throughput, only enabled on AMX-bf16 & LLM serving use cases.
auto can_use_amx_bf16 = dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx) && (inferencePrecision == element::bf16);
if (can_use_amx_bf16) {
- auto has_paged_attention = op::util::has_op_with_type<ov::op::PagedAttentionExtension>(model);
- if (has_paged_attention) {
- CPU_REGISTER_PASS_X64(postLPTPassManager, MLPFusion);
- CPU_SET_CALLBACK_X64(postLPTPassManager,
- [](const_node_ptr &node) -> bool {
- std::string errorMsg;
- return node::LLMMLP::isSupportedOperation(node, errorMsg);
- },
- MLPFusion);
- }
+ CPU_REGISTER_PASS_X64(postLPTPassManager, MLPFusion);
+ CPU_SET_CALLBACK_X64(postLPTPassManager,
+ [](const_node_ptr &node) -> bool {
+ std::string errorMsg;
+ return node::LLMMLP::isSupportedOperation(node, errorMsg);
+ },
+ MLPFusion);
- // Limitations: at least 3 workers are required for QKV fusion
size_t concurrency = config.streamExecutorConfig.get_threads_per_stream();
if (concurrency == 0)
concurrency = parallel_get_max_threads();
- if (concurrency >= 3) {
- if (has_paged_attention) {
- CPU_REGISTER_PASS_X64(postLPTPassManager, QKVProjFusion);
- CPU_SET_CALLBACK_X64(postLPTPassManager,
- [](const_node_ptr &node) -> bool {
- std::string errorMsg;
- return node::QKVProjection::isSupportedOperation(node, errorMsg);
- },
- QKVProjFusion);
- }
- }
+ CPU_REGISTER_PASS_X64(postLPTPassManager, QKVProjFusion);
+ CPU_SET_CALLBACK_X64(postLPTPassManager,
+ [concurrency](const_node_ptr &node) -> bool {
+ std::string errorMsg;
+ return node::QKVProjection::isSupportedOperation(node, errorMsg, concurrency);
+ },
+ QKVProjFusion);
}
+
CPU_REGISTER_PASS_COMMON(postLPTPassManager, ov::pass::transpose_sinking::TSShapeOfForward);
CPU_REGISTER_PASS_COMMON(postLPTPassManager, StatefulSDPAFusion);
CPU_REGISTER_PASS_X64(postLPTPassManager, ov::pass::RMSFusion, false);
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/mlp_fusion.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/mlp_fusion.cpp
new file mode 100644
index 00000000000..7a3745d9e1e
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/mlp_fusion.cpp
@@ -0,0 +1,120 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <string>
+#include <vector>
+
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "openvino/runtime/exec_model_info.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+
+namespace ov {
+namespace test {
+
+struct LLMMLPFusionParams {
+ ov::test::InputShape inputShape;
+ size_t down_size;
+ size_t up_size;
+ std::string act_type;
+};
+
+class LLMMLPFusionTest : public testing::WithParamInterface<LLMMLPFusionParams>, public ov::test::SubgraphBaseTest {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<LLMMLPFusionParams>& obj) {
+ std::ostringstream result;
+ result << "IS=" << ov::test::utils::partialShape2str({obj.param.inputShape.first}) << "_";
+ result << "TS=";
+ for (const auto& shape : obj.param.inputShape.second) {
+ result << ov::test::utils::vec2str(shape);
+ result << "_";
+ }
+ result << "down_size=" << obj.param.down_size << "_";
+ result << "up_size=" << obj.param.up_size << "_";
+ result << "act_type=" << obj.param.act_type << "_";
+ result << obj.index;
+ return result.str();
+ }
+
+protected:
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_CPU;
+
+ auto& param = this->GetParam();
+
+ configuration[ov::hint::inference_precision.name()] = "bf16";
+
+ init_input_shapes({param.inputShape});
+
+ auto src = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, inputDynamicShapes[0]);
+
+ auto create_const = [](ov::Shape shape, int resolution) {
+ ov::test::utils::InputGenerateData in_data;
+ in_data.start_from = -0.5;
+ in_data.range = 1;
+ in_data.resolution = resolution;
+ auto tensor = ov::test::utils::create_and_fill_tensor(ov::element::f32, shape, in_data);
+ return std::make_shared<ov::op::v0::Constant>(tensor);
+ };
+
+ auto gate_weight = create_const(ov::Shape{param.up_size, param.down_size}, 100);
+ auto up_weight = create_const(ov::Shape{param.up_size, param.down_size}, 100);
+ // down_proj has special cache blocking along K dimension requires lower weight resolution
+ auto down_weight = create_const(ov::Shape{param.down_size, param.up_size}, 16);
+
+ auto gate_proj = std::make_shared<ov::op::v0::MatMul>(src, gate_weight, false, true);
+ auto up_proj = std::make_shared<ov::op::v0::MatMul>(src, up_weight, false, true);
+
+ std::shared_ptr<Node> gate_act;
+ if (param.act_type == "Swish")
+ gate_act = std::make_shared<ov::op::v4::Swish>(gate_proj);
+ if (param.act_type == "Gelu")
+ gate_act = std::make_shared<ov::op::v7::Gelu>(gate_proj);
+
+ auto gate_up = std::make_shared<ov::op::v1::Multiply>(gate_act, up_proj);
+ auto output = std::make_shared<ov::op::v0::MatMul>(gate_up, down_weight, false, true);
+
+ function = std::make_shared<ov::Model>(ov::NodeVector{output}, ov::ParameterVector{src});
+ }
+
+ void check_results() {
+ auto exec_model = compiledModel.get_runtime_model();
+
+ int fused_node_found = 0;
+ for (const auto& n : exec_model->get_ordered_ops()) {
+ auto layer_type = n->get_rt_info().at(ov::exec_model_info::LAYER_TYPE).as<std::string>();
+ if (layer_type == "LLMMLP")
+ fused_node_found++;
+ }
+ ASSERT_EQ(fused_node_found, 1);
+ }
+};
+
+TEST_P(LLMMLPFusionTest, CompareWithRefs) {
+ if (!ov::with_cpu_x86_avx512_core_amx_bf16())
+ GTEST_SKIP();
+ run();
+ check_results();
+}
+
+namespace {
+
+const std::vector<LLMMLPFusionParams> mlp_params = {
+ {ov::test::InputShape{ov::PartialShape{-1, -1, 4096 / 4}, {ov::Shape{1, 8, 4096 / 4}, ov::Shape{5, 37, 4096 / 4}}},
+ 4096 / 4,
+ 11008 / 4,
+ "Gelu"},
+ {ov::test::InputShape{ov::PartialShape{-1, -1, 4096 / 4}, {ov::Shape{1, 8, 4096 / 4}, ov::Shape{5, 37, 4096 / 4}}},
+ 4096 / 4,
+ 11008 / 4,
+ "Swish"},
+};
+
+INSTANTIATE_TEST_SUITE_P(smoke_LLMMLPFusion,
+ LLMMLPFusionTest,
+ ::testing::ValuesIn(mlp_params),
+ LLMMLPFusionTest::getTestCaseName);
+
+} // namespace
+} // namespace test
+} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/qkv_proj_fusion.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/qkv_proj_fusion.cpp
new file mode 100644
index 00000000000..4bb6eaa188b
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/qkv_proj_fusion.cpp
@@ -0,0 +1,118 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <string>
+#include <vector>
+
+#include "common_test_utils/ov_tensor_utils.hpp"
+#include "openvino/runtime/exec_model_info.hpp"
+#include "shared_test_classes/base/ov_subgraph.hpp"
+
+namespace ov {
+namespace test {
+
+struct QKVProjFusionParams {
+ ov::test::InputShape inputShape;
+ size_t hidden;
+ size_t q_proj_size;
+ size_t k_proj_size;
+ size_t v_proj_size;
+};
+
+class QKVProjFusionTest : public testing::WithParamInterface<QKVProjFusionParams>,
+ public ov::test::SubgraphBaseTest {
+public:
+ static std::string getTestCaseName(const testing::TestParamInfo<QKVProjFusionParams>& obj) {
+ std::ostringstream result;
+ result << "IS=" << ov::test::utils::partialShape2str({obj.param.inputShape.first}) << "_";
+ result << "TS=";
+ for (const auto& shape : obj.param.inputShape.second) {
+ result << ov::test::utils::vec2str(shape);
+ result << "_";
+ }
+ result << "hidden=" << obj.param.hidden << "_";
+ result << "q_proj_size=" << obj.param.q_proj_size << "_";
+ result << "k_proj_size=" << obj.param.k_proj_size << "_";
+ result << "v_proj_size=" << obj.param.v_proj_size << "_";
+ result << obj.index;
+ return result.str();
+ }
+
+protected:
+ void SetUp() override {
+ targetDevice = ov::test::utils::DEVICE_CPU;
+
+ auto& param = this->GetParam();
+
+ configuration[ov::hint::inference_precision.name()] = "bf16";
+
+ init_input_shapes({param.inputShape});
+
+ auto src = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, inputDynamicShapes[0]);
+
+ auto create_const = [](ov::Shape shape, int resolution) {
+ ov::test::utils::InputGenerateData in_data;
+ in_data.start_from = -0.5;
+ in_data.range = 1;
+ in_data.resolution = resolution;
+ auto tensor = ov::test::utils::create_and_fill_tensor(ov::element::f32, shape, in_data);
+ return std::make_shared<ov::op::v0::Constant>(tensor);
+ };
+
+ auto q_proj_weight = create_const(ov::Shape{param.q_proj_size, param.hidden}, 128);
+ auto k_proj_weight = create_const(ov::Shape{param.k_proj_size, param.hidden}, 128);
+ auto v_proj_weight = create_const(ov::Shape{param.v_proj_size, param.hidden}, 128);
+
+ auto q_proj = std::make_shared<ov::op::v0::MatMul>(src, q_proj_weight, false, true);
+ auto k_proj = std::make_shared<ov::op::v0::MatMul>(src, k_proj_weight, false, true);
+ auto v_proj = std::make_shared<ov::op::v0::MatMul>(src, v_proj_weight, false, true);
+
+ function = std::make_shared<ov::Model>(ov::NodeVector{q_proj, k_proj, v_proj}, ov::ParameterVector{src});
+ }
+ void check_results() {
+ auto exec_model = compiledModel.get_runtime_model();
+
+ int fused_node_found = 0;
+ for (const auto& n : exec_model->get_ordered_ops()) {
+ auto layer_type = n->get_rt_info().at(ov::exec_model_info::LAYER_TYPE).as<std::string>();
+ if (layer_type == "QKVProjection")
+ fused_node_found++;
+ }
+ ASSERT_EQ(fused_node_found, 1);
+ }
+};
+
+TEST_P(QKVProjFusionTest, CompareWithRefs) {
+ if (!ov::with_cpu_x86_avx512_core_amx_bf16())
+ GTEST_SKIP();
+ run();
+ check_results();
+}
+
+namespace {
+
+// the shape size is divided by a const to reduce test time
+const std::vector<QKVProjFusionParams> qkv_params = {
+ // Llama-7B
+ {ov::test::InputShape{ov::PartialShape{-1, -1, 4096 / 4}, {ov::Shape{1, 8, 4096 / 4}, ov::Shape{5, 7, 4096 / 4}}},
+ 4096 / 4,
+ 4096 / 4,
+ 4096 / 4,
+ 4096 / 4},
+ // Qwen2-7B: hidden_size_per_head:128, num_attention_heads:28, num_key_value_heads:4
+ {ov::test::InputShape{ov::PartialShape{-1, -1, 3584 / 2}, {ov::Shape{1, 8, 3584 / 2}, ov::Shape{5, 7, 3584 / 2}}},
+ 3584 / 2,
+ 128 * 28 / 2,
+ 128 * 4 / 2,
+ 128 * 4 / 2},
+};
+
+INSTANTIATE_TEST_SUITE_P(smoke_QKVProjFusion,
+ QKVProjFusionTest,
+ ::testing::ValuesIn(qkv_params),
+ QKVProjFusionTest::getTestCaseName);
+
+} // namespace
+} // namespace test
+} // namespace ov