Skip to content

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

[CPU] Add per-token asym INT8 dynamic quantization support to QKV/MLP node (#27001)

Tingqian Lie279492be8ec
diff --git a/src/plugins/intel_cpu/CMakeLists.txt b/src/plugins/intel_cpu/CMakeLists.txt
index 3f349bebb4d..6965b7a25ce 100644
--- a/src/plugins/intel_cpu/CMakeLists.txt
+++ b/src/plugins/intel_cpu/CMakeLists.txt
@@ -326,7 +326,7 @@ cross_compiled_file(${TARGET_NAME}
ARCH AVX512F ANY
src/nodes/kernels/x64/mlp_utils.cpp
API src/nodes/kernels/x64/mlp_utils.hpp
- NAME llm_mlp_transpose_epi32_16x16
+ NAME llm_mlp_transpose_epi32_16x16 llm_mlp_quantize_bf16_i8 llm_mlp_quantize_f16_i8 llm_mlp_dequantize_i32_f32
NAMESPACE ov::Extensions::Cpu::XARCH
)
diff --git a/src/plugins/intel_cpu/src/graph.cpp b/src/plugins/intel_cpu/src/graph.cpp
index fa3502468a9..45118763a3e 100644
--- a/src/plugins/intel_cpu/src/graph.cpp
+++ b/src/plugins/intel_cpu/src/graph.cpp
@@ -1688,7 +1688,9 @@ void Graph::EnforceInferencePrecision() {
Type::MatMul, // bert nets
Type::ROIPooling, // object detection nets
Type::Interpolate, // super resolution nets
- Type::PagedAttention))// page attention
+ Type::PagedAttention, // page attention
+ Type::QKVProjection,
+ Type::LLMMLP))
continue; // stop at significant nodes
} else if (inferPrec == ov::element::f16) {
/* list of node types that must be forced to be executed in FP16 precision
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 24528e7c5af..fd00fca8431 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
@@ -5,6 +5,7 @@
#include "mlp_kernel.hpp"
#include "emitters/plugin/x64/jit_dnnl_emitters.hpp"
#include "mlp_utils.hpp"
+#include "openvino/core/parallel.hpp"
using namespace dnnl::impl;
using namespace dnnl::impl::utils;
@@ -16,7 +17,7 @@ using TileConfiger = ov::Extensions::Cpu::TileConfiger;
namespace ov {
namespace intel_cpu {
-void MKernel::generate() {
+void MKernel::generate_2x2() {
Xbyak::Reg64 reg_A_addr = abi_param2;
Xbyak::Reg64 reg_A_stride = abi_param3;
Xbyak::Reg64 reg_B_addr = abi_param4;
@@ -95,27 +96,27 @@ void MKernel::generate() {
tileloadd(tmmB0, ptr[reg_B_addr + reg_B_stride]);
lea(reg_B_addr, ptr[reg_B_addr + 1024]);
- tdpbf16ps(tmmC00, tmmA0, tmmB0);
+ tmul(tmmC00, tmmA0, tmmB0);
if (cur_PFB < num_PFB) {
prefetcht2(ptr[reg_prefetch + cur_PFB * 64]);
cur_PFB++;
}
tileloadd(tmmA1, ptr[reg_A1_addr + reg_A_stride]);
- tdpbf16ps(tmmC10, tmmA1, tmmB0);
+ tmul(tmmC10, tmmA1, tmmB0);
if (cur_PFB < num_PFB) {
prefetcht2(ptr[reg_prefetch + cur_PFB * 64]);
cur_PFB++;
}
tileloadd(tmmB1, ptr[reg_B_addr + reg_B_stride]);
- tdpbf16ps(tmmC01, tmmA0, tmmB1);
+ tmul(tmmC01, tmmA0, tmmB1);
if (cur_PFB < num_PFB) {
prefetcht2(ptr[reg_prefetch + cur_PFB * 64]);
cur_PFB++;
}
- tdpbf16ps(tmmC11, tmmA1, tmmB1);
+ tmul(tmmC11, tmmA1, tmmB1);
if (cur_PFB < num_PFB) {
for (int pi = cur_PFB; pi < num_PFB; pi++) {
prefetcht2(ptr[reg_prefetch + pi * 64]);
@@ -168,6 +169,93 @@ void MKernel::tile_config_M(TileConfig& tile_cfg, int M) {
});
}
+void MKernel::generate_1x2() {
+ Xbyak::Reg64 reg_A_addr = abi_param2;
+ Xbyak::Reg64 reg_A_stride = abi_param3;
+ Xbyak::Reg64 reg_B_addr = abi_param4;
+ Xbyak::Reg64 reg_C_addr = abi_param5;
+ Xbyak::Reg64 reg_C_stride = abi_param6;
+
+ Xbyak::Reg64 reg_ktiles = rax;
+ Xbyak::Reg64 reg_B_stride = r10;
+ // Xbyak::Reg64 reg_prefetch = r12;
+
+ Xbyak::Tmm tmmC00 = tmm0;
+ Xbyak::Tmm tmmC01 = tmm1;
+ Xbyak::Tmm tmmA0 = tmm4;
+ Xbyak::Tmm tmmB0 = tmm6;
+ Xbyak::Tmm tmmB1 = tmm7;
+
+ Xbyak::Label loop_over_ktiles;
+ Xbyak::Label skip_load;
+
+ {
+ auto reg_tmp = reg_B_stride;
+
+ mov(reg_A_addr, ptr[abi_param1 + offsetof(call_args, pA)]);
+ mov(reg_A_stride, ptr[abi_param1 + offsetof(call_args, strideA)]);
+ mov(reg_B_addr, ptr[abi_param1 + offsetof(call_args, pB)]);
+ mov(reg_C_addr, ptr[abi_param1 + offsetof(call_args, pC)]);
+ mov(reg_C_stride, ptr[abi_param1 + offsetof(call_args, strideC)]);
+ mov(reg_ktiles, ptr[abi_param1 + offsetof(call_args, k_tiles)]);
+
+ mov(reg_tmp, ptr[abi_param1 + offsetof(call_args, do_accumulation)]);
+ // new: bit0: 0-skip load from mem, 1-load from mem; bit1: 0-skip tilezero, 1-tilezero; bit2: 0-skip store, 1-store
+ mov(abi_param1, reg_tmp);
+ and_(reg_tmp, 1);
+ jz(skip_load);
+ {
+ tileloadd(tmmC00, ptr[reg_C_addr + reg_C_stride]);
+ tileloadd(tmmC01, ptr[reg_C_addr + reg_C_stride + 64]);
+ }
+ L(skip_load);
+ mov(reg_tmp, abi_param1);
+ and_(reg_tmp, 2);
+ Xbyak::Label skip_zero;
+ jz(skip_zero);
+ {
+ tilezero(tmmC00);
+ tilezero(tmmC01);
+ }
+ L(skip_zero);
+ }
+
+ mov(reg_B_stride, 64);
+
+ auto const_A_steps = 64;
+
+ align(64, false);
+ L(loop_over_ktiles);
+ {
+ // B: 1x2 tiles
+ // A : 2x1 tiles C: 2x2 tiles
+ tileloadd(tmmA0, ptr[reg_A_addr + reg_A_stride]);
+ tileloadd(tmmB0, ptr[reg_B_addr + reg_B_stride]);
+ lea(reg_B_addr, ptr[reg_B_addr + 1024]);
+
+ tmul(tmmC00, tmmA0, tmmB0);
+
+ tileloadd(tmmB1, ptr[reg_B_addr + reg_B_stride]);
+ tmul(tmmC01, tmmA0, tmmB1);
+
+ lea(reg_A_addr, ptr[reg_A_addr + const_A_steps]);
+ lea(reg_B_addr, ptr[reg_B_addr + 1024]);
+ }
+ dec(reg_ktiles);
+ jnz(loop_over_ktiles, T_NEAR);
+
+ and_(abi_param1, 4);
+ Xbyak::Label skip_store;
+ jz(skip_store);
+ {
+ tilestored(ptr[reg_C_addr + reg_C_stride], tmmC00);
+ tilestored(ptr[reg_C_addr + reg_C_stride + 64], tmmC01);
+ }
+ L(skip_store);
+
+ ret();
+}
+
class FP16ToBF16Kernel : public dnnl::impl::cpu::x64::jit_generator {
public:
DECLARE_CPU_JIT_AUX_FUNCTIONS(FP16ToBF16Kernel)
@@ -190,95 +278,186 @@ public:
}
};
-template <typename T>
-void MKernel::repackB(ov::bfloat16* dst, T* src, int N_stride, int N, int K) {
+template <typename Tdst>
+static typename std::enable_if<std::is_same<ov::bfloat16, Tdst>::value || std::is_same<ov::float16, Tdst>::value>::type
+repackB(Tdst* dst, ov::float16* src, int N_stride, int N, int K) {
static FP16ToBF16Kernel fp16_to_bf16;
-
- if (N == 16 && K == 32 && (std::is_same<T, ov::bfloat16>::value || std::is_same<T, ov::float16>::value)) {
+ if (N == 16 && K == 32) {
// 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) {
+ ov::Extensions::Cpu::XARCH::llm_mlp_transpose_epi32_16x16(dst, src, N_stride * sizeof(Tdst));
+ if (std::is_same<ov::bfloat16, Tdst>::value)
fp16_to_bf16(dst);
- }
return;
}
assert(K <= 32);
assert(N <= 16);
int k = 0;
- ov::bfloat16 bf16zero(0.0f);
+ Tdst zero(0.0f);
for (; k < 32; k += 2) {
int n = 0;
bool is_k0_valid = (k) < K;
bool is_k1_valid = (k + 1) < K;
auto* psrc = src + k;
for (; n < 16 && n < N; n++, psrc += N_stride) {
- *dst++ = is_k0_valid ? ov::bfloat16(psrc[0]) : bf16zero;
- *dst++ = is_k1_valid ? ov::bfloat16(psrc[1]) : bf16zero;
+ *dst++ = is_k0_valid ? static_cast<Tdst>(psrc[0]) : zero;
+ *dst++ = is_k1_valid ? static_cast<Tdst>(psrc[1]) : zero;
+ }
+ for (; n < 16; n++) {
+ *dst++ = 0;
+ *dst++ = 0;
+ }
+ }
+}
+
+static void repackB(int8_t* dst, int8_t* src, int N_stride, int N, int K) {
+ if (N == 16 && K == 64) {
+ // SIMD optimized version
+ ov::Extensions::Cpu::XARCH::llm_mlp_transpose_epi32_16x16(dst, src, N_stride * sizeof(int8_t));
+ return;
+ }
+
+ assert(K <= 64);
+ assert(N <= 16);
+ for (int k = 0; k < 64; k += 4) {
+ bool is_k0_valid = (k) < K;
+ bool is_k1_valid = (k + 1) < K;
+ bool is_k2_valid = (k + 2) < K;
+ bool is_k3_valid = (k + 3) < K;
+ auto* psrc = src + k;
+ int n = 0;
+ for (; n < 16 && n < N; n++, psrc += N_stride) {
+ *dst++ = is_k0_valid ? psrc[0] : 0;
+ *dst++ = is_k1_valid ? psrc[1] : 0;
+ *dst++ = is_k2_valid ? psrc[2] : 0;
+ *dst++ = is_k3_valid ? psrc[3] : 0;
}
for (; n < 16; n++) {
*dst++ = 0;
*dst++ = 0;
+ *dst++ = 0;
+ *dst++ = 0;
}
}
}
-template <typename T>
-void MKernel::prepareB(PlainTensor& ret, ov::bfloat16* dst, T* p_weight, int stride, int N, int K) {
+template<typename Tdst>
+void MKernel::BMatrix::setup(Tdst* ext_buff, ov::float16* p_weight, int weight_stride_in_bytes, 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);
- for (int n = 0, blkn = 0; n < N; n += 32, blkn++) {
- 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 = dst_base;
- auto* dst1 = dst0 + 16 * 32;
- auto valid_k = (K - k) < 32 ? (K - k) : 32;
-
- auto* src0 = p_weight + n * N_stride + k;
- auto valid_n0 = (N - n) < 16 ? (N - n) : 16;
- repackB<T>(dst0, src0, N_stride, valid_n0, valid_k);
-
- auto* src1 = p_weight + (n + 16) * N_stride + k;
- auto valid_n1 = (N - (n + 16)) < 16 ? (N - (n + 16)) : 16;
- repackB<T>(dst1, src1, N_stride, valid_n1, valid_k);
+
+ this->ptr = reinterpret_cast<uint8_t*>(ext_buff);
+ this->Bpair_rows = K/32;
+ this->Bpair_cols = N/32;
+
+ const int k_step = 32;
+ auto N_stride = weight_stride_in_bytes / sizeof(Tdst);
+ auto* pdst = reinterpret_cast<int8_t*>(ext_buff);
+ for (int n = 0; n < N; n += 32) {
+ auto* src0 = p_weight + n * N_stride;
+ auto* src1 = p_weight + (n + 16) * N_stride;
+ auto valid_n0 = std::min((N - n), 16);
+ auto valid_n1 = std::min((N - (n + 16)), 16);
+ for (int k = 0, blkk = 0; k < K; k += k_step, blkk++) {
+ auto valid_k = std::min((K - k), k_step);
+ repackB(reinterpret_cast<Tdst*>(pdst), src0 + k, N_stride, valid_n0, valid_k);
+ pdst += 1024;
+ repackB(reinterpret_cast<Tdst*>(pdst), src1 + k, N_stride, valid_n1, valid_k);
+ pdst += 1024;
+ }
+ }
+}
+
+template void MKernel::BMatrix::setup<ov::bfloat16>(ov::bfloat16*, ov::float16*, int, int, int);
+template void MKernel::BMatrix::setup<ov::float16>(ov::float16*, ov::float16*, int, int, int);
+
+void MKernel::BMatrix::setup(int8_t* ext_buff, int8_t* p_weight, int weight_stride_in_bytes, int N, int K) {
+ OPENVINO_ASSERT((N % 32) == 0);
+ OPENVINO_ASSERT((K % 64) == 0);
+
+ this->ptr = reinterpret_cast<uint8_t*>(ext_buff);
+ this->Bpair_rows = K/64;
+ this->Bpair_cols = N/32;
+
+ const int k_step = 64;
+ auto N_stride = weight_stride_in_bytes / sizeof(int8_t);
+ auto* pdst = reinterpret_cast<int8_t*>(ext_buff);
+ for (int n = 0; n < N; n += 32) {
+ auto* src0 = p_weight + n * N_stride;
+ auto* src1 = p_weight + (n + 16) * N_stride;
+ auto valid_n0 = std::min((N - n), 16);
+ auto valid_n1 = std::min((N - (n + 16)), 16);
+ for (int k = 0, blkk = 0; k < K; k += k_step, blkk++) {
+ auto valid_k = std::min((K - k), k_step);
+ repackB(reinterpret_cast<int8_t*>(pdst), src0 + k, N_stride, valid_n0, valid_k);
+ pdst += 1024;
+ repackB(reinterpret_cast<int8_t*>(pdst), src1 + k, N_stride, valid_n1, valid_k);
+ pdst += 1024;
}
}
}
// 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) {
+template<typename Tdst>
+void MKernel::BMatrix::setup(Tdst* ext_buff,
+ ov::float16* p_weight_B0,
+ ov::float16* p_weight_B1,
+ int weight_stride_in_bytes,
+ 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);
+ this->ptr = reinterpret_cast<uint8_t*>(ext_buff);
+ this->Bpair_rows = K / 32;
+ this->Bpair_cols = N / 32;
+
+ const int k_step = 32;
+ auto N_stride = weight_stride_in_bytes / sizeof(Tdst);
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);
+ auto* pdst = reinterpret_cast<int8_t*>(ext_buff);
+ for (int n = 0; n < N2; n += 16) {
+ auto valid_n0 = std::min((N2 - n), 16);
+ for (int k = 0; k < K; k += k_step) {
+ auto valid_k = std::min((K - k), k_step);
+ repackB(reinterpret_cast<Tdst*>(pdst), p_weight_B0 + n * N_stride + k, N_stride, valid_n0, valid_k);
+ pdst += 1024;
+ repackB(reinterpret_cast<Tdst*>(pdst), p_weight_B1 + n * N_stride + k, N_stride, valid_n0, valid_k);
+ pdst += 1024;
}
}
}
+template void MKernel::BMatrix::setup<ov::bfloat16>(ov::bfloat16*, ov::float16*, ov::float16*, int, int, int);
+template void MKernel::BMatrix::setup<ov::float16>(ov::float16*, ov::float16*, ov::float16*, int, int, int);
+
+void MKernel::BMatrix::setup(int8_t* ext_buff,
+ int8_t* p_weight_B0,
+ int8_t* p_weight_B1,
+ int weight_stride_in_bytes,
+ int N,
+ int K) {
+ OPENVINO_ASSERT((N % 32) == 0);
+ OPENVINO_ASSERT((K % 64) == 0);
-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);
+ this->ptr = reinterpret_cast<uint8_t*>(ext_buff);
+ this->Bpair_rows = K / 64;
+ this->Bpair_cols = N / 32;
+
+ const int k_step = 64;
+ auto N_stride = weight_stride_in_bytes / sizeof(int8_t);
+ auto N2 = N / 2;
+ auto* pdst = reinterpret_cast<int8_t*>(ext_buff);
+ for (int n = 0; n < N2; n += 16) {
+ auto valid_n0 = std::min((N2 - n), 16);
+ for (int k = 0; k < K; k += k_step) {
+ auto valid_k = std::min((K - k), k_step);
+ repackB(reinterpret_cast<int8_t*>(pdst), p_weight_B0 + n * N_stride + k, N_stride, valid_n0, valid_k);
+ pdst += 1024;
+ repackB(reinterpret_cast<int8_t*>(pdst), p_weight_B1 + n * N_stride + k, N_stride, valid_n0, valid_k);
+ pdst += 1024;
+ }
+ }
+}
// run L2 cache blocking kernel with size:
// [BM, BK]*[BK, BN] => [BM, BN]
@@ -288,26 +467,24 @@ template void MKernel::prepareB<ov::float16>(PlainTensor& ret, ov::bfloat16* dst
// but prefetch of next B must be specified by caller.
//
void MKernel::run(int M, // actual M
- uint8_t* pA,
- int strideA, // A [M, K]
- PlainTensor& repacked_B, // B [N/32, K*32] ov::bfloat16
- uint8_t* pC,
- int strideC, // C [M, N]
- uint8_t* prefetch_B, // prefetch B
- bool do_accumulation) {
+ uint8_t* pA,
+ int strideA, // A [M, K]
+ BMatrix& repacked_B, // B [N/32, K*32] ov::bfloat16
+ uint8_t* pC,
+ int strideC, // C [M, N]
+ uint8_t* prefetch_B, // prefetch B
+ bool do_accumulation) {
call_args args;
- // number of blocks in N dimension (in unit of 32 columns)
- auto num_blkN = static_cast<int>(repacked_B.size(0));
- auto K = repacked_B.size(1) / 32;
- auto* pB = repacked_B.ptr<uint8_t>();
- auto strideB = repacked_B.stride_bytes(0);
+
+ auto* pB = repacked_B.ptr;
+ auto strideB = repacked_B.Bpair_rows * repacked_B.Bpair_size;
+ auto num_blkN = repacked_B.Bpair_cols;
args.do_accumulation = do_accumulation;
- args.k_tiles = K / 32;
+ args.k_tiles = repacked_B.Bpair_rows;
args.strideA = strideA;
args.strideC = strideC;
args.prefetch = prefetch_B;
- assert((K % 32) == 0);
auto prefetch_step = m_prefetch_Blines * 64 * args.k_tiles;
@@ -316,13 +493,47 @@ void MKernel::run(int M, // actual M
args.pB = pB;
args.M = std::min(M - m, 32);
args.pA = pA;
- for (int ni = 0; ni < num_blkN; ni++, args.pB += strideB, args.prefetch += prefetch_step) {
+ for (size_t ni = 0; ni < num_blkN; ni++, args.pB += strideB, args.prefetch += prefetch_step) {
args.pC = pC + ni * 32 * sizeof(float);
(*this)(&args);
}
}
}
+void MatrixDynQuantPerRow::quantize(size_t BM, ov::bfloat16* psrc, int src_stride) {
+ assert(BM <= M);
+ parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
+ size_t start{0}, end{0};
+ splitter(BM, nthr, ithr, start, end);
+ ov::Extensions::Cpu::XARCH::llm_mlp_quantize_bf16_i8(psrc + start * src_stride,
+ src_stride,
+ data + start * K,
+ K,
+ end - start,
+ K,
+ scale + start,
+ zp + start,
+ asym);
+ });
+}
+
+void MatrixDynQuantPerRow::quantize(size_t BM, ov::float16* psrc, int src_stride) {
+ assert(BM <= M);
+ parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
+ size_t start{0}, end{0};
+ splitter(BM, nthr, ithr, start, end);
+ ov::Extensions::Cpu::XARCH::llm_mlp_quantize_f16_i8(psrc + start * src_stride,
+ src_stride,
+ data + start * K,
+ K,
+ end - start,
+ K,
+ scale + start,
+ zp + start,
+ asym);
+ });
+}
+
void GateUpCombine::generate() {
Xbyak::Label loop_begin;
@@ -365,7 +576,11 @@ void GateUpCombine::generate() {
injector->compute_vector(zmm_silu.getIdx());
vmovups(zmm_up, ptr[src + loop_i * 8 + 16 * 4]);
vmulps(zmm_up, zmm_up, zmm_silu);
- vcvtneps2bf16(ymm_dst, zmm_up);
+ if (m_to_f16) {
+ vcvtps2ph(ymm_dst, zmm_up, 0x4);
+ } else {
+ vcvtneps2bf16(ymm_dst, zmm_up);
+ }
prefetchwt1(ptr[prefetch_dst + loop_i * 2]);
vmovdqu(ptr[dst + loop_i * 2], ymm_dst);
}
@@ -401,9 +616,15 @@ void ReduceAdd2bh::generate() {
vmovups(zmm3, ptr[src1 + loop_i * 4 + 16 * 4]);
vaddps(zmm0, zmm0, zmm1);
vaddps(zmm2, zmm2, zmm3);
- vcvtne2ps2bf16(zmm4, zmm2, zmm0);
- prefetchwt1(ptr[prefetch_dst + loop_i * 2]);
- vmovups(ptr[dst + loop_i * 2], zmm4);
+ if (m_to_f16) {
+ vcvtps2ph(ptr[dst + loop_i * 2], zmm0, 0x4);
+ vcvtps2ph(ptr[dst + loop_i * 2 + 32], zmm2, 0x4);
+ prefetchwt1(ptr[prefetch_dst + loop_i * 2]);
+ } else {
+ vcvtne2ps2bf16(zmm4, zmm2, zmm0);
+ prefetchwt1(ptr[prefetch_dst + loop_i * 2]);
+ vmovups(ptr[dst + loop_i * 2], zmm4);
+ }
}
add(loop_i, 32);
cmp(loop_i, BN);
@@ -426,9 +647,15 @@ void ReduceAdd2bh::generate() {
{
vmovups(zmm0, ptr[src0 + loop_i * 4]);
vmovups(zmm2, ptr[src0 + loop_i * 4 + 16 * 4]);
- vcvtne2ps2bf16(zmm4, zmm2, zmm0);
- prefetchwt1(ptr[prefetch_dst + loop_i * 2]);
- vmovups(ptr[dst + loop_i * 2], zmm4);
+ if (m_to_f16) {
+ vcvtps2ph(ptr[dst + loop_i * 2], zmm0, 0x4);
+ vcvtps2ph(ptr[dst + loop_i * 2 + 32], zmm2, 0x4);
+ prefetchwt1(ptr[prefetch_dst + loop_i * 2]);
+ } else {
+ vcvtne2ps2bf16(zmm4, zmm2, zmm0);
+ prefetchwt1(ptr[prefetch_dst + loop_i * 2]);
+ vmovups(ptr[dst + loop_i * 2], zmm4);
+ }
}
add(loop_i, 32);
cmp(loop_i, 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 1e9634b0d56..26b6c1b0cc1 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
@@ -11,6 +11,7 @@
// register blocking size for K dimension (1x2 AMX B-tiles)
#define REG_BLK_K_SIZE 32
+#define REG_BLK_K_SIZE_I8 64
// register blocking size for N dimension (1x2 AMX B-tiles)
#define REG_BLK_N_SIZE 32
@@ -42,23 +43,67 @@ private:
void* last_cfg = nullptr;
};
+enum class TMUL_TYPE { SSD = 1, USD = 2, SUD = 3, UUD = 4, FP16 = 5, BF16 = 6 };
+
class MKernel : public dnnl::impl::cpu::x64::jit_generator {
public:
DECLARE_CPU_JIT_AUX_FUNCTIONS(MKernel)
int m_prefetch_Blines;
-
- MKernel(int M_hint = 256) : jit_generator("MKernel") {
+ const TMUL_TYPE m_tmul_type;
+ int m_tile_reg_ksize;
+ int m_M_hint;
+
+ MKernel(int M_hint, TMUL_TYPE tmul_type) : jit_generator("MKernel"), m_tmul_type(tmul_type), m_M_hint(M_hint) {
+ if (m_tmul_type == TMUL_TYPE::FP16 || m_tmul_type == TMUL_TYPE::BF16)
+ m_tile_reg_ksize = 32;
+ else
+ m_tile_reg_ksize = 64;
setup(M_hint);
}
- void generate() override;
+ void tmul(const Xbyak::Tmm& x1, const Xbyak::Tmm& x2, const Xbyak::Tmm& x3) {
+ switch (m_tmul_type) {
+ case TMUL_TYPE::SSD:
+ tdpbssd(x1, x2, x3);
+ break;
+ case TMUL_TYPE::USD:
+ tdpbusd(x1, x2, x3);
+ break;
+ case TMUL_TYPE::SUD:
+ tdpbsud(x1, x2, x3);
+ break;
+ case TMUL_TYPE::UUD:
+ tdpbuud(x1, x2, x3);
+ break;
+ case TMUL_TYPE::FP16:
+ tdpfp16ps(x1, x2, x3);
+ break;
+ case TMUL_TYPE::BF16:
+ tdpbf16ps(x1, x2, x3);
+ break;
+ }
+ }
+
+ void generate() override {
+ if (m_M_hint <= 16) {
+ generate_1x2();
+ } else {
+ generate_2x2();
+ }
+ }
+
+ void generate_2x2();
+ void generate_1x2();
// M_hint is only a hint for prefetching, set to 0 to avoid prefetch
void setup(int M_hint = 0) {
if (M_hint == 0) {
m_prefetch_Blines = 0;
} else {
+ // next block size: 32 * N * sizeof(ov::bfloat16),
+ // call number: N / 32 * M / 32
+ // each call needs fetch: 32 * N * sizeof(ov::bfloat16) / (N / 32 * M / 32) = 32 * 1024 * sizeof(ov::bfloat16) / M
m_prefetch_Blines = 32768 * sizeof(ov::bfloat16) / 64 / M_hint;
}
@@ -71,26 +116,14 @@ public:
// - tile config controls behaviour of tileload & TMUL
void tile_config_M(ov::Extensions::Cpu::TileConfig& tile_cfg, int M);
- // row data is in layout [N, K], maybe smaller than [32, 16]
- template <typename T>
- void repackB(ov::bfloat16* dst, T* src, int N_stride, int N, int K);
-
- // weight is supposed to be of shape[N, K], stride in unit of bytes
- template <typename T>
- 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;
struct call_args {
- const uint8_t* pA; // bfloat16
+ const uint8_t* pA; // bfloat16/int8
int64_t strideA; // in bytes
- const uint8_t* pB; // bfloat16
- const uint8_t* pC; // float32
+ const uint8_t* pB; // bfloat16/int8
+ const uint8_t* pC; // float32/int32
int64_t strideC; // in bytes
const uint8_t* prefetch;
int64_t k_tiles; // K / 32
@@ -98,6 +131,27 @@ public:
int64_t M;
};
+ // each 32x16(64x16) sub-matrix in [K, N]-shaped BMatrix to be loaded as B-tile is packed into AMX B-tile layout
+ // and two neighboring B-tiles in same row are grouped as a pair (B0-B1), and all such pairs are arranged in [nN, nK] shape
+ struct BMatrix {
+ uint8_t * ptr;
+ // Bpair is two 1KB sub-matrixes repacked in AMX-Btile layout
+ const size_t Bpair_size = 2048;
+ size_t Bpair_rows;
+ size_t Bpair_cols;
+
+ // convert
+ template<typename Tdst>
+ void setup(Tdst* ext_buff, ov::float16* p_weight, int stride, int N, int K);
+
+ void setup(int8_t* ext_buff, int8_t* p_weight, int stride, int N, int K);
+ // two B tiles in each pair (B0 & B1) comes from different raw weight matrix
+ template<typename Tdst>
+ void setup(Tdst* ext_buff, ov::float16* p_weight_B0, ov::float16* p_weight_B1, int stride, int N, int K);
+
+ void setup(int8_t* ext_buff, int8_t* p_weight_B0, int8_t* p_weight_B1, int stride, int N, int K);
+ };
+
// run L2 cache blocking kernel with size:
// [BM, BK]*[BK, BN] => [BM, BN]
//
@@ -107,17 +161,19 @@ public:
//
void run(int M, // actual M
uint8_t* pA,
- int strideA, // A [M, K]
- PlainTensor& repacked_B, // B [N/32, K*32] ov::bfloat16
+ int strideA, // A [M, K]
+ BMatrix& repacked_B, // B
uint8_t* pC,
int strideC, // C [M, N]
uint8_t* prefetch_B, // prefetch B
bool do_accumulation);
};
-
struct Work {
- std::vector<PlainTensor> weights; // ov::bfloat16 weights for current thread
+ std::vector<MKernel::BMatrix> weights;
+
+ // will be used only when activation is being quantized asymmetrically
+ PlainTensor w_sum_per_oc;
std::shared_ptr<std::atomic_int> sync_flag;
int n0 = 0;
@@ -127,29 +183,57 @@ struct Work {
int BN = 0;
int blk_K_size = 0;
int output_id;
- ov::float16* p_raw_weights;
+ void* p_raw_weights;
operator bool() {
return BN > 0;
}
+ bool quant_i8 = false;
+ bool is_f16 = false;
+
MKernel& get_MKernel() {
constexpr int BM = 256;
- static MKernel jit_amx0(BM);
- return jit_amx0;
+ static MKernel jit_amx_bf16(BM, TMUL_TYPE::BF16);
+ static MKernel jit_amx_f16(BM, TMUL_TYPE::FP16);
+ static MKernel jit_amx_i8(BM, TMUL_TYPE::SSD);
+ if (quant_i8) return jit_amx_i8;
+ if (is_f16) return jit_amx_f16;
+ return jit_amx_bf16;
+ }
+
+ MKernel& get_MKernel_1x2() {
+ static MKernel jit_amx_bf16(16, TMUL_TYPE::BF16);
+ static MKernel jit_amx_f16(16, TMUL_TYPE::FP16);
+ static MKernel jit_amx_i8(16, TMUL_TYPE::SSD);
+ if (quant_i8) return jit_amx_i8;
+ if (is_f16) return jit_amx_f16;
+ return jit_amx_bf16;
}
// input : weight [N, K], setup repacks range of N [n_start, n_end)
- template <typename T>
- void setup(ov::bfloat16* dst, T* p_weight, int stride) {
+ template <typename Tsrc, typename Tdst>
+ void setup(Tdst* dst, Tsrc* p_weight, int stride_in_bytes, bool do_sum_per_oc = false) {
auto& mkernel = get_MKernel();
auto num_blk_K = (k1 - k0 + blk_K_size - 1) / blk_K_size;
- auto* pw = p_weight + n0 * stride / sizeof(T);
+ auto* pw = p_weight + n0 * stride_in_bytes / sizeof(Tsrc);
+
+ if (do_sum_per_oc) {
+ w_sum_per_oc.resize<float>({static_cast<size_t>(n1 - n0)});
+ auto * p_wsum_per_oc = w_sum_per_oc.ptr<float>();
+ auto* pw_temp = pw;
+ for (int n = n0; n < n1; n++, pw_temp += stride_in_bytes / sizeof(Tsrc)) {
+ float fsum = 0;
+ for (int k = k0; k < k1; k++)
+ fsum += pw_temp[k];
+ *p_wsum_per_oc++ = fsum;
+ }
+ }
// 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, pw + k, stride, BN, subK);
+ weights[ki].setup(dst, pw + k, stride_in_bytes, BN, subK);
dst += BN*subK;
k += subK;
ki++;
@@ -160,18 +244,40 @@ struct Work {
}
}
- template <typename T>
- void setup(ov::bfloat16* dst, T* p_weight1, T* p_weight2, int stride) {
+ // two weight matrix interleaved in unit of B-tiles
+ // in each Bpair, p_weight1 stored in B0, p_weight2 stored in B1
+ template <typename Tsrc, typename Tdst>
+ void setup(Tdst* dst, Tsrc* p_weight1, Tsrc* p_weight2, int stride_in_bytes, bool do_sum_per_oc = false) {
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);
+ auto* pw1 = p_weight1 + (n0/2) * stride_in_bytes / sizeof(Tsrc);
+ auto* pw2 = p_weight2 + (n0/2) * stride_in_bytes / sizeof(Tsrc);
+
+ if (do_sum_per_oc) {
+ w_sum_per_oc.resize<float>({static_cast<size_t>(n1 - n0)});
+ auto * p_wsum_per_oc = w_sum_per_oc.ptr<float>();
+ auto* pw1_temp = pw1;
+ auto* pw2_temp = pw2;
+ auto stride_temp = stride_in_bytes / sizeof(Tsrc);
+ for (int n = n0; n < n1; n+=32) {
+ for (int dn = 0; dn < 16; dn++, pw1_temp += stride_temp) {
+ float fsum = 0;
+ for (int k = k0; k < k1; k++) fsum += pw1_temp[k];
+ *p_wsum_per_oc++ = fsum;
+ }
+ for (int dn = 0; dn < 16; dn++, pw2_temp += stride_temp) {
+ float fsum = 0;
+ for (int k = k0; k < k1; k++) fsum += pw2_temp[k];
+ *p_wsum_per_oc++ = fsum;
+ }
+ }
+ }
// 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);
+ weights[ki].setup(dst, pw1 + k, pw2 + k, stride_in_bytes, BN, subK);
dst += BN*subK;
k += subK;
ki++;
@@ -198,7 +304,7 @@ struct Work {
void run(int M, uint8_t* pA, int strideA) {
auto& mkernel = get_MKernel();
- int num_blk_K = weights.size();
+ auto num_blk_K = weights.size();
auto Mtails = M % 32;
auto Mbody = M - Mtails;
@@ -208,36 +314,75 @@ struct Work {
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;
-
- for (int ki = 0; ki < num_blk_K; ki++) {
- PlainTensor& blockB = weights[ki];
- PlainTensor& blockB1 = weights[(ki + 1) < num_blk_K ? (ki + 1) : ki];
- if (Mbody) {
- m_tile_configer.do_config(&m_tcfg[0]);
- mkernel.run(Mbody,
- pA + ki * blk_K_size * sizeof(ov::bfloat16),
- strideA,
- blockB,
- pC,
- C_stride_bytes,
- reinterpret_cast<uint8_t*>(blockB1.ptr_v()),
- do_accumulation);
+ auto element_size = quant_i8 ? sizeof(int8_t) : sizeof(ov::bfloat16);
+
+ pA += k0 * element_size;
+
+ if (M > 16 || num_blk_K ==1) {
+ bool do_accumulation = false;
+ for (size_t ki = 0; ki < num_blk_K; ki++) {
+ auto& blockB = weights[ki];
+ auto& blockB1 = weights[(ki + 1) < num_blk_K ? (ki + 1) : ki];
+ if (Mbody) {
+ m_tile_configer.do_config(&m_tcfg[0]);
+ mkernel.run(Mbody,
+ pA + ki * blk_K_size * element_size,
+ strideA,
+ blockB,
+ pC,
+ C_stride_bytes,
+ blockB1.ptr,
+ do_accumulation);
+ }
+
+ if (Mtails) {
+ m_tile_configer.do_config(&m_tcfg[Mtails]);
+ mkernel.run(Mtails,
+ pA + ki * blk_K_size * element_size + Mbody * strideA,
+ strideA,
+ blockB,
+ pC + Mbody * C_stride_bytes,
+ C_stride_bytes,
+ blockB1.ptr,
+ do_accumulation);
+ }
+ do_accumulation = true;
}
-
- if (Mtails) {
- m_tile_configer.do_config(&m_tcfg[Mtails]);
- mkernel.run(Mtails,
- pA + ki * blk_K_size * sizeof(ov::bfloat16) + Mbody * strideA,
- strideA,
- blockB,
- pC + Mbody * C_stride_bytes,
- C_stride_bytes,
- reinterpret_cast<uint8_t*>(blockB1.ptr_v()),
- do_accumulation);
+ } else {
+ auto& jit = get_MKernel_1x2();
+ auto& blockB = weights[0];
+ // number of blocks in N dimension (in unit of 32 columns)
+ auto num_blkN = blockB.Bpair_cols;
+ m_tile_configer.do_config(&m_tcfg[Mtails]);
+ // original: bit0: 0-tilezero+skip load from mem, 1-tilezero+load from mem; tilestore
+ // new: bit0: 0-skip load from mem, 1-load from mem; bit1: 0-skip tilezero, 1-tilezero; bit2: 0-skip store, 1-store
+ // if M > 32, firstK: 1 1 0(store, tilezero, skip load)
+ // the otherK except last: 1 0 1(store, skip tilezero, load) lastK: 1 0 1
+ // else
+ // firstK: 0 1 0(skip store, tilezero, skip load), the otherK except last: 0 0 0(skip all),
+ // lastK: 1 0 0(store, skip tile zero, skip load)
+ int do_accumulation;
+ MKernel::call_args args;
+ args.strideA = strideA;
+ args.strideC = C_stride_bytes;
+ args.M = Mtails;
+ for (size_t ni = 0; ni < num_blkN; ni++) {
+ args.pC = pC + ni * 32 * sizeof(float);
+ do_accumulation = 0b010;
+ for (size_t ki = 0; ki < num_blk_K; ki++) {
+ auto& blockB = weights[ki];
+ args.k_tiles = blockB.Bpair_rows;
+ args.pA = pA + ki * blk_K_size * element_size;
+ args.pB = blockB.ptr + ni * blockB.Bpair_rows * blockB.Bpair_size;
+ args.do_accumulation = do_accumulation;
+ // prefetch next N block. In memory bound, it seems no prefetch will be better.
+ // args.prefetch = args.pB + (ni == num_blkN - 1 ? 0 : strideB);
+ // args.prefetch = args.pB;
+ // [M, K] * [K, N]: [1..32, 256] * [256, 32]
+ jit(&args);
+ do_accumulation = (ki == num_blk_K - 2) ? 0b100 : 0;
+ }
}
- do_accumulation = true;
}
m_tile_configer.do_config(nullptr);
}
@@ -247,19 +392,75 @@ struct Work {
struct WeightBuffer {
PlainTensor buffer;
std::vector<size_t> offsets;
- void alloc(std::vector<Work>& works) {
- size_t weight_cnt = 0;
+ void alloc(std::vector<Work>& works, int element_size) {
+ size_t weight_size = 0;
for (auto& work : works) {
- offsets.push_back(weight_cnt);
- weight_cnt += (work.n1 - work.n0) * (work.k1 - work.k0);
+ offsets.push_back(weight_size);
+ weight_size += (work.n1 - work.n0) * (work.k1 - work.k0) * element_size;
}
- buffer.resize<ov::bfloat16>({weight_cnt});
+ buffer.resize<int8_t>({weight_size});
}
- ov::bfloat16* get(int work_id) {
- return buffer.ptr<ov::bfloat16>() + offsets[work_id];
+ template<typename T = ov::bfloat16>
+ T* get(int work_id) {
+ return reinterpret_cast<T*>(buffer.ptr<int8_t>() + offsets[work_id]);
}
};
+struct ScratchBuffAllocator {
+ using CallBack = std::function<void(void * ptr)>;
+ std::vector<CallBack> m_allocs;
+ std::vector<size_t> m_sizes;
+ size_t m_total_size = 0;
+ ScratchBuffAllocator() = default;
+
+ // register size / allocate totally size / inform consumers
+ void register_allocation(size_t size, CallBack cb) {
+ m_allocs.push_back(cb);
+ m_total_size += size;
+ m_sizes.push_back(size);
+ }
+ size_t size() {
+ return m_total_size;
+ }
+ void finalize(void* base) {
+ auto* ptr = reinterpret_cast<uint8_t*>(base);
+ for (size_t i = 0; i < m_allocs.size(); i++) {
+ m_allocs[i](ptr);
+ ptr += m_sizes[i];
+ }
+ }
+};
+
+struct MatrixDynQuantPerRow {
+ // M x K
+ int M;
+ int K;
+ int8_t * data;
+ float * scale;
+ float * zp;
+ bool asym = true;
+
+ MatrixDynQuantPerRow() = default;
+
+ size_t size() {
+ // size of data & scale & zp
+ return M*K + M*sizeof(float)*2;
+ }
+
+ size_t stride() {
+ return K;
+ }
+
+ void setup(void * ext_buf) {
+ data = reinterpret_cast<int8_t*>(ext_buf);
+ scale = reinterpret_cast<float*>(data + M*K);
+ zp = reinterpret_cast<float*>(scale + M);
+ }
+
+ void quantize(size_t BM, ov::bfloat16* psrc, int src_stride);
+ void quantize(size_t BM, ov::float16* psrc, int src_stride);
+};
+
// 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 {
@@ -267,13 +468,16 @@ public:
DECLARE_CPU_JIT_AUX_FUNCTIONS(GateUpCombine)
const dnnl_alg_kind_t m_act_alg;
- GateUpCombine(dnnl_alg_kind_t act_alg) : jit_generator(jit_name()), m_act_alg(act_alg) {
+ const bool m_to_f16;
+
+ GateUpCombine(dnnl_alg_kind_t act_alg, bool to_f16) : jit_generator(jit_name()), m_act_alg(act_alg), m_to_f16(to_f16) {
create_kernel();
}
void generate() override;
- void call(float* src, size_t src_stride, ov::bfloat16 * dst, size_t dst_stride, int num_rows, int num_cols) {
+ void call(float* src, size_t src_stride, void * pv_dst, size_t dst_stride, int num_rows, int num_cols) {
+ auto* dst = reinterpret_cast<int16_t*>(pv_dst);
for (int m = 0; m < num_rows; m++, src += src_stride, dst += dst_stride) {
auto* prefetch_dst = (m + 1 < num_rows) ? (dst + dst_stride) : (dst);
@@ -296,15 +500,17 @@ class ReduceAdd2bh : public dnnl::impl::cpu::x64::jit_generator {
public:
DECLARE_CPU_JIT_AUX_FUNCTIONS(ReduceAdd2bh)
- bool m_do_reduce2;
- ReduceAdd2bh(bool do_reduce2) : jit_generator(jit_name()), m_do_reduce2(do_reduce2) {
+ const bool m_do_reduce2;
+ const bool m_to_f16;
+ ReduceAdd2bh(bool do_reduce2, bool to_f16) : jit_generator(jit_name()), m_do_reduce2(do_reduce2), m_to_f16(to_f16) {
create_kernel();
}
void generate() override;
// add two float input eltwise and convert to bf16 : ConvertFP32toBF16(src0 + src1)
- void call(float * src0, float * src1, size_t src_stride, ov::bfloat16 * dst, size_t dst_stride, int num_rows, int num_cols) {
+ void call(float * src0, float * src1, size_t src_stride, void * pf16_dst, size_t dst_stride, int num_rows, int num_cols) {
+ auto* dst = reinterpret_cast<int16_t*>(pf16_dst);
for (int m = 0; m < num_rows; m++, src0 += src_stride, src1 += src_stride, dst += dst_stride) {
// the prefetch distance is increased to ensure by the time store happens
// prefetch has done and no HW prefetcher is triggered
@@ -314,7 +520,8 @@ public:
}
// convert tensor to bf16: ConvertFP32toBF16(src0)
- void call(float * src0, size_t src_stride, ov::bfloat16 * dst, size_t dst_stride, int num_rows, int num_cols) {
+ void call(float * src0, size_t src_stride, void * pf16_dst, size_t dst_stride, int num_rows, int num_cols) {
+ auto* dst = reinterpret_cast<int16_t*>(pf16_dst);
for (int m = 0; m < num_rows; m++, src0 += src_stride, dst += dst_stride) {
// the prefetch distance is increased to ensure by the time store happens
// prefetch has done and no HW prefetcher is triggered
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_utils.cpp b/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_utils.cpp
index 996561a04af..f95d8da6211 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_utils.cpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_utils.cpp
@@ -4,10 +4,9 @@
#include "mlp_utils.hpp"
-
#include <cstring>
#if defined(HAVE_AVX512F)
-#include <immintrin.h>
+# include <immintrin.h>
#endif
#include "../scaled_attn/transpose_kernel.hpp"
@@ -17,12 +16,181 @@ namespace Cpu {
namespace XARCH {
void llm_mlp_transpose_epi32_16x16(void* dst, void* src, int stride) {
- transpose_16x16_kernel(reinterpret_cast<uint32_t*>(dst), reinterpret_cast<uint32_t*>(src), 16, stride/sizeof(uint32_t));
+ transpose_16x16_kernel(reinterpret_cast<uint32_t*>(dst),
+ reinterpret_cast<uint32_t*>(src),
+ 16,
+ stride / sizeof(uint32_t));
+}
+
+template <typename T>
+void llm_mlp_quantize_to_i8(T* psrc,
+ int src_stride,
+ int8_t* pdst,
+ int dst_stride,
+ int rows,
+ int cols,
+ float* p_scales,
+ float* p_zp,
+ bool asym) {
+ auto clamp_i8 = [](float x) {
+ auto v = static_cast<int>(std::round(x));
+ if (v < -128)
+ return -128;
+ if (v > 127)
+ return 127;
+ return v;
+ };
+
+ for (int y = 0; y < rows; y++, psrc += src_stride, pdst += dst_stride) {
+ int x = 0;
+ float f_min, f_max;
+#if defined(HAVE_AVX512F)
+ auto v_max = mm512_uni_loadu_ps(psrc + 0);
+ auto v_min = mm512_uni_loadu_ps(psrc + 0);
+ for (; x + 16 <= cols; x += 16) {
+ auto v = mm512_uni_loadu_ps(psrc + x);
+ v_max = _mm512_max_ps(v, v_max);
+ v_min = _mm512_min_ps(v, v_min);
+ }
+ f_max = _mm512_reduce_max_ps(v_max);
+ f_min = _mm512_reduce_min_ps(v_min);
+#else
+ f_min = psrc[0];
+ f_max = psrc[0];
+#endif
+ for (; x < cols; x++) {
+ auto f_cur = static_cast<float>(psrc[x]);
+ f_min = std::min(f_min, f_cur);
+ f_max = std::max(f_max, f_cur);
+ }
+ // (q - z) * s = f
+ // (-128 - z) * s = f_min;
+ // ( 127 - z) * s = f_max;
+ float scale, zp;
+ if (f_max == f_min || std::isnan(f_max) || std::isnan(f_min)) {
+ // special case
+ p_zp[y] = 0;
+ p_scales[y] = std::isnan(f_min) ? 0 : f_min;
+#if defined(HAVE_AVX512F)
+ auto vi8x16 = _mm_set1_epi8(1);
+ for (; x + 16 <= cols; x += 16) {
+ _mm_storeu_si128(reinterpret_cast<__m128i*>(pdst + x), vi8x16);
+ }
+#endif
+ for (; x < cols; x++) {
+ pdst[x] = 1;
+ }
+ continue;
+ } else if (asym) {
+ scale = (f_max - f_min) / 255.0f;
+ zp = 127 - (f_max / scale);
+ } else {
+ auto fx = std::max(std::abs(f_max), std::abs(f_min));
+ scale = fx / 127.0f;
+ zp = 0;
+ }
+ p_zp[y] = zp;
+ p_scales[y] = scale;
+ x = 0;
+#if defined(HAVE_AVX512F)
+ auto vscale = _mm512_set1_ps(1.0f / scale);
+ auto vzp = _mm512_set1_ps(zp);
+ for (; x + 16 <= cols; x += 16) {
+ auto v = mm512_uni_loadu_ps(psrc + x);
+ v = _mm512_fmadd_ps(v, vscale, vzp);
+ auto vi32x16 = _mm512_cvtps_epi32(v);
+ auto vi8x16 = _mm512_cvtepi32_epi8(vi32x16);
+ _mm_storeu_si128(reinterpret_cast<__m128i*>(pdst + x), vi8x16);
+ }
+#endif
+ for (; x < cols; x++) {
+ pdst[x] = clamp_i8(psrc[x] / scale + zp);
+ }
+ }
+}
+
+void llm_mlp_quantize_bf16_i8(ov::bfloat16* psrc,
+ int src_stride,
+ int8_t* pdst,
+ int dst_stride,
+ int rows,
+ int cols,
+ float* p_scales,
+ float* p_zp,
+ bool asym) {
+ llm_mlp_quantize_to_i8(psrc, src_stride, pdst, dst_stride, rows, cols, p_scales, p_zp, asym);
+}
+
+void llm_mlp_quantize_f16_i8(ov::float16* psrc,
+ int src_stride,
+ int8_t* pdst,
+ int dst_stride,
+ int rows,
+ int cols,
+ float* p_scales,
+ float* p_zp,
+ bool asym) {
+ llm_mlp_quantize_to_i8(psrc, src_stride, pdst, dst_stride, rows, cols, p_scales, p_zp, asym);
+}
+
+void llm_mlp_dequantize_i32_f32(int Batch,
+ int OC,
+ int32_t* src,
+ int stride_src,
+ float* dst,
+ int stride_dst,
+ float* p_src_scale_per_row,
+ float* p_src_zp_per_row,
+ float* p_wsum_per_oc,
+ float* p_wscale_per_oc,
+ bool asym) {
+ for (int b = 0; b < Batch; b++, src += stride_src, dst += stride_dst) {
+ float s1 = p_src_scale_per_row[b];
+ float z1s1 = p_src_zp_per_row[b] * s1;
+ int oc = 0;
+#if defined(HAVE_AVX512F)
+ if (asym) {
+ auto vs1 = _mm512_set1_ps(s1);
+ auto vz1s1 = _mm512_set1_ps(z1s1);
+ for (; oc + 16 <= OC; oc += 16) {
+ auto vs2 = mm512_uni_loadu_ps(p_wscale_per_oc + oc);
+ auto vi32x16 = _mm512_loadu_si512(src + oc);
+ auto vsrc = _mm512_cvtepi32_ps(vi32x16);
+ auto vwsum = mm512_uni_loadu_ps(p_wsum_per_oc + oc);
+ auto vwsum_z1s1 = _mm512_mul_ps(vwsum, vz1s1);
+ vsrc = _mm512_fmsub_ps(vsrc, vs1, vwsum_z1s1);
+ vsrc = _mm512_mul_ps(vsrc, vs2);
+ mm512_uni_storeu_ps(dst + oc, vsrc);
+ }
+ } else {
+ auto vs1 = _mm512_set1_ps(s1);
+ for (; oc + 16 <= OC; oc += 16) {
+ auto vs2 = mm512_uni_loadu_ps(p_wscale_per_oc + oc);
+ auto vi32x16 = _mm512_loadu_si512(src + oc);
+ auto vsrc = _mm512_cvtepi32_ps(vi32x16);
+ vsrc = _mm512_mul_ps(vsrc, vs1);
+ vsrc = _mm512_mul_ps(vsrc, vs2);
+ mm512_uni_storeu_ps(dst + oc, vsrc);
+ }
+ }
+#endif
+ for (; oc < OC; oc++) {
+ //
+ // fdst = sum{(qi-z1)*s1 * wi*s2}
+ // = sum{[qi*wi] *(s1*s2) - z1*s1*wi*s2}
+ // = sum{qi*wi} *(s1*s2) - sum{wi}*(z1*s1*s2)
+ //
+ float s2 = p_wscale_per_oc[oc];
+ if (asym) {
+ dst[oc] = src[oc] * (s1 * s2) - p_wsum_per_oc[oc] * (z1s1 * s2);
+ } else {
+ dst[oc] = src[oc] * (s1 * s2); // - sum_w *(z1 * s1 * s2);
+ }
+ }
+ }
}
} // namespace XARCH
} // namespace Cpu
} // namespace Extensions
} // namespace ov
-
-
diff --git a/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_utils.hpp b/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_utils.hpp
index 075717971f4..d60cf143d37 100644
--- a/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_utils.hpp
+++ b/src/plugins/intel_cpu/src/nodes/kernels/x64/mlp_utils.hpp
@@ -2,9 +2,12 @@
// SPDX-License-Identifier: Apache-2.0
//
+#include <array>
#include <cstddef>
#include <vector>
-#include <array>
+
+#include "openvino/core/type/bfloat16.hpp"
+#include "openvino/core/type/float16.hpp"
namespace ov {
namespace Extensions {
@@ -12,7 +15,35 @@ namespace Cpu {
namespace XARCH {
void llm_mlp_transpose_epi32_16x16(void* dst, void* src, int stride);
-
+void llm_mlp_quantize_bf16_i8(ov::bfloat16* psrc,
+ int src_stride,
+ int8_t* pdst,
+ int dst_stride,
+ int rows,
+ int cols,
+ float* p_scales,
+ float* p_zp,
+ bool asym);
+void llm_mlp_quantize_f16_i8(ov::float16* psrc,
+ int src_stride,
+ int8_t* pdst,
+ int dst_stride,
+ int rows,
+ int cols,
+ float* p_scales,
+ float* p_zp,
+ bool asym);
+void llm_mlp_dequantize_i32_f32(int Batch,
+ int OC,
+ int32_t* src,
+ int stride_src,
+ float* dst,
+ int stride_dst,
+ float* p_src_scale_per_row,
+ float* p_src_zp_per_row,
+ float* p_wsum_per_oc,
+ float* p_wscale_per_oc,
+ bool asym);
} // namespace XARCH
} // namespace Cpu
} // namespace Extensions
diff --git a/src/plugins/intel_cpu/src/nodes/llm_mlp.cpp b/src/plugins/intel_cpu/src/nodes/llm_mlp.cpp
index 72f9ca87200..13c46a7c976 100644
--- a/src/plugins/intel_cpu/src/nodes/llm_mlp.cpp
+++ b/src/plugins/intel_cpu/src/nodes/llm_mlp.cpp
@@ -14,8 +14,11 @@
#include "shape_inference/shape_inference_internal_dyn.hpp"
#include "utils/plain_tensor.hpp"
+#include "openvino/core/parallel.hpp"
+
#if defined(OPENVINO_ARCH_X86_64)
#include "kernels/x64/mlp_kernel.hpp"
+#include "kernels/x64/mlp_utils.hpp"
#endif
namespace ov {
@@ -24,6 +27,7 @@ namespace node {
#if defined(OPENVINO_ARCH_X86_64)
+template<typename T>
class LinearKsplit2 {
public:
std::vector<Work> works;
@@ -35,22 +39,24 @@ public:
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) {
- static ReduceAdd2bh jit_reduce2bh_2(true);
+ void setup(void* p_weight, int stride, int N, int K, const LLMMLPNode::Config& config) {
+ bool is_quantized = config.down_quantized;
+
+ auto reg_blk_K_size = is_quantized ? REG_BLK_K_SIZE_I8 : REG_BLK_K_SIZE;
+ auto cache_blk_k_size = is_quantized ? CACHE_BLK_K_SIZE : CACHE_BLK_K_SIZE;
+ auto weight_element_size = is_quantized ? sizeof(int8_t) : sizeof(ov::float16);
OPENVINO_ASSERT((N % REG_BLK_N_SIZE) == 0);
- OPENVINO_ASSERT((K % REG_BLK_K_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);
- p_jit_reduce2bh = &jit_reduce2bh_2;
-
auto K_splits = 2;
// split task on more cores is better on TBB
auto valid_nthr = nthr / 2;
@@ -70,7 +76,7 @@ public:
// 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 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);
@@ -78,13 +84,15 @@ public:
auto& work = works[ithr + ik];
work.sync_flag = shared_atomic;
- work.blk_K_size = CACHE_BLK_K_SIZE;
+ 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 = start_blkK * REG_BLK_K_SIZE;
- work.k1 = (start_blkK + blk_K) * REG_BLK_K_SIZE;
+ work.k0 = start_blkK * reg_blk_K_size;
+ work.k1 = (start_blkK + blk_K) * reg_blk_K_size;
+ work.quant_i8 = is_quantized;
+ work.is_f16 = std::is_same<T, ov::float16>::value;
start_blkK += blk_K;
used_nthr++;
@@ -96,39 +104,70 @@ public:
DEBUG_LOG("Linear N,K=", N, ",", K, " used_nthr=", used_nthr);
- wbuffer.alloc(works);
+ wbuffer.alloc(works, weight_element_size);
ov::parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
auto& work = works[ithr];
if (work) {
- work.setup(wbuffer.get(ithr), p_weight, stride);
+ if (is_quantized) {
+ work.setup(wbuffer.get<int8_t>(ithr), reinterpret_cast<int8_t*>(p_weight), stride, true);
+ } else {
+ work.setup(wbuffer.get<T>(ithr), reinterpret_cast<ov::float16*>(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) {
+ void run(uint8_t* pA, int strideA, int M, T* dstC, int strideC,
+ const LLMMLPNode::Config& config,
+ MatrixDynQuantPerRow& src_dq,
+ float * w_scale) {
+ static ReduceAdd2bh jit_reduce2cvt(true, std::is_same<T, ov::float16>::value);
+
ov::parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
auto& work = works[ithr];
auto& workC = work.m_C;
if (work) {
work.run(M, pA, strideA);
+ if (config.down_quantized) {
+ // de-quantize i32 results in-place into f32
+ auto* ptr_c = work.m_C.template ptr<float>();
+ auto* ptr_wsum = work.w_sum_per_oc.template ptr<float>();
+ auto stride_c = work.m_C.stride(0);
+ ov::Extensions::Cpu::XARCH::llm_mlp_dequantize_i32_f32(
+ M,
+ work.BN,
+ reinterpret_cast<int32_t*>(ptr_c),
+ stride_c,
+ ptr_c,
+ stride_c,
+ src_dq.scale,
+ src_dq.zp,
+ ptr_wsum,
+ w_scale + work.n0,
+ src_dq.asym);
+ }
+
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;
+ auto* p_peerC = works[peer_ithr].m_C.template ptr<float>();
// 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);
+ auto* p_curC = workC.template ptr<float>();
+ jit_reduce2cvt.call(p_curC, p_peerC,
+ workC.stride(0),
+ dstC + work.n0, strideC / sizeof(*dstC),
+ M, work.BN);
}
}
});
}
};
+template<typename T>
class LinearGateUp {
public:
std::vector<Work> works;
@@ -145,10 +184,9 @@ public:
// 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);
+ void setup(void* p_weight_gate, void* p_weight_up, int stride, int N, int K, const LLMMLPNode::Config& config) {
+ static GateUpCombine jit_gateup_silu(dnnl_eltwise_swish, std::is_same<T, ov::float16>::value);
+ static GateUpCombine jit_gateup_gelu(dnnl_eltwise_gelu_tanh, std::is_same<T, ov::float16>::value);
if (config.act == LLMMLPNode::ACT_FN::GELU)
jit_gateup = &jit_gateup_gelu;
@@ -157,10 +195,16 @@ public:
else
OPENVINO_THROW("unsupported act in GateUpCombine");
+ bool quantized_int8 = config.gate_up_quantized;
+
+ auto reg_blk_K_size = quantized_int8 ? REG_BLK_K_SIZE_I8 : REG_BLK_K_SIZE;
+ auto cache_blk_k_size = quantized_int8 ? CACHE_BLK_K_SIZE : CACHE_BLK_K_SIZE;
+ auto weight_element_size = quantized_int8 ? sizeof(int8_t) : sizeof(ov::float16);
+
// 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);
+ 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);
@@ -182,41 +226,78 @@ public:
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.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;
+ work.quant_i8 = quantized_int8;
+ work.is_f16 = std::is_same<T, ov::float16>::value;
used_nthr++;
}
start_blkN += blkN;
}
- wbuffer.alloc(works);
+ wbuffer.alloc(works, weight_element_size);
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];
if (work) {
- work.setup(wbuffer.get(ithr), p_weight_gate, p_weight_up, stride);
+ if (quantized_int8)
+ work.setup(wbuffer.get<int8_t>(ithr),
+ reinterpret_cast<int8_t*>(p_weight_gate),
+ reinterpret_cast<int8_t*>(p_weight_up),
+ stride, true);
+ else
+ work.setup(wbuffer.get<T>(ithr),
+ reinterpret_cast<ov::float16*>(p_weight_gate),
+ reinterpret_cast<ov::float16*>(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) {
+ void runGateUp(uint8_t* pA, int strideA_in_bytes, int M,
+ T* dstC, int strideC,
+ const LLMMLPNode::Config& config,
+ MatrixDynQuantPerRow& src_dq,
+ float * w_scale) {
ov::parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
auto& work = works[ithr];
if (work) {
- work.run(M, pA, strideA);
+ work.run(M, pA, strideA_in_bytes);
+
// K reduce is done, results of [M, BN] sub-block is ready in L2.
// combine Gate & Up
- jit_gateup->call(work.m_C.ptr<float>(), work.m_C.stride(0),
+ float * ptr_c;
+ size_t stride_c;
+ if (config.gate_up_quantized) {
+ // dequantize m_C in-place
+ ptr_c = work.m_C.template ptr<float>();
+ stride_c = work.m_C.stride(0);
+ auto* p_wsum = work.w_sum_per_oc.template ptr<float>();
+ ov::Extensions::Cpu::XARCH::llm_mlp_dequantize_i32_f32(
+ M,
+ work.BN,
+ reinterpret_cast<int32_t*>(ptr_c),
+ stride_c,
+ ptr_c,
+ stride_c,
+ src_dq.scale,
+ src_dq.zp,
+ p_wsum,
+ w_scale + work.n0,
+ src_dq.asym);
+ } else {
+ ptr_c = work.m_C.template ptr<float>();
+ stride_c = work.m_C.stride(0);
+ }
+ jit_gateup->call(ptr_c, stride_c,
dstC + (work.n0 / 2), strideC / sizeof(*dstC),
M, work.BN);
}
@@ -224,31 +305,68 @@ public:
}
};
-struct LLMMLP::Impl {
+template<typename T>
+struct LLMMLP::Executor : public LLMMLP::ExecutorBase {
+ LLMMLP* m_pnode;
const LLMMLPNode::Config m_config;
DnnlScratchPadPtr m_scrachPad;
MemoryPtr m_scratchMem;
uint8_t* m_scratch_base = nullptr;
- LinearGateUp gate_up;
- LinearKsplit2 down;
+ LinearGateUp<T> gate_up;
+ LinearKsplit2<T> down;
int m_N;
int m_M = 0;
// MLP is not supposed to run in parallel
PlainTensor m_actUp;
+ // quantized input: in scratch buffer
+ MatrixDynQuantPerRow m_quant_act;
+ MatrixDynQuantPerRow m_quant_up_act;
+
+ PlainTensor m_w_scale_gateup;
+
+ bool m_rt_prec_f16;
+
// [M, K] x [N, K] => [M, N] x [K, N] => [M, K]
// w_gate/w_up : [N, K]
// w_down : [K, N]
- Impl(PlainTensor w_gate, PlainTensor w_up, PlainTensor w_down, const LLMMLPNode::Config& config, DnnlScratchPadPtr scrachPad)
- : m_config(config), m_scrachPad(scrachPad) {
+ Executor(LLMMLP* pnode, const LLMMLPNode::Config& config, DnnlScratchPadPtr scrachPad)
+ : m_pnode(pnode), m_config(config), m_scrachPad(scrachPad) {
+ PlainTensor w_gate(pnode->getSrcMemoryAtPort(1));
+ PlainTensor w_up(pnode->getSrcMemoryAtPort(2));
+ PlainTensor w_down(pnode->getSrcMemoryAtPort(3));
+
+ m_rt_prec_f16 = std::is_same<T, ov::float16>::value;
+
// [N, K] [N, K] interleave (16-16-...) into [2*N, K]
auto K = w_gate.size(1);
auto N = w_gate.size(0);
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);
+ if (m_config.gate_up_combined) {
+ N = w_gate.size(0) / 2;
+ gate_up.setup(w_gate.ptr_v(), w_up.ptr_v(N, 0), w_up.stride_bytes(0), N * 2, K, config);
+ } else {
+ gate_up.setup(w_gate.ptr_v(), w_up.ptr_v(), w_up.stride_bytes(0), N * 2, K, config);
+ }
+ down.setup(w_down.ptr_v(), w_down.stride_bytes(0), K, N, config);
+
+ if (m_config.gate_up_quantized) {
+ m_w_scale_gateup.resize<float>({N * 2});
+ auto* w_scale_gate = pnode->getSrcMemoryAtPort(4)->getDataAs<float>();
+ auto* w_scale_up = pnode->getSrcMemoryAtPort(5)->getDataAs<float>();
+ auto* dst = m_w_scale_gateup.ptr<float>();
+ if (m_config.gate_up_combined) {
+ w_scale_up = w_scale_gate + N;
+ }
+ for (size_t i = 0; i < N; i += 16) {
+ memcpy(dst, w_scale_gate + i, 16 * sizeof(float));
+ dst += 16;
+ memcpy(dst, w_scale_up + i, 16 * sizeof(float));
+ dst += 16;
+ }
+ }
m_N = N;
}
@@ -259,69 +377,125 @@ struct LLMMLP::Impl {
cur_scratch_base = m_scratchMem->getDataAs<uint8_t>();
// new M larger than previous or the scratch pointer is changed after the following allocation
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;
+ ScratchBuffAllocator allocator;
+
+ allocator.register_allocation(M * m_N * sizeof(T), [&](void* ptr) {
+ m_actUp.resize<T>({static_cast<size_t>(M), static_cast<size_t>(m_N)},
+ reinterpret_cast<T*>(ptr));
+ });
+
auto nthr = parallel_get_max_threads();
for (int ithr = 0; ithr < nthr; ithr++) {
- scratch_offsets.push_back(total_scratch_size);
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;
+ allocator.register_allocation(max_C_size, [this, ithr, M](void* ptr) {
+ // these two op runs at different time step, so can share same scratch buffer
+ gate_up.works[ithr].set_C(M, reinterpret_cast<float*>(ptr));
+ down.works[ithr].set_C(M, reinterpret_cast<float*>(ptr));
+ });
}
- auto newMemDesc = std::make_shared<CpuBlockedMemoryDesc>(ov::element::u8, Shape{total_scratch_size});
- m_scratchMem = m_scrachPad->createScratchPadMem(newMemDesc);
+ if (m_config.gate_up_quantized) {
+ m_quant_act.M = M;
+ m_quant_act.K = m_config.hidden_size;
+ allocator.register_allocation(m_quant_act.size(), [&](void* ptr){
+ m_quant_act.setup(ptr);
+ });
+ }
+ if (m_config.down_quantized) {
+ m_quant_up_act.M = M;
+ m_quant_up_act.K = m_config.up_size;
+ allocator.register_allocation(m_quant_up_act.size(), [&](void* ptr){
+ m_quant_up_act.setup(ptr);
+ });
+ }
+
+ auto newMemDesc = std::make_shared<CpuBlockedMemoryDesc>(ov::element::u8, Shape{allocator.size()});
+ m_scratchMem = m_scrachPad->createScratchPadMem(newMemDesc);
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 (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);
- }
+ allocator.finalize(m_scratch_base);
m_M = M;
}
}
- void execute(LLMMLP* pnode) {
- auto input = pnode->getSrcMemoryAtPort(0);
+ void execute() override {
+ auto input = m_pnode->getSrcMemoryAtPort(0);
const auto& ishape = input->getStaticDims();
uint8_t* pA = input->getDataAs<uint8_t>();
const auto& srcStrides = input->getDescWithType<BlockedMemoryDesc>()->getStrides();
- int strideA = srcStrides[srcStrides.size() - 2] * sizeof(ov::bfloat16);
+ int strideA = srcStrides[srcStrides.size() - 2];
+ int strideA_in_bytes = strideA * sizeof(T);
int M = shape_size(ishape) / ishape[ishape.size() - 1];
- auto output = pnode->getDstMemoryAtPort(0);
- auto* dstC = output->getDataAs<ov::bfloat16>();
+ auto output = m_pnode->getDstMemoryAtPort(0);
+ auto* dstC = output->getDataAs<T>();
const auto& dstStrides = output->getDescWithType<BlockedMemoryDesc>()->getStrides();
- int strideC = dstStrides[dstStrides.size() - 2] * sizeof(ov::bfloat16);
+ int strideC = dstStrides[dstStrides.size() - 2] * sizeof(T);
+
+ float* p_w_scale_down = nullptr;
+ if (m_config.down_quantized) {
+ p_w_scale_down = m_pnode->getSrcMemoryAtPort(6)->getDataAs<float>();
+ }
for (int m = 0; m < M;) {
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);
- down.run(reinterpret_cast<uint8_t*>(m_actUp.ptr<ov::bfloat16>()), m_actUp.stride_bytes(0), BM, dstC, strideC);
+
+ uint8_t* psrc = pA;
+ auto stride_src_in_bytes = strideA_in_bytes;
+ auto strideA_in_bytes = strideA * sizeof(T);
+ if (m_config.gate_up_quantized) {
+ m_quant_act.quantize(BM, reinterpret_cast<T*>(pA), strideA);
+ psrc = reinterpret_cast<uint8_t*>(m_quant_act.data);
+ stride_src_in_bytes = m_quant_act.K;
+ }
+
+ // dequantize is fused into gate_up
+ gate_up.runGateUp(psrc,
+ stride_src_in_bytes,
+ BM,
+ m_actUp.ptr<T>(),
+ m_actUp.stride_bytes(0),
+ m_config,
+ m_quant_act,
+ m_w_scale_gateup.ptr<float>());
+
+ uint8_t * p_up_act = reinterpret_cast<uint8_t*>(m_actUp.ptr<T>());
+ size_t stride_up_act = m_actUp.stride_bytes(0);
+ if (m_config.down_quantized) {
+ m_quant_up_act.quantize(BM, m_actUp.ptr<T>(), m_actUp.stride(0));
+ p_up_act = reinterpret_cast<uint8_t*>(m_quant_up_act.data);
+ stride_up_act = m_quant_up_act.stride();
+ }
+
+ down.run(p_up_act, stride_up_act, BM, dstC, strideC,
+ m_config,
+ m_quant_up_act,
+ p_w_scale_down);
m += BM;
- pA += BM * strideA;
- dstC += BM * strideC / sizeof(ov::bfloat16);
+ pA += BM * strideA_in_bytes;
+ dstC += BM * strideC / sizeof(T);
}
}
};
#else
-struct LLMMLP::Impl {
- Impl(PlainTensor w_gate, PlainTensor w_up, PlainTensor w_down, const LLMMLPNode::Config& config, DnnlScratchPadPtr scrachPad) {}
- void execute(LLMMLP* pnode) {}
+template<typename T>
+struct LLMMLP::Executor : public LLMMLP::ExecutorBase {
+ Executor(LLMMLP* pnode, const LLMMLPNode::Config& config, DnnlScratchPadPtr scrachPad) {}
+ void execute() {}
};
#endif
LLMMLP::LLMMLP(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr context)
: Node(op, context, NgraphShapeInferFactory(op, EMPTY_PORT_MASK)) {
std::string errorMessage;
- if (!isSupportedOperation(op, errorMessage)) {
+ const auto & config = context->getConfig();
+ if (!isSupportedOperation(op, errorMessage, config.fcDynamicQuantizationGroupSize)) {
OPENVINO_THROW("CPU: " + errorMessage);
}
const auto node_mlp = std::dynamic_pointer_cast<const LLMMLPNode>(op);
@@ -332,39 +506,73 @@ void LLMMLP::initSupportedPrimitiveDescriptors() {
if (!supportedPrimitiveDescriptors.empty())
return;
- auto rtPrecision = 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
-
- // initialize output port
std::vector<PortConfigurator> outPortConfigs;
- outPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getOutputShapeAtPort(0), false, -1);
+ auto rtPrecision = getOriginalInputPrecisionAtPort(0);
+
+ if (rtPrecision == ov::element::f32) {
+ // fallback to supported precision if possible
+ if (dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx_fp16)) {
+ rtPrecision = ov::element::f16;
+ } else if (dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx)) {
+ rtPrecision = ov::element::bf16;
+ }
+ }
+
+ OPENVINO_ASSERT(rtPrecision == ov::element::bf16 || rtPrecision == ov::element::f16, "Unexpected rtPrecision:", rtPrecision);
+
+ if (m_mlp_config.gate_up_quantized) {
+ auto weightPrecision = ov::element::i8;
+
+ // initialize input ports
+ 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, m_mlp_config.down_quantized ? ov::element::i8 : ov::element::f16,
+ getInputShapeAtPort(3), false, -1); // down
+ inPortConfigs.emplace_back(LayoutType::ncsp, ov::element::f32, getInputShapeAtPort(4), false, -1); // gate_weight scales per OC
+ inPortConfigs.emplace_back(LayoutType::ncsp, ov::element::f32, getInputShapeAtPort(5), false, -1); // up_weight scales per OC
+ if (m_mlp_config.down_quantized)
+ inPortConfigs.emplace_back(LayoutType::ncsp, ov::element::f32, getInputShapeAtPort(6), false, -1); // down_weight scales per OC
+
+ // initialize output port
+ outPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getOutputShapeAtPort(0), false, -1);
+ } else {
+ auto weightPrecision = ov::element::f16;
+
+ // initialize input ports
+ 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
+
+ // initialize output port
+ outPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getOutputShapeAtPort(0), false, -1);
+ }
addSupportedPrimDesc(inPortConfigs, outPortConfigs, impl_desc_type::ref_any);
}
-void LLMMLP::prepareParams() {
- if (!m_pimpl) {
- m_pimpl = std::make_shared<Impl>(getSrcMemoryAtPort(1),
- getSrcMemoryAtPort(2),
- getSrcMemoryAtPort(3),
- m_mlp_config,
- context->getScratchPad());
+void LLMMLP::createPrimitive() {
+ auto rtPrecision = getInputPrecisions()[0];
+#ifdef OPENVINO_ARCH_X86_64
+ if (rtPrecision == ov::element::bf16) {
+ m_executor = std::make_shared<Executor<ov::bfloat16>>(this, m_mlp_config, context->getScratchPad());
+ } else if (rtPrecision == ov::element::f16) {
+ m_executor = std::make_shared<Executor<ov::float16>>(this, m_mlp_config, context->getScratchPad());
+ }
+#endif
+ if (!m_executor) {
+ OPENVINO_THROW("LLMMLP Executor creation fails with precision " + rtPrecision.to_string());
}
}
void LLMMLP::execute(dnnl::stream strm) {
MAYBE_UNUSED(strm);
- m_pimpl->execute(this);
+ m_executor->execute();
}
-bool LLMMLP::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept {
+bool LLMMLP::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage, uint64_t fcDynamicQuantizationGroupSize) noexcept {
#if defined(OPENVINO_ARCH_X86_64)
try {
const auto node_mlp = std::dynamic_pointer_cast<const LLMMLPNode>(op);
@@ -377,6 +585,18 @@ 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();
+
+ auto& config = node_mlp->get_config();
+ if (config.gate_up_quantized && (fcDynamicQuantizationGroupSize < static_cast<uint64_t>(config.hidden_size))) {
+ errorMessage = "LLMMLPNode gate-up-proj only support per-token dynamic quantization";
+ return false;
+ }
+
+ if (config.down_quantized && (fcDynamicQuantizationGroupSize < static_cast<uint64_t>(config.up_size))) {
+ errorMessage = "LLMMLPNode down_proj only support per-token dynamic quantization";
+ return false;
+ }
+
if (down_size % REG_BLK_K_SIZE) {
errorMessage = "LLMMLPNode down_proj size is not multiple of register blocking size";
return false;
diff --git a/src/plugins/intel_cpu/src/nodes/llm_mlp.h b/src/plugins/intel_cpu/src/nodes/llm_mlp.h
index 3cdf6a0f1f7..47f9faf70c5 100644
--- a/src/plugins/intel_cpu/src/nodes/llm_mlp.h
+++ b/src/plugins/intel_cpu/src/nodes/llm_mlp.h
@@ -20,18 +20,27 @@ public:
bool created() const override {
return getType() == Type::LLMMLP;
}
- void prepareParams() override;
+ bool needPrepareParams() const override {
+ return false;
+ }
+ void createPrimitive() override;
void executeDynamicImpl(dnnl::stream strm) override {
execute(strm);
}
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,
+ uint64_t fcDynamicQuantizationGroupSize = 0) noexcept;
private:
- struct Impl;
+ struct ExecutorBase {
+ virtual void execute() = 0;
+ virtual ~ExecutorBase() = default;
+ };
+ std::shared_ptr<ExecutorBase> m_executor;
+ template <typename T> struct Executor;
LLMMLPNode::Config m_mlp_config;
- std::shared_ptr<Impl> m_pimpl;
};
} // 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 27ed49b2301..3260b12f1b5 100644
--- a/src/plugins/intel_cpu/src/nodes/qkv_proj.cpp
+++ b/src/plugins/intel_cpu/src/nodes/qkv_proj.cpp
@@ -7,6 +7,7 @@
#include <string>
#include <vector>
+#include "common/primitive_hashing_utils.hpp"
#include "common/bfloat16.hpp"
#include "common/cpu_memcpy.h"
#include "cpu/x64/cpu_isa_traits.hpp"
@@ -14,6 +15,15 @@
#include "shape_inference/shape_inference_internal_dyn.hpp"
#include "utils/plain_tensor.hpp"
+#if defined(OPENVINO_ARCH_X86_64)
+#include "kernels/x64/mlp_utils.hpp"
+#endif
+
+#include "openvino/core/parallel.hpp"
+
+using namespace dnnl::impl;
+using namespace dnnl::impl::utils;
+
namespace ov {
namespace intel_cpu {
namespace node {
@@ -42,7 +52,8 @@ static std::vector<int> allocate_workers(const std::vector<int>& grouped_works,
return g_workers;
}
-struct QKVProjection::Impl {
+template <typename T>
+struct QKVProjection::Executor : public QKVProjection::ExecutorBase {
std::vector<Work> works;
QKVProjection * m_node;
DnnlScratchPadPtr m_scrachPad;
@@ -50,23 +61,32 @@ struct QKVProjection::Impl {
uint8_t* m_scratch_base = nullptr;
int m_M = 0;
+ MatrixDynQuantPerRow m_quant_act;
+
WeightBuffer wbuffer;
- Impl(QKVProjection * pnode, DnnlScratchPadPtr scrachPad) : m_node(pnode), m_scrachPad(scrachPad) {
+ Executor(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));
+ // in quantized mode, weights are already quantized in per-OC mode into INT8
+ // and activations will be dynamically per-token quantized and using AMX-INT8 to get the result
+ bool quantized_int8 = m_node->m_config.quantized;
+
+ auto cache_blk_k_size = quantized_int8 ? CACHE_BLK_K_SIZE : CACHE_BLK_K_SIZE;
+ auto weight_element_size = quantized_int8 ? sizeof(int8_t) : sizeof(ov::float16);
+
auto K = w0.size(1);
- OPENVINO_ASSERT((K % CACHE_BLK_K_SIZE) == 0);
+ OPENVINO_ASSERT((K % cache_blk_k_size) == 0);
auto nthr = parallel_get_max_threads();
- auto num_blk_K = K / CACHE_BLK_K_SIZE;
- int stride = K * sizeof(ov::float16);
+ auto num_blk_K = K / cache_blk_k_size;
+ int stride_in_bytes = K * weight_element_size;
works.resize(nthr);
int cur_work_id = 0;
- auto create_works = [&](ov::float16* pw, int output_id, int N, int valid_nthr) {
+ auto create_works = [&](void* pw, int output_id, int N, int valid_nthr) {
// split task on more cores is better on TBB
OPENVINO_ASSERT((N % REG_BLK_N_SIZE) == 0);
auto num_blk_N = N / REG_BLK_N_SIZE;
@@ -82,37 +102,51 @@ struct QKVProjection::Impl {
}
if (blkN) {
auto& work = works[cur_work_id++];
- work.blk_K_size = CACHE_BLK_K_SIZE;
+ 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 = CACHE_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;
+ work.quant_i8 = quantized_int8;
+ work.is_f16 = std::is_same<T, ov::float16>::value;
}
start_blkN += blkN;
}
};
- auto proj_size0 = static_cast<int>(w0.size(0));
- auto proj_size1 = static_cast<int>(w1.size(0));
- auto proj_size2 = static_cast<int>(w2.size(0));
+ auto proj_size0 = m_node->m_config.proj_size0;
+ auto proj_size1 = m_node->m_config.proj_size1;
+ auto proj_size2 = m_node->m_config.proj_size2;
auto n_group_workers = allocate_workers({proj_size0, proj_size1, proj_size2}, nthr);
- 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]);
+ if (m_node->m_config.weights_combined) {
+ auto* ptr_weights = reinterpret_cast<int8_t*>(w0.ptr_v());
+ create_works(ptr_weights, 0, proj_size0, n_group_workers[0]);
+ ptr_weights += proj_size0 * stride_in_bytes;
+ create_works(ptr_weights, 1, proj_size1, n_group_workers[1]);
+ ptr_weights += proj_size1 * stride_in_bytes;
+ create_works(ptr_weights, 2, proj_size2, n_group_workers[2]);
+ } else {
+ create_works(w0.ptr_v(), 0, proj_size0, n_group_workers[0]);
+ create_works(w1.ptr_v(), 1, proj_size1, n_group_workers[1]);
+ create_works(w2.ptr_v(), 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);
+ wbuffer.alloc(works, weight_element_size);
ov::parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
auto& work = works[ithr];
if (work) {
- work.setup(wbuffer.get(ithr), work.p_raw_weights, stride);
+ if (quantized_int8)
+ work.setup(wbuffer.get<int8_t>(ithr), reinterpret_cast<int8_t*>(work.p_raw_weights), stride_in_bytes, true);
+ else
+ work.setup(wbuffer.get<T>(ithr), reinterpret_cast<ov::float16*>(work.p_raw_weights), stride_in_bytes);
}
});
}
@@ -123,145 +157,245 @@ struct QKVProjection::Impl {
cur_scratch_base = m_scratchMem->getDataAs<uint8_t>();
// new M larger than previous or the scratch pointer is changed after the following allocation
if (m_M < M || cur_scratch_base != m_scratch_base) {
- size_t total_scratch_size = 0;
- std::vector<size_t> scratch_offsets;
+ ScratchBuffAllocator allocator;
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;
+ allocator.register_allocation(C_size, [&](void* ptr){
+ work.set_C(M, reinterpret_cast<float*>(ptr));
+ });
}
}
- auto newMemDesc = std::make_shared<CpuBlockedMemoryDesc>(ov::element::u8, Shape{total_scratch_size});
- m_scratchMem = m_scrachPad->createScratchPadMem(newMemDesc);
+ if (m_node->m_config.quantized) {
+ m_quant_act.M = M;
+ m_quant_act.K = m_node->m_config.hidden_size;
+ allocator.register_allocation(m_quant_act.size(), [&](void* ptr){
+ m_quant_act.setup(ptr);
+ });
+ }
+ // make sure scratch is big enough
+ auto newMemDesc = std::make_shared<CpuBlockedMemoryDesc>(ov::element::u8, Shape{allocator.size()});
+ m_scratchMem = m_scrachPad->createScratchPadMem(newMemDesc);
m_scratch_base = m_scratchMem->getDataAs<uint8_t>();
- 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]));
- }
- }
+ allocator.finalize(m_scratch_base);
m_M = M;
}
}
- void execute() {
- static ReduceAdd2bh jit_2bh(false);
+ void execute() override {
+ static ReduceAdd2bh jit_cvt(false, std::is_same<T, ov::float16>::value);
+
auto input = m_node->getSrcMemoryAtPort(0);
const auto& ishape = input->getStaticDims();
- uint8_t* pA = input->getDataAs<uint8_t>();
+ uint8_t* psrc0 = input->getDataAs<uint8_t>();
int M = shape_size(ishape) / ishape[ishape.size() - 1];
- auto* dst0 = m_node->getDstMemoryAtPort(0)->getDataAs<ov::bfloat16>();
- auto* dst1 = m_node->getDstMemoryAtPort(1)->getDataAs<ov::bfloat16>();
- auto* dst2 = m_node->getDstMemoryAtPort(2)->getDataAs<ov::bfloat16>();
+ auto* dst0 = m_node->getDstMemoryAtPort(0)->getDataAs<T>();
+ auto* dst1 = m_node->getDstMemoryAtPort(1)->getDataAs<T>();
+ auto* dst2 = m_node->getDstMemoryAtPort(2)->getDataAs<T>();
+
+ float* w_scale[3];
+
+ if (m_node->m_config.quantized) {
+ w_scale[0] = m_node->getSrcMemoryAtPort(4)->getDataAs<float>();
+ if (m_node->m_config.weights_combined) {
+ w_scale[1] = w_scale[0] + m_node->m_config.proj_size0;
+ w_scale[2] = w_scale[1] + m_node->m_config.proj_size1;
+ } else {
+ w_scale[1] = m_node->getSrcMemoryAtPort(5)->getDataAs<float>();
+ w_scale[2] = m_node->getSrcMemoryAtPort(6)->getDataAs<float>();
+ }
+ }
const auto& srcStrides = input->getDescWithType<BlockedMemoryDesc>()->getStrides();
const auto& dstStrides0 = m_node->getDstMemoryAtPort(0)->getDescWithType<BlockedMemoryDesc>()->getStrides();
const auto& dstStrides1 = m_node->getDstMemoryAtPort(1)->getDescWithType<BlockedMemoryDesc>()->getStrides();
const auto& dstStrides2 = m_node->getDstMemoryAtPort(2)->getDescWithType<BlockedMemoryDesc>()->getStrides();
- int strideA = srcStrides[1] * sizeof(ov::bfloat16);
- auto stride_0 = dstStrides0[1];
- auto stride_1 = dstStrides1[1];
- auto stride_2 = dstStrides2[1];
+ int stride_src = srcStrides[1] * sizeof(T);
+ auto stride_dst_0 = dstStrides0[1];
+ auto stride_dst_1 = dstStrides1[1];
+ auto stride_dst_2 = dstStrides2[1];
+ auto asym = true;
for (int m = 0; m < M;) {
int BM = std::min(M - m, CACHE_BLK_M_SIZE);
setM(BM);
+ // dynamic quantize input tensor A[m0:m1, :] into scratch buffer
+ // because it's being shared by all kernels
+ uint8_t* pA = psrc0;
+ auto strideA = stride_src;
+ if (m_node->m_config.quantized) {
+ // quantize psrc0 into m_quantized_act buffer
+ // per-token asym
+ m_quant_act.quantize(BM, reinterpret_cast<T*>(psrc0), srcStrides[1]);
+ pA = reinterpret_cast<uint8_t*>(m_quant_act.data);
+ strideA = m_quant_act.K;
+ }
+
ov::parallel_nt_static(0, [&](const size_t ithr, const size_t nthr) {
auto& work = works[ithr];
if (work) {
work.run(BM, pA, strideA);
- // compress accumulation result into target
- auto* src = work.m_C.ptr<float>();
- auto stride_src = work.m_C.stride(0);
- ov::bfloat16* dst = nullptr;
+ // determine destination buffer
+ T* dst = nullptr;
int stride_dst = 0;
+
if (work.output_id == 0) {
dst = dst0 + work.n0;
- stride_dst = stride_0;
+ stride_dst = stride_dst_0;
}
if (work.output_id == 1) {
dst = dst1 + work.n0;
- stride_dst = stride_1;
+ stride_dst = stride_dst_1;
}
if (work.output_id == 2) {
dst = dst2 + work.n0;
- stride_dst = stride_2;
+ stride_dst = stride_dst_2;
}
+ auto* src = work.m_C.template ptr<float>();
+ auto stride_src = work.m_C.stride(0);
+ if (m_node->m_config.quantized) {
+ // dequantize output & convert to f32 in-place
+ auto* p_wsum = work.w_sum_per_oc.template ptr<float>();
+ ov::Extensions::Cpu::XARCH::llm_mlp_dequantize_i32_f32(
+ BM,
+ work.BN,
+ reinterpret_cast<int32_t*>(src),
+ stride_src,
+ src,
+ stride_src,
+ m_quant_act.scale,
+ m_quant_act.zp,
+ p_wsum,
+ w_scale[work.output_id] + work.n0,
+ asym);
+ }
+ // compress accumulation result into target
for (int mi = 0; mi < BM; mi++, src += stride_src, dst += stride_dst) {
// the prefetch distance is increased to ensure by the time store happens
// prefetch has done and no HW prefetcher is triggered
auto* prefetch_dst = (mi + 2 < BM) ? (dst + 2 * stride_dst) : (dst);
- jit_2bh(src, dst, prefetch_dst, work.BN);
+ jit_cvt(src, dst, prefetch_dst, work.BN);
}
}
});
m += BM;
- pA += BM * strideA;
- dst0 += BM * stride_0;
- dst1 += BM * stride_1;
- dst2 += BM * stride_2;
+ psrc0 += BM * stride_src;
+ dst0 += BM * stride_dst_0;
+ dst1 += BM * stride_dst_1;
+ dst2 += BM * stride_dst_2;
}
}
};
#else
-struct QKVProjection::Impl {
- Impl(QKVProjection * pnode, DnnlScratchPadPtr scrachPad) {}
- void execute() {}
+template <typename T>
+struct QKVProjection::Executor : public QKVProjection::ExecutorBase {
+ QKVProjection * m_pnode;
+ Executor(QKVProjection * pnode) : m_pnode(pnode) {}
+ void execute() override {}
};
#endif
-void QKVProjection::prepareParams() {
- if (!m_pimpl) {
- m_pimpl = std::make_shared<Impl>(this, context->getScratchPad());
+void QKVProjection::createPrimitive() {
+ auto rtPrecision = getInputPrecisions()[0];
+#ifdef OPENVINO_ARCH_X86_64
+ if (rtPrecision == ov::element::bf16) {
+ m_executor = std::make_shared<Executor<ov::bfloat16>>(this, context->getScratchPad());
+ } else if (rtPrecision == ov::element::f16) {
+ m_executor = std::make_shared<Executor<ov::float16>>(this, context->getScratchPad());
+ }
+#endif
+ if (!m_executor) {
+ OPENVINO_THROW("QKVProjection Executor creation fails with precision " + rtPrecision.to_string());
}
}
void QKVProjection::execute(dnnl::stream strm) {
MAYBE_UNUSED(strm);
- m_pimpl->execute();
+ m_executor->execute();
}
QKVProjection::QKVProjection(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr context)
: Node(op, context, NgraphShapeInferFactory(op, EMPTY_PORT_MASK)) {
std::string errorMessage;
- if (!isSupportedOperation(op, errorMessage)) {
+
+ const auto & config = context->getConfig();
+ size_t concurrency = config.streamExecutorConfig.get_threads_per_stream();
+ if (concurrency == 0)
+ concurrency = parallel_get_max_threads();
+
+ if (!isSupportedOperation(op, errorMessage, concurrency, config.fcDynamicQuantizationGroupSize)) {
OPENVINO_THROW("CPU: " + errorMessage);
}
+ const auto node = std::dynamic_pointer_cast<const QKVProjectionNode>(op);
+ m_config = node->get_config();
}
void QKVProjection::initSupportedPrimitiveDescriptors() {
if (!supportedPrimitiveDescriptors.empty())
return;
- auto rtPrecision = 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); // 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;
- outPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getOutputShapeAtPort(0), false, -1);
- outPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getOutputShapeAtPort(1), false, -1);
- outPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getOutputShapeAtPort(2), false, -1);
+
+ auto rtPrecision = getOriginalInputPrecisionAtPort(0);
+
+ if (rtPrecision == ov::element::f32) {
+ // fallback to supported precision if possible
+ if (dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx_fp16)) {
+ rtPrecision = ov::element::f16;
+ } else if (dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx)) {
+ rtPrecision = ov::element::bf16;
+ }
+ }
+
+ OPENVINO_ASSERT(rtPrecision == ov::element::bf16 || rtPrecision == ov::element::f16, "Unexpected rtPrecision:", rtPrecision);
+
+ if (m_config.quantized) {
+ auto weightPrecision = ov::element::i8;
+ auto wScalePrecision = ov::element::f32;
+
+ inPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getInputShapeAtPort(0), false, -1); // input
+ 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
+ inPortConfigs.emplace_back(LayoutType::ncsp, wScalePrecision, getInputShapeAtPort(4), false, -1); // q_proj deq-scale per-OC
+ inPortConfigs.emplace_back(LayoutType::ncsp, wScalePrecision, getInputShapeAtPort(5), false, -1); // k_proj deq-scale per-OC
+ inPortConfigs.emplace_back(LayoutType::ncsp, wScalePrecision, getInputShapeAtPort(6), false, -1); // v_proj deq-scale per-OC
+
+ // initialize output port
+ outPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getOutputShapeAtPort(0), false, -1);
+ outPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getOutputShapeAtPort(1), false, -1);
+ outPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getOutputShapeAtPort(2), false, -1);
+ } else {
+ auto weightPrecision = ov::element::f16;
+
+ // initialize input ports
+ inPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getInputShapeAtPort(0), false, -1); // input
+ 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
+ outPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getOutputShapeAtPort(0), false, -1);
+ outPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getOutputShapeAtPort(1), false, -1);
+ outPortConfigs.emplace_back(LayoutType::ncsp, rtPrecision, getOutputShapeAtPort(2), false, -1);
+ }
addSupportedPrimDesc(inPortConfigs, outPortConfigs, impl_desc_type::ref_any);
}
-bool QKVProjection::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage, int concurrency) noexcept {
+bool QKVProjection::isSupportedOperation(const std::shared_ptr<const ov::Node>& op,
+ std::string& errorMessage,
+ int concurrency,
+ uint64_t fcDynamicQuantizationGroupSize) noexcept {
#if defined(OPENVINO_ARCH_X86_64)
try {
const auto node_qkv = std::dynamic_pointer_cast<const QKVProjectionNode>(op);
@@ -277,22 +411,27 @@ bool QKVProjection::isSupportedOperation(const std::shared_ptr<const ov::Node>&
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] % CACHE_BLK_K_SIZE) != 0) {
+ const auto& config = node_qkv->get_config();
+ if ((config.hidden_size % CACHE_BLK_K_SIZE) != 0) {
errorMessage = "QKVProjection input channel size is not multiple of cache blocking size";
return false;
}
- if ((proj_pshape1[0] % REG_BLK_K_SIZE) != 0) {
+
+ if (config.quantized && (fcDynamicQuantizationGroupSize < static_cast<uint64_t>(config.hidden_size))) {
+ errorMessage = "QKVProjection input channel only support per-token dynamic quantization";
+ return false;
+ }
+
+ auto reg_blk_k_size = node_qkv->get_config().quantized ? REG_BLK_K_SIZE_I8 : REG_BLK_K_SIZE;
+ if ((config.proj_size0 % 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] % REG_BLK_K_SIZE) != 0) {
+ if ((config.proj_size1 % 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] % REG_BLK_K_SIZE) != 0) {
+ if ((config.proj_size2 % reg_blk_k_size) != 0) {
errorMessage = "QKVProjection 3rd proj output channel size is not multiple of register blocking size";
return false;
}
diff --git a/src/plugins/intel_cpu/src/nodes/qkv_proj.h b/src/plugins/intel_cpu/src/nodes/qkv_proj.h
index 7717d00e5de..7a94b3e704f 100644
--- a/src/plugins/intel_cpu/src/nodes/qkv_proj.h
+++ b/src/plugins/intel_cpu/src/nodes/qkv_proj.h
@@ -23,17 +23,29 @@ public:
bool created() const override {
return getType() == Type::QKVProjection;
}
- void prepareParams() override;
+ bool needPrepareParams() const override {
+ return false;
+ }
+ void createPrimitive() override;
void executeDynamicImpl(dnnl::stream strm) override {
execute(strm);
}
void initSupportedPrimitiveDescriptors() override;
void execute(dnnl::stream strm) override;
- static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage, int concurrency = 0) noexcept;
+ static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op,
+ std::string& errorMessage,
+ int concurrency = 0,
+ uint64_t fcDynamicQuantizationGroupSize = 0) noexcept;
private:
- struct Impl;
- std::shared_ptr<Impl> m_pimpl;
+ struct ExecutorBase {
+ virtual void execute() = 0;
+ virtual ~ExecutorBase() = default;
+ };
+ std::shared_ptr<ExecutorBase> m_executor;
+ template <typename T> struct Executor;
+
+ QKVProjectionNode::Config m_config;
};
} // namespace node
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/llm_mlp.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/llm_mlp.cpp
index 2ad643d3ad4..0706f13c3a5 100644
--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/llm_mlp.cpp
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/llm_mlp.cpp
@@ -25,6 +25,11 @@ bool LLMMLPNode::visit_attributes(ov::AttributeVisitor& visitor) {
INTERNAL_OP_SCOPE(LLMMLPNode_visit_attributes);
visitor.start_structure("config");
visitor.on_attribute("act", m_config.act);
+ visitor.on_attribute("gate_up_quantized", m_config.gate_up_quantized);
+ visitor.on_attribute("down_quantized", m_config.down_quantized);
+ visitor.on_attribute("hidden_size", m_config.hidden_size);
+ visitor.on_attribute("up_size", m_config.up_size);
+ visitor.on_attribute("gate_up_combined", m_config.gate_up_combined);
visitor.finish_structure();
return true;
}
@@ -32,7 +37,10 @@ bool LLMMLPNode::visit_attributes(ov::AttributeVisitor& visitor) {
void LLMMLPNode::validate_and_infer_types() {
INTERNAL_OP_SCOPE(LLMMLPNode_validate_and_infer_types);
const auto input_size = get_input_size();
- NODE_VALIDATION_CHECK(this, input_size == 4);
+ size_t expect_input_size = 4;
+ if (m_config.gate_up_quantized) expect_input_size += 2;
+ if (m_config.down_quantized) expect_input_size += 1;
+ NODE_VALIDATION_CHECK(this, input_size == expect_input_size);
const auto& ishape = get_input_partial_shape(0);
const auto& itype = get_input_element_type(0);
@@ -44,6 +52,7 @@ void LLMMLPNode::validate_and_infer_types() {
const auto length = ishape[1];
const auto feature = ishape[2];
NODE_VALIDATION_CHECK(this, feature.is_static());
+ NODE_VALIDATION_CHECK(this, itype.is_real(), "feature data type must be real");
auto oshape = ishape;
oshape[oshape.size() - 1] = w_down_shape[0];
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/llm_mlp.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/llm_mlp.hpp
index f4f3c72b7e4..fa1569dbb8e 100644
--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/llm_mlp.hpp
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/llm_mlp.hpp
@@ -20,6 +20,11 @@ public:
struct Config {
ACT_FN act;
+ bool gate_up_quantized;
+ bool down_quantized;
+ int hidden_size;
+ int up_size;
+ bool gate_up_combined;
};
// args:
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/qkv_proj.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/qkv_proj.cpp
index cb9cc543c40..e770a7f530d 100644
--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/qkv_proj.cpp
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/qkv_proj.cpp
@@ -11,7 +11,7 @@ namespace intel_cpu {
void QKVProjectionNode::validate_and_infer_types() {
INTERNAL_OP_SCOPE(QKVProjection_validate_and_infer_types);
const auto input_size = get_input_size();
- NODE_VALIDATION_CHECK(this, input_size == 4);
+ NODE_VALIDATION_CHECK(this, input_size == (m_config.quantized ? 7 : 4));
const auto& ishape = get_input_partial_shape(0);
const auto& itype = get_input_element_type(0);
@@ -23,9 +23,10 @@ void QKVProjectionNode::validate_and_infer_types() {
auto oshape0 = ishape;
auto oshape1 = ishape;
auto oshape2 = ishape;
- oshape0[oshape0.size()-1] = get_input_partial_shape(1)[0];
- oshape1[oshape1.size()-1] = get_input_partial_shape(2)[0];
- oshape2[oshape2.size()-1] = get_input_partial_shape(3)[0];
+ oshape0[oshape0.size()-1] = m_config.proj_size0;
+ oshape1[oshape1.size()-1] = m_config.proj_size1;
+ oshape2[oshape2.size()-1] = m_config.proj_size2;
+
set_output_type(0, itype, oshape0);
set_output_type(1, itype, oshape1);
set_output_type(2, itype, oshape2);
@@ -34,7 +35,7 @@ void QKVProjectionNode::validate_and_infer_types() {
std::shared_ptr<Node> QKVProjectionNode::clone_with_new_inputs(const ov::OutputVector& new_args) const {
INTERNAL_OP_SCOPE(QKVProjection_with_new_inputs);
check_new_args_count(this, new_args);
- return std::make_shared<QKVProjectionNode>(new_args);
+ return std::make_shared<QKVProjectionNode>(new_args, m_config);
}
} // namespace intel_cpu
} // namespace ov
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/qkv_proj.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/qkv_proj.hpp
index 98f226ccdb4..d107515635c 100644
--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/qkv_proj.hpp
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/op/qkv_proj.hpp
@@ -16,18 +16,29 @@ public:
QKVProjectionNode() = default;
- // args:
- // 0: input
- // 1: gate_proj
- // 2: up_proj
- // 3: down_proj
- QKVProjectionNode(const OutputVector& args) : Op(args) {
+ struct Config {
+ bool quantized;
+ int hidden_size;
+ int proj_size0;
+ int proj_size1;
+ int proj_size2;
+ bool weights_combined;
+ };
+
+ QKVProjectionNode(const OutputVector& args, const Config& cfg) : Op(args), m_config(cfg) {
validate_and_infer_types();
}
void validate_and_infer_types() override;
std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;
+
+ const Config& get_config() const {
+ return m_config;
+ }
+
+private:
+ Config m_config;
};
} // namespace intel_cpu
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/mlp_fusion.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/mlp_fusion.cpp
index d1efb226ff1..6b31f7d4987 100644
--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/mlp_fusion.cpp
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/mlp_fusion.cpp
@@ -31,18 +31,68 @@ ov::intel_cpu::MLPFusion::MLPFusion() {
auto gate_proj_weight_compressed = makePattern<opset1::Constant>({}); // [up_size, down_size]
auto gate_proj_weight = makePattern<opset1::Convert>({gate_proj_weight_compressed}, {{"destination_type", "f32"}});
+
auto up_proj_weight_compressed = makePattern<opset1::Constant>({}); // [up_size, down_size]
auto up_proj_weight = makePattern<opset1::Convert>({up_proj_weight_compressed}, {{"destination_type", "f32"}});
+
auto down_proj_weight_compressed = makePattern<opset1::Constant>({}); // [down_size, up_size]
auto down_proj_weight = makePattern<opset1::Convert>({down_proj_weight_compressed}, {{"destination_type", "f32"}});
- auto mlp_gate_proj = makePattern<opset1::MatMul>({input, gate_proj_weight | gate_proj_weight_compressed},
+
+ // symmetrically INT8 quantized version
+ // all 3 layers must be quantized at the same time (checked in callback)
+ auto gate_proj_weight_i8 =
+ makeConst(ov::element::i8, ov::PartialShape({ov::Dimension(), ov::Dimension()}), nullptr);
+ auto gate_proj_weight_scales_per_OC = makeConst(ov::element::f32, ov::PartialShape({ov::Dimension(), 1}), nullptr);
+ auto gate_proj_weight_f32 = makePattern<opset1::Convert>({gate_proj_weight_i8}, {{"destination_type", "f32"}});
+ auto gate_proj_weight_deq =
+ makePattern<opset1::Multiply>({gate_proj_weight_f32, gate_proj_weight_scales_per_OC}, {{"auto_broadcast", "numpy"}});
+
+ auto up_proj_weight_i8 =
+ makeConst(ov::element::i8, ov::PartialShape({ov::Dimension(), ov::Dimension()}), nullptr);
+ auto up_proj_weight_scales_per_OC = makeConst(ov::element::f32, ov::PartialShape({ov::Dimension(), 1}), nullptr);
+ auto up_proj_weight_f32 = makePattern<opset1::Convert>({up_proj_weight_i8}, {{"destination_type", "f32"}});
+ auto up_proj_weight_deq =
+ makePattern<opset1::Multiply>({up_proj_weight_f32, up_proj_weight_scales_per_OC}, {{"auto_broadcast", "numpy"}});
+
+ auto down_proj_weight_i8 =
+ makeConst(ov::element::i8, ov::PartialShape({ov::Dimension(), ov::Dimension()}), nullptr);
+ auto down_proj_weight_scales_per_OC = makeConst(ov::element::f32, ov::PartialShape({ov::Dimension(), 1}), nullptr);
+ auto down_proj_weight_f32 = makePattern<opset1::Convert>({down_proj_weight_i8}, {{"destination_type", "f32"}});
+ auto down_proj_weight_deq =
+ makePattern<opset1::Multiply>({down_proj_weight_f32, down_proj_weight_scales_per_OC}, {{"auto_broadcast", "numpy"}});
+
+ // gate-up weights are combined
+ auto gate_up_proj_weight = makeConst(ov::element::f16, ov::PartialShape({ov::Dimension(), ov::Dimension()}), nullptr);
+ auto gate_up_proj_weight_f32 = makePattern<opset1::Convert>({gate_up_proj_weight}, {{"destination_type", "f32"}});
+
+ auto gate_up_proj_weight_const_i8 =
+ makeConst(ov::element::i8, ov::PartialShape({ov::Dimension(), ov::Dimension()}), nullptr);
+ auto gate_up_proj_weight_cvt_f32 = makePattern<opset1::Convert>({gate_up_proj_weight_const_i8}, {{"destination_type", "f32"}});
+ auto gate_up_proj_weight_scales_per_OC = makeConst(ov::element::f32, ov::PartialShape({ov::Dimension(), 1}), nullptr);
+ auto gate_up_proj_weight_deq = makePattern<opset1::Multiply>({gate_up_proj_weight_cvt_f32, gate_up_proj_weight_scales_per_OC},
+ {{"auto_broadcast", "numpy"}});
+
+ auto gate_up_proj = makePattern<opset1::MatMul>({input, gate_up_proj_weight_f32 | gate_up_proj_weight_deq},
+ {{"transpose_a", false}, {"transpose_b", true}});
+ auto gate_up_split_lengths = makeConst(ov::element::i32,
+ ov::Shape({
+ 2,
+ }),
+ nullptr);
+ auto gate_up_proj_split = makePattern<opset1::VariadicSplit>({gate_up_proj, -1, gate_up_split_lengths});
+ gate_up_proj_split->set_output_size(2);
+
+ auto mlp_gate_proj = makePattern<opset1::MatMul>({input, gate_proj_weight | gate_proj_weight_compressed | gate_proj_weight_deq},
{{"transpose_a", false}, {"transpose_b", true}}); // [?,?,up_size]
- auto mlp_silu_gate = makePattern<opset4::Swish>({mlp_gate_proj});
- auto mlp_gelu_gate = makePattern<opset7::Gelu>({mlp_gate_proj});
- auto mlp_up_proj = makePattern<opset1::MatMul>({input, up_proj_weight | up_proj_weight_compressed},
+ auto mlp_silu_gate = makePattern<opset4::Swish>({mlp_gate_proj | gate_up_proj_split->output(0)});
+ auto mlp_gelu_gate = makePattern<opset7::Gelu>({mlp_gate_proj | gate_up_proj_split->output(0)});
+ auto mlp_up_proj = makePattern<opset1::MatMul>({input, up_proj_weight | up_proj_weight_compressed | up_proj_weight_deq},
{{"transpose_a", false}, {"transpose_b", true}});
- auto mlp_gated_up = makePattern<opset1::Multiply>({mlp_silu_gate | mlp_gelu_gate, mlp_up_proj}, {{"auto_broadcast", "numpy"}});
- auto down_proj = makePattern<opset1::MatMul>({mlp_gated_up, down_proj_weight | down_proj_weight_compressed},
+
+ auto mlp_gated_up =
+ makePattern<opset1::Multiply>({mlp_silu_gate | mlp_gelu_gate, mlp_up_proj | gate_up_proj_split->output(1)},
+ {{"auto_broadcast", "numpy"}});
+ auto down_proj = makePattern<opset1::MatMul>({mlp_gated_up, down_proj_weight | down_proj_weight_compressed | down_proj_weight_deq},
{{"transpose_a", false}, {"transpose_b", true}}); // [?,?,down_size]
auto result = down_proj;
@@ -55,10 +105,56 @@ ov::intel_cpu::MLPFusion::MLPFusion() {
const auto& pattern_map = m.get_pattern_value_map();
auto root = m.get_match_root();
-
- auto gate_proj_w = pattern_map.at(gate_proj_weight_compressed);
- auto up_proj_w = pattern_map.at(up_proj_weight_compressed);
- auto down_proj_w = pattern_map.at(down_proj_weight_compressed);
+ auto src = pattern_map.at(input);
+ if (!src.get_element_type().is_real()) {
+ // FakeQuantize, should skip fusion
+ return false;
+ }
+ Output<Node> gate_proj_w;
+ Output<Node> up_proj_w;
+ Output<Node> down_proj_w;
+
+ // down projection is harder to quantize w/o causing accuracy problem, so it may be un-quantized instead
+ bool is_gate_up_quantized_int8 = false;
+ bool is_down_proj_int8 = false;
+ bool is_gate_up_combined = false;
+ if (pattern_map.count(gate_up_proj_weight_const_i8) > 0 && pattern_map.count(down_proj_weight_compressed) > 0) {
+ //gate-up combined & quantized
+ is_gate_up_quantized_int8 = true;
+ is_gate_up_combined = true;
+ gate_proj_w = pattern_map.at(gate_up_proj_weight_const_i8);
+ up_proj_w = pattern_map.at(gate_up_proj_weight_const_i8);
+ down_proj_w = pattern_map.at(down_proj_weight_compressed);
+ } else if (pattern_map.count(gate_up_proj_weight) > 0 && pattern_map.count(down_proj_weight_compressed) > 0) {
+ //gate-up combined
+ is_gate_up_combined = true;
+ gate_proj_w = pattern_map.at(gate_up_proj_weight);
+ up_proj_w = pattern_map.at(gate_up_proj_weight);
+ down_proj_w = pattern_map.at(down_proj_weight_compressed);
+ } else if (pattern_map.count(gate_proj_weight_compressed) > 0 && pattern_map.count(up_proj_weight_compressed) > 0 &&
+ pattern_map.count(down_proj_weight_compressed) > 0) {
+ is_gate_up_quantized_int8 = false;
+ is_down_proj_int8 = false;
+ gate_proj_w = pattern_map.at(gate_proj_weight_compressed);
+ up_proj_w = pattern_map.at(up_proj_weight_compressed);
+ down_proj_w = pattern_map.at(down_proj_weight_compressed);
+ } else if (pattern_map.count(gate_proj_weight_i8) > 0 && pattern_map.count(up_proj_weight_i8) > 0 &&
+ pattern_map.count(gate_proj_weight_scales_per_OC) > 0 && pattern_map.count(up_proj_weight_scales_per_OC) > 0) {
+ is_gate_up_quantized_int8 = true;
+ gate_proj_w = pattern_map.at(gate_proj_weight_i8);
+ up_proj_w = pattern_map.at(up_proj_weight_i8);
+
+ if (pattern_map.count(down_proj_weight_i8) > 0) {
+ if (pattern_map.count(down_proj_weight_scales_per_OC) == 0) return false;
+ is_down_proj_int8 = true;
+ down_proj_w = pattern_map.at(down_proj_weight_i8);
+ } else {
+ is_down_proj_int8 = false;
+ down_proj_w = pattern_map.at(down_proj_weight_compressed);
+ }
+ } else {
+ return false;
+ }
auto gate_proj_w_pshape = gate_proj_w.get_partial_shape();
auto up_proj_w_pshape = up_proj_w.get_partial_shape();
@@ -84,7 +180,7 @@ ov::intel_cpu::MLPFusion::MLPFusion() {
if (down_shape.size() != 2)
return false;
- auto up_size = up_shape[0];
+ auto up_size = is_gate_up_combined ? (up_shape[0] / 2) : (up_shape[0]);
auto down_size = up_shape[1];
if (down_shape[0] != down_size)
return false;
@@ -94,6 +190,12 @@ ov::intel_cpu::MLPFusion::MLPFusion() {
LLMMLPNode::Config config;
OutputVector new_args;
std::shared_ptr<Node> gate_act;
+
+ config.gate_up_quantized = is_gate_up_quantized_int8;
+ config.down_quantized = is_down_proj_int8;
+ config.hidden_size = down_size;
+ config.up_size = up_size;
+ config.gate_up_combined = is_gate_up_combined;
if (pattern_map.count(mlp_silu_gate) > 0) {
config.act = LLMMLPNode::ACT_FN::SILU;
gate_act = mlp_silu_gate;
@@ -104,20 +206,35 @@ ov::intel_cpu::MLPFusion::MLPFusion() {
return false;
}
- new_args.push_back(pattern_map.at(input));
+ new_args.push_back(src);
new_args.push_back(gate_proj_w);
new_args.push_back(up_proj_w);
new_args.push_back(down_proj_w);
+ if (is_gate_up_quantized_int8) {
+ if (is_gate_up_combined) {
+ new_args.push_back(pattern_map.at(gate_up_proj_weight_scales_per_OC));
+ new_args.push_back(pattern_map.at(gate_up_proj_weight_scales_per_OC));
+ } else {
+ new_args.push_back(pattern_map.at(gate_proj_weight_scales_per_OC));
+ new_args.push_back(pattern_map.at(up_proj_weight_scales_per_OC));
+ }
+ }
+ if (is_down_proj_int8) {
+ new_args.push_back(pattern_map.at(down_proj_weight_scales_per_OC));
+ }
auto old_node = root;
auto new_node = std::make_shared<LLMMLPNode>(new_args, config);
new_node->set_friendly_name(old_node->get_friendly_name());
- ov::copy_runtime_info({pattern_map.at(mlp_gate_proj).get_node_shared_ptr(),
- pattern_map.at(gate_act).get_node_shared_ptr(),
- pattern_map.at(mlp_up_proj).get_node_shared_ptr(),
+ ov::copy_runtime_info({pattern_map.at(gate_act).get_node_shared_ptr(),
pattern_map.at(down_proj).get_node_shared_ptr()},
new_node);
-
+ if (is_gate_up_combined) {
+ ov::copy_runtime_info({pattern_map.at(gate_up_proj).get_node_shared_ptr()}, new_node);
+ } else {
+ ov::copy_runtime_info({pattern_map.at(mlp_gate_proj).get_node_shared_ptr(),
+ pattern_map.at(mlp_up_proj).get_node_shared_ptr()}, new_node);
+ }
// callback is for plugin implementation to check if it can be supported
if (!transformation_callback(new_node)) {
return false;
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/qkv_proj_fusion.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/qkv_proj_fusion.cpp
index 11ef6ca09ff..10e3f39801a 100644
--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/qkv_proj_fusion.cpp
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/qkv_proj_fusion.cpp
@@ -18,8 +18,8 @@
#include "openvino/pass/pattern/op/wrap_type.hpp"
#include "ov_ops/type_relaxed.hpp"
#include "transformations/cpu_opset/x64/op/qkv_proj.hpp"
-#include "transformations/utils/utils.hpp"
#include "transformations/utils/gen_pattern.hpp"
+#include "transformations/utils/utils.hpp"
using namespace ov::gen_pattern;
@@ -28,10 +28,18 @@ ov::intel_cpu::QKVProjFusion::QKVProjFusion() {
auto input = makePattern("[?,?,?]");
- auto q_proj_weight = makePattern<opset1::Constant>({});
+ auto q_proj_weight_const = makePattern<opset1::Constant>({});
+
+ auto q_proj_weight_const_i8 =
+ makeConst(ov::element::i8, ov::PartialShape({ov::Dimension(), ov::Dimension()}), nullptr);
+ auto q_proj_weight_f32 = makePattern<opset1::Convert>({q_proj_weight_const_i8}, {{"destination_type", "f32"}});
+ auto q_proj_weight_scales_per_OC = makeConst(ov::element::f32, ov::PartialShape({ov::Dimension(), 1}), nullptr);
+ auto q_proj_weight_deq =
+ makePattern<opset1::Multiply>({q_proj_weight_f32, q_proj_weight_scales_per_OC}, {{"auto_broadcast", "numpy"}});
+
auto q_proj_weight_cvt =
- makePattern<opset1::Convert>({q_proj_weight}, {{"destination_type", "f32"}}); // [4096,4096]
- auto q_proj = makePattern<opset1::MatMul>({input, q_proj_weight_cvt | q_proj_weight},
+ makePattern<opset1::Convert>({q_proj_weight_const}, {{"destination_type", "f32"}}); // [4096,4096]
+ auto q_proj = makePattern<opset1::MatMul>({input, q_proj_weight_cvt | q_proj_weight_const | q_proj_weight_deq},
{{"transpose_a", false}, {"transpose_b", true}}); // [?,?,4096]
auto result = q_proj;
@@ -56,7 +64,10 @@ ov::intel_cpu::QKVProjFusion::QKVProjFusion() {
return false;
}
+ bool is_quantized_int8 = pattern_map.count(q_proj_weight_const_i8);
+
OutputVector args = {src};
+ OutputVector deq_scales;
OutputVector outputs;
size_t hidden_size = 0;
std::vector<int> proj_size;
@@ -69,16 +80,42 @@ ov::intel_cpu::QKVProjFusion::QKVProjFusion() {
if (mm->get_transpose_a() != false || mm->get_transpose_b() != true) {
return false;
}
- auto constw = ov::as_type_ptr<opset1::Constant>(mm->input_value(1).get_node_shared_ptr());
- if (!constw) {
- auto cvt = ov::as_type_ptr<opset1::Convert>(mm->input_value(1).get_node_shared_ptr());
- if (!cvt) {
+
+ auto mm_input1 = mm->input_value(1).get_node_shared_ptr();
+
+ std::shared_ptr<opset1::Constant> constw;
+ std::shared_ptr<opset1::Constant> deq_scale;
+
+ if (is_quantized_int8) {
+ auto deq_mul = ov::as_type_ptr<opset1::Multiply>(mm_input1);
+ if (!deq_mul)
return false;
- }
+
+ auto deq_mul_in0 = deq_mul->input_value(0).get_node_shared_ptr();
+ auto deq_mul_in1 = deq_mul->input_value(1).get_node_shared_ptr();
+
+ auto cvt = ov::as_type_ptr<opset1::Convert>(deq_mul_in0);
+ if (!cvt)
+ return false;
+
constw = ov::as_type_ptr<opset1::Constant>(cvt->input_value(0).get_node_shared_ptr());
- }
- if (!constw) {
- return false;
+ if (!constw || constw->get_element_type() != ov::element::i8)
+ return false;
+
+ deq_scale = ov::as_type_ptr<opset1::Constant>(deq_mul_in1);
+ if (!deq_scale || deq_scale->get_element_type() != ov::element::f32)
+ return false;
+ } else {
+ constw = ov::as_type_ptr<opset1::Constant>(mm_input1);
+ if (!constw) {
+ if (auto cvt = ov::as_type_ptr<opset1::Convert>(mm_input1)) {
+ constw = ov::as_type_ptr<opset1::Constant>(cvt->input_value(0).get_node_shared_ptr());
+ } else {
+ return false;
+ }
+ }
+ if (!constw)
+ return false;
}
// input feature size should be the same
@@ -91,6 +128,7 @@ ov::intel_cpu::QKVProjFusion::QKVProjFusion() {
proj_size.push_back(wshape[0]);
args.push_back(constw);
+ deq_scales.push_back(deq_scale);
outputs.push_back(mm->get_default_output());
}
@@ -101,9 +139,22 @@ ov::intel_cpu::QKVProjFusion::QKVProjFusion() {
if (args.size() != 4) {
return false;
}
+ // append dequantize scales at the end
+ if (is_quantized_int8) {
+ for (auto& d : deq_scales)
+ args.push_back(d);
+ }
+
+ QKVProjectionNode::Config config;
+ config.quantized = is_quantized_int8;
+ config.hidden_size = hidden_size;
+ config.weights_combined = false;
+ config.proj_size0 = proj_size[0];
+ config.proj_size1 = proj_size[1];
+ config.proj_size2 = proj_size[2];
auto old_node = root;
- auto new_node = std::make_shared<QKVProjectionNode>(args);
+ auto new_node = std::make_shared<QKVProjectionNode>(args, config);
new_node->set_friendly_name(old_node->get_friendly_name());
ov::copy_runtime_info({old_node}, new_node);
@@ -125,3 +176,107 @@ ov::intel_cpu::QKVProjFusion::QKVProjFusion() {
auto m = std::make_shared<ov::pass::pattern::Matcher>(result, matcher_name);
this->register_matcher(m, callback);
}
+
+ov::intel_cpu::QKVProjFusion2::QKVProjFusion2() {
+ MATCHER_SCOPE(QKVProjFusion2);
+
+ auto input = makePattern("[?,?,?]");
+
+ auto qkv_proj_weight_const = makePattern<opset1::Constant>({});
+ auto qkv_proj_cvt = makePattern<opset1::Convert>({qkv_proj_weight_const}, {{"destination_type", "f32"}});
+
+ auto qkv_proj_weight_const_i8 =
+ makeConst(ov::element::i8, ov::PartialShape({ov::Dimension(), ov::Dimension()}), nullptr);
+ auto qkv_proj_weight_f32 = makePattern<opset1::Convert>({qkv_proj_weight_const_i8}, {{"destination_type", "f32"}});
+ auto qkv_proj_weight_scales_per_OC = makeConst(ov::element::f32, ov::PartialShape({ov::Dimension(), 1}), nullptr);
+ auto qkv_proj_weight_deq = makePattern<opset1::Multiply>({qkv_proj_weight_f32, qkv_proj_weight_scales_per_OC},
+ {{"auto_broadcast", "numpy"}});
+
+ auto qkv_proj = makePattern<opset1::MatMul>({input, qkv_proj_cvt | qkv_proj_weight_deq},
+ {{"transpose_a", false}, {"transpose_b", true}});
+ auto qkv_split_lengths = makePattern<opset1::Constant>({}, {}, "i32[3]");
+ auto qkv_split = makePattern<opset1::VariadicSplit>({qkv_proj, 2, qkv_split_lengths});
+
+ auto result = qkv_split->output(0);
+
+ matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {
+ PatternValidator validator(m);
+ if (!validator) {
+ return false;
+ }
+
+ const auto& pattern_map = m.get_pattern_value_map();
+ auto root = m.get_match_root();
+
+ auto node_split_lengths =
+ ov::as_type_ptr<opset1::Constant>(pattern_map.at(qkv_split_lengths).get_node_shared_ptr());
+ if (!node_split_lengths)
+ return false;
+ auto split_lengths = node_split_lengths->get_vector<int32_t>();
+ if (split_lengths.size() != 3)
+ return false;
+
+ auto proj_size = split_lengths[0];
+ if (split_lengths[1] != proj_size)
+ return false;
+ if (split_lengths[2] != proj_size)
+ return false;
+
+ bool is_quantized_int8 = pattern_map.count(qkv_proj_weight_const_i8);
+
+ std::shared_ptr<opset1::Constant> qkv_proj_weight_node;
+ if (is_quantized_int8) {
+ qkv_proj_weight_node =
+ ov::as_type_ptr<opset1::Constant>(pattern_map.at(qkv_proj_weight_const_i8).get_node_shared_ptr());
+ } else {
+ qkv_proj_weight_node =
+ ov::as_type_ptr<opset1::Constant>(pattern_map.at(qkv_proj_weight_const).get_node_shared_ptr());
+ }
+ if (!qkv_proj_weight_node)
+ return false;
+
+ auto w_shape = qkv_proj_weight_node->get_shape();
+ if (w_shape[0] != static_cast<uint64_t>(proj_size * 3))
+ return false;
+
+ QKVProjectionNode::Config config;
+ config.quantized = is_quantized_int8;
+ config.hidden_size = w_shape[1];
+ config.weights_combined = true;
+ config.proj_size0 = split_lengths[0];
+ config.proj_size1 = split_lengths[1];
+ config.proj_size2 = split_lengths[2];
+
+ OutputVector args = {pattern_map.at(input), qkv_proj_weight_node, qkv_proj_weight_node, qkv_proj_weight_node};
+ if (is_quantized_int8) {
+ auto scales = pattern_map.at(qkv_proj_weight_scales_per_OC).get_node_shared_ptr();
+ args.push_back(scales);
+ args.push_back(scales);
+ args.push_back(scales);
+ }
+ auto old_node = root;
+ auto new_node = std::make_shared<QKVProjectionNode>(args, config);
+ new_node->set_friendly_name(old_node->get_friendly_name());
+ ov::copy_runtime_info({old_node}, new_node);
+
+ // callback is for plugin implementation to check if it can be supported
+ if (!transformation_callback(new_node)) {
+ return false;
+ }
+
+ auto vsplit = pattern_map.at(qkv_split).get_node_shared_ptr();
+
+ for (size_t i = 0; i < vsplit->get_output_size(); i++) {
+ vsplit->output(i).replace(new_node->output(i));
+ }
+
+ new_node->add_node_control_dependents(vsplit);
+ new_node->add_node_control_dependencies(vsplit);
+ vsplit->clear_control_dependents();
+
+ return true;
+ };
+
+ auto m = std::make_shared<ov::pass::pattern::Matcher>(result, matcher_name);
+ this->register_matcher(m, callback);
+}
\ No newline at end of file
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/qkv_proj_fusion.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/qkv_proj_fusion.hpp
index 7127fdabf21..4c398cb478a 100644
--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/qkv_proj_fusion.hpp
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/qkv_proj_fusion.hpp
@@ -15,5 +15,11 @@ public:
QKVProjFusion();
};
+class QKVProjFusion2: public ov::pass::MatcherPass {
+public:
+ OPENVINO_RTTI("QKVProjFusion2", "0");
+ QKVProjFusion2();
+};
+
} // namespace intel_cpu
} // namespace ov
\ No newline at end of file
diff --git a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
index c12782831ef..fcf38440b8a 100644
--- a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
+++ b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
@@ -842,28 +842,42 @@ void Transformations::PostLpt() {
CPU_REGISTER_PASS_ARM64(postLPTPassManager, ov::pass::RoPEFusion, true);
CPU_REGISTER_PASS_X64(postLPTPassManager, CausalMaskPreprocessFusion);
+#if defined(OPENVINO_ARCH_X86_64)
// 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) && (config.inferencePrecision == element::bf16);
- if (can_use_amx_bf16) {
+ auto can_use_amx_bf16_int8 = dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx) && (config.inferencePrecision == element::bf16);
+ auto can_use_amx_fp16 = dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx_fp16) && (config.inferencePrecision == element::f16);
+
+ if (can_use_amx_bf16_int8 || can_use_amx_fp16) {
+ const auto fcDynamicQuantizationGroupSize = config.fcDynamicQuantizationGroupSize;
CPU_REGISTER_PASS_X64(postLPTPassManager, MLPFusion);
CPU_SET_CALLBACK_X64(postLPTPassManager,
- [](const_node_ptr &node) -> bool {
+ [fcDynamicQuantizationGroupSize](const_node_ptr &node) -> bool {
std::string errorMsg;
- return node::LLMMLP::isSupportedOperation(node, errorMsg);
+ return node::LLMMLP::isSupportedOperation(node, errorMsg, fcDynamicQuantizationGroupSize);
},
MLPFusion);
size_t concurrency = config.streamExecutorConfig.get_threads_per_stream();
if (concurrency == 0)
concurrency = parallel_get_max_threads();
+
CPU_REGISTER_PASS_X64(postLPTPassManager, QKVProjFusion);
CPU_SET_CALLBACK_X64(postLPTPassManager,
- [concurrency](const_node_ptr &node) -> bool {
+ [=](const_node_ptr &node) -> bool {
std::string errorMsg;
- return node::QKVProjection::isSupportedOperation(node, errorMsg, concurrency);
+ return node::QKVProjection::isSupportedOperation(node, errorMsg, concurrency, fcDynamicQuantizationGroupSize);
},
QKVProjFusion);
+
+ CPU_REGISTER_PASS_X64(postLPTPassManager, QKVProjFusion2);
+ CPU_SET_CALLBACK_X64(postLPTPassManager,
+ [=](const_node_ptr &node) -> bool {
+ std::string errorMsg;
+ return node::QKVProjection::isSupportedOperation(node, errorMsg, concurrency, fcDynamicQuantizationGroupSize);
+ },
+ QKVProjFusion2);
}
+#endif // OPENVINO_ARCH_X86_64
CPU_REGISTER_PASS_COMMON(postLPTPassManager, ov::pass::transpose_sinking::TSShapeOfForward);
CPU_REGISTER_PASS_COMMON(postLPTPassManager, StatefulSDPAFusion);
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
index 7a3745d9e1e..9f74cacb454 100644
--- 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
@@ -17,6 +17,7 @@ struct LLMMLPFusionParams {
size_t down_size;
size_t up_size;
std::string act_type;
+ bool use_dynamic_quant;
};
class LLMMLPFusionTest : public testing::WithParamInterface<LLMMLPFusionParams>, public ov::test::SubgraphBaseTest {
@@ -32,6 +33,7 @@ public:
result << "down_size=" << obj.param.down_size << "_";
result << "up_size=" << obj.param.up_size << "_";
result << "act_type=" << obj.param.act_type << "_";
+ result << "use_dynamic_quant=" << obj.param.use_dynamic_quant << "_";
result << obj.index;
return result.str();
}
@@ -48,19 +50,42 @@ protected:
auto src = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, inputDynamicShapes[0]);
- auto create_const = [](ov::Shape shape, int resolution) {
+ auto create_const = [&](size_t OC, size_t IC, int resolution) -> std::shared_ptr<ov::Node> {
+ if (param.use_dynamic_quant) {
+ ov::test::utils::InputGenerateData in_data;
+ // range [-128, +127]
+ in_data.start_from = -64;
+ in_data.range = 63;
+ in_data.resolution = 128;
+ auto tensor = ov::test::utils::create_and_fill_tensor(ov::element::i8, ov::Shape{OC, IC}, in_data);
+ auto weight_const_i8 = std::make_shared<ov::op::v0::Constant>(tensor);
+ auto weight_const_f32 = std::make_shared<ov::op::v0::Convert>(weight_const_i8, ov::element::f32);
+
+ // range after dequantize, [-1, +1]
+ in_data.start_from = 0;
+ in_data.range = 1;
+ in_data.resolution = 128;
+ auto tensor_scale_per_oc = ov::test::utils::create_and_fill_tensor(ov::element::f32, ov::Shape{OC, 1}, in_data);
+ auto scale_per_oc = std::make_shared<ov::op::v0::Constant>(tensor_scale_per_oc);
+
+ auto weight_deq = std::make_shared<ov::op::v1::Multiply>(weight_const_f32, scale_per_oc);
+ return weight_deq;
+ }
+
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);
+ auto tensor = ov::test::utils::create_and_fill_tensor(ov::element::f32, ov::Shape{OC, IC}, in_data);
return std::make_shared<ov::op::v0::Constant>(tensor);
};
+ if (param.use_dynamic_quant)
+ configuration.insert({ov::hint::dynamic_quantization_group_size.name(), std::numeric_limits<uint64_t>::max()});
- 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);
+ auto gate_weight = create_const(param.up_size, param.down_size, 100);
+ auto up_weight = create_const(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 down_weight = create_const(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);
@@ -99,15 +124,13 @@ TEST_P(LLMMLPFusionTest, CompareWithRefs) {
namespace {
+static ov::test::InputShape ishape{ov::PartialShape{-1, -1, 4096 / 4}, {ov::Shape{1, 8, 4096 / 4}, ov::Shape{5, 37, 4096 / 4}}};
+
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"},
+ {ishape, 4096 / 4, 11008 / 4, "Gelu", false},
+ {ishape, 4096 / 4, 11008 / 4, "Gelu", true},
+ {ishape, 4096 / 4, 11008 / 4, "Swish", false},
+ {ishape, 4096 / 4, 11008 / 4, "Swish", true},
};
INSTANTIATE_TEST_SUITE_P(smoke_LLMMLPFusion,
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
index 4bb6eaa188b..854969abfaa 100644
--- 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
@@ -18,6 +18,7 @@ struct QKVProjFusionParams {
size_t q_proj_size;
size_t k_proj_size;
size_t v_proj_size;
+ bool use_dynamic_quant;
};
class QKVProjFusionTest : public testing::WithParamInterface<QKVProjFusionParams>,
@@ -35,6 +36,7 @@ public:
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 << "use_dynamic_quant=" << obj.param.use_dynamic_quant << "_";
result << obj.index;
return result.str();
}
@@ -51,18 +53,40 @@ protected:
auto src = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, inputDynamicShapes[0]);
- auto create_const = [](ov::Shape shape, int resolution) {
+ auto create_const = [&](size_t OC, size_t IC) -> std::shared_ptr<ov::Node> {
+ if (param.use_dynamic_quant) {
+ ov::test::utils::InputGenerateData in_data;
+ // range [-128, +127]
+ in_data.start_from = -128;
+ in_data.range = 256;
+ in_data.resolution = 256;
+ auto tensor = ov::test::utils::create_and_fill_tensor(ov::element::i8, ov::Shape{OC, IC}, in_data);
+ auto weight_const_i8 = std::make_shared<ov::op::v0::Constant>(tensor);
+ auto weight_const_f32 = std::make_shared<ov::op::v0::Convert>(weight_const_i8, ov::element::f32);
+
+ // range after dequantize, [-1, +1]
+ in_data.start_from = 0;
+ in_data.range = 1;
+ in_data.resolution = 128;
+ auto tensor_scale_per_oc = ov::test::utils::create_and_fill_tensor(ov::element::f32, ov::Shape{OC, 1}, in_data);
+ auto scale_per_oc = std::make_shared<ov::op::v0::Constant>(tensor_scale_per_oc);
+
+ auto weight_deq = std::make_shared<ov::op::v1::Multiply>(weight_const_f32, scale_per_oc);
+ return weight_deq;
+ }
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);
+ in_data.resolution = 128;
+ auto tensor = ov::test::utils::create_and_fill_tensor(ov::element::f32, ov::Shape{OC, IC}, in_data);
return std::make_shared<ov::op::v0::Constant>(tensor);
};
+ if (param.use_dynamic_quant)
+ configuration.insert({ov::hint::dynamic_quantization_group_size.name(), std::numeric_limits<uint64_t>::max()});
- 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_weight = create_const(param.q_proj_size, param.hidden);
+ auto k_proj_weight = create_const(param.k_proj_size, param.hidden);
+ auto v_proj_weight = create_const(param.v_proj_size, param.hidden);
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);
@@ -93,19 +117,16 @@ TEST_P(QKVProjFusionTest, CompareWithRefs) {
namespace {
// the shape size is divided by a const to reduce test time
+static ov::test::InputShape ishape_llama2_7b{ov::PartialShape{-1, -1, 4096 / 4}, {ov::Shape{1, 8, 4096 / 4}, ov::Shape{5, 7, 4096 / 4}}};
+static ov::test::InputShape ishape_qwen2_7b{ov::test::InputShape{ov::PartialShape{-1, -1, 3584 / 2}, {ov::Shape{1, 8, 3584 / 2}, ov::Shape{5, 7, 3584 / 2}}}};
+
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},
+ // Llama-7B with reduced size
+ {ishape_llama2_7b, 4096 / 4, 4096 / 4, 4096 / 4, 4096 / 4, false},
+ {ishape_llama2_7b, 4096 / 4, 4096 / 4, 4096 / 4, 4096 / 4, true},
// 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},
+ {ishape_qwen2_7b, 3584 / 2, 128 * 28 / 2, 128 * 4 / 2, 128 * 4 / 2, false},
+ {ishape_qwen2_7b, 3584 / 2, 128 * 28 / 2, 128 * 4 / 2, 128 * 4 / 2, true},
};
INSTANTIATE_TEST_SUITE_P(smoke_QKVProjFusion,