Skip to content

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

[Snippets][CPU][ARM] Support dynamic GEMM weights repacking (#36712)

Arseniy Obolenskiy3dad25c46d2f
diff --git a/src/plugins/intel_cpu/CMakeLists.txt b/src/plugins/intel_cpu/CMakeLists.txt
index 9df556712cf..e0323f0ee92 100644
--- a/src/plugins/intel_cpu/CMakeLists.txt
+++ b/src/plugins/intel_cpu/CMakeLists.txt
@@ -191,6 +191,7 @@ endif()
if(NOT AARCH64)
list(APPEND EXCLUDE_PATHS ${CMAKE_CURRENT_SOURCE_DIR}/src/transformations/snippets/aarch64/*
${CMAKE_CURRENT_SOURCE_DIR}/src/emitters/snippets/aarch64/*
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/nodes/executors/aarch64/subgraph.*
${CMAKE_CURRENT_SOURCE_DIR}/src/nodes/executors/kleidiai/*)
endif()
diff --git a/src/plugins/intel_cpu/src/emitters/snippets/aarch64/kernel_executors/gemm_copy_b.cpp b/src/plugins/intel_cpu/src/emitters/snippets/aarch64/kernel_executors/gemm_copy_b.cpp
index 8f41e83fcdc..4809c27fb11 100644
--- a/src/plugins/intel_cpu/src/emitters/snippets/aarch64/kernel_executors/gemm_copy_b.cpp
+++ b/src/plugins/intel_cpu/src/emitters/snippets/aarch64/kernel_executors/gemm_copy_b.cpp
@@ -11,7 +11,9 @@
#include <memory>
#include <sstream>
#include <string>
+#include <type_traits>
#include <utility>
+#include <variant>
#include <vector>
#include "emitters/utils.hpp"
@@ -25,6 +27,7 @@
#include "kai/ukernels/matmul/pack/kai_rhs_pack_nxk_qsi8cxp_qsi8cx_neon.h"
#include "kai/ukernels/matmul/pack/kai_rhs_pack_nxk_x16p32x1bx16_x16_x16_neon.h"
#include "kai/ukernels/matmul/pack/kai_rhs_pack_nxk_x32p16x1bx32_x32_x32_neon.h"
+#include "openvino/core/except.hpp"
#include "openvino/core/type/element_type.hpp"
#include "openvino/runtime/system_conf.hpp"
#include "snippets/kernel_executor_table.hpp"
@@ -348,4 +351,43 @@ void GemmCopyBI8KaiKernelExecutor::execute(const GemmCopyBI8KaiKernelExecutor* e
execute_copy_b_i8_common(config, *kernel->copy_b_ukernel, kernel->scales, in0, out0);
}
+GemmCopyBKernel::GemmCopyBKernel(const ov::element::Type& prc) {
+ if (prc == ov::element::f16) {
+ m_executor = std::make_shared<GemmCopyBF16KaiKernelExecutor>(GemmCopyBKernelKaiConfig());
+ } else if (prc == ov::element::f32) {
+ m_executor = std::make_shared<GemmCopyBF32KaiKernelExecutor>(GemmCopyBKernelKaiConfig());
+ } else if (prc == ov::element::i8) {
+ m_executor = std::make_shared<GemmCopyBI8KaiKernelExecutor>(GemmCopyBKernelKaiConfig());
+ } else {
+ OPENVINO_THROW("Unexpected precision for GemmCopyB executor: ", prc.get_type_name());
+ }
+}
+
+void GemmCopyBKernel::update_by_config(const GemmCopyBKernelKaiConfig& config) const {
+ std::visit(
+ [&config](const auto& executor) {
+ executor->update_by_config(config);
+ },
+ m_executor);
+}
+
+const GemmCopyBKernelKaiConfig& GemmCopyBKernel::get_config() const {
+ return std::visit(
+ [](const auto& executor) -> const GemmCopyBKernelKaiConfig& {
+ return static_cast<const GemmCopyBKernelKaiConfig&>(executor->get_config());
+ },
+ m_executor);
+}
+
+void GemmCopyBKernel::operator()(const void* args) const {
+ const auto* call_args = reinterpret_cast<const GemmCopyBKernel::call_args*>(args);
+ OV_CPU_JIT_EMITTER_ASSERT(call_args, "Call arguments are nullptr!");
+ std::visit(
+ [call_args](const auto& executor) {
+ using ExecutorType = typename std::decay_t<decltype(executor)>::element_type;
+ ExecutorType::execute(executor.get(), const_cast<void*>(call_args->src), call_args->tr_src);
+ },
+ m_executor);
+}
+
} // namespace ov::intel_cpu::aarch64
diff --git a/src/plugins/intel_cpu/src/emitters/snippets/aarch64/kernel_executors/gemm_copy_b.hpp b/src/plugins/intel_cpu/src/emitters/snippets/aarch64/kernel_executors/gemm_copy_b.hpp
index 699fb14728a..f5f12d8aa53 100644
--- a/src/plugins/intel_cpu/src/emitters/snippets/aarch64/kernel_executors/gemm_copy_b.hpp
+++ b/src/plugins/intel_cpu/src/emitters/snippets/aarch64/kernel_executors/gemm_copy_b.hpp
@@ -5,11 +5,13 @@
#pragma once
#include <memory>
+#include <variant>
#include <vector>
#include "common/utils.hpp"
#include "cpu_memory.h"
#include "emitters/snippets/brgemm_generic.hpp"
+#include "emitters/snippets/input_repacker.hpp"
#include "emitters/utils.hpp"
#include "kai/ukernels/matmul/matmul_clamp_f16_f16_f16p/kai_matmul_clamp_f16_f16_f16p32x1b_6x32_neon_mla.h"
#include "kai/ukernels/matmul/matmul_clamp_f16_f16_f16p/kai_matmul_clamp_f16_f16_f16p_interface.h"
@@ -18,6 +20,7 @@
#include "kai/ukernels/matmul/matmul_clamp_f32_qai8dxp_qsi8cxp/kai_matmul_clamp_f32_qai8dxp_qsi8cxp_interface.h"
#include "kai/ukernels/matmul/pack/kai_rhs_pack_kxn_x16p32x1b_x16_x16_neon.h"
#include "kai/ukernels/matmul/pack/kai_rhs_pack_kxn_x32p16x1b_x32_x32_neon.h"
+#include "openvino/core/type/element_type.hpp"
namespace ov::intel_cpu::aarch64 {
@@ -183,4 +186,26 @@ private:
GemmCopyBKernelKaiConfig& config) const override;
};
+class GemmCopyBKernel : public InputRepackerKernel {
+public:
+ struct call_args {
+ const void* src = nullptr;
+ void* tr_src = nullptr;
+ };
+
+ explicit GemmCopyBKernel(const ov::element::Type& prc);
+
+ void update_by_config(const GemmCopyBKernelKaiConfig& config) const;
+ [[nodiscard]] const GemmCopyBKernelKaiConfig& get_config() const;
+
+ void operator()(const void* args) const override;
+
+private:
+ using Executor = std::variant<std::shared_ptr<GemmCopyBF32KaiKernelExecutor>,
+ std::shared_ptr<GemmCopyBF16KaiKernelExecutor>,
+ std::shared_ptr<GemmCopyBI8KaiKernelExecutor>>;
+
+ Executor m_executor;
+};
+
} // namespace ov::intel_cpu::aarch64
diff --git a/src/plugins/intel_cpu/src/nodes/executors/aarch64/subgraph.cpp b/src/plugins/intel_cpu/src/nodes/executors/aarch64/subgraph.cpp
index a59b7297af5..67af9f33eb4 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/aarch64/subgraph.cpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/aarch64/subgraph.cpp
@@ -4,25 +4,25 @@
#include "nodes/executors/aarch64/subgraph.hpp"
-#include <csignal>
-#include <cstddef>
-#include <cstdint>
-#include <iostream>
-#include <memory>
-#include <mutex>
-#include <string>
-#include <vector>
-
-#include "cache/multi_cache.h"
-#include "emitters/snippets/aarch64/cpu_generator.hpp"
-#include "emitters/snippets/cpu_runtime_configurator.hpp"
-#include "emitters/snippets/jit_snippets_call_args.hpp"
-#include "nodes/executors/subgraph.hpp"
-#include "openvino/core/except.hpp"
-#include "openvino/core/parallel.hpp"
-
#if defined(SNIPPETS_DEBUG_CAPS) && (defined(__linux__) || defined(__APPLE__))
+# include <csignal>
+# include <cstddef>
+# include <iostream>
+# include <memory>
+# include <mutex>
+# include <string>
+# include <vector>
+
+# include "cache/multi_cache.h"
+# include "emitters/snippets/aarch64/cpu_generator.hpp"
# include "emitters/snippets/aarch64/jit_segfault_detector_emitter.hpp"
+# include "emitters/snippets/aarch64/kernel_executors/gemm_copy_b.hpp"
+# include "emitters/snippets/cpu_runtime_configurator.hpp"
+# include "nodes/executors/repacking_subgraph.hpp"
+# include "nodes/executors/subgraph.hpp"
+# include "openvino/core/except.hpp"
+# include "openvino/core/parallel.hpp"
+
#endif
namespace ov::intel_cpu {
@@ -34,15 +34,13 @@ SubgraphExecutor::SubgraphExecutor(const std::shared_ptr<CPURuntimeConfig>& snip
const std::vector<ptrdiff_t>& start_offset_out,
const BufferScratchpadAllocator& allocator,
const ov::intel_cpu::MultiCacheWeakPtr& kernel_cache)
- : SubgraphBaseExecutor(snippet_config,
- snippet_attrs,
- snippet,
- start_offset_in,
- start_offset_out,
- allocator,
- kernel_cache) {
- m_buffer_scratchpad = allocator(m_internal_buffer_size);
-
+ : SubgraphRepackingExecutor<aarch64::GemmCopyBKernel>(snippet_config,
+ snippet_attrs,
+ snippet,
+ start_offset_in,
+ start_offset_out,
+ allocator,
+ kernel_cache) {
#if defined(SNIPPETS_DEBUG_CAPS) && (defined(__linux__) || defined(__APPLE__))
const auto target = std::dynamic_pointer_cast<const aarch64::CPUTargetMachine>(
snippet_attrs->snippet->get_generator()->get_target_machine());
@@ -59,7 +57,9 @@ void SubgraphExecutor::segfault_detector() const {
[]([[maybe_unused]] int signal) {
std::lock_guard<std::mutex> guard(err_print_lock);
if (auto* segfault_detector_emitter =
- ov::intel_cpu::g_custom_segfault_handler<ov::intel_cpu::aarch64::jit_uni_segfault_detector_emitter>->local()) {
+ ov::intel_cpu::g_custom_segfault_handler<
+ ov::intel_cpu::aarch64::jit_uni_segfault_detector_emitter>
+ ->local()) {
std::cout << segfault_detector_emitter->info() << '\n';
}
auto tid = parallel_get_thread_num();
@@ -74,65 +74,4 @@ void SubgraphExecutor::segfault_detector() const {
// NOLINTEND(misc-include-cleaner) bug in clang-tidy
#endif
-void SubgraphStaticExecutor::exec_impl(const std::vector<MemoryPtr>& inMemPtrs,
- const std::vector<MemoryPtr>& outMemPtrs) {
- const auto& callable = m_schedule->get_callable<kernel>();
-
- auto initializer = [&](jit_snippets_call_args& call_args, size_t ithr) {
- init_call_args(call_args, inMemPtrs, outMemPtrs, m_start_offset_in, m_start_offset_out);
- update_scratchpad_ptr(call_args.buffer_scratchpad_ptr, ithr);
- };
- auto caller =
- [&](jit_snippets_call_args& call_args, const std::vector<size_t>& indexes, [[maybe_unused]] size_t ithr) {
- callable(&call_args, indexes.data());
- };
-
-#if defined(SNIPPETS_DEBUG_CAPS) && (defined(__linux__) || defined(__APPLE__))
- segfault_detector();
-#endif
-
- if (m_parallel_exec_domain.size() == rank6D) {
- parallel_for6d(initializer, caller);
- } else {
- parallel_forNd(initializer, caller);
- }
-}
-
-void SubgraphDynamicSpecializedExecutor::exec_impl(const std::vector<MemoryPtr>& inMemPtrs,
- const std::vector<MemoryPtr>& outMemPtrs) {
- const auto& callable = m_schedule->get_callable<dynamic_kernel>();
-
- OPENVINO_ASSERT(m_data_offsets.size() == inMemPtrs.size() + outMemPtrs.size(), "Incorrect data offset count!");
- OPENVINO_ASSERT(m_data_offsets.front().size() == m_parallel_exec_domain.size(),
- "Data offsets with invalid ranks detected");
-
- // Note: we need to reset KernelExecutorTable to the state that was recorded in the
- // SubgraphDynamicSpecializedExecutor constructor because the table might've been used for other shapes
- m_reset_exec_table_state();
-
- std::vector<const uint8_t*> src_ptrs;
- std::vector<uint8_t*> dst_ptrs;
- init_original_ptrs(inMemPtrs, outMemPtrs, src_ptrs, dst_ptrs, m_start_offset_in, m_start_offset_out);
-
- auto initializer = [&](jit_snippets_call_args& call_args, size_t ithr) {
- init_call_args(call_args);
- update_scratchpad_ptr(call_args.buffer_scratchpad_ptr, ithr);
- };
- auto caller =
- [&](jit_snippets_call_args& call_args, const std::vector<size_t>& indexes, [[maybe_unused]] size_t ithr) {
- update_ptrs(call_args, src_ptrs, dst_ptrs, indexes);
- callable(&call_args);
- };
-
-#if defined(SNIPPETS_DEBUG_CAPS) && (defined(__linux__) || defined(__APPLE__))
- segfault_detector();
-#endif
-
- if (m_parallel_exec_domain.size() == rank6D) {
- parallel_for6d(initializer, caller);
- } else {
- parallel_forNd(initializer, caller);
- }
-}
-
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/executors/aarch64/subgraph.hpp b/src/plugins/intel_cpu/src/nodes/executors/aarch64/subgraph.hpp
index adc9be87e7e..954cb5bbe8b 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/aarch64/subgraph.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/aarch64/subgraph.hpp
@@ -6,17 +6,21 @@
#include <cstddef>
#include <memory>
+#include <oneapi/dnnl/dnnl_common.hpp>
+#include <set>
#include <vector>
#include "cache/multi_cache.h"
-#include "cpu_memory.h"
+#include "emitters/snippets/aarch64/kernel_executors/gemm_copy_b.hpp"
#include "emitters/snippets/cpu_runtime_configurator.hpp"
-#include "nodes/executors/subgraph.hpp"
+#include "nodes/executors/repacking_subgraph.hpp"
namespace ov::intel_cpu {
-class SubgraphExecutor : public SubgraphBaseExecutor {
+class SubgraphExecutor : public SubgraphRepackingExecutor<aarch64::GemmCopyBKernel> {
public:
+ using SubgraphRepackingExecutor<aarch64::GemmCopyBKernel>::SubgraphRepackingExecutor;
+
SubgraphExecutor(const std::shared_ptr<CPURuntimeConfig>& snippet_config,
const std::shared_ptr<SubgraphAttrs>& snippet_attrs,
const std::shared_ptr<SubgraphCodeGenerator>& snippet,
@@ -27,35 +31,21 @@ public:
#ifdef SNIPPETS_DEBUG_CAPS
protected:
+ void segfault_detector() const override;
+
+private:
bool enabled_segfault_detector = false;
- inline void segfault_detector() const;
#endif
};
-class SubgraphStaticExecutor : public SubgraphExecutor, public SubgraphStaticBaseExecutor {
+class SubgraphStaticExecutor : public SubgraphRepackingStaticExecutor<SubgraphExecutor> {
public:
- template <typename... Args>
- SubgraphStaticExecutor(const std::shared_ptr<ov::intel_cpu::CPURuntimeConfig>& config,
- const std::set<size_t>& external_ptrs_idces,
- size_t in_num,
- Args&&... rest)
- : SubgraphExecutor(config, std::forward<Args>(rest)...),
- SubgraphStaticBaseExecutor(external_ptrs_idces, in_num) {}
-
- void exec_impl(const std::vector<MemoryPtr>& inMemPtrs, const std::vector<MemoryPtr>& outMemPtrs) override;
+ using SubgraphRepackingStaticExecutor<SubgraphExecutor>::SubgraphRepackingStaticExecutor;
};
-class SubgraphDynamicSpecializedExecutor : public SubgraphExecutor, public SubgraphDynamicSpecializedBaseExecutor {
+class SubgraphDynamicSpecializedExecutor : public SubgraphRepackingDynamicSpecializedExecutor<SubgraphExecutor> {
public:
- template <typename... Args>
- SubgraphDynamicSpecializedExecutor(const std::shared_ptr<ov::intel_cpu::CPURuntimeConfig>& config,
- const std::set<size_t>& external_ptrs_idces,
- size_t in_num,
- Args&&... rest)
- : SubgraphExecutor(config, std::forward<Args>(rest)...),
- SubgraphDynamicSpecializedBaseExecutor(config, external_ptrs_idces, in_num) {}
-
- void exec_impl(const std::vector<MemoryPtr>& inMemPtrs, const std::vector<MemoryPtr>& outMemPtrs) override;
+ using SubgraphRepackingDynamicSpecializedExecutor<SubgraphExecutor>::SubgraphRepackingDynamicSpecializedExecutor;
};
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/executors/repacking_subgraph.hpp b/src/plugins/intel_cpu/src/nodes/executors/repacking_subgraph.hpp
new file mode 100644
index 00000000000..8583f7efe45
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/executors/repacking_subgraph.hpp
@@ -0,0 +1,410 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <limits>
+#include <memory>
+#include <numeric>
+#include <oneapi/dnnl/dnnl_common.hpp>
+#include <set>
+#include <utility>
+#include <vector>
+
+#include "cache/multi_cache.h"
+#include "cpu_memory.h"
+#include "cpu_types.h"
+#include "dnnl_extension_utils.h"
+#include "emitters/snippets/cpu_runtime_configurator.hpp"
+#include "emitters/snippets/input_repacker.hpp"
+#include "emitters/snippets/jit_snippets_call_args.hpp"
+#include "memory_desc/blocked_memory_desc.h"
+#include "memory_desc/cpu_memory_desc.h"
+#include "nodes/executors/subgraph.hpp"
+#include "openvino/core/except.hpp"
+#include "openvino/core/parallel.hpp"
+#include "utils/general_utils.h"
+
+namespace ov::intel_cpu {
+
+template <typename RepackingKernel>
+class SubgraphRepackingExecutor : public SubgraphBaseExecutor {
+public:
+ SubgraphRepackingExecutor(const std::shared_ptr<CPURuntimeConfig>& snippet_config,
+ const std::shared_ptr<SubgraphAttrs>& snippet_attrs,
+ const std::shared_ptr<SubgraphCodeGenerator>& snippet,
+ const std::vector<ptrdiff_t>& start_offset_in,
+ const std::vector<ptrdiff_t>& start_offset_out,
+ const BufferScratchpadAllocator& allocator,
+ const ov::intel_cpu::MultiCacheWeakPtr& kernel_cache)
+ : SubgraphBaseExecutor(snippet_config,
+ snippet_attrs,
+ snippet,
+ start_offset_in,
+ start_offset_out,
+ allocator,
+ kernel_cache),
+ m_input_repackers(snippet_config->input_repackers),
+ m_repacking_impl_type(snippet_config->repacking_impl_type) {
+ auto external_buffer_size =
+ std::accumulate(m_input_repackers.begin(),
+ m_input_repackers.end(),
+ static_cast<size_t>(0),
+ [](size_t sum, const std::pair<size_t, InputRepacker>& p) {
+ auto curr_mem_size = p.second.desc()->getCurrentMemSize();
+ OPENVINO_ASSERT(curr_mem_size != ov::intel_cpu::MemoryDesc::UNDEFINED_SIZE,
+ "Current repacking buffer memory size is undefined");
+ return sum + curr_mem_size;
+ });
+
+ if (get_repacking_impl_type() == RepackingImplType::IN_PARALLEL) {
+ external_buffer_size *= m_nthreads;
+
+ m_repacked_offsets_by_threads.resize(m_nthreads);
+ for (size_t i = 0; i < m_repacked_offsets_by_threads.size(); ++i) {
+ clean_repacked_offsets(i);
+ }
+
+ if (m_tensor_rank == rank6D) {
+ init_offset =
+ [](const std::vector<size_t>& offsets, const std::vector<size_t>& indexes, size_t& offset) {
+ offset += offsets[0] * indexes[0] + offsets[1] * indexes[1] + offsets[2] * indexes[2] +
+ offsets[3] * indexes[3];
+ };
+ } else {
+ init_offset =
+ [](const std::vector<size_t>& offsets, const std::vector<size_t>& indexes, size_t& offset) {
+ for (size_t j = 0; j < indexes.size(); j++) {
+ offset += offsets[j] * indexes[j];
+ }
+ };
+ }
+ }
+
+ m_buffer_scratchpad = allocator(m_internal_buffer_size + external_buffer_size);
+ }
+
+ void execute(const dnnl::stream& strm,
+ const std::vector<MemoryPtr>& in_mem_ptrs,
+ const std::vector<MemoryPtr>& out_mem_ptrs) override {
+ switch (get_repacking_impl_type()) {
+ case RepackingImplType::SEPARATE:
+ exec_impl(separately_repack_inputs(strm, in_mem_ptrs), out_mem_ptrs);
+ return;
+ case RepackingImplType::IN_PARALLEL:
+ case RepackingImplType::NONE:
+ exec_impl(in_mem_ptrs, out_mem_ptrs);
+ return;
+ default:
+ OPENVINO_THROW("Uknown RepackingImplType");
+ }
+ }
+
+protected:
+ static void parallel4d_repacking(const RepackingKernel* ker,
+ const VectorDims& dom,
+ const VectorDims& in_str,
+ const VectorDims& out_str,
+ const uint8_t* const src,
+ uint8_t* const dst) { // NOLINT(readability-non-const-parameter)
+ parallel_for4d(dom[0], dom[1], dom[2], dom[3], [&](size_t d0, size_t d1, size_t d2, size_t d3) {
+ typename RepackingKernel::call_args args;
+ args.src = src + d0 * in_str[0] + d1 * in_str[1] + d2 * in_str[2] + d3 * in_str[3];
+ args.tr_src = dst + d0 * out_str[0] + d1 * out_str[1] + d2 * out_str[2] + d3 * out_str[3];
+ (*ker)(&args);
+ });
+ }
+
+ static void parallelNd_repacking(const RepackingKernel* ker,
+ const VectorDims& dom,
+ const VectorDims& in_str,
+ const VectorDims& out_str,
+ const uint8_t* const src,
+ uint8_t* const dst) { // NOLINT(readability-non-const-parameter)
+ const size_t batch = std::accumulate(dom.rbegin() + 2, dom.rend(), 1LU, std::multiplies<>());
+ parallel_nt_static(0, [&](const int ithr, const int nthr) {
+ typename RepackingKernel::call_args args;
+ size_t start = 0;
+ size_t end = 0;
+ splitter(batch, nthr, ithr, start, end);
+ for (size_t iwork = start; iwork < end; ++iwork) {
+ const uint8_t* src_u8 = src;
+ uint8_t* dst_u8 = dst;
+ size_t tmp = iwork;
+ for (ptrdiff_t j = static_cast<ptrdiff_t>(dom.size()) - 3; j >= 0; j--) {
+ auto idx = tmp % dom[j];
+ tmp /= dom[j];
+
+ src_u8 += idx * in_str[j];
+ dst_u8 += idx * out_str[j];
+ }
+ args.src = src_u8;
+ args.tr_src = dst_u8;
+ (*ker)(&args);
+ }
+ });
+ }
+
+ static void separately_repack_input(const MemoryPtr& src_mem_ptr,
+ const MemoryPtr& dst_mem_ptr,
+ const ov::intel_cpu::InputRepacker& input_repacker,
+ size_t tensor_rank) {
+ auto get_offset = [](const BlockedMemoryDescPtr& desc) {
+ return static_cast<ptrdiff_t>(desc->getOffsetPadding() * desc->getPrecision().size());
+ };
+
+ const auto* src_ptr =
+ src_mem_ptr->getDataAs<const uint8_t>() + get_offset(src_mem_ptr->getDescWithType<BlockedMemoryDesc>());
+ auto* dst_ptr =
+ dst_mem_ptr->getDataAs<uint8_t>() + get_offset(dst_mem_ptr->getDescWithType<BlockedMemoryDesc>());
+
+ VectorDims dom;
+ const auto& shape = dst_mem_ptr->getShape().getDims();
+ OPENVINO_ASSERT(shape.size() <= tensor_rank, "Unsupported shape rank of repacking data");
+ init_parallel_domain(shape, tensor_rank, 2LU, dom);
+
+ const auto& in_strides = input_repacker.in_offsets();
+ const auto& out_strides = input_repacker.out_offsets();
+ OPENVINO_ASSERT(all_of(tensor_rank, in_strides.size(), out_strides.size(), dom.size()),
+ "Unsupported shape rank of repacking data");
+
+ const auto& kernel = input_repacker.template kernel<RepackingKernel>();
+ if (tensor_rank == rank6D) {
+ parallel4d_repacking(kernel.get(), dom, in_strides, out_strides, src_ptr, dst_ptr);
+ } else {
+ parallelNd_repacking(kernel.get(), dom, in_strides, out_strides, src_ptr, dst_ptr);
+ }
+ }
+
+ std::vector<MemoryPtr> separately_repack_inputs(const dnnl::stream& strm,
+ const std::vector<MemoryPtr>& src_mem_ptrs) {
+ auto reordered_in_ptrs = src_mem_ptrs;
+ size_t offset = m_internal_buffer_size;
+ for (const auto& [in_idx, input_repacker] : m_input_repackers) {
+ const auto& desc = input_repacker.desc();
+ const void* data_ptr = m_buffer_scratchpad->getDataAs<uint8_t>() + offset;
+
+ OPENVINO_ASSERT(in_idx < src_mem_ptrs.size(), "Incorrect index of input repacked mem ptr");
+ const auto& src_mem = src_mem_ptrs[in_idx];
+ const auto& dst_mem = std::make_shared<Memory>(strm.get_engine(), desc, data_ptr, false);
+ separately_repack_input(src_mem, dst_mem, input_repacker, m_tensor_rank);
+
+ reordered_in_ptrs[in_idx] = dst_mem;
+ offset += desc->getCurrentMemSize();
+ }
+ return reordered_in_ptrs;
+ }
+
+ void in_parallel_repack_inputs(const std::vector<MemoryPtr>& in_mem_ptrs,
+ const std::vector<size_t>& indexes,
+ int ithr,
+ jit_snippets_call_args& call_args) {
+ size_t repacked_offset_idx = 0;
+ for (const auto& [in_idx, input_repacker] : m_input_repackers) {
+ size_t src_offset = m_start_offset_in[in_idx];
+ init_offset(input_repacker.in_offsets(), indexes, src_offset);
+
+ auto* repacked_ptr = get_external_scratchpad_ptr(ithr, in_idx);
+
+ auto& last_processed_src_offset = m_repacked_offsets_by_threads[ithr][repacked_offset_idx];
+ if (src_offset != last_processed_src_offset) {
+ typename RepackingKernel::call_args args;
+ args.src = in_mem_ptrs[in_idx]->template getDataAs<const uint8_t>() + src_offset;
+ args.tr_src = repacked_ptr;
+ (*input_repacker.template kernel<RepackingKernel>())(&args);
+
+ last_processed_src_offset = src_offset;
+ }
+
+ call_args.src_ptrs[in_idx] = repacked_ptr;
+ ++repacked_offset_idx;
+ }
+ }
+
+ void* get_external_scratchpad_ptr(size_t ithr, size_t idx) const {
+ if (m_input_repackers.empty()) {
+ return nullptr;
+ }
+
+ uint8_t* data_ptr = m_buffer_scratchpad->getDataAs<uint8_t>() + m_internal_buffer_size;
+ for (const auto& p : m_input_repackers) {
+ const auto& desc = p.second.desc();
+ const auto size = desc->getCurrentMemSize();
+ if (p.first == idx) {
+ return data_ptr + ithr * size;
+ }
+ data_ptr += m_nthreads * size;
+ }
+ OPENVINO_THROW("External buffer pointer has not been found");
+ }
+
+ using RepackingImplType = CPURuntimeConfig::RepackingImplType;
+ const RepackingImplType& get_repacking_impl_type() const {
+ return m_repacking_impl_type;
+ }
+
+ void clean_repacked_offsets(size_t ithr) {
+ m_repacked_offsets_by_threads[ithr].assign(m_input_repackers.size(), std::numeric_limits<size_t>::max());
+ }
+
+#ifdef SNIPPETS_DEBUG_CAPS
+ virtual void segfault_detector() const {}
+#endif
+
+ std::vector<std::vector<size_t>> m_repacked_offsets_by_threads;
+ InputRepackerMap m_input_repackers;
+ std::function<void(const std::vector<size_t>&, const std::vector<size_t>&, size_t&)> init_offset;
+
+private:
+ RepackingImplType m_repacking_impl_type = RepackingImplType::NONE;
+};
+
+template <typename RepackingExecutor>
+class SubgraphRepackingStaticExecutor : public RepackingExecutor, public SubgraphStaticBaseExecutor {
+public:
+ template <typename... Args>
+ SubgraphRepackingStaticExecutor(const std::shared_ptr<ov::intel_cpu::CPURuntimeConfig>& config,
+ const std::set<size_t>& external_ptrs_idces,
+ size_t in_num,
+ Args&&... rest)
+ : RepackingExecutor(config, std::forward<Args>(rest)...),
+ SubgraphStaticBaseExecutor(external_ptrs_idces, in_num) {}
+
+private:
+ void exec_impl(const std::vector<MemoryPtr>& in_mem_ptrs, const std::vector<MemoryPtr>& out_mem_ptrs) override {
+ const auto& callable = this->m_schedule->template get_callable<typename SubgraphStaticBaseExecutor::kernel>();
+
+ typename SubgraphBaseExecutor::initializer_functor initializer;
+ typename SubgraphBaseExecutor::call_functor caller;
+
+ switch (this->get_repacking_impl_type()) {
+ case RepackingExecutor::RepackingImplType::IN_PARALLEL:
+ initializer = [&](jit_snippets_call_args& call_args, size_t ithr) {
+ this->init_call_args(call_args,
+ in_mem_ptrs,
+ out_mem_ptrs,
+ this->m_start_offset_in,
+ this->m_start_offset_out);
+ this->update_scratchpad_ptr(call_args.buffer_scratchpad_ptr, ithr);
+ this->clean_repacked_offsets(ithr);
+ };
+ caller = [&](jit_snippets_call_args& call_args, const std::vector<size_t>& indexes, size_t ithr) {
+ this->in_parallel_repack_inputs(in_mem_ptrs, indexes, ithr, call_args);
+ callable(&call_args, indexes.data());
+ };
+ break;
+ case RepackingExecutor::RepackingImplType::SEPARATE:
+ case RepackingExecutor::RepackingImplType::NONE:
+ initializer = [&](jit_snippets_call_args& call_args, size_t ithr) {
+ this->init_call_args(call_args,
+ in_mem_ptrs,
+ out_mem_ptrs,
+ this->m_start_offset_in,
+ this->m_start_offset_out);
+ this->update_scratchpad_ptr(call_args.buffer_scratchpad_ptr, ithr);
+ };
+ caller = [&](jit_snippets_call_args& call_args,
+ const std::vector<size_t>& indexes,
+ [[maybe_unused]] size_t ithr) {
+ callable(&call_args, indexes.data());
+ };
+ break;
+ default:
+ OPENVINO_THROW("Uknown RepackingImplType");
+ }
+
+#if defined(SNIPPETS_DEBUG_CAPS) && (defined(__linux__) || defined(__APPLE__))
+ this->segfault_detector();
+#endif
+
+ if (this->m_parallel_exec_domain.size() == this->rank6D) {
+ this->parallel_for6d(initializer, caller);
+ } else {
+ this->parallel_forNd(initializer, caller);
+ }
+ }
+};
+
+template <typename RepackingExecutor>
+class SubgraphRepackingDynamicSpecializedExecutor : public RepackingExecutor,
+ public SubgraphDynamicSpecializedBaseExecutor {
+public:
+ template <typename... Args>
+ SubgraphRepackingDynamicSpecializedExecutor(const std::shared_ptr<ov::intel_cpu::CPURuntimeConfig>& config,
+ const std::set<size_t>& external_ptrs_idces,
+ size_t in_num,
+ Args&&... rest)
+ : RepackingExecutor(config, std::forward<Args>(rest)...),
+ SubgraphDynamicSpecializedBaseExecutor(config, external_ptrs_idces, in_num) {}
+
+private:
+ void exec_impl(const std::vector<MemoryPtr>& in_mem_ptrs, const std::vector<MemoryPtr>& out_mem_ptrs) override {
+ const auto& callable =
+ this->m_schedule->template get_callable<typename SubgraphDynamicSpecializedBaseExecutor::dynamic_kernel>();
+
+ OPENVINO_ASSERT(this->m_data_offsets.size() == in_mem_ptrs.size() + out_mem_ptrs.size(),
+ "Incorrect data offset count!");
+ OPENVINO_ASSERT(this->m_data_offsets.front().size() == this->m_parallel_exec_domain.size(),
+ "Data offsets with invalid ranks detected");
+
+ this->m_reset_exec_table_state();
+
+ std::vector<const uint8_t*> src_ptrs;
+ std::vector<uint8_t*> dst_ptrs;
+ this->init_original_ptrs(in_mem_ptrs,
+ out_mem_ptrs,
+ src_ptrs,
+ dst_ptrs,
+ this->m_start_offset_in,
+ this->m_start_offset_out);
+
+ typename SubgraphBaseExecutor::initializer_functor initializer;
+ typename SubgraphBaseExecutor::call_functor caller;
+
+ switch (this->get_repacking_impl_type()) {
+ case RepackingExecutor::RepackingImplType::IN_PARALLEL:
+ initializer = [&](jit_snippets_call_args& call_args, size_t ithr) {
+ this->init_call_args(call_args);
+ this->update_scratchpad_ptr(call_args.buffer_scratchpad_ptr, ithr);
+ this->clean_repacked_offsets(ithr);
+ };
+ caller = [&](jit_snippets_call_args& call_args, const std::vector<size_t>& indexes, size_t ithr) {
+ this->update_ptrs(call_args, src_ptrs, dst_ptrs, indexes);
+ this->in_parallel_repack_inputs(in_mem_ptrs, indexes, ithr, call_args);
+ callable(&call_args);
+ };
+ break;
+ case RepackingExecutor::RepackingImplType::SEPARATE:
+ case RepackingExecutor::RepackingImplType::NONE:
+ initializer = [&](jit_snippets_call_args& call_args, size_t ithr) {
+ this->init_call_args(call_args);
+ this->update_scratchpad_ptr(call_args.buffer_scratchpad_ptr, ithr);
+ };
+ caller = [&](jit_snippets_call_args& call_args,
+ const std::vector<size_t>& indexes,
+ [[maybe_unused]] size_t ithr) {
+ this->update_ptrs(call_args, src_ptrs, dst_ptrs, indexes);
+ callable(&call_args);
+ };
+ break;
+ default:
+ OPENVINO_THROW("Uknown RepackingImplType");
+ }
+
+#if defined(SNIPPETS_DEBUG_CAPS) && (defined(__linux__) || defined(__APPLE__))
+ this->segfault_detector();
+#endif
+
+ if (this->m_parallel_exec_domain.size() == this->rank6D) {
+ this->parallel_for6d(initializer, caller);
+ } else {
+ this->parallel_forNd(initializer, caller);
+ }
+ }
+};
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/executors/x64/subgraph.cpp b/src/plugins/intel_cpu/src/nodes/executors/x64/subgraph.cpp
index 3b76616ea8f..cd05bd52817 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/x64/subgraph.cpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/x64/subgraph.cpp
@@ -4,86 +4,29 @@
#include "nodes/executors/x64/subgraph.hpp"
-#include <csignal>
-#include <cstddef>
-#include <cstdint>
-#include <functional>
-#include <memory>
-#include <numeric>
-#include <oneapi/dnnl/dnnl_common.hpp>
-#include <utility>
-#include <vector>
-
-#include "cache/multi_cache.h"
-#include "cpu_types.h"
-#include "dnnl_extension_utils.h"
-#include "emitters/snippets/cpu_runtime_configurator.hpp"
-#include "emitters/snippets/input_repacker.hpp"
-#include "emitters/snippets/jit_snippets_call_args.hpp"
-#include "emitters/snippets/x64/kernel_executors/brgemm_copy_b.hpp"
-#include "memory_desc/blocked_memory_desc.h"
-#include "memory_desc/cpu_memory_desc_utils.h"
-#include "nodes/executors/subgraph.hpp"
-#include "openvino/core/except.hpp"
-#include "openvino/core/parallel.hpp"
-#include "utils/general_utils.h"
-
#if defined(SNIPPETS_DEBUG_CAPS) && (defined(__linux__) || defined(__APPLE__))
+# include <csignal>
+# include <cstddef>
# include <iostream>
+# include <memory>
# include <mutex>
# include <string>
+# include <vector>
+# include "cache/multi_cache.h"
+# include "emitters/snippets/cpu_runtime_configurator.hpp"
# include "emitters/snippets/x64/cpu_generator.hpp"
# include "emitters/snippets/x64/jit_segfault_detector_emitter.hpp"
+# include "emitters/snippets/x64/kernel_executors/brgemm_copy_b.hpp"
+# include "nodes/executors/repacking_subgraph.hpp"
+# include "nodes/executors/subgraph.hpp"
+# include "openvino/core/except.hpp"
+# include "openvino/core/parallel.hpp"
+
#endif
namespace ov::intel_cpu {
-namespace {
-inline void parallel4d_repacking(const BrgemmCopyBKernel* ker,
- const VectorDims& dom,
- const VectorDims& in_str,
- const VectorDims& out_str,
- const uint8_t* src,
- uint8_t* dst) {
- parallel_for4d(dom[0], dom[1], dom[2], dom[3], [&](size_t d0, size_t d1, size_t d2, size_t d3) {
- BrgemmCopyBKernel::call_args args;
- args.src = src + d0 * in_str[0] + d1 * in_str[1] + d2 * in_str[2] + d3 * in_str[3];
- args.tr_src = dst + d0 * out_str[0] + d1 * out_str[1] + d2 * out_str[2] + d3 * out_str[3];
- (*ker)(&args);
- });
-};
-inline void parallelNd_repacking(const BrgemmCopyBKernel* ker,
- const VectorDims& dom,
- const VectorDims& in_str,
- const VectorDims& out_str,
- const uint8_t* src,
- uint8_t* dst) {
- const size_t batch = std::accumulate(dom.rbegin() + 2, dom.rend(), 1LU, std::multiplies<>());
- parallel_nt_static(0, [&](const int ithr, const int nthr) {
- BrgemmCopyBKernel::call_args args;
- size_t start = 0;
- size_t end = 0;
- splitter(batch, nthr, ithr, start, end);
- for (size_t iwork = start; iwork < end; ++iwork) {
- const uint8_t* src_u8 = src;
- uint8_t* dst_u8 = dst;
- size_t tmp = iwork;
- for (ptrdiff_t j = static_cast<ptrdiff_t>(dom.size()) - 3; j >= 0; j--) {
- auto idx = tmp % dom[j];
- tmp /= dom[j];
-
- src_u8 += idx * in_str[j];
- dst_u8 += idx * out_str[j];
- }
- args.src = src_u8;
- args.tr_src = dst_u8;
- (*ker)(&args);
- }
- });
-};
-} // namespace
-
SubgraphExecutor::SubgraphExecutor(const std::shared_ptr<CPURuntimeConfig>& snippet_config,
const std::shared_ptr<SubgraphAttrs>& snippet_attrs,
const std::shared_ptr<SubgraphCodeGenerator>& snippet,
@@ -91,54 +34,13 @@ SubgraphExecutor::SubgraphExecutor(const std::shared_ptr<CPURuntimeConfig>& snip
const std::vector<ptrdiff_t>& start_offset_out,
const BufferScratchpadAllocator& allocator,
const ov::intel_cpu::MultiCacheWeakPtr& kernel_cache)
- : SubgraphBaseExecutor(snippet_config,
- snippet_attrs,
- snippet,
- start_offset_in,
- start_offset_out,
- allocator,
- kernel_cache),
- m_input_repackers(snippet_config->input_repackers),
- m_repacking_impl_type(snippet_config->repacking_impl_type) {
- auto external_buffer_size =
- std::accumulate(m_input_repackers.begin(),
- m_input_repackers.end(),
- static_cast<size_t>(0),
- [](size_t sum, const std::pair<size_t, InputRepacker>& p) {
- auto curr_mem_size = p.second.desc()->getCurrentMemSize();
- OPENVINO_ASSERT(curr_mem_size != ov::intel_cpu::MemoryDesc::UNDEFINED_SIZE,
- "Current repacking buffer memory size is undefined");
- return sum + curr_mem_size;
- });
-
- if (get_repacking_impl_type() == RepackingImplType::IN_PARALLEL) {
- // When external repacking is applied in parallel section,
- // each thread should have own buffer to store repacked data
- external_buffer_size *= m_nthreads;
-
- // To avoid extra overheads in runtime on vector creation,
- // we initialize `repacked_offsets_by_threads` by default here
- m_repacked_offsets_by_threads.resize(m_nthreads);
- for (size_t i = 0; i < m_repacked_offsets_by_threads.size(); ++i) {
- clean_repacked_offsets(i);
- }
-
- if (m_tensor_rank == rank6D) {
- init_offset = [](const std::vector<size_t>& offsets, const std::vector<size_t>& indexes, size_t& offset) {
- offset += offsets[0] * indexes[0] + offsets[1] * indexes[1] + offsets[2] * indexes[2] +
- offsets[3] * indexes[3];
- };
- } else {
- init_offset = [](const std::vector<size_t>& offsets, const std::vector<size_t>& indexes, size_t& offset) {
- for (size_t j = 0; j < indexes.size(); j++) {
- offset += offsets[j] * indexes[j];
- }
- };
- }
- }
-
- m_buffer_scratchpad = allocator(m_internal_buffer_size + external_buffer_size);
-
+ : SubgraphRepackingExecutor<BrgemmCopyBKernel>(snippet_config,
+ snippet_attrs,
+ snippet,
+ start_offset_in,
+ start_offset_out,
+ allocator,
+ kernel_cache) {
#if defined(SNIPPETS_DEBUG_CAPS) && (defined(__linux__) || defined(__APPLE__))
const auto target = std::dynamic_pointer_cast<const CPUTargetMachine>(
snippet_attrs->snippet->get_generator()->get_target_machine());
@@ -146,36 +48,6 @@ SubgraphExecutor::SubgraphExecutor(const std::shared_ptr<CPURuntimeConfig>& snip
#endif
}
-void SubgraphExecutor::separately_repack_input(const MemoryPtr& src_mem_ptr,
- const MemoryPtr& dst_mem_ptr,
- const ov::intel_cpu::InputRepacker& input_repacker,
- size_t tensor_rank) {
- auto get_offset = [](const BlockedMemoryDescPtr& desc) {
- return static_cast<ptrdiff_t>(desc->getOffsetPadding() * desc->getPrecision().size());
- };
-
- const auto* src_ptr =
- src_mem_ptr->getDataAs<const uint8_t>() + get_offset(src_mem_ptr->getDescWithType<BlockedMemoryDesc>());
- auto* dst_ptr = dst_mem_ptr->getDataAs<uint8_t>() + get_offset(dst_mem_ptr->getDescWithType<BlockedMemoryDesc>());
-
- VectorDims dom;
- const auto& shape = dst_mem_ptr->getShape().getDims();
- OPENVINO_ASSERT(shape.size() <= tensor_rank, "Unsupported shape rank of repacking data");
- init_parallel_domain(shape, tensor_rank, 2LU, dom);
-
- const auto& in_strides = input_repacker.in_offsets();
- const auto& out_strides = input_repacker.out_offsets();
- OPENVINO_ASSERT(all_of(tensor_rank, in_strides.size(), out_strides.size(), dom.size()),
- "Unsupported shape rank of repacking data");
-
- const auto& kernel = input_repacker.kernel<BrgemmCopyBKernel>();
- if (tensor_rank == rank6D) {
- parallel4d_repacking(kernel.get(), dom, in_strides, out_strides, src_ptr, dst_ptr);
- } else {
- parallelNd_repacking(kernel.get(), dom, in_strides, out_strides, src_ptr, dst_ptr);
- }
-}
-
#if defined(SNIPPETS_DEBUG_CAPS) && (defined(__linux__) || defined(__APPLE__))
// NOLINTBEGIN(misc-include-cleaner) bug in clang-tidy
void SubgraphExecutor::segfault_detector() const {
@@ -199,169 +71,4 @@ void SubgraphExecutor::segfault_detector() const {
// NOLINTEND(misc-include-cleaner) bug in clang-tidy
#endif
-std::vector<MemoryPtr> SubgraphExecutor::separately_repack_inputs(const dnnl::stream& strm,
- const std::vector<MemoryPtr>& src_mem_ptrs) {
- auto reordered_in_ptrs = src_mem_ptrs;
- size_t offset = m_internal_buffer_size;
- for (const auto& [in_idx, input_repacker] : m_input_repackers) {
- const auto& desc = input_repacker.desc();
- const void* data_ptr = m_buffer_scratchpad->getDataAs<uint8_t>() + offset;
-
- OPENVINO_ASSERT(in_idx < src_mem_ptrs.size(), "Incorrect index of input repacked mem ptr");
- const auto& src_mem = src_mem_ptrs[in_idx];
- const auto& dst_mem = std::make_shared<Memory>(strm.get_engine(), desc, data_ptr, false);
- separately_repack_input(src_mem, dst_mem, input_repacker, m_tensor_rank);
-
- reordered_in_ptrs[in_idx] = dst_mem;
- offset += desc->getCurrentMemSize();
- }
- return reordered_in_ptrs;
-}
-
-void SubgraphExecutor::in_parallel_repack_inputs(const std::vector<MemoryPtr>& in_mem_ptrs,
- const std::vector<size_t>& indexes,
- int ithr,
- jit_snippets_call_args& call_args) {
- size_t repacked_offset_idx = 0;
- for (const auto& [in_idx, input_repacker] : m_input_repackers) {
- size_t src_offset = m_start_offset_in[in_idx];
- init_offset(input_repacker.in_offsets(), indexes, src_offset);
-
- auto* repacked_ptr = get_external_scratchpad_ptr(ithr, in_idx);
-
- auto& last_processed_src_offset = m_repacked_offsets_by_threads[ithr][repacked_offset_idx];
- if (src_offset != last_processed_src_offset) {
- BrgemmCopyBKernel::call_args args;
- args.src = in_mem_ptrs[in_idx]->getDataAs<const uint8_t>() + src_offset;
- args.tr_src = repacked_ptr;
- (*input_repacker.kernel<BrgemmCopyBKernel>())(&args);
-
- last_processed_src_offset = src_offset;
- }
-
- call_args.src_ptrs[in_idx] = repacked_ptr;
- ++repacked_offset_idx;
- }
-}
-
-void SubgraphExecutor::execute(const dnnl::stream& strm,
- const std::vector<MemoryPtr>& in_mem_ptrs,
- const std::vector<MemoryPtr>& out_mem_ptrs) {
- switch (get_repacking_impl_type()) {
- case RepackingImplType::SEPARATE:
- exec_impl(separately_repack_inputs(strm, in_mem_ptrs), out_mem_ptrs);
- return;
- case RepackingImplType::IN_PARALLEL:
- case RepackingImplType::NONE:
- exec_impl(in_mem_ptrs, out_mem_ptrs);
- return;
- default:
- OPENVINO_THROW("Uknown RepackingImplType");
- }
-}
-
-void SubgraphStaticExecutor::exec_impl(const std::vector<MemoryPtr>& in_mem_ptrs,
- const std::vector<MemoryPtr>& out_mem_ptrs) {
- const auto& callable = m_schedule->get_callable<kernel>();
-
- initializer_functor initializer;
- call_functor caller;
-
- switch (get_repacking_impl_type()) {
- case RepackingImplType::IN_PARALLEL:
- initializer = [&](jit_snippets_call_args& call_args, size_t ithr) {
- init_call_args(call_args, in_mem_ptrs, out_mem_ptrs, m_start_offset_in, m_start_offset_out);
- update_scratchpad_ptr(call_args.buffer_scratchpad_ptr, ithr);
- clean_repacked_offsets(ithr);
- };
- caller = [&](jit_snippets_call_args& call_args, const std::vector<size_t>& indexes, size_t ithr) {
- in_parallel_repack_inputs(in_mem_ptrs, indexes, ithr, call_args);
- callable(&call_args, indexes.data());
- };
- break;
- case RepackingImplType::SEPARATE:
- case RepackingImplType::NONE:
- initializer = [&](jit_snippets_call_args& call_args, size_t ithr) {
- init_call_args(call_args, in_mem_ptrs, out_mem_ptrs, m_start_offset_in, m_start_offset_out);
- update_scratchpad_ptr(call_args.buffer_scratchpad_ptr, ithr);
- };
- caller =
- [&](jit_snippets_call_args& call_args, const std::vector<size_t>& indexes, [[maybe_unused]] size_t ithr) {
- callable(&call_args, indexes.data());
- };
- break;
- default:
- OPENVINO_THROW("Uknown RepackingImplType");
- }
-
-#if defined(SNIPPETS_DEBUG_CAPS) && (defined(__linux__) || defined(__APPLE__))
- segfault_detector();
-#endif
-
- if (m_parallel_exec_domain.size() == rank6D) {
- parallel_for6d(initializer, caller);
- } else {
- parallel_forNd(initializer, caller);
- }
-}
-
-void SubgraphDynamicSpecializedExecutor::exec_impl(const std::vector<MemoryPtr>& in_mem_ptrs,
- const std::vector<MemoryPtr>& out_mem_ptrs) {
- const auto& callable = m_schedule->get_callable<dynamic_kernel>();
-
- OPENVINO_ASSERT(m_data_offsets.size() == in_mem_ptrs.size() + out_mem_ptrs.size(), "Incorrect data offset count!");
- OPENVINO_ASSERT(m_data_offsets.front().size() == m_parallel_exec_domain.size(),
- "Data offsets with invalid ranks detected");
-
- // Note: we need to reset KernelExecutorTable to the state that was recorded in the
- // SubgraphDynamicSpecializedExecutor constructor because the table might've been used for other shapes
- m_reset_exec_table_state();
-
- std::vector<const uint8_t*> src_ptrs;
- std::vector<uint8_t*> dst_ptrs;
- init_original_ptrs(in_mem_ptrs, out_mem_ptrs, src_ptrs, dst_ptrs, m_start_offset_in, m_start_offset_out);
-
- initializer_functor initializer;
- call_functor caller;
-
- switch (get_repacking_impl_type()) {
- case RepackingImplType::IN_PARALLEL:
- initializer = [&](jit_snippets_call_args& call_args, size_t ithr) {
- init_call_args(call_args);
- update_scratchpad_ptr(call_args.buffer_scratchpad_ptr, ithr);
- clean_repacked_offsets(ithr);
- };
- caller = [&](jit_snippets_call_args& call_args, const std::vector<size_t>& indexes, size_t ithr) {
- update_ptrs(call_args, src_ptrs, dst_ptrs, indexes);
- in_parallel_repack_inputs(in_mem_ptrs, indexes, ithr, call_args);
- callable(&call_args);
- };
- break;
- case RepackingImplType::SEPARATE:
- case RepackingImplType::NONE:
- initializer = [&](jit_snippets_call_args& call_args, size_t ithr) {
- init_call_args(call_args);
- update_scratchpad_ptr(call_args.buffer_scratchpad_ptr, ithr);
- };
- caller =
- [&](jit_snippets_call_args& call_args, const std::vector<size_t>& indexes, [[maybe_unused]] size_t ithr) {
- update_ptrs(call_args, src_ptrs, dst_ptrs, indexes);
- callable(&call_args);
- };
- break;
- default:
- OPENVINO_THROW("Uknown RepackingImplType");
- }
-
-#if defined(SNIPPETS_DEBUG_CAPS) && (defined(__linux__) || defined(__APPLE__))
- segfault_detector();
-#endif
-
- if (m_parallel_exec_domain.size() == rank6D) {
- parallel_for6d(initializer, caller);
- } else {
- parallel_forNd(initializer, caller);
- }
-}
-
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/executors/x64/subgraph.hpp b/src/plugins/intel_cpu/src/nodes/executors/x64/subgraph.hpp
index 754a2b85847..c8e9b0dd2f5 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/x64/subgraph.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/x64/subgraph.hpp
@@ -5,26 +5,22 @@
#pragma once
#include <cstddef>
-#include <cstdint>
-#include <functional>
-#include <limits>
#include <memory>
#include <oneapi/dnnl/dnnl_common.hpp>
+#include <set>
#include <vector>
#include "cache/multi_cache.h"
-#include "cpu_memory.h"
#include "emitters/snippets/cpu_runtime_configurator.hpp"
-#include "emitters/snippets/input_repacker.hpp"
-#include "emitters/snippets/jit_snippets_call_args.hpp"
-#include "graph_context.h"
-#include "nodes/executors/subgraph.hpp"
-#include "openvino/core/except.hpp"
+#include "emitters/snippets/x64/kernel_executors/brgemm_copy_b.hpp"
+#include "nodes/executors/repacking_subgraph.hpp"
namespace ov::intel_cpu {
-class SubgraphExecutor : public SubgraphBaseExecutor {
+class SubgraphExecutor : public SubgraphRepackingExecutor<BrgemmCopyBKernel> {
public:
+ using SubgraphRepackingExecutor<BrgemmCopyBKernel>::SubgraphRepackingExecutor;
+
SubgraphExecutor(const std::shared_ptr<CPURuntimeConfig>& snippet_config,
const std::shared_ptr<SubgraphAttrs>& snippet_attrs,
const std::shared_ptr<SubgraphCodeGenerator>& snippet,
@@ -33,88 +29,23 @@ public:
const BufferScratchpadAllocator& allocator,
const ov::intel_cpu::MultiCacheWeakPtr& kernel_cache);
- void execute(const dnnl::stream& strm,
- const std::vector<MemoryPtr>& in_mem_ptrs,
- const std::vector<MemoryPtr>& out_mem_ptrs) override;
-
+#ifdef SNIPPETS_DEBUG_CAPS
protected:
- static void separately_repack_input(const MemoryPtr& src_mem_ptr,
- const MemoryPtr& dst_mem_ptr,
- const ov::intel_cpu::InputRepacker& input_repacker,
- size_t tensor_rank);
-
- std::vector<MemoryPtr> separately_repack_inputs(const dnnl::stream& strm,
- const std::vector<MemoryPtr>& src_mem_ptrs);
- void in_parallel_repack_inputs(const std::vector<MemoryPtr>& in_mem_ptrs,
- const std::vector<size_t>& indexes,
- int ithr,
- jit_snippets_call_args& call_args);
-
- void* get_external_scratchpad_ptr(size_t ithr, size_t idx) const {
- if (m_input_repackers.empty()) {
- return nullptr;
- }
-
- uint8_t* data_ptr = m_buffer_scratchpad->getDataAs<uint8_t>() + m_internal_buffer_size;
- for (const auto& p : m_input_repackers) {
- const auto& desc = p.second.desc();
- const auto size = desc->getCurrentMemSize();
- if (p.first == idx) {
- return data_ptr + ithr * size;
- }
- data_ptr += m_nthreads * size;
- }
- OPENVINO_THROW("External buffer pointer has not been found");
- }
-
- // [ Thread Index -> Index of input with repacking data - > last repacked src_offset ]
- std::vector<std::vector<size_t>> m_repacked_offsets_by_threads;
- InputRepackerMap m_input_repackers;
-
- std::function<void(const std::vector<size_t>&, const std::vector<size_t>&, size_t&)> init_offset;
+ void segfault_detector() const override;
- using RepackingImplType = CPURuntimeConfig::RepackingImplType;
- const RepackingImplType& get_repacking_impl_type() const {
- return m_repacking_impl_type;
- }
-
- void clean_repacked_offsets(size_t ithr) {
- m_repacked_offsets_by_threads[ithr].assign(m_input_repackers.size(), std::numeric_limits<size_t>::max());
- }
-
-#ifdef SNIPPETS_DEBUG_CAPS
+private:
bool enabled_segfault_detector = false;
- inline void segfault_detector() const;
#endif
-
-private:
- RepackingImplType m_repacking_impl_type = RepackingImplType::NONE;
};
-class SubgraphStaticExecutor : public SubgraphExecutor, public SubgraphStaticBaseExecutor {
+class SubgraphStaticExecutor : public SubgraphRepackingStaticExecutor<SubgraphExecutor> {
public:
- template <typename... Args>
- SubgraphStaticExecutor(const std::shared_ptr<ov::intel_cpu::CPURuntimeConfig>& config,
- const std::set<size_t>& external_ptrs_idces,
- size_t in_num,
- Args&&... rest)
- : SubgraphExecutor(config, std::forward<Args>(rest)...),
- SubgraphStaticBaseExecutor(external_ptrs_idces, in_num) {}
-
- void exec_impl(const std::vector<MemoryPtr>& in_mem_ptrs, const std::vector<MemoryPtr>& out_mem_ptrs) override;
+ using SubgraphRepackingStaticExecutor<SubgraphExecutor>::SubgraphRepackingStaticExecutor;
};
-class SubgraphDynamicSpecializedExecutor : public SubgraphExecutor, public SubgraphDynamicSpecializedBaseExecutor {
+class SubgraphDynamicSpecializedExecutor : public SubgraphRepackingDynamicSpecializedExecutor<SubgraphExecutor> {
public:
- template <typename... Args>
- SubgraphDynamicSpecializedExecutor(const std::shared_ptr<ov::intel_cpu::CPURuntimeConfig>& config,
- const std::set<size_t>& external_ptrs_idces,
- size_t in_num,
- Args&&... rest)
- : SubgraphExecutor(config, std::forward<Args>(rest)...),
- SubgraphDynamicSpecializedBaseExecutor(config, external_ptrs_idces, in_num) {}
-
- void exec_impl(const std::vector<MemoryPtr>& in_mem_ptrs, const std::vector<MemoryPtr>& out_mem_ptrs) override;
+ using SubgraphRepackingDynamicSpecializedExecutor<SubgraphExecutor>::SubgraphRepackingDynamicSpecializedExecutor;
};
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/subgraph.cpp b/src/plugins/intel_cpu/src/nodes/subgraph.cpp
index bfed9a30929..5ae145a409e 100644
--- a/src/plugins/intel_cpu/src/nodes/subgraph.cpp
+++ b/src/plugins/intel_cpu/src/nodes/subgraph.cpp
@@ -657,18 +657,19 @@ Subgraph::DataFlowPasses Subgraph::getDataFlowPasses() {
ov::intel_cpu::pass::x64::RepackMatMulWeights,
context,
cpu_config->input_repackers,
- srcMemPtrs);
+ srcMemPtrs,
+ getConstantInputIndexes());
SNIPPETS_REGISTER_PASS_RELATIVE_ARM64(Place::After,
ov::intel_cpu::pass::BrgemmToGemmCPU,
ov::intel_cpu::pass::aarch64::EliminateGemmCopyB,
- cpu_config->input_repackers,
- getConstantInputIndexes());
+ cpu_config->input_repackers);
SNIPPETS_REGISTER_PASS_RELATIVE_ARM64(Place::After,
ov::intel_cpu::pass::aarch64::EliminateGemmCopyB,
ov::intel_cpu::pass::aarch64::RepackMatMulWeights,
context,
cpu_config->input_repackers,
- srcMemPtrs);
+ srcMemPtrs,
+ getConstantInputIndexes());
}
SNIPPETS_REGISTER_PASS_ABSOLUTE_X86_64(Place::PipelineEnd, ov::intel_cpu::pass::RemoveConverts);
SNIPPETS_REGISTER_PASS_ABSOLUTE_COMMON(Place::PipelineEnd, ov::intel_cpu::pass::MulAddToFMA);
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/eliminate_gemm_copy_b.hpp b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/eliminate_gemm_copy_b.hpp
index c96b277537b..fc7ae2e0c22 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/eliminate_gemm_copy_b.hpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/eliminate_gemm_copy_b.hpp
@@ -6,8 +6,6 @@
#include <cstddef>
#include <memory>
-#include <set>
-#include <utility>
#include "emitters/snippets/input_repacker.hpp"
#include "openvino/core/node.hpp"
@@ -23,9 +21,7 @@ namespace ov::intel_cpu::pass::aarch64 {
class EliminateGemmCopyB : public ov::intel_cpu::pass::EliminateCopyB {
public:
OPENVINO_MODEL_PASS_RTTI("EliminateGemmCopyB");
- explicit EliminateGemmCopyB(ov::intel_cpu::InputRepackerMap& input_repackers,
- std::set<size_t> compile_time_repacking_idxs)
- : EliminateCopyB(input_repackers, false, std::move(compile_time_repacking_idxs)) {}
+ explicit EliminateGemmCopyB(ov::intel_cpu::InputRepackerMap& input_repackers) : EliminateCopyB(input_repackers) {}
private:
[[nodiscard]] std::shared_ptr<ov::Node> get_copy_b_pattern(const std::shared_ptr<ov::Node>& input) const override;
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/adjust_gemm_copy_b_loop_ports.cpp b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/adjust_gemm_copy_b_loop_ports.cpp
index 0218f1ce15a..852c8a63f7e 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/adjust_gemm_copy_b_loop_ports.cpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/adjust_gemm_copy_b_loop_ports.cpp
@@ -8,38 +8,22 @@
#include <cstdint>
#include <limits>
#include <memory>
+#include <vector>
#include "openvino/core/except.hpp"
#include "openvino/core/type.hpp"
#include "openvino/core/type/element_type.hpp"
#include "snippets/itt.hpp"
-#include "snippets/lowered/linear_ir.hpp"
+#include "snippets/lowered/expression.hpp"
#include "snippets/lowered/loop_info.hpp"
-#include "snippets/lowered/loop_manager.hpp"
#include "snippets/lowered/loop_port.hpp"
#include "snippets/utils/utils.hpp"
#include "transformations/snippets/aarch64/op/gemm_cpu.hpp"
#include "transformations/snippets/aarch64/op/gemm_utils.hpp"
-#include "utils/general_utils.h"
namespace ov::intel_cpu {
namespace {
-void assign_new_ptr_increment(int64_t new_ptr_increment,
- ov::snippets::lowered::UnifiedLoopInfo::LoopPortDesc& loop_desc) {
- const auto old_ptr_incr = loop_desc.ptr_increment;
- const auto old_final_offset = loop_desc.finalization_offset;
-
- if (none_of(old_ptr_incr, 0, new_ptr_increment)) {
- loop_desc.ptr_increment = new_ptr_increment;
- if (!ov::snippets::utils::is_dynamic_value(old_final_offset)) {
- OPENVINO_ASSERT(old_final_offset % old_ptr_incr == 0, "Can't rescale finalization offsets");
- loop_desc.finalization_offset =
- ov::snippets::utils::dynamic_safe_mul(loop_desc.ptr_increment, (old_final_offset / old_ptr_incr));
- }
- }
-}
-
int64_t get_rhs_packed_ptr_increment(const ov::element::Type& precision, size_t n_increment, size_t K) {
if (snippets::utils::is_dynamic_value(n_increment) || snippets::utils::is_dynamic_value(K)) {
return snippets::utils::get_dynamic_value<int64_t>();
@@ -96,33 +80,25 @@ bool pass::aarch64::AdjustGemmCopyBLoopPorts::update_loop_info(
return modified;
}
-bool pass::aarch64::AdjustGemmCopyBLoopPorts::run(const snippets::lowered::LinearIR& linear_ir) {
- OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::AdjustGemmCopyBLoopPorts")
+bool pass::aarch64::AdjustGemmCopyBLoopPorts::is_target_expr(const snippets::lowered::ExpressionPtr& expr) const {
+ return static_cast<bool>(ov::as_type_ptr<ov::intel_cpu::aarch64::GemmCPU>(expr->get_node()));
+}
- bool modified = false;
+snippets::lowered::ExpressionPtr pass::aarch64::AdjustGemmCopyBLoopPorts::get_copy_b_expr(
+ const snippets::lowered::ExpressionPtr& gemm_expr) const {
+ return ov::intel_cpu::aarch64::gemm_utils::repacking::get_copy_b_expr(gemm_expr);
+}
- for (const auto& expr : linear_ir) {
- const auto gemm = ov::as_type_ptr<ov::intel_cpu::aarch64::GemmCPU>(expr->get_node());
- if (!gemm) {
- continue;
- }
- const auto& gemm_loop_ids = expr->get_loop_ids();
- if (gemm_loop_ids.empty()) {
- continue;
- }
- const auto& loop_manager = linear_ir.get_loop_manager();
- // only adjust inner most loop(N loop)
- const auto& loop = loop_manager->get_loop_info(gemm_loop_ids.back());
- auto uni_loop = ov::as_type_ptr<snippets::lowered::UnifiedLoopInfo>(loop);
- if (!uni_loop) {
- uni_loop = ov::as_type_ptr<snippets::lowered::ExpandedLoopInfo>(loop)->get_unified_loop_info();
- }
- if (!m_affected_loops.count(uni_loop) && update_loop_info(uni_loop)) {
- m_affected_loops.insert(uni_loop);
- modified = true;
- }
- }
+bool pass::aarch64::AdjustGemmCopyBLoopPorts::update_loop_info_impl(
+ const snippets::lowered::UnifiedLoopInfoPtr& loop_info) const {
+ return update_loop_info(loop_info);
+}
- return modified;
+const char* pass::aarch64::AdjustGemmCopyBLoopPorts::copy_b_not_found_message() const {
+ return "GemmCopyB expression is not found";
+}
+
+const char* pass::aarch64::AdjustGemmCopyBLoopPorts::invalid_loop_config_message() const {
+ return "Invalid GemmCopyB loop configuration";
}
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/adjust_gemm_copy_b_loop_ports.hpp b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/adjust_gemm_copy_b_loop_ports.hpp
index 20370706de4..77dc9efbafd 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/adjust_gemm_copy_b_loop_ports.hpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/adjust_gemm_copy_b_loop_ports.hpp
@@ -4,8 +4,7 @@
#pragma once
-#include "snippets/lowered/loop_info.hpp"
-#include "snippets/lowered/pass/pass.hpp"
+#include "transformations/snippets/common/pass/lowered/adjust_copy_b_loop_ports.hpp"
namespace ov::intel_cpu::pass::aarch64 {
@@ -16,18 +15,18 @@ namespace ov::intel_cpu::pass::aarch64 {
* Finds loop ports connected to GemmCopyB and sets appropriate pointer increments.
* @ingroup snippets
*/
-class AdjustGemmCopyBLoopPorts : public snippets::lowered::pass::ConstPass {
+class AdjustGemmCopyBLoopPorts : public ov::intel_cpu::pass::AdjustCopyBLoopPorts {
public:
- OPENVINO_RTTI("AdjustGemmCopyBLoopPorts", "", ConstPass)
+ OPENVINO_RTTI("AdjustGemmCopyBLoopPorts", "", AdjustCopyBLoopPorts)
AdjustGemmCopyBLoopPorts() = default;
- bool run(const snippets::lowered::LinearIR& linear_ir) override;
static bool update_loop_info(const snippets::lowered::UnifiedLoopInfoPtr& uni_loop_info);
- const std::unordered_set<snippets::lowered::UnifiedLoopInfoPtr>& get_affected_loops() {
- return m_affected_loops;
- }
private:
- std::unordered_set<snippets::lowered::UnifiedLoopInfoPtr> m_affected_loops;
+ bool is_target_expr(const snippets::lowered::ExpressionPtr& expr) const override;
+ snippets::lowered::ExpressionPtr get_copy_b_expr(const snippets::lowered::ExpressionPtr& gemm_expr) const override;
+ bool update_loop_info_impl(const snippets::lowered::UnifiedLoopInfoPtr& loop_info) const override;
+ const char* copy_b_not_found_message() const override;
+ const char* invalid_loop_config_message() const override;
};
} // namespace ov::intel_cpu::pass::aarch64
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/external_repacking_adjuster.cpp b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/external_repacking_adjuster.cpp
index e3d613b3b4c..8c1f91f255e 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/external_repacking_adjuster.cpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/external_repacking_adjuster.cpp
@@ -4,33 +4,34 @@
#include "external_repacking_adjuster.hpp"
+#include <algorithm>
#include <cstddef>
+#include <memory>
+#include "cpu_shape.h"
+#include "emitters/snippets/aarch64/kernel_executors/gemm_copy_b.hpp"
#include "emitters/snippets/cpu_runtime_configurator.hpp"
+#include "memory_desc/cpu_blocked_memory_desc.h"
#include "openvino/core/except.hpp"
#include "openvino/core/type.hpp"
#include "openvino/core/type/element_type.hpp"
-#include "openvino/itt.hpp"
-#include "snippets/itt.hpp"
#include "snippets/lowered/linear_ir.hpp"
-#include "snippets/lowered/pass/runtime_optimizer.hpp"
#include "snippets/shape_types.hpp"
#include "snippets/utils/utils.hpp"
#include "transformations/snippets/aarch64/op/gemm_utils.hpp"
+#include "transformations/snippets/common/pass/lowered/external_repacking_adjuster.hpp"
namespace ov::intel_cpu::pass::aarch64 {
namespace {
-ov::snippets::VectorDims get_repacked_offsets(const ov::snippets::VectorDims& planar_shape,
- size_t target_rank,
+ov::snippets::VectorDims get_allocation_shape(const ov::snippets::VectorDims& planar_shape,
const ov::element::Type& precision) {
OPENVINO_ASSERT(planar_shape.size() >= 2, "GEMM weights must have rank >= 2");
- OPENVINO_ASSERT(target_rank >= planar_shape.size(), "Incorrect target rank for repacked GEMM weights offsets");
const auto K = *++planar_shape.rbegin();
const auto N = *planar_shape.rbegin();
OPENVINO_ASSERT(!ov::snippets::utils::is_dynamic_value(N) && !ov::snippets::utils::is_dynamic_value(K),
- "N and K shape should not be dynamic for pre-packed aarch64 GEMM weights");
+ "N and K shape should not be dynamic for repacked aarch64 GEMM weights");
const auto packed_bytes = ov::intel_cpu::aarch64::gemm_utils::repacking::get_rhs_packed_size(precision, N, K);
OPENVINO_ASSERT(packed_bytes % precision.size() == 0, "Unexpected packed weights byte size alignment");
@@ -38,7 +39,14 @@ ov::snippets::VectorDims get_repacked_offsets(const ov::snippets::VectorDims& pl
auto allocation_shape = planar_shape;
allocation_shape[allocation_shape.size() - 2] = 1;
allocation_shape[allocation_shape.size() - 1] = packed_bytes / precision.size();
+ return allocation_shape;
+}
+ov::snippets::VectorDims get_repacked_offsets(const ov::snippets::VectorDims& planar_shape,
+ size_t target_rank,
+ const ov::element::Type& precision) {
+ const auto allocation_shape = get_allocation_shape(planar_shape, precision);
+ OPENVINO_ASSERT(target_rank >= allocation_shape.size(), "Incorrect target rank for repacked GEMM weights offsets");
ov::snippets::VectorDims shape_for_offset(target_rank - allocation_shape.size(), 1);
shape_for_offset.insert(shape_for_offset.end(), allocation_shape.begin(), allocation_shape.end());
@@ -49,32 +57,121 @@ ov::snippets::VectorDims get_repacked_offsets(const ov::snippets::VectorDims& pl
} // namespace
+const size_t GemmExternalRepackingAdjuster::gemm_kernel_rank = 2;
+
GemmExternalRepackingAdjuster::GemmExternalRepackingAdjuster(const ov::snippets::lowered::LinearIRCPtr& linear_ir,
const CPURuntimeConfigurator* configurator)
- : ov::snippets::lowered::pass::RuntimeOptimizer(configurator) {
+ : ExternalRepackingAdjusterBase(configurator, "Snippets::GemmExternalRepackingAdjuster") {
const auto& cpu_config = ov::as_type_ptr<CPURuntimeConfig>(m_configurator->get_config());
+ const auto& input_repackers = cpu_config->input_repackers;
const auto& params = linear_ir->get_parameters();
- for (const auto& [idx, input_repacker] : cpu_config->input_repackers) {
+ for (const auto& [idx, input_repacker] : input_repackers) {
OPENVINO_ASSERT(idx < params.size(), "Incorrect index of repacked input");
- OPENVINO_ASSERT(input_repacker.already_repacked(), "Runtime aarch64 GEMM weights repacking is not supported");
- m_repacked_inputs.push_back(idx);
+ register_repacked_input(idx, !input_repacker.already_repacked());
}
}
-bool GemmExternalRepackingAdjuster::run(const snippets::lowered::LinearIR& linear_ir) {
- OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::GemmExternalRepackingAdjuster")
- const auto& cpu_config = ov::as_type_ptr<CPURuntimeConfig>(m_configurator->get_config());
- for (const auto idx : m_repacked_inputs) {
- const auto& shape = cpu_config->io_shapes[idx];
- const auto& layout = cpu_config->io_layouts[idx];
- const auto& precision = linear_ir.get_parameters()[idx]->get_node()->get_output_element_type(0);
- const auto planar_shape = ov::snippets::utils::get_planar_vdims(shape, layout);
-
- cpu_config->io_data_offsets[idx] =
- get_repacked_offsets(planar_shape, cpu_config->io_data_offsets[idx].size(), precision);
- cpu_config->input_repackers.erase(idx);
+CpuBlockedMemoryDescPtr GemmExternalRepackingAdjuster::get_desc(const ov::snippets::VectorDims& planar_shape,
+ const ov::element::Type& prc) {
+ const auto allocation_shape = get_allocation_shape(planar_shape, prc);
+ const auto blocked_order = ov::snippets::utils::get_planar_layout(allocation_shape.size());
+ return std::make_shared<CpuBlockedMemoryDesc>(prc, Shape(planar_shape), allocation_shape, blocked_order);
+}
+
+void GemmExternalRepackingAdjuster::update_kernel(const RepackExecutorPtr& executor,
+ const ov::snippets::VectorDims& shape,
+ const ov::snippets::VectorDims& layout,
+ size_t N,
+ size_t K,
+ const ov::element::Type& prc) {
+ OPENVINO_ASSERT(executor, "Input marked for runtime repacking has no executor");
+ OPENVINO_ASSERT(!ov::snippets::utils::is_dynamic_value(N) && !ov::snippets::utils::is_dynamic_value(K),
+ "N and K shape should not be dynamic at GemmExternalRepackingAdjuster update kernel stage.");
+
+ const auto row_stride_bytes = ov::snippets::utils::get_dim_in_stride(shape, layout, 1) * prc.size();
+ const auto col_stride_bytes = ov::snippets::utils::get_dim_in_stride(shape, layout, 0) * prc.size();
+ const auto is_transposed = ov::snippets::utils::get_input_dim_idx(layout, 0) != layout.size() - 1;
+
+ auto config = executor->get_config();
+ config.update(N, K, row_stride_bytes, col_stride_bytes, is_transposed);
+ executor->update_by_config(config);
+}
+
+GemmExternalRepackingAdjuster::RepackExecutorPtr GemmExternalRepackingAdjuster::create_executor(
+ const ov::element::Type& prc) {
+ return std::make_shared<ov::intel_cpu::aarch64::GemmCopyBKernel>(prc);
+}
+
+size_t GemmExternalRepackingAdjuster::update_runtime_repacking_data_size(const snippets::lowered::LinearIR& linear_ir,
+ const CPURuntimeConfig& cpu_config,
+ size_t idx) {
+ const auto& shape = cpu_config.io_shapes[idx];
+ const auto& layout = cpu_config.io_layouts[idx];
+ const auto& prc = linear_ir.get_parameters()[idx]->get_node()->get_output_element_type(0);
+ const auto planar_shape = ov::snippets::utils::get_planar_vdims(shape, layout);
+ const auto& K = *++planar_shape.rbegin();
+ const auto& N = *planar_shape.rbegin();
+
+ const auto packed_bytes = ov::intel_cpu::aarch64::gemm_utils::repacking::get_rhs_packed_size(prc, N, K);
+ const auto src_data = N * K * prc.size();
+ return src_data + packed_bytes;
+}
+
+void GemmExternalRepackingAdjuster::update_runtime_repacking_input(const snippets::lowered::LinearIR& linear_ir,
+ CPURuntimeConfig& cpu_config,
+ size_t i,
+ bool is_impl_parallel) {
+ const auto& shape = cpu_config.io_shapes[i];
+ const auto& layout = cpu_config.io_layouts[i];
+ auto& input_repacker = cpu_config.input_repackers[i];
+
+ const auto& prc = linear_ir.get_parameters()[i]->get_node()->get_output_element_type(0);
+ auto planar_shape = ov::snippets::utils::get_planar_vdims(shape, layout);
+ const auto& K = *++planar_shape.rbegin();
+ const auto& N = *planar_shape.rbegin();
+ const auto executor = create_executor(prc);
+ update_kernel(executor, shape, layout, N, K, prc);
+
+ // In parallel impl, each thread needs buffer with only inner shape to store repacking data.
+ if (is_impl_parallel) {
+ const auto batch_count = planar_shape.size() - gemm_kernel_rank;
+ std::fill(planar_shape.begin(), planar_shape.begin() + batch_count, 1);
}
- return true;
+
+ const auto dst_desc = get_desc(planar_shape, prc);
+
+ // Save original input offsets for input before repacking.
+ // If the shape has not been changed, it means that we already created `InputRepacker` for this input
+ // on previous pass call and now `cpu_config.io_data_offsets[i]` contains offsets not for original input -
+ // they were updated for packed shapes/zeroed for previous initialization and we cannot use them as original
+ // offsets.
+ const auto in_offsets =
+ shape == cpu_config.latest_shapes[i] ? input_repacker.in_offsets() : cpu_config.io_data_offsets[i];
+
+ // In parallel case Kernel should not add offsets to repacked inputs because
+ // they will be applied during repacking in execution stage.
+ if (is_impl_parallel) {
+ auto& offsets = cpu_config.io_data_offsets[i];
+ std::fill(offsets.begin(), offsets.end(), 0);
+ } else {
+ cpu_config.io_data_offsets[i] = get_repacked_offsets(planar_shape, in_offsets.size(), prc);
+ }
+ const auto out_offsets = cpu_config.io_data_offsets[i];
+
+ input_repacker = InputRepacker(executor, dst_desc, in_offsets, out_offsets);
+}
+
+void GemmExternalRepackingAdjuster::update_compile_time_repacked_input(const snippets::lowered::LinearIR& linear_ir,
+ CPURuntimeConfig& cpu_config,
+ size_t idx) {
+ const auto& shape = cpu_config.io_shapes[idx];
+ const auto& layout = cpu_config.io_layouts[idx];
+ const auto& precision = linear_ir.get_parameters()[idx]->get_node()->get_output_element_type(0);
+ const auto planar_shape = ov::snippets::utils::get_planar_vdims(shape, layout);
+
+ cpu_config.io_data_offsets[idx] =
+ get_repacked_offsets(planar_shape, cpu_config.io_data_offsets[idx].size(), precision);
+ cpu_config.input_repackers.erase(idx);
}
} // namespace ov::intel_cpu::pass::aarch64
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/external_repacking_adjuster.hpp b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/external_repacking_adjuster.hpp
index 18aa9cf1b78..096249996f9 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/external_repacking_adjuster.hpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/lowered/external_repacking_adjuster.hpp
@@ -5,33 +5,57 @@
#pragma once
#include <cstddef>
+#include <memory>
+#include <unordered_map>
#include <vector>
+#include "emitters/snippets/aarch64/kernel_executors/gemm_copy_b.hpp"
#include "emitters/snippets/cpu_runtime_configurator.hpp"
+#include "memory_desc/cpu_blocked_memory_desc.h"
#include "openvino/core/rtti.hpp"
+#include "openvino/core/type/element_type.hpp"
#include "snippets/lowered/linear_ir.hpp"
-#include "snippets/lowered/pass/runtime_optimizer.hpp"
+#include "transformations/snippets/common/pass/lowered/external_repacking_adjuster.hpp"
namespace ov::intel_cpu::pass::aarch64 {
/**
* @class GemmExternalRepackingAdjuster
- * @brief A runtime optimizer that adjusts input offsets for aarch64 GEMM inputs pre-packed at compile time.
+ * @brief A runtime optimizer that configures external repacking for aarch64 GEMM inputs.
*/
-class GemmExternalRepackingAdjuster : public ov::snippets::lowered::pass::RuntimeOptimizer {
+class GemmExternalRepackingAdjuster : public ov::intel_cpu::pass::ExternalRepackingAdjusterBase {
public:
- OPENVINO_RTTI("GemmExternalRepackingAdjuster", "", RuntimeOptimizer)
+ OPENVINO_RTTI("GemmExternalRepackingAdjuster", "", ExternalRepackingAdjusterBase)
GemmExternalRepackingAdjuster() = default;
GemmExternalRepackingAdjuster(const ov::snippets::lowered::LinearIRCPtr& linear_ir,
const CPURuntimeConfigurator* configurator);
- bool run(const snippets::lowered::LinearIR& linear_ir) override;
- bool applicable() const override {
- return !m_repacked_inputs.empty();
- }
-
private:
- std::vector<size_t> m_repacked_inputs;
+ using RepackExecutorPtr = std::shared_ptr<ov::intel_cpu::aarch64::GemmCopyBKernel>;
+
+ size_t update_runtime_repacking_data_size(const snippets::lowered::LinearIR& linear_ir,
+ const CPURuntimeConfig& cpu_config,
+ size_t idx) override;
+ void update_runtime_repacking_input(const snippets::lowered::LinearIR& linear_ir,
+ CPURuntimeConfig& cpu_config,
+ size_t idx,
+ bool is_impl_parallel) override;
+ void update_compile_time_repacked_input(const snippets::lowered::LinearIR& linear_ir,
+ CPURuntimeConfig& cpu_config,
+ size_t idx) override;
+
+ static CpuBlockedMemoryDescPtr get_desc(const ov::snippets::VectorDims& planar_shape, const ov::element::Type& prc);
+
+ static void update_kernel(const RepackExecutorPtr& executor,
+ const ov::snippets::VectorDims& shape,
+ const ov::snippets::VectorDims& layout,
+ size_t N,
+ size_t K,
+ const ov::element::Type& prc);
+
+ static RepackExecutorPtr create_executor(const ov::element::Type& prc);
+
+ static const size_t gemm_kernel_rank;
};
} // namespace ov::intel_cpu::pass::aarch64
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/repack_matmul_weights.cpp b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/repack_matmul_weights.cpp
index ba9c02bc460..211dfd85e27 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/repack_matmul_weights.cpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/repack_matmul_weights.cpp
@@ -10,7 +10,6 @@
#include <functional>
#include <memory>
#include <numeric>
-#include <optional>
#include <vector>
#include "cpu_memory.h"
@@ -213,7 +212,7 @@ MemoryPtr prepare_weights_memory(const GraphContext::CPtr& context,
} // namespace
-std::optional<RepackMatMulWeights::RepackedMatMulWeights> RepackMatMulWeights::repack(
+RepackMatMulWeights::RepackedMatMulWeights RepackMatMulWeights::repack(
const std::shared_ptr<ov::Node>& consumer,
const RepackMatMulWeights::MatMulWeightsSource& source,
const MemoryPtr& orig_src_mem_ptr) {
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/repack_matmul_weights.hpp b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/repack_matmul_weights.hpp
index 37a39dbb569..a8e1cbc8f28 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/repack_matmul_weights.hpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/aarch64/pass/repack_matmul_weights.hpp
@@ -5,7 +5,7 @@
#pragma once
#include <memory>
-#include <optional>
+#include <set>
#include <utility>
#include <vector>
@@ -25,16 +25,17 @@ public:
OPENVINO_MODEL_PASS_RTTI("RepackMatMulWeights");
RepackMatMulWeights(GraphContext::CPtr context,
ov::intel_cpu::InputRepackerMap& input_repackers,
- std::vector<MemoryPtr>& src_mem_ptrs)
- : ov::intel_cpu::pass::RepackMatMulWeights(std::move(context), input_repackers, src_mem_ptrs) {}
+ std::vector<MemoryPtr>& src_mem_ptrs,
+ std::set<size_t> compile_time_repacking_idxs)
+ : ov::intel_cpu::pass::RepackMatMulWeights(std::move(context),
+ input_repackers,
+ src_mem_ptrs,
+ std::move(compile_time_repacking_idxs)) {}
private:
- [[nodiscard]] std::optional<RepackedMatMulWeights> repack(const std::shared_ptr<ov::Node>& consumer,
- const MatMulWeightsSource& source,
- const MemoryPtr& orig_src_mem_ptr) override;
- [[nodiscard]] bool supports_runtime_repacking() const override {
- return false;
- }
+ [[nodiscard]] RepackedMatMulWeights repack(const std::shared_ptr<ov::Node>& consumer,
+ const MatMulWeightsSource& source,
+ const MemoryPtr& orig_src_mem_ptr) override;
};
} // namespace ov::intel_cpu::pass::aarch64
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/common/pass/eliminate_copy_b.cpp b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/eliminate_copy_b.cpp
index 3e1f55f54aa..2842a3ad2bb 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/common/pass/eliminate_copy_b.cpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/eliminate_copy_b.cpp
@@ -26,10 +26,6 @@
namespace ov::intel_cpu {
-bool pass::EliminateCopyB::should_extract(size_t param_idx) const {
- return m_runtime_repacking_supported || m_compile_time_repacking_idxs.count(param_idx) > 0;
-}
-
bool pass::EliminateCopyB::run_on_model(const std::shared_ptr<ov::Model>& model) {
RUN_ON_MODEL_SCOPE(EliminateCopyB);
OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "ov::intel_cpu::pass::EliminateCopyB")
@@ -57,10 +53,6 @@ bool pass::EliminateCopyB::run_on_model(const std::shared_ptr<ov::Model>& model)
const auto param_idx = static_cast<size_t>(model->get_parameter_index(param));
OPENVINO_ASSERT(param_idx < model->get_parameters().size(),
"Parameter index is invalid in EliminateCopyB transformation");
- if (!should_extract(param_idx)) {
- continue;
- }
-
const auto& in_desc = snippets::lowered::PortDescriptorUtils::get_port_descriptor_ptr(copy_b_node->input(0));
const auto& layout = in_desc->get_layout();
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/common/pass/eliminate_copy_b.hpp b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/eliminate_copy_b.hpp
index 67479c2a930..17a89df2f3e 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/common/pass/eliminate_copy_b.hpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/eliminate_copy_b.hpp
@@ -6,8 +6,6 @@
#include <cstddef>
#include <memory>
-#include <set>
-#include <utility>
#include "emitters/snippets/input_repacker.hpp"
#include "openvino/core/model.hpp"
@@ -30,22 +28,14 @@ public:
bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
protected:
- EliminateCopyB(ov::intel_cpu::InputRepackerMap& input_repackers,
- bool runtime_repacking_supported,
- std::set<size_t> compile_time_repacking_idxs)
- : m_input_repackers(input_repackers),
- m_runtime_repacking_supported(runtime_repacking_supported),
- m_compile_time_repacking_idxs(std::move(compile_time_repacking_idxs)) {}
+ explicit EliminateCopyB(ov::intel_cpu::InputRepackerMap& input_repackers) : m_input_repackers(input_repackers) {}
private:
[[nodiscard]] virtual std::shared_ptr<ov::Node> get_copy_b_pattern(
const std::shared_ptr<ov::Node>& input) const = 0;
[[nodiscard]] virtual bool is_supported_copy_b(const std::shared_ptr<ov::Node>& node) const = 0;
- [[nodiscard]] bool should_extract(size_t param_idx) const;
ov::intel_cpu::InputRepackerMap& m_input_repackers;
- bool m_runtime_repacking_supported = false;
- std::set<size_t> m_compile_time_repacking_idxs;
};
} // namespace ov::intel_cpu::pass
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/common/pass/lowered/adjust_copy_b_loop_ports.cpp b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/lowered/adjust_copy_b_loop_ports.cpp
new file mode 100644
index 00000000000..7cd7d2d9f1e
--- /dev/null
+++ b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/lowered/adjust_copy_b_loop_ports.cpp
@@ -0,0 +1,79 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "adjust_copy_b_loop_ports.hpp"
+
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <unordered_set>
+#include <vector>
+
+#include "openvino/core/except.hpp"
+#include "openvino/core/type.hpp"
+#include "openvino/op/parameter.hpp"
+#include "snippets/lowered/expression.hpp"
+#include "snippets/lowered/linear_ir.hpp"
+#include "snippets/lowered/loop_info.hpp"
+#include "snippets/lowered/loop_manager.hpp"
+#include "snippets/utils/utils.hpp"
+#include "utils/general_utils.h"
+
+namespace ov::intel_cpu::pass {
+
+void AdjustCopyBLoopPorts::assign_new_ptr_increment(int64_t new_ptr_increment,
+ snippets::lowered::UnifiedLoopInfo::LoopPortDesc& loop_desc) {
+ const auto old_ptr_incr = loop_desc.ptr_increment;
+ const auto old_final_offset = loop_desc.finalization_offset;
+
+ if (none_of(old_ptr_incr, 0, new_ptr_increment)) {
+ loop_desc.ptr_increment = new_ptr_increment;
+ if (!ov::snippets::utils::is_dynamic_value(old_final_offset)) {
+ OPENVINO_ASSERT(old_final_offset % old_ptr_incr == 0, "Can't rescale finalization offsets");
+ loop_desc.finalization_offset =
+ ov::snippets::utils::dynamic_safe_mul(loop_desc.ptr_increment, (old_final_offset / old_ptr_incr));
+ }
+ }
+}
+
+bool AdjustCopyBLoopPorts::run(const snippets::lowered::LinearIR& linear_ir) {
+ bool modified = false;
+ for (const auto& expr : linear_ir) {
+ if (!is_target_expr(expr)) {
+ continue;
+ }
+
+ const auto& gemm_loop_ids = expr->get_loop_ids();
+ const auto& gemm_in1 = expr->get_input_port_connector(1)->get_source();
+ const auto& shape_infer_seq = ov::snippets::utils::get_first_parent_shape_infer_expr_seq(gemm_in1.get_expr());
+ const auto source =
+ shape_infer_seq.empty() ? gemm_in1 : shape_infer_seq.back()->get_input_port_connector(0)->get_source();
+ std::vector<size_t> repacking_loop_ids;
+ if (!is_type<ov::op::v0::Parameter>(source.get_expr()->get_node())) {
+ const auto repacking_expr = get_copy_b_expr(expr);
+ OPENVINO_ASSERT(repacking_expr, copy_b_not_found_message());
+ repacking_loop_ids = repacking_expr->get_loop_ids();
+ }
+ if (gemm_loop_ids.empty() && repacking_loop_ids.empty()) {
+ continue;
+ }
+
+ OPENVINO_ASSERT(gemm_loop_ids.size() > repacking_loop_ids.size(), invalid_loop_config_message());
+ const snippets::lowered::LoopManagerPtr& loop_manager = linear_ir.get_loop_manager();
+ for (auto i = repacking_loop_ids.size(); i < gemm_loop_ids.size(); i++) {
+ const auto& loop = loop_manager->get_loop_info(gemm_loop_ids[i]);
+ auto uni_loop = ov::as_type_ptr<snippets::lowered::UnifiedLoopInfo>(loop);
+ if (!uni_loop) {
+ uni_loop = ov::as_type_ptr<snippets::lowered::ExpandedLoopInfo>(loop)->get_unified_loop_info();
+ }
+ if (!m_affected_loops.count(uni_loop) && update_loop_info_impl(uni_loop)) {
+ m_affected_loops.insert(uni_loop);
+ modified = true;
+ }
+ }
+ }
+ return modified;
+}
+
+} // namespace ov::intel_cpu::pass
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/common/pass/lowered/adjust_copy_b_loop_ports.hpp b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/lowered/adjust_copy_b_loop_ports.hpp
new file mode 100644
index 00000000000..c54225667b5
--- /dev/null
+++ b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/lowered/adjust_copy_b_loop_ports.hpp
@@ -0,0 +1,50 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstdint>
+#include <memory>
+#include <string>
+#include <unordered_set>
+#include <vector>
+
+#include "snippets/lowered/expression.hpp"
+#include "snippets/lowered/linear_ir.hpp"
+#include "snippets/lowered/loop_info.hpp"
+#include "snippets/lowered/pass/pass.hpp"
+
+namespace ov::intel_cpu::pass {
+
+/**
+ * @brief Base pass for adjusting loop ports after CopyB extraction.
+ */
+class AdjustCopyBLoopPorts : public snippets::lowered::pass::ConstPass {
+public:
+ bool run(const snippets::lowered::LinearIR& linear_ir) override;
+
+ const std::unordered_set<snippets::lowered::UnifiedLoopInfoPtr>& get_affected_loops() const {
+ return m_affected_loops;
+ }
+
+protected:
+ static void assign_new_ptr_increment(int64_t new_ptr_increment,
+ snippets::lowered::UnifiedLoopInfo::LoopPortDesc& loop_desc);
+ /// Returns true when @p expr is a backend MatMul operation that needs CopyB loop port adjustment.
+ virtual bool is_target_expr(const snippets::lowered::ExpressionPtr& expr) const = 0;
+ /// Returns the CopyB expression that supplies the weights for @p gemm_expr.
+ virtual snippets::lowered::ExpressionPtr get_copy_b_expr(
+ const snippets::lowered::ExpressionPtr& gemm_expr) const = 0;
+ /// Adjusts all affected ports in @p loop_info for the backend layout.
+ virtual bool update_loop_info_impl(const snippets::lowered::UnifiedLoopInfoPtr& loop_info) const = 0;
+ /// Returns the diagnostic used when the expected CopyB expression is absent.
+ virtual const char* copy_b_not_found_message() const = 0;
+ /// Returns the diagnostic used for invalid MatMul and CopyB loop nesting.
+ virtual const char* invalid_loop_config_message() const = 0;
+
+private:
+ std::unordered_set<snippets::lowered::UnifiedLoopInfoPtr> m_affected_loops;
+};
+
+} // namespace ov::intel_cpu::pass
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/common/pass/lowered/external_repacking_adjuster.cpp b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/lowered/external_repacking_adjuster.cpp
new file mode 100644
index 00000000000..23f6b0c41ba
--- /dev/null
+++ b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/lowered/external_repacking_adjuster.cpp
@@ -0,0 +1,65 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "external_repacking_adjuster.hpp"
+
+#include <cstddef>
+#include <string>
+#include <utility>
+
+#include "emitters/snippets/cpu_runtime_configurator.hpp"
+#include "onednn/dnnl.h"
+#include "openvino/core/type.hpp"
+#include "openvino/itt.hpp"
+#include "snippets/itt.hpp"
+#include "snippets/lowered/linear_ir.hpp"
+#include "snippets/lowered/pass/runtime_optimizer.hpp"
+
+namespace ov::intel_cpu::pass {
+
+ExternalRepackingAdjusterBase::ExternalRepackingAdjusterBase(const CPURuntimeConfigurator* configurator,
+ std::string itt_name)
+ : ov::snippets::lowered::pass::RuntimeOptimizer(configurator),
+ m_itt_name(std::move(itt_name)) {}
+
+void ExternalRepackingAdjusterBase::register_repacked_input(size_t idx, bool needs_runtime_repacking) {
+ m_repacked_inputs.emplace(idx, needs_runtime_repacking);
+}
+
+bool ExternalRepackingAdjusterBase::run(const snippets::lowered::LinearIR& linear_ir) {
+ OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, m_itt_name.c_str())
+ const auto& cpu_config = ov::as_type_ptr<CPURuntimeConfig>(m_configurator->get_config());
+
+ size_t data_size = 0;
+ bool has_runtime_repacking = false;
+ for (const auto& [idx, needs_runtime_repacking] : m_repacked_inputs) {
+ if (!needs_runtime_repacking) {
+ continue;
+ }
+ has_runtime_repacking = true;
+ data_size += update_runtime_repacking_data_size(linear_ir, *cpu_config, idx);
+ }
+
+ if (!has_runtime_repacking) {
+ cpu_config->repacking_impl_type = CPURuntimeConfig::RepackingImplType::NONE;
+ } else {
+ const auto cache_size = dnnl::utils::get_cache_size(1, true) + dnnl::utils::get_cache_size(2, true);
+ const auto fit_into_cache = data_size < cache_size;
+ cpu_config->repacking_impl_type = fit_into_cache ? CPURuntimeConfig::RepackingImplType::IN_PARALLEL
+ : CPURuntimeConfig::RepackingImplType::SEPARATE;
+ }
+
+ const auto is_impl_parallel = cpu_config->repacking_impl_type == CPURuntimeConfig::RepackingImplType::IN_PARALLEL;
+ for (const auto& [idx, needs_runtime_repacking] : m_repacked_inputs) {
+ if (needs_runtime_repacking) {
+ update_runtime_repacking_input(linear_ir, *cpu_config, idx, is_impl_parallel);
+ } else {
+ update_compile_time_repacked_input(linear_ir, *cpu_config, idx);
+ }
+ }
+
+ return true;
+}
+
+} // namespace ov::intel_cpu::pass
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/common/pass/lowered/external_repacking_adjuster.hpp b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/lowered/external_repacking_adjuster.hpp
new file mode 100644
index 00000000000..fe7e3ba9956
--- /dev/null
+++ b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/lowered/external_repacking_adjuster.hpp
@@ -0,0 +1,50 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cstddef>
+#include <string>
+#include <unordered_map>
+
+#include "emitters/snippets/cpu_runtime_configurator.hpp"
+#include "snippets/lowered/linear_ir.hpp"
+#include "snippets/lowered/pass/runtime_optimizer.hpp"
+
+namespace ov::intel_cpu::pass {
+
+class ExternalRepackingAdjusterBase : public ov::snippets::lowered::pass::RuntimeOptimizer {
+public:
+ bool run(const snippets::lowered::LinearIR& linear_ir) override;
+ bool applicable() const override {
+ return !m_repacked_inputs.empty();
+ }
+
+protected:
+ ExternalRepackingAdjusterBase() = default;
+ ExternalRepackingAdjusterBase(const CPURuntimeConfigurator* configurator, std::string itt_name);
+
+ /// Registers an externally repacked input and whether it needs repacking at runtime.
+ void register_repacked_input(size_t idx, bool needs_runtime_repacking);
+
+private:
+ /// Returns the runtime buffer size required to repack input @p idx.
+ virtual size_t update_runtime_repacking_data_size(const snippets::lowered::LinearIR& linear_ir,
+ const CPURuntimeConfig& cpu_config,
+ size_t idx) = 0;
+ /// Updates runtime configuration for input @p idx that is repacked during execution.
+ virtual void update_runtime_repacking_input(const snippets::lowered::LinearIR& linear_ir,
+ CPURuntimeConfig& cpu_config,
+ size_t idx,
+ bool is_impl_parallel) = 0;
+ /// Updates runtime configuration for input @p idx that was repacked during compilation.
+ virtual void update_compile_time_repacked_input(const snippets::lowered::LinearIR& linear_ir,
+ CPURuntimeConfig& cpu_config,
+ size_t idx) = 0;
+
+ std::string m_itt_name;
+ std::unordered_map<size_t, bool> m_repacked_inputs;
+};
+
+} // namespace ov::intel_cpu::pass
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/common/pass/repack_matmul_weights.cpp b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/repack_matmul_weights.cpp
index fceecb9e096..32265c6aba5 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/common/pass/repack_matmul_weights.cpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/repack_matmul_weights.cpp
@@ -58,6 +58,9 @@ bool RepackMatMulWeights::run_on_model(const std::shared_ptr<ov::Model>& model)
const auto i = repacker_entry.first;
OPENVINO_ASSERT(i < params.size(), "Incorrect index of externally repacked weights");
OPENVINO_ASSERT(i < m_src_mem_ptrs.size(), "Incorrect memory index of externally repacked weights");
+ if (!m_compile_time_repacking_idxs.count(i)) {
+ continue;
+ }
const auto& parameter = params[i];
const auto shape_infer_leaf = ov::snippets::utils::get_leaf_node_of_first_child_shape_infer_seq(parameter);
@@ -68,18 +71,9 @@ bool RepackMatMulWeights::run_on_model(const std::shared_ptr<ov::Model>& model)
const auto& orig_src_mem_ptr = m_src_mem_ptrs[i];
const auto repacked = repack(consumer, get_weights_source(consumer, orig_src_mem_ptr), orig_src_mem_ptr);
- if (!repacked) {
- OPENVINO_ASSERT(supports_runtime_repacking(),
- "Failed to repack weights input ",
- i,
- " for ",
- consumer->get_friendly_name(),
- ": runtime repacking is not supported");
- continue;
- }
- m_src_mem_ptrs[i] = repacked->memory;
- m_input_repackers[i] = InputRepacker(nullptr, repacked->desc, {}, {});
+ m_src_mem_ptrs[i] = repacked.memory;
+ m_input_repackers[i] = InputRepacker(nullptr, repacked.desc, {}, {});
weights_idxs.insert(i);
}
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/common/pass/repack_matmul_weights.hpp b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/repack_matmul_weights.hpp
index e49b7f98fdc..4806d1fb383 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/common/pass/repack_matmul_weights.hpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/common/pass/repack_matmul_weights.hpp
@@ -5,7 +5,7 @@
#pragma once
#include <memory>
-#include <optional>
+#include <set>
#include <utility>
#include <vector>
@@ -29,10 +29,12 @@ public:
OPENVINO_MODEL_PASS_RTTI("RepackMatMulWeights");
RepackMatMulWeights(GraphContext::CPtr context,
ov::intel_cpu::InputRepackerMap& input_repackers,
- std::vector<MemoryPtr>& src_mem_ptrs)
+ std::vector<MemoryPtr>& src_mem_ptrs,
+ std::set<size_t> compile_time_repacking_idxs)
: m_context(std::move(context)),
m_input_repackers(input_repackers),
- m_src_mem_ptrs(src_mem_ptrs) {}
+ m_src_mem_ptrs(src_mem_ptrs),
+ m_compile_time_repacking_idxs(std::move(compile_time_repacking_idxs)) {}
bool run_on_model(const std::shared_ptr<ov::Model>& model) override;
@@ -58,18 +60,16 @@ protected:
* @param source Logical weights shape and layout after CopyB extraction. When extraction inserts a graph Reorder,
* this metadata is not recoverable from @p orig_src_mem_ptr alone.
* @param orig_src_mem_ptr Original constant weights memory buffer.
- * @return Repacked weights memory with its CPU descriptor, or std::nullopt when this consumer cannot be repacked.
+ * @return Repacked weights memory with its CPU descriptor.
*/
- [[nodiscard]] virtual std::optional<RepackedMatMulWeights> repack(const std::shared_ptr<ov::Node>& consumer,
- const MatMulWeightsSource& source,
- const MemoryPtr& orig_src_mem_ptr) = 0;
- [[nodiscard]] virtual bool supports_runtime_repacking() const {
- return true;
- }
+ [[nodiscard]] virtual RepackedMatMulWeights repack(const std::shared_ptr<ov::Node>& consumer,
+ const MatMulWeightsSource& source,
+ const MemoryPtr& orig_src_mem_ptr) = 0;
const GraphContext::CPtr m_context;
ov::intel_cpu::InputRepackerMap& m_input_repackers;
std::vector<MemoryPtr>& m_src_mem_ptrs;
+ const std::set<size_t> m_compile_time_repacking_idxs;
};
} // namespace ov::intel_cpu::pass
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/eliminate_brgemm_copy_b.hpp b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/eliminate_brgemm_copy_b.hpp
index 7909e5845ef..a64081b5281 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/eliminate_brgemm_copy_b.hpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/eliminate_brgemm_copy_b.hpp
@@ -21,8 +21,7 @@ namespace ov::intel_cpu::pass::x64 {
class EliminateBrgemmCopyB : public ov::intel_cpu::pass::EliminateCopyB {
public:
OPENVINO_MODEL_PASS_RTTI("EliminateBrgemmCopyB");
- explicit EliminateBrgemmCopyB(ov::intel_cpu::InputRepackerMap& input_repackers)
- : EliminateCopyB(input_repackers, true, {}) {}
+ explicit EliminateBrgemmCopyB(ov::intel_cpu::InputRepackerMap& input_repackers) : EliminateCopyB(input_repackers) {}
private:
[[nodiscard]] std::shared_ptr<ov::Node> get_copy_b_pattern(const std::shared_ptr<ov::Node>& input) const override;
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/adjust_brgemm_copy_b_loop_ports.cpp b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/adjust_brgemm_copy_b_loop_ports.cpp
index 45e22cb67b2..8297007ceeb 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/adjust_brgemm_copy_b_loop_ports.cpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/adjust_brgemm_copy_b_loop_ports.cpp
@@ -4,45 +4,22 @@
#include "adjust_brgemm_copy_b_loop_ports.hpp"
-#include <cstddef>
#include <cstdint>
#include <memory>
-#include <vector>
#include "openvino/core/except.hpp"
#include "openvino/core/type.hpp"
#include "openvino/itt.hpp"
-#include "openvino/op/parameter.hpp"
#include "snippets/itt.hpp"
#include "snippets/lowered/expression.hpp"
-#include "snippets/lowered/linear_ir.hpp"
#include "snippets/lowered/loop_info.hpp"
-#include "snippets/lowered/loop_manager.hpp"
#include "snippets/lowered/loop_port.hpp"
#include "snippets/utils/utils.hpp"
#include "transformations/snippets/x64/op/brgemm_cpu.hpp"
#include "transformations/snippets/x64/op/brgemm_utils.hpp"
-#include "utils/general_utils.h"
namespace ov::intel_cpu {
-namespace {
-void assign_new_ptr_increment(int64_t new_ptr_increment,
- ov::snippets::lowered::UnifiedLoopInfo::LoopPortDesc& loop_desc) {
- const auto old_ptr_incr = loop_desc.ptr_increment;
- const auto old_final_offset = loop_desc.finalization_offset;
-
- if (none_of(old_ptr_incr, 0, new_ptr_increment)) {
- loop_desc.ptr_increment = new_ptr_increment;
- if (!ov::snippets::utils::is_dynamic_value(old_final_offset)) {
- OPENVINO_ASSERT(old_final_offset % old_ptr_incr == 0, "Can't rescale finalization offsets");
- loop_desc.finalization_offset =
- ov::snippets::utils::dynamic_safe_mul(loop_desc.ptr_increment, (old_final_offset / old_ptr_incr));
- }
- }
-}
-} // namespace
-
bool pass::AdjustBrgemmCopyBLoopPorts::update_loop_info(
const std::shared_ptr<snippets::lowered::UnifiedLoopInfo>& loop_info) {
OPENVINO_ASSERT(loop_info, "Invalid loop info pointer");
@@ -98,53 +75,26 @@ bool pass::AdjustBrgemmCopyBLoopPorts::update_loop_info(
return modified;
}
-bool pass::AdjustBrgemmCopyBLoopPorts::run(const snippets::lowered::LinearIR& linear_ir) {
- OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::AdjustBrgemmCopyBLoopPorts")
-
- bool modified = false;
+bool pass::AdjustBrgemmCopyBLoopPorts::is_target_expr(const snippets::lowered::ExpressionPtr& expr) const {
+ const auto brgemm = ov::as_type_ptr<BrgemmCPU>(expr->get_node());
+ return brgemm && brgemm->get_config().with_wei_repacking();
+}
- auto get_repacking_loop_idces = [](const snippets::lowered::ExpressionPtr& brgemm_expr) {
- // Repacking may be extracted outside the snippets kernel. In this case, brgemm parent expression is a
- // parameter.
- const auto& brgemm_in1 = brgemm_expr->get_input_port_connector(1)->get_source();
- const auto& shape_infer_seq = ov::snippets::utils::get_first_parent_shape_infer_expr_seq(brgemm_in1.get_expr());
- const auto source =
- shape_infer_seq.empty() ? brgemm_in1 : shape_infer_seq.back()->get_input_port_connector(0)->get_source();
- if (is_type<ov::op::v0::Parameter>(source.get_expr()->get_node())) {
- return std::vector<size_t>{};
- }
- const auto repacking_expr = brgemm_utils::repacking::get_copy_b_expr(brgemm_expr);
- OPENVINO_ASSERT(repacking_expr, "BrgemmCopyB expression is not found");
- return repacking_expr->get_loop_ids();
- };
+snippets::lowered::ExpressionPtr pass::AdjustBrgemmCopyBLoopPorts::get_copy_b_expr(
+ const snippets::lowered::ExpressionPtr& gemm_expr) const {
+ return brgemm_utils::repacking::get_copy_b_expr(gemm_expr);
+}
- for (const auto& expr : linear_ir) {
- const auto brgemm = ov::as_type_ptr<BrgemmCPU>(expr->get_node());
- if (!brgemm || !brgemm->get_config().with_wei_repacking()) {
- continue;
- }
- const auto& brgemm_loop_ids = expr->get_loop_ids();
- const auto& repacking_loop_ids = get_repacking_loop_idces(expr);
- // Continue if there is no blocking loop
- if (brgemm_loop_ids.empty() && repacking_loop_ids.empty()) {
- continue;
- }
+bool pass::AdjustBrgemmCopyBLoopPorts::update_loop_info_impl(
+ const snippets::lowered::UnifiedLoopInfoPtr& loop_info) const {
+ return update_loop_info(loop_info);
+}
- OPENVINO_ASSERT(brgemm_loop_ids.size() > repacking_loop_ids.size(), "Invalid BrgemmCopyB loop configuration");
- const snippets::lowered::LoopManagerPtr& loop_manager = linear_ir.get_loop_manager();
- for (auto i = repacking_loop_ids.size(); i < brgemm_loop_ids.size(); i++) {
- const auto& loop = loop_manager->get_loop_info(brgemm_loop_ids[i]);
- auto uni_loop = ov::as_type_ptr<snippets::lowered::UnifiedLoopInfo>(loop);
- if (!uni_loop) {
- uni_loop = ov::as_type_ptr<snippets::lowered::ExpandedLoopInfo>(loop)->get_unified_loop_info();
- }
- if (!m_affected_loops.count(uni_loop) && update_loop_info(uni_loop)) {
- m_affected_loops.insert(uni_loop);
- modified = true;
- }
- }
- }
+const char* pass::AdjustBrgemmCopyBLoopPorts::copy_b_not_found_message() const {
+ return "BrgemmCopyB expression is not found";
+}
- return modified;
+const char* pass::AdjustBrgemmCopyBLoopPorts::invalid_loop_config_message() const {
+ return "Invalid BrgemmCopyB loop configuration";
}
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/adjust_brgemm_copy_b_loop_ports.hpp b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/adjust_brgemm_copy_b_loop_ports.hpp
index b5e111ff33c..5dd1faab166 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/adjust_brgemm_copy_b_loop_ports.hpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/adjust_brgemm_copy_b_loop_ports.hpp
@@ -4,12 +4,9 @@
#pragma once
-#include <unordered_set>
-
#include "openvino/core/rtti.hpp"
-#include "snippets/lowered/linear_ir.hpp"
#include "snippets/lowered/loop_info.hpp"
-#include "snippets/lowered/pass/pass.hpp"
+#include "transformations/snippets/common/pass/lowered/adjust_copy_b_loop_ports.hpp"
namespace ov::intel_cpu::pass {
@@ -20,18 +17,18 @@ namespace ov::intel_cpu::pass {
* Finds loop ports connected to BrgemmCopyB and sets appropriate pointer increments.
* @ingroup snippets
*/
-class AdjustBrgemmCopyBLoopPorts : public snippets::lowered::pass::ConstPass {
+class AdjustBrgemmCopyBLoopPorts : public AdjustCopyBLoopPorts {
public:
- OPENVINO_RTTI("AdjustBrgemmCopyBLoopPorts", "", ConstPass)
+ OPENVINO_RTTI("AdjustBrgemmCopyBLoopPorts", "", AdjustCopyBLoopPorts)
AdjustBrgemmCopyBLoopPorts() = default;
- bool run(const snippets::lowered::LinearIR& linear_ir) override;
static bool update_loop_info(const snippets::lowered::UnifiedLoopInfoPtr& uni_loop_info);
- const std::unordered_set<snippets::lowered::UnifiedLoopInfoPtr>& get_affected_loops() {
- return m_affected_loops;
- }
private:
- std::unordered_set<snippets::lowered::UnifiedLoopInfoPtr> m_affected_loops;
+ bool is_target_expr(const snippets::lowered::ExpressionPtr& expr) const override;
+ snippets::lowered::ExpressionPtr get_copy_b_expr(const snippets::lowered::ExpressionPtr& gemm_expr) const override;
+ bool update_loop_info_impl(const snippets::lowered::UnifiedLoopInfoPtr& loop_info) const override;
+ const char* copy_b_not_found_message() const override;
+ const char* invalid_loop_config_message() const override;
};
} // namespace ov::intel_cpu::pass
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/external_repacking_adjuster.cpp b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/external_repacking_adjuster.cpp
index a9f870367cd..d7ce4a46e58 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/external_repacking_adjuster.cpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/external_repacking_adjuster.cpp
@@ -20,17 +20,14 @@
#include "emitters/snippets/cpu_runtime_configurator.hpp"
#include "emitters/snippets/x64/kernel_executors/brgemm_copy_b.hpp"
#include "memory_desc/cpu_blocked_memory_desc.h"
-#include "onednn/dnnl.h"
#include "openvino/core/except.hpp"
#include "openvino/core/type.hpp"
#include "openvino/core/type/element_type.hpp"
-#include "openvino/itt.hpp"
-#include "snippets/itt.hpp"
#include "snippets/lowered/expression.hpp"
#include "snippets/lowered/linear_ir.hpp"
-#include "snippets/lowered/pass/runtime_optimizer.hpp"
#include "snippets/shape_types.hpp"
#include "snippets/utils/utils.hpp"
+#include "transformations/snippets/common/pass/lowered/external_repacking_adjuster.hpp"
#include "transformations/snippets/x64/op/brgemm_cpu.hpp"
#include "transformations/snippets/x64/op/brgemm_utils.hpp"
@@ -40,7 +37,7 @@ const size_t BrgemmExternalRepackingAdjuster::brgemm_kernel_rank = 2;
BrgemmExternalRepackingAdjuster::BrgemmExternalRepackingAdjuster(const ov::snippets::lowered::LinearIRCPtr& linear_ir,
const CPURuntimeConfigurator* configurator)
- : snippets::lowered::pass::RuntimeOptimizer(configurator) {
+ : ExternalRepackingAdjusterBase(configurator, "Snippets::BrgemmExternalRepackingAdjuster") {
const auto& cpu_config = ov::as_type_ptr<CPURuntimeConfig>(m_configurator->get_config());
const auto& input_repackers = cpu_config->input_repackers;
const auto& params = linear_ir->get_parameters();
@@ -48,14 +45,14 @@ BrgemmExternalRepackingAdjuster::BrgemmExternalRepackingAdjuster(const ov::snipp
OPENVINO_ASSERT(idx < params.size(), "Incorrect index of repacked input");
auto config = RepackedInputConfig{get_kernel_config(params[idx])};
- // If not already repacked at compile time, create a runtime executor for it.
- if (!input_repacker.already_repacked()) {
+ const auto needs_runtime_repacking = !input_repacker.already_repacked();
+ register_repacked_input(idx, needs_runtime_repacking);
+ if (needs_runtime_repacking) {
config.executor = create_executor(config.kernel_config, configurator->get_cache());
- config.needs_runtime_repacking = true;
}
- m_repacked_inputs.emplace(idx, std::move(config));
+ m_repacked_input_configs.emplace(idx, std::move(config));
}
- OPENVINO_ASSERT(input_repackers.size() == m_repacked_inputs.size(), "Incorrect count of repacked inputs");
+ OPENVINO_ASSERT(input_repackers.size() == m_repacked_input_configs.size(), "Incorrect count of repacked inputs");
}
BrgemmCopyBKernelConfig BrgemmExternalRepackingAdjuster::get_kernel_config(
@@ -123,170 +120,110 @@ void BrgemmExternalRepackingAdjuster::update_kernel(const RepackExecutorPtr& exe
executor->update_by_config(*config);
}
-bool BrgemmExternalRepackingAdjuster::run(const snippets::lowered::LinearIR& linear_ir) {
- OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::BrgemmExternalRepackingAdjuster")
- const auto& cpu_config = ov::as_type_ptr<CPURuntimeConfig>(m_configurator->get_config());
-
- size_t data_size = 0;
- bool has_runtime_repacking = false;
- for (const auto& [i, repacked_input] : m_repacked_inputs) {
- if (!repacked_input.needs_runtime_repacking) {
- continue;
- }
- has_runtime_repacking = true;
- const auto& executor = repacked_input.executor;
- OPENVINO_ASSERT(executor, "Input marked for runtime repacking has no executor");
-
- const auto& shape = cpu_config->io_shapes[i];
- const auto& layout = cpu_config->io_layouts[i];
- const auto& prc = linear_ir.get_parameters()[i]->get_node()->get_output_element_type(0);
- const auto planar_shape = ov::snippets::utils::get_planar_vdims(shape, layout);
- const auto& K = *++planar_shape.rbegin();
- const auto& N = *planar_shape.rbegin();
-
- update_kernel(executor, shape, layout, N, K);
-
- const auto& config = static_cast<const BrgemmCopyBKernelConfig&>(executor->get_config());
-
- const auto buffer_b_allocation_shape =
- brgemm_utils::repacking::compute_buffer_b_allocation_shape({K, N},
- prc,
- config.get_wei_K_blk(),
- config.get_wei_N_blk(),
- config.are_wei_blocked(),
- config.is_transposed_B());
-
- const auto src_dt_size = dnnl_data_type_size(config.get_original_wei_dt());
- const auto dst_dt_size = dnnl_data_type_size(config.get_wei_dt());
- // src data + dst data per kernel call
- const auto src_data = N * K * src_dt_size;
- const auto dst_data = std::accumulate(buffer_b_allocation_shape.cbegin(),
- buffer_b_allocation_shape.cend(),
- static_cast<size_t>(1),
- std::multiplies<>()) *
- dst_dt_size;
- data_size += src_data + dst_data;
- }
-
- if (!has_runtime_repacking) {
- cpu_config->repacking_impl_type = CPURuntimeConfig::RepackingImplType::NONE;
- } else {
- const auto cache_size = dnnl::utils::get_cache_size(1, true) + dnnl::utils::get_cache_size(2, true);
- const auto fit_into_cache = data_size < cache_size;
- // Heuristic: If external repacking data doesn't fit in the caches L1 and L2,
- // external repacking should be executed in seperate parallel section before kernel execution.
- cpu_config->repacking_impl_type = fit_into_cache ? CPURuntimeConfig::RepackingImplType::IN_PARALLEL
- : CPURuntimeConfig::RepackingImplType::SEPARATE;
- }
-
- const auto is_impl_parallel = cpu_config->repacking_impl_type == CPURuntimeConfig::RepackingImplType::IN_PARALLEL;
-
- for (const auto& [i, repacked_input] : m_repacked_inputs) {
- if (!repacked_input.needs_runtime_repacking) {
- continue;
- }
- const auto& executor = repacked_input.executor;
- OPENVINO_ASSERT(executor, "Input marked for runtime repacking has no executor");
-
- const auto& shape = cpu_config->io_shapes[i];
- const auto& layout = cpu_config->io_layouts[i];
- auto& input_repacker = cpu_config->input_repackers[i];
-
- const auto& prc = linear_ir.get_parameters()[i]->get_node()->get_output_element_type(0);
- auto planar_shape = ov::snippets::utils::get_planar_vdims(shape, layout);
- // In parallel impl, each thread needs buffer with only inner blocked shape to store repacking datata
- if (is_impl_parallel) {
- const auto batch_count = planar_shape.size() - brgemm_kernel_rank;
- std::fill(planar_shape.begin(), planar_shape.begin() + batch_count, 1);
- }
-
- const auto& config = static_cast<const BrgemmCopyBKernelConfig&>(executor->get_config());
- const auto dst_desc = get_desc(planar_shape,
- prc,
- config.get_wei_K_blk(),
- config.get_wei_N_blk(),
- config.are_wei_blocked(),
- config.is_transposed_B());
-
- auto process_src_offsets = [&config](const ov::snippets::VectorDims& cpu_config_offsets) {
- const auto orig_size = dnnl_data_type_size(config.get_original_wei_dt());
- const auto wei_size = dnnl_data_type_size(config.get_wei_dt());
- if (orig_size == wei_size) {
- return cpu_config_offsets;
- }
- // Note: original cpu config offsets are calculated for the repacked output
- // If repacked out precision is not equal to original weights precision,
- // we need to correspondingly scale offsets to correct positions in original memory
- ov::snippets::VectorDims recalculated_offsets(cpu_config_offsets.size());
- std::transform(cpu_config_offsets.begin(),
- cpu_config_offsets.end(),
- recalculated_offsets.begin(),
- [orig_size, wei_size](size_t offset) {
- OPENVINO_ASSERT(offset % wei_size == 0,
- "Offset (",
- offset,
- ") must be divisible by wei_size (",
- wei_size,
- ")");
- return offset / wei_size * orig_size;
- });
- return recalculated_offsets;
- };
-
- // Save original input offsets for input before repacking.
- // If the shape has not been changed, it means that we already created `InputRepacker` for this input
- // on previous pass call and now `cpu_config->io_data_offsets[i]` contains offsets not for original input -
- // they were updated for blocked shapes/zeroed for previous initialization and we cannot use them as original
- // offsets.
- const auto in_offsets = shape == cpu_config->latest_shapes[i]
- ? input_repacker.in_offsets()
- : process_src_offsets(cpu_config->io_data_offsets[i]);
-
- // In parallel case Kernel should not add offsets to repacked inputs because
- // they will be applied during repacking in execution stage
- if (is_impl_parallel) {
- auto& offsets = cpu_config->io_data_offsets[i];
- std::fill(offsets.begin(), offsets.end(), 0);
- } else {
- const auto blocked_dims = dst_desc->getBlockDims();
- const auto inner_blocks_num = blocked_dims.size() - planar_shape.size();
- const auto rank = in_offsets.size() + inner_blocks_num; // to align with src offsets rank
- OPENVINO_ASSERT(rank >= blocked_dims.size(), "Incorrect target rank for dst offsets");
-
- ov::snippets::VectorDims shape_for_offset(rank - blocked_dims.size(), 1);
- shape_for_offset.insert(shape_for_offset.end(), blocked_dims.begin(), blocked_dims.end());
-
- ov::snippets::VectorDims dst_offsets;
- ov::snippets::utils::init_strides(shape_for_offset, rank, prc.size(), 0, dst_offsets);
- dst_offsets.resize(dst_offsets.size() - inner_blocks_num);
- cpu_config->io_data_offsets[i] = dst_offsets;
- }
- const auto out_offsets = cpu_config->io_data_offsets[i];
+size_t BrgemmExternalRepackingAdjuster::update_runtime_repacking_data_size(const snippets::lowered::LinearIR& linear_ir,
+ const CPURuntimeConfig& cpu_config,
+ size_t idx) {
+ const auto& executor = m_repacked_input_configs.at(idx).executor;
+ OPENVINO_ASSERT(executor, "Input marked for runtime repacking has no executor");
+
+ const auto& shape = cpu_config.io_shapes[idx];
+ const auto& layout = cpu_config.io_layouts[idx];
+ const auto& prc = linear_ir.get_parameters()[idx]->get_node()->get_output_element_type(0);
+ const auto planar_shape = ov::snippets::utils::get_planar_vdims(shape, layout);
+ const auto& K = *++planar_shape.rbegin();
+ const auto& N = *planar_shape.rbegin();
+
+ update_kernel(executor, shape, layout, N, K);
+
+ const auto& config = static_cast<const BrgemmCopyBKernelConfig&>(executor->get_config());
+ const auto buffer_b_allocation_shape =
+ brgemm_utils::repacking::compute_buffer_b_allocation_shape({K, N},
+ prc,
+ config.get_wei_K_blk(),
+ config.get_wei_N_blk(),
+ config.are_wei_blocked(),
+ config.is_transposed_B());
+
+ const auto src_dt_size = dnnl_data_type_size(config.get_original_wei_dt());
+ const auto dst_dt_size = dnnl_data_type_size(config.get_wei_dt());
+ const auto src_data = N * K * src_dt_size;
+ const auto dst_data = std::accumulate(buffer_b_allocation_shape.cbegin(),
+ buffer_b_allocation_shape.cend(),
+ static_cast<size_t>(1),
+ std::multiplies<>()) *
+ dst_dt_size;
+ return src_data + dst_data;
+}
- input_repacker = InputRepacker(executor->get_kernel(), dst_desc, in_offsets, out_offsets);
+void BrgemmExternalRepackingAdjuster::update_runtime_repacking_input(const snippets::lowered::LinearIR& linear_ir,
+ CPURuntimeConfig& cpu_config,
+ size_t i,
+ bool is_impl_parallel) {
+ const auto& executor = m_repacked_input_configs.at(i).executor;
+ OPENVINO_ASSERT(executor, "Input marked for runtime repacking has no executor");
+
+ const auto& shape = cpu_config.io_shapes[i];
+ const auto& layout = cpu_config.io_layouts[i];
+ auto& input_repacker = cpu_config.input_repackers[i];
+
+ const auto& prc = linear_ir.get_parameters()[i]->get_node()->get_output_element_type(0);
+ auto planar_shape = ov::snippets::utils::get_planar_vdims(shape, layout);
+ // In parallel impl, each thread needs buffer with only inner blocked shape to store repacking data.
+ if (is_impl_parallel) {
+ const auto batch_count = planar_shape.size() - brgemm_kernel_rank;
+ std::fill(planar_shape.begin(), planar_shape.begin() + batch_count, 1);
}
- // Inputs prepacked during model preparation do not need runtime repacking kernels.
- // For them, we only adjust blocked output offsets for current runtime shapes.
- for (const auto& [i, repacked_input] : m_repacked_inputs) {
- if (repacked_input.needs_runtime_repacking) {
- continue;
+ const auto& config = static_cast<const BrgemmCopyBKernelConfig&>(executor->get_config());
+ const auto dst_desc = get_desc(planar_shape,
+ prc,
+ config.get_wei_K_blk(),
+ config.get_wei_N_blk(),
+ config.are_wei_blocked(),
+ config.is_transposed_B());
+
+ auto process_src_offsets = [&config](const ov::snippets::VectorDims& cpu_config_offsets) {
+ const auto orig_size = dnnl_data_type_size(config.get_original_wei_dt());
+ const auto wei_size = dnnl_data_type_size(config.get_wei_dt());
+ if (orig_size == wei_size) {
+ return cpu_config_offsets;
}
- const auto& config = repacked_input.kernel_config;
- const auto& shape = cpu_config->io_shapes[i];
- const auto& layout = cpu_config->io_layouts[i];
- const auto& prc = linear_ir.get_parameters()[i]->get_node()->get_output_element_type(0);
- const auto planar_shape = ov::snippets::utils::get_planar_vdims(shape, layout);
- const auto dst_desc = get_desc(planar_shape,
- prc,
- config.get_wei_K_blk(),
- config.get_wei_N_blk(),
- config.are_wei_blocked(),
- config.is_transposed_B());
-
+ // Note: original cpu config offsets are calculated for the repacked output.
+ // If repacked out precision is not equal to original weights precision,
+ // we need to correspondingly scale offsets to correct positions in original memory.
+ ov::snippets::VectorDims recalculated_offsets(cpu_config_offsets.size());
+ std::transform(cpu_config_offsets.begin(),
+ cpu_config_offsets.end(),
+ recalculated_offsets.begin(),
+ [orig_size, wei_size](size_t offset) {
+ OPENVINO_ASSERT(offset % wei_size == 0,
+ "Offset (",
+ offset,
+ ") must be divisible by wei_size (",
+ wei_size,
+ ")");
+ return offset / wei_size * orig_size;
+ });
+ return recalculated_offsets;
+ };
+
+ // Save original input offsets for input before repacking.
+ // If the shape has not been changed, it means that we already created `InputRepacker` for this input
+ // on previous pass call and now `cpu_config.io_data_offsets[i]` contains offsets not for original input -
+ // they were updated for blocked shapes/zeroed for previous initialization and we cannot use them as original
+ // offsets.
+ const auto in_offsets = shape == cpu_config.latest_shapes[i] ? input_repacker.in_offsets()
+ : process_src_offsets(cpu_config.io_data_offsets[i]);
+
+ // In parallel case Kernel should not add offsets to repacked inputs because
+ // they will be applied during repacking in execution stage.
+ if (is_impl_parallel) {
+ auto& offsets = cpu_config.io_data_offsets[i];
+ std::fill(offsets.begin(), offsets.end(), 0);
+ } else {
const auto blocked_dims = dst_desc->getBlockDims();
const auto inner_blocks_num = blocked_dims.size() - planar_shape.size();
- const auto rank = cpu_config->io_data_offsets[i].size() + inner_blocks_num;
+ const auto rank = in_offsets.size() + inner_blocks_num; // to align with src offsets rank
OPENVINO_ASSERT(rank >= blocked_dims.size(), "Incorrect target rank for dst offsets");
ov::snippets::VectorDims shape_for_offset(rank - blocked_dims.size(), 1);
@@ -295,11 +232,41 @@ bool BrgemmExternalRepackingAdjuster::run(const snippets::lowered::LinearIR& lin
ov::snippets::VectorDims dst_offsets;
ov::snippets::utils::init_strides(shape_for_offset, rank, prc.size(), 0, dst_offsets);
dst_offsets.resize(dst_offsets.size() - inner_blocks_num);
- cpu_config->io_data_offsets[i] = std::move(dst_offsets);
- cpu_config->input_repackers.erase(i);
+ cpu_config.io_data_offsets[i] = dst_offsets;
}
+ const auto out_offsets = cpu_config.io_data_offsets[i];
+
+ input_repacker = InputRepacker(executor->get_kernel(), dst_desc, in_offsets, out_offsets);
+}
- return true;
+void BrgemmExternalRepackingAdjuster::update_compile_time_repacked_input(const snippets::lowered::LinearIR& linear_ir,
+ CPURuntimeConfig& cpu_config,
+ size_t i) {
+ const auto& config = m_repacked_input_configs.at(i).kernel_config;
+ const auto& shape = cpu_config.io_shapes[i];
+ const auto& layout = cpu_config.io_layouts[i];
+ const auto& prc = linear_ir.get_parameters()[i]->get_node()->get_output_element_type(0);
+ const auto planar_shape = ov::snippets::utils::get_planar_vdims(shape, layout);
+ const auto dst_desc = get_desc(planar_shape,
+ prc,
+ config.get_wei_K_blk(),
+ config.get_wei_N_blk(),
+ config.are_wei_blocked(),
+ config.is_transposed_B());
+
+ const auto blocked_dims = dst_desc->getBlockDims();
+ const auto inner_blocks_num = blocked_dims.size() - planar_shape.size();
+ const auto rank = cpu_config.io_data_offsets[i].size() + inner_blocks_num;
+ OPENVINO_ASSERT(rank >= blocked_dims.size(), "Incorrect target rank for dst offsets");
+
+ ov::snippets::VectorDims shape_for_offset(rank - blocked_dims.size(), 1);
+ shape_for_offset.insert(shape_for_offset.end(), blocked_dims.begin(), blocked_dims.end());
+
+ ov::snippets::VectorDims dst_offsets;
+ ov::snippets::utils::init_strides(shape_for_offset, rank, prc.size(), 0, dst_offsets);
+ dst_offsets.resize(dst_offsets.size() - inner_blocks_num);
+ cpu_config.io_data_offsets[i] = std::move(dst_offsets);
+ cpu_config.input_repackers.erase(i);
}
} // namespace ov::intel_cpu::pass
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/external_repacking_adjuster.hpp b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/external_repacking_adjuster.hpp
index b285e5b6ad5..72d3a95af19 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/external_repacking_adjuster.hpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/lowered/external_repacking_adjuster.hpp
@@ -16,7 +16,7 @@
#include "openvino/core/type/element_type.hpp"
#include "snippets/lowered/expression.hpp"
#include "snippets/lowered/linear_ir.hpp"
-#include "snippets/lowered/pass/runtime_optimizer.hpp"
+#include "transformations/snippets/common/pass/lowered/external_repacking_adjuster.hpp"
namespace ov::intel_cpu::pass {
@@ -25,26 +25,31 @@ namespace ov::intel_cpu::pass {
* @brief A runtime optimizer that creates the memory descs for BRGEMM inputs which require external repacking.
* The generated memory descs are stored in the CPU runtime config.
*/
-class BrgemmExternalRepackingAdjuster : public ov::snippets::lowered::pass::RuntimeOptimizer {
+class BrgemmExternalRepackingAdjuster : public ov::intel_cpu::pass::ExternalRepackingAdjusterBase {
public:
- OPENVINO_RTTI("BrgemmExternalRepackingAdjuster", "", RuntimeOptimizer)
+ OPENVINO_RTTI("BrgemmExternalRepackingAdjuster", "", ExternalRepackingAdjusterBase)
BrgemmExternalRepackingAdjuster() = default;
BrgemmExternalRepackingAdjuster(const ov::snippets::lowered::LinearIRCPtr& linear_ir,
const CPURuntimeConfigurator* configurator);
- bool run(const snippets::lowered::LinearIR& linear_ir) override;
- bool applicable() const override {
- return !m_repacked_inputs.empty();
- }
-
private:
using RepackExecutorPtr = std::shared_ptr<BrgemmCopyBKernelExecutor>;
struct RepackedInputConfig {
BrgemmCopyBKernelConfig kernel_config;
RepackExecutorPtr executor = nullptr;
- bool needs_runtime_repacking = false;
};
+ size_t update_runtime_repacking_data_size(const snippets::lowered::LinearIR& linear_ir,
+ const CPURuntimeConfig& cpu_config,
+ size_t idx) override;
+ void update_runtime_repacking_input(const snippets::lowered::LinearIR& linear_ir,
+ CPURuntimeConfig& cpu_config,
+ size_t idx,
+ bool is_impl_parallel) override;
+ void update_compile_time_repacked_input(const snippets::lowered::LinearIR& linear_ir,
+ CPURuntimeConfig& cpu_config,
+ size_t idx) override;
+
static CpuBlockedMemoryDescPtr get_desc(const ov::snippets::VectorDims& planar_shape,
const ov::element::Type& prc,
size_t wei_k_blk,
@@ -63,7 +68,7 @@ private:
const ov::intel_cpu::MultiCacheWeakPtr& cache);
static const size_t brgemm_kernel_rank;
- std::unordered_map<size_t, RepackedInputConfig> m_repacked_inputs;
+ std::unordered_map<size_t, RepackedInputConfig> m_repacked_input_configs;
};
} // namespace ov::intel_cpu::pass
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/repack_matmul_weights.cpp b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/repack_matmul_weights.cpp
index decc99d6f3e..c6f594ce96d 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/repack_matmul_weights.cpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/repack_matmul_weights.cpp
@@ -5,7 +5,6 @@
#include "repack_matmul_weights.hpp"
#include <memory>
-#include <optional>
#include <utility>
#include "cpu_memory.h"
@@ -44,7 +43,7 @@ DnnlMemoryDescPtr RepackMatMulWeights::get_dst_desc(const Shape& shape, const Br
return MemoryDescUtils::convertToDnnlMemoryDesc(get_dst_cpu_desc(shape, brgemm_config));
}
-std::optional<RepackMatMulWeights::RepackedMatMulWeights> RepackMatMulWeights::repack(
+RepackMatMulWeights::RepackedMatMulWeights RepackMatMulWeights::repack(
const std::shared_ptr<ov::Node>& consumer,
const RepackMatMulWeights::MatMulWeightsSource& source,
const MemoryPtr& orig_src_mem_ptr) {
@@ -52,9 +51,7 @@ std::optional<RepackMatMulWeights::RepackedMatMulWeights> RepackMatMulWeights::r
OPENVINO_ASSERT(brgemm_cpu != nullptr, "Expected one consumer - BrgemmCPU");
const auto& brgemm_config = brgemm_cpu->get_config();
- if (!brgemm_config.are_wei_constant()) {
- return std::nullopt;
- }
+ OPENVINO_ASSERT(brgemm_config.are_wei_constant(), "Expected constant weights for compile-time repacking");
const auto& eng = m_context->getEngine();
const auto src_mem_desc = get_src_desc(source, brgemm_config);
diff --git a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/repack_matmul_weights.hpp b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/repack_matmul_weights.hpp
index 60af7d6351a..26f4f875f4f 100644
--- a/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/repack_matmul_weights.hpp
+++ b/src/plugins/intel_cpu/src/transformations/snippets/x64/pass/repack_matmul_weights.hpp
@@ -5,7 +5,7 @@
#pragma once
#include <memory>
-#include <optional>
+#include <set>
#include <utility>
#include <vector>
@@ -27,8 +27,12 @@ public:
OPENVINO_MODEL_PASS_RTTI("RepackMatMulWeights");
RepackMatMulWeights(GraphContext::CPtr context,
ov::intel_cpu::InputRepackerMap& input_repackers,
- std::vector<MemoryPtr>& src_mem_ptrs)
- : ov::intel_cpu::pass::RepackMatMulWeights(std::move(context), input_repackers, src_mem_ptrs) {}
+ std::vector<MemoryPtr>& src_mem_ptrs,
+ std::set<size_t> compile_time_repacking_idxs)
+ : ov::intel_cpu::pass::RepackMatMulWeights(std::move(context),
+ input_repackers,
+ src_mem_ptrs,
+ std::move(compile_time_repacking_idxs)) {}
private:
[[nodiscard]] static DnnlMemoryDescPtr get_src_desc(const MatMulWeightsSource& source,
@@ -38,9 +42,9 @@ private:
[[nodiscard]] static DnnlMemoryDescPtr get_dst_desc(const Shape& shape,
const brgemm_utils::BrgemmConfig& brgemm_config);
- [[nodiscard]] std::optional<RepackedMatMulWeights> repack(const std::shared_ptr<ov::Node>& consumer,
- const MatMulWeightsSource& source,
- const MemoryPtr& orig_src_mem_ptr) override;
+ [[nodiscard]] RepackedMatMulWeights repack(const std::shared_ptr<ov::Node>& consumer,
+ const MatMulWeightsSource& source,
+ const MemoryPtr& orig_src_mem_ptr) override;
};
} // namespace ov::intel_cpu::pass::x64