OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[CPU] GatherMatmul: size each gather index GEMM to its routed rows in AMX bf16 mode (#38830)
R. Demetri Vallejos1ac0ccb7583e
diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.cpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.cppindex e29fdccc754..1da741b6c8a 100644--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.cpp+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.cpp@@ -337,6 +337,13 @@ GatherMatmulDnnlExecutor::GatherMatmulDnnlExecutor([[maybe_unused]] const Gatherreturn std::make_shared<InnerProduct>(eng, threadPool, k);});+ if (m_bf16AmxMode) {+ // The M > 1 GEMMs solve the GEMV problem on the weights layout the GEMV selected (the weights are+ // repacked to it below); createGemm() sets the row count.+ key.weights_md = m_gemvImpl->get_weights_md();+ m_gemmKey = std::make_shared<const InnerProductKey>(std::move(key));+ }+// Repack weights: convert from [G, K, N] to [G, (packed_N, K)] format expected by oneDNNauto gemvWeightsDesc =MemoryDescUtils::convertToBlockedMemoryDesc(DnnlExtensionUtils::makeDescriptor(m_gemvImpl->get_weights_md()));@@ -411,6 +418,7 @@ bool GatherMatmulDnnlExecutor::update(const MemoryArgs& memory) {// srcShape is [B, M, K]if (Dim{1} == srcShape[1]) {// If M is 1, we can skip the temporary buffer and execute GEMV in-place on the src buffer+ m_implType = m_gemvImpl->get_impl_type();return true;}const Dim M = normalizeM(srcShape[1]);@@ -428,44 +436,26 @@ bool GatherMatmulDnnlExecutor::update(const MemoryArgs& memory) {auto scratchPadDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(ov::element::u8, Shape({totalSize}));m_tmpInpBuffer = m_context->getScratchPad()->createScratchPadMem(scratchPadDesc);- OPENVINO_ASSERT(m_gemvImpl, "GEMV implementation is not created");-- dnnl::memory::desc src_md({static_cast<dnnl::memory::dim>(M), static_cast<dnnl::memory::dim>(srcShape[2])},- DnnlExtensionUtils::ElementTypeToDataType(srcPrc),- dnnl::memory::format_tag::ab);- auto weights_md = m_gemvImpl->get_weights_md();-- VectorDims scale_shape{};- VectorDims zp_shape{};- if (m_scalesMemory) {- const auto& fullScaleDims = m_scalesMemory->getStaticDims();- if (1 == fullScaleDims.size()) {- scale_shape.push_back(fullScaleDims[0]);- } else {- scale_shape.assign(fullScaleDims.begin() + 1, fullScaleDims.end());- }- }- if (m_zpMemory) {- const auto& fullZpDims = m_zpMemory->getStaticDims();- if (1 == fullZpDims.size()) {- zp_shape.push_back(fullZpDims[0]);- } else {- zp_shape.assign(fullZpDims.begin() + 1, fullZpDims.end());- }- }+ // The GEMMs are created in execute(), each sized to the rows its gather index receives, so the oneDNN+ // primitive that will run is not known here. DNNL_VERBOSE reports the implementation.+ m_implType = impl_desc_type::unknown;+ return true;+}- InnerProductKey key{src_md,- weights_md,- makeBiasMd(static_cast<dnnl::memory::dim>(weights_md.get_dims()[0]), memory.at(ARG_BIAS)),- scale_shape,- zp_shape};+GatherMatmulDnnlExecutor::InnerProductPtr GatherMatmulDnnlExecutor::createGemm(size_t rows) const {+ OPENVINO_ASSERT(m_gemmKey, "GEMM key is not initialized");+ InnerProductKey key = *m_gemmKey;+ key.src_md = dnnl::memory::desc({static_cast<dnnl::memory::dim>(rows), key.src_md.get_dims()[1]},+ key.src_md.get_data_type(),+ dnnl::memory::format_tag::ab);const auto& eng = m_context->getEngine();const auto threadPool = m_context->getThreadPool();- auto cache = m_context->getRuntimeCache();- std::tie(m_gemmImpl, std::ignore) = cache->getOrCreate(key, [&eng, &threadPool](const InnerProductKey& k) {- return std::make_shared<InnerProduct>(eng, threadPool, k);- });- return true;+ InnerProductPtr gemm;+ std::tie(gemm, std::ignore) =+ m_context->getRuntimeCache()->getOrCreate(key, [&eng, &threadPool](const InnerProductKey& k) {+ return std::make_shared<InnerProduct>(eng, threadPool, k);+ });+ return gemm;}void GatherMatmulDnnlExecutor::execute(const MemoryArgs& memory) {@@ -526,14 +516,26 @@ void GatherMatmulDnnlExecutor::execute(const MemoryArgs& memory) {auto tmp_input_offset = OffsetHelper::createOffsetHelper(tmpInput);auto tmp_dst_offset = OffsetHelper::createOffsetHelper(tmpOutput);- OPENVINO_ASSERT(m_gemmImpl, "GEMM implementation is not created");+ // Gather indices with the same rounded row count share one GEMM within this call. The runtime cache+ // keeps the primitives across calls.+ std::unordered_map<size_t, InnerProductPtr> gemmBySize;for (size_t gather_axis_index = 0; gather_axis_index < gather_axis_size; gather_axis_index++) {const size_t num_valid_rows = elements_per_gather_indx[gather_axis_index];if (0 == num_valid_rows) {continue;}- cpu_parallel->parallel_for(M_size, [&](size_t m) {+ // Size the GEMM to the rows routed to this gather index (rounded up by normalizeM), not to+ // the full input length: with top-k routing most rows of a full-length GEMM are zero padding.+ OPENVINO_ASSERT(num_valid_rows <= M_size,+ "GatherMatmul: a gather index received more rows than the input has");+ const size_t gemm_rows = normalizeM(num_valid_rows);+ auto& gemmImpl = gemmBySize[gemm_rows];+ if (!gemmImpl) {+ gemmImpl = createGemm(gemm_rows);+ }++ cpu_parallel->parallel_for(gemm_rows, [&](size_t m) {auto* dst_row = tmp_input_offset(m);if (m < num_valid_rows) {const auto row_id = gather_idx_map[gather_axis_index * M + m].first;@@ -551,7 +553,7 @@ void GatherMatmulDnnlExecutor::execute(const MemoryArgs& memory) {auto* bias = bias_offset(gather_axis_index);auto* scale = scale_offset(gather_axis_index);auto* zp = zp_offset(gather_axis_index);- m_gemmImpl->exec(src, dst, wei, bias, scale, zp);+ gemmImpl->exec(src, dst, wei, bias, scale, zp);cpu_parallel->parallel_for(num_valid_rows, [&](size_t m) {const auto* src_row = tmp_dst_offset(m);diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.hpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.hppindex e09f0bd6a0c..4e0b7122807 100644--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.hpp@@ -4,6 +4,7 @@#pragma once+#include <cstddef>#include <memory>#include <oneapi/dnnl/dnnl.hpp>@@ -16,6 +17,8 @@namespace ov::intel_cpu {+struct InnerProductKey;+class GatherMatmulDnnlExecutor : public Executor {public:static bool supports(const GatherMatmulConfig& config);@@ -32,6 +35,9 @@ private:class InnerProduct;using InnerProductPtr = std::shared_ptr<InnerProduct>;+ // The GEMM for an input of the given number of rows, from m_gemmKey through the runtime cache.+ [[nodiscard]] InnerProductPtr createGemm(size_t rows) const;+ExecutorContext::CPtr m_context;MemoryPtr m_weightsMemory;@@ -39,7 +45,9 @@ private:MemoryPtr m_zpMemory;InnerProductPtr m_gemvImpl;- InnerProductPtr m_gemmImpl;+ // Key of the GEMMs run for M > 1 in AMX bf16 mode, each sized to the rows routed to its gather index+ // instead of the full input length. createGemm() sets the row count.+ std::shared_ptr<const InnerProductKey> m_gemmKey;MemoryPtr m_tmpInpBuffer;MemoryDescPtr m_tmpInputDesc;diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/moe.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/moe.cppindex 77a8ae3e09a..8293fa44037 100644--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/moe.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/moe.cpp@@ -236,7 +236,11 @@ void MoECompressedWeightsSubgraphTest::SetUp() {}}-void MoECompressedWeightsSubgraphTest::generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) {+namespace {+// One input in [0.125, 2.125) with a resolution of 1/8, the same values for every run.+void generate_small_range_inputs(std::map<std::shared_ptr<ov::Node>, ov::Tensor>& inputs,+ const std::shared_ptr<ov::Model>& function,+ const std::vector<ov::Shape>& targetInputStaticShapes) {inputs.clear();const auto& itTargetShape = targetInputStaticShapes.front();const auto& params = function->get_parameters();@@ -251,6 +255,15 @@ void MoECompressedWeightsSubgraphTest::generate_inputs(const std::vector<ov::Shainputs.insert({param, input_tensor});}+} // namespace++void MoESubgraphSmallInputsTest::generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) {+ generate_small_range_inputs(inputs, function, targetInputStaticShapes);+}++void MoECompressedWeightsSubgraphTest::generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) {+ generate_small_range_inputs(inputs, function, targetInputStaticShapes);+}void MoECompressedWeightsSubgraphTest::check_results() {const auto& test_param = GetParam();@@ -278,6 +291,19 @@ TEST_P(MoESubgraphTest, CompareWithRefs) {check_results();}+TEST_P(MoESubgraphSmallInputsTest, CompareWithRefs) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED()+#if defined(OPENVINO_ARCH_ARM)+ GTEST_SKIP();+#elif defined(OPENVINO_ARCH_ARM64)+ if (!ov::with_cpu_arm_dotprod() && !ov::with_cpu_arm_i8mm()) {+ GTEST_SKIP();+ }+#endif+ run();+ check_results();+}+TEST_P(MoECompressedWeightsSubgraphTest, CompareWithRefs) {SKIP_IF_CURRENT_TEST_IS_DISABLED()#if defined(OPENVINO_ARCH_ARM)diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/moe.hpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/moe.hppindex 8d02bb0d193..f6b13592430 100644--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/moe.hpp+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/classes/moe.hpp@@ -53,6 +53,14 @@ protected:void check_results();};++// MoESubgraphTest with inputs in a small range, as MoECompressedWeightsSubgraphTest uses. With the default+// [1, 10) inputs and integer weights the activations grow to about 1e8, and over a sequence of a thousand rows+// a bf16 inference no longer meets the 10% tolerance against the f32 reference at every element.+class MoESubgraphSmallInputsTest : public MoESubgraphTest {+protected:+ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override;+};class MoECompressedWeightsSubgraphTest : public testing::WithParamInterface<MoeCompressedWeightsTestParams>,virtual public SubgraphBaseTest,public CpuTestWithFusing {diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/gathermatmul.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/gathermatmul.cppindex 6267ee56220..dd10c7c7a17 100644--- a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/gathermatmul.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/gathermatmul.cpp@@ -26,6 +26,67 @@ const std::vector<MoeTestShapeParams> moe_params_smoke = {},};+// More experts than top-k and longer, varying sequences: each expert receives a different number of rows+// (some none), and the row count changes between inferences. With bf16 on AMX hardware every expert then+// runs a GEMM of its own height, so these cases cover several GEMM sizes inside one node, an expert whose+// rows differ between experts, and a single-row input (GEMV) following a multi-row one.+const std::vector<MoeTestShapeParams> moe_params_uneven_routing = {+ {+ {{-1, -1, 256}, {{1, 96, 256}, {1, 1, 256}, {1, 40, 256}, {2, 64, 256}}}, // data_shape+ 4, // topk+ 32, // number_of_experts+ 512 // intermediate_size+ },+ {+ {{-1, -1, 128}, {{1, 48, 128}, {1, 1, 128}}}, // ends on a single-row input (GEMV)+ 2, // topk+ 16, // number_of_experts+ 256 // intermediate_size+ },+};++// Longer sequences: an expert whose rows pass the 512-row rounding step, a sequence that returns to an earlier+// length so the per-height GEMM table is rebuilt, and a case shaped like a 128-expert top-8 model where one+// input produces many distinct GEMM heights. Run with small-range inputs (see MoESubgraphSmallInputsTest).+const std::vector<MoeTestShapeParams> moe_params_long_sequences = {+ {+ {{-1, -1, 128}, {{1, 1100, 128}, {1, 17, 128}}}, // 4 experts, top-2: about 550 rows each+ 2, // topk+ 4, // number_of_experts+ 256 // intermediate_size+ },+ {+ {{-1, -1, 128}, {{1, 200, 128}, {1, 64, 128}, {1, 200, 128}}}, // returns to an earlier length+ 2, // topk+ 8, // number_of_experts+ 256 // intermediate_size+ },+ {+ {{-1, -1, 64}, {{1, 1024, 64}}}, // 128 experts, top-8, 1024 rows: about 64 rows per expert+ 8, // topk+ 128, // number_of_experts+ 64 // intermediate_size+ },+};++// Top-k equal to the number of experts: every expert receives every row, so the GEMM height for each expert+// is exactly the rounded total row count, with no dependence on the router. The row counts sit on both sides+// of the rounding steps at 512 and 1024 rows.+const std::vector<MoeTestShapeParams> moe_params_all_experts = {+ {+ {{-1, -1, 64}, {{1, 511, 64}, {1, 512, 64}, {1, 513, 64}}}, // data_shape+ 4, // topk+ 4, // number_of_experts+ 64 // intermediate_size+ },+ {+ {{-1, -1, 64}, {{1, 1023, 64}, {1, 1024, 64}, {1, 1025, 64}}}, // data_shape+ 4, // topk+ 4, // number_of_experts+ 64 // intermediate_size+ },+};+std::vector<ov::AnyMap> generate_additional_config() {std::vector<ov::AnyMap> additional_config = {{{ov::hint::inference_precision.name(), ov::element::f32}}};if (ov::with_cpu_x86_bfloat16()) {@@ -52,6 +113,46 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoESubgraph_3gemm_gelu,::testing::ValuesIn(generate_additional_config())),MoESubgraphTest::getTestCaseName);+INSTANTIATE_TEST_SUITE_P(smoke_MoESubgraph_uneven_routing,+ MoESubgraphTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_uneven_routing),+ ::testing::ValuesIn(moe_types),+ ::testing::Values(MoEActivationType::SWISH),+ ::testing::ValuesIn(generate_additional_config())),+ MoESubgraphTest::getTestCaseName);++INSTANTIATE_TEST_SUITE_P(smoke_MoESubgraph_uneven_routing_gelu,+ MoESubgraphTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_uneven_routing),+ ::testing::Values(MoEType::MoE3GeMM),+ ::testing::Values(MoEActivationType::GELU),+ ::testing::ValuesIn(generate_additional_config())),+ MoESubgraphTest::getTestCaseName);++INSTANTIATE_TEST_SUITE_P(smoke_MoESubgraph_long_sequences,+ MoESubgraphSmallInputsTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_long_sequences),+ ::testing::ValuesIn(moe_types),+ ::testing::Values(MoEActivationType::SWISH),+ ::testing::ValuesIn(generate_additional_config())),+ MoESubgraphSmallInputsTest::getTestCaseName);++INSTANTIATE_TEST_SUITE_P(smoke_MoESubgraph_long_sequences_gelu,+ MoESubgraphSmallInputsTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_long_sequences),+ ::testing::Values(MoEType::MoE3GeMM),+ ::testing::Values(MoEActivationType::GELU),+ ::testing::ValuesIn(generate_additional_config())),+ MoESubgraphSmallInputsTest::getTestCaseName);++INSTANTIATE_TEST_SUITE_P(smoke_MoESubgraph_all_experts_rounding_steps,+ MoESubgraphSmallInputsTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_all_experts),+ ::testing::ValuesIn(moe_types),+ ::testing::Values(MoEActivationType::SWISH),+ ::testing::ValuesIn(generate_additional_config())),+ MoESubgraphSmallInputsTest::getTestCaseName);+const std::vector<ov::test::ElementType> decompression_precisions = {ov::element::f32};const std::vector<ov::test::ElementType> weights_precisions = {ov::element::u8,ov::element::i8,@@ -90,5 +191,37 @@ INSTANTIATE_TEST_SUITE_P(smoke_MoeCompressedWeights_3gemm_gelu,::testing::Values(true)), // use_matmul_decompression_implMoECompressedWeightsSubgraphTest::getTestCaseName);+INSTANTIATE_TEST_SUITE_P(smoke_MoeCompressedWeights_long_sequences,+ MoECompressedWeightsSubgraphTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_long_sequences),+ ::testing::ValuesIn(moe_types),+ ::testing::Values(MoEActivationType::SWISH),+ ::testing::ValuesIn(weights_precisions),+ ::testing::ValuesIn(decompression_precisions),+ ::testing::Values(ov::element::f32),+ ::testing::Values(ov::test::utils::DecompressionType::full),+ ::testing::Values(ov::test::utils::DecompressionType::full),+ ::testing::Values(false), // reshape on decompression+ ::testing::Values(16), // decompression group size+ ::testing::ValuesIn(generate_additional_config()),+ ::testing::Values(true)), // use_matmul_decompression_impl+ MoECompressedWeightsSubgraphTest::getTestCaseName);++INSTANTIATE_TEST_SUITE_P(smoke_MoeCompressedWeights_uneven_routing,+ MoECompressedWeightsSubgraphTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_uneven_routing),+ ::testing::ValuesIn(moe_types),+ ::testing::Values(MoEActivationType::SWISH),+ ::testing::ValuesIn(weights_precisions),+ ::testing::ValuesIn(decompression_precisions),+ ::testing::Values(ov::element::f32),+ ::testing::Values(ov::test::utils::DecompressionType::full),+ ::testing::Values(ov::test::utils::DecompressionType::full),+ ::testing::Values(false), // reshape on decompression+ ::testing::Values(16), // decompression group size+ ::testing::ValuesIn(generate_additional_config()),+ ::testing::Values(true)), // use_matmul_decompression_impl+ MoECompressedWeightsSubgraphTest::getTestCaseName);+} // namespace test-} // namespace ov\ No newline at end of file+} // namespace ov