OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[CPU][Refactoring] Introduce VariableExecutor (#27883)
Egor Duplenskii0dd7434e299b
diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected.hpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected.hppindex 3266bf8965c..1d078feaa65 100644--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected.hpp@@ -8,12 +8,12 @@#include <oneapi/dnnl/dnnl.hpp>#include "cpu_memory.h"-#include "nodes/executors/dnnl/dnnl_fullyconnected_primitive.hpp"-#include "nodes/executors/dnnl/dnnl_convolution_primitive.hpp"#include "nodes/executors/dnnl/dnnl_aliases.hpp"+#include "nodes/executors/dnnl/dnnl_utils.hpp"#include "nodes/executors/executor.hpp"#include "memory_desc/cpu_memory_desc_utils.h"#include "nodes/executors/memory_arguments.hpp"+#include "post_ops.hpp"namespace ov {namespace intel_cpu {diff --git a/src/plugins/intel_cpu/src/nodes/executors/executor_factory.hpp b/src/plugins/intel_cpu/src/nodes/executors/executor_factory.hppindex 419ab4abf52..f12795d5d1e 100644--- a/src/plugins/intel_cpu/src/nodes/executors/executor_factory.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/executor_factory.hpp@@ -1,4 +1,4 @@-// Copyright (C) 2018-2022 Intel Corporation+// Copyright (C) 2018-2024 Intel Corporation// SPDX-License-Identifier: Apache-2.0//@@ -6,50 +6,22 @@#include <memory>#include <string>-#include <unordered_map>#include "executor.hpp"-#include "nodes/executors/implementations.hpp"#include "nodes/executors/executor_config.hpp"#include "nodes/executors/executor_implementation.hpp"#include "nodes/executors/graph_emitter.hpp"+#include "nodes/executors/implementations.hpp"#include "nodes/executors/memory_arguments.hpp"#include "nodes/executors/printers.hpp"-#include "openvino/core/except.hpp"+#include "nodes/executors/variable_executor.hpp"#include "post_ops.hpp"namespace ov {namespace intel_cpu {using namespace executor;-template <typename Attrs, typename NodeT>-static ExecutorPtr fallback(const executor::Config<Attrs>& config,- const executor::Config<Attrs>& fallbackConfig,- const MemoryArgs& memory,- const ExecutorContext::CPtr context,- const std::string& name) {- DEBUG_LOG("Falling back to graph executor for ",- name,- ". Original config: ",- config,- " new config:",- fallbackConfig);-- GraphEmitter<Attrs> graphEmitter(config.descs, config.attrs, config.postOps, memory, context, name);-- const auto& graphExecutor =- graphEmitter.createGraph(fallbackConfig.descs, fallbackConfig.attrs, fallbackConfig.postOps, context)- .ensureAttrsMatch()- .ensureSrcDescsMatch()- .ensureDstDescsMatch()- .ensurePostOpsMatch()- .emit();- (void)graphExecutor;-- OPENVINO_THROW("Fallback logic is not implemented yet"); // return graphExecutor;-}--template <typename Attrs, typename NodeT>+template <typename Attrs>class ExecutorFactory {public:using ExecutorImplementationRef = std::reference_wrapper<const ExecutorImplementation<Attrs>>;@@ -62,9 +34,7 @@ public:: m_attrs(attrs),m_postOps(postOps),m_context(context),- m_suitableImplementations(filter(m_attrs, m_postOps, descriptors, implementationPriority)),- m_implementationRequiresFallback(m_suitableImplementations.size(), true),- m_executors(m_suitableImplementations.size()) {}+ m_suitableImplementations(filter(m_attrs, m_postOps, descriptors, implementationPriority)) {}/*** @brief Retrieves the proper memory descriptors based on the provided memory descriptors.@@ -95,104 +65,42 @@ public:}/**- * @brief Preconfigures an executor based on the provided memory arguments.- *- * Preconfigures an executor by selecting an appropriate implementation based on the provided- * memory arguments and by creating an executor using the implementation.- *- * @param memory The memory parameters used for selecting the appropriate executor implementation.- *- * @note The main use case is to offload executor data preparation (i.e. weights packing)- * From the make() call- * @todo Currently supports creating a single executor.- * For some nodes it can be worth to preconfigure all the executors.- */- void preconfigure(const MemoryArgs& memory) {- executor::Config<Attrs> config{memoryDescsFromMemory(memory), m_attrs, m_postOps};-- cacheFallbackStatus(config);-- const size_t implId = select(memory, 0);- const auto& impl = m_suitableImplementations[implId].get();- DEBUG_LOG("Preconfiguring executor: ", impl.name());-- if (m_implementationRequiresFallback[implId]) {- if (auto fallbackConfig = impl.requiresFallback(config)) {- fallback<Attrs, NodeT>(config, *fallbackConfig, memory, m_context, impl.name());- }- }-- (void)create(implId, memory, m_context);- }-- /**- * @brief Creates an Executor instance based on provided memory arguments.+ * @brief Creates an Executor instance based on the provided memory arguments.*- * Creates an Executor instance using the provided MemoryArgs, selecting an appropriate implementation- * based on the characteristics of the memory. It handles fallback scenarios if necessary and updates the executor- * with the given memory information.+ * Depending on the number of available implementations, returns:+ * - VariableExecutor, if the number of implementations is two or more+ * - Simple Executor, if there is only one available implementation** @param memory memory arguments.** @return A shared pointer to the created Executor.- *- * The function follows the steps below:- * - Selects an implementation based on the provided memory using the select() function.- * - Retrieves the selected implementation and checks if fallback is required.- * - If fallback is required, it creates a fallback configuration and returns a fallback executor.- * - Otherwise creates the executor using the selected implementation.- * - Updates the executor with the given memory information.- **/- ExecutorPtr make(MemoryArgs& memory) {- auto createExec = [this](MemoryArgs& memory, size_t implId) -> ExecutorPtr {- const auto& impl = m_suitableImplementations[implId].get();- if (m_implementationRequiresFallback[implId]) {- executor::Config<Attrs> config{memoryDescsFromMemory(memory), m_attrs, m_postOps};- if (auto fallbackConfig = impl.requiresFallback(config)) {- return fallback<Attrs, NodeT>(config, *fallbackConfig, memory, m_context, impl.name());- }- }- const auto executor = create(implId, memory, m_context);- if (!executor->update(memory)) {- return nullptr;+ ExecutorPtr make(const MemoryArgs& memory) {+ // only single executor is available+ if (m_suitableImplementations.size() == 1) {+ auto config = GraphEmitter<Attrs>::createConfig(memory, m_attrs, m_postOps);++ const auto& theOnlyImplementation = m_suitableImplementations.front().get();++ if (const auto fallbackConfig = theOnlyImplementation.requiresFallback(config)) {+ return GraphEmitter<Attrs>::fallback(config,+ *fallbackConfig,+ memory,+ m_context,+ theOnlyImplementation.name());}- return executor;- };-- auto implId = select(memory, 0);- auto executor = createExec(memory, implId);- while (!executor) {- implId = select(memory, ++implId);- executor = createExec(memory, implId);- }- return executor;- }-private:- static MemoryDescArgs memoryDescsFromMemory(const MemoryArgs& memory) {- MemoryDescArgs memoryDescs;- memoryDescs.reserve(memory.size());-- for (const auto& mem : memory) {- memoryDescs[mem.first] = mem.second->getDescPtr();+ return theOnlyImplementation.create(m_attrs, m_postOps, memory, m_context);}- return memoryDescs;- }-- /**- * @brief Caches the fallback status for each suitable implementation.- */- void cacheFallbackStatus(const executor::Config<Attrs>& config) {- std::transform(m_suitableImplementations.begin(),- m_suitableImplementations.end(),- m_implementationRequiresFallback.begin(),- [&config](const ExecutorImplementationRef& impl) {- return impl.get().requiresFallback(config);- });+ return std::make_shared<VariableExecutor<Attrs>>(memory,+ m_attrs,+ m_postOps,+ m_context,+ m_suitableImplementations);}+private:/*** @brief Filters and retrieves suitable implementations based on the provided executor configuration.*@@ -205,11 +113,10 @@ private:* @note If an implementation is shape agnostic, no further implementations with lower* priority are considered.*/- static std::vector<ExecutorImplementationRef> filter(- const Attrs& attrs,- const PostOps& postOps,- const MemoryDescArgs& descs,- const std::string& implementationPriority = {}) {+ static std::vector<ExecutorImplementationRef> filter(const Attrs& attrs,+ const PostOps& postOps,+ const MemoryDescArgs& descs,+ const std::string& implementationPriority = {}) {const auto& implementations = getImplementations<Attrs>();std::vector<ExecutorImplementationRef> suitableImplementations;const executor::Config<Attrs> config{descs, attrs, postOps};@@ -244,51 +151,17 @@ private:return suitableImplementations;}- size_t select(const MemoryArgs& memory, const size_t startIdx) const {- OPENVINO_ASSERT(startIdx < m_suitableImplementations.size(),- "Failed to find an implementation since start indx: ", startIdx,- " is out of range of the suitable implementations array: ", m_suitableImplementations.size());- auto startIt = m_suitableImplementations.begin();- std::advance(startIt, startIdx);- const auto selectedImplementation =- std::find_if(startIt,- m_suitableImplementations.end(),- [&memory](const ExecutorImplementationRef& implementation) {- return implementation.get().shapeAgnostic() || implementation.get().acceptsShapes(memory);- });- OPENVINO_ASSERT(selectedImplementation != m_suitableImplementations.end(), "Failed to select an implemetation");-- return std::distance(m_suitableImplementations.begin(), selectedImplementation);- }-- ExecutorPtr create(const size_t implId,- const MemoryArgs& memory,- const ExecutorContext::CPtr context) {- assert(implId < m_executors.size() && implId < m_suitableImplementations.size());-- if (!m_executors[implId]) {- const auto& impl = m_suitableImplementations[implId].get();- m_executors[implId] = impl.create(m_attrs, m_postOps, memory, context);- }-- return m_executors[implId];- }-const Attrs& m_attrs;const PostOps& m_postOps;const ExecutorContext::CPtr m_context;std::vector<ExecutorImplementationRef> m_suitableImplementations;- // stores fallback status to avoid performing the check for every make() call- std::vector<bool> m_implementationRequiresFallback;- // executors cache- std::vector<ExecutorPtr> m_executors;};-template <typename Attrs, typename NodeT>-using ExecutorFactoryPtr = std::shared_ptr<ExecutorFactory<Attrs, NodeT>>;+template <typename Attrs>+using ExecutorFactoryPtr = std::shared_ptr<ExecutorFactory<Attrs>>;-template <typename Attrs, typename NodeT>-using ExecutorFactoryCPtr = std::shared_ptr<const ExecutorFactory<Attrs, NodeT>>;+template <typename Attrs>+using ExecutorFactoryCPtr = std::shared_ptr<const ExecutorFactory<Attrs>>;} // namespace intel_cpu} // namespace ovdiff --git a/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_implementations.cpp b/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_implementations.cppindex 5834c3dda4b..4cf6992985e 100644--- a/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_implementations.cpp+++ b/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_implementations.cpp@@ -11,6 +11,7 @@#include "memory_desc/cpu_memory_desc.h"#include "nodes/executors/convolution_config.hpp"#include "nodes/executors/dnnl/dnnl_convolution_primitive.hpp"+#include "nodes/executors/dnnl/dnnl_fullyconnected_primitive.hpp"#include "nodes/executors/dnnl/dnnl_fullyconnected.hpp"#include "nodes/executors/dnnl/dnnl_matmul_primitive.hpp"#include "nodes/executors/dnnl/dnnl_shape_agnostic_data.hpp"diff --git a/src/plugins/intel_cpu/src/nodes/executors/graph_emitter.hpp b/src/plugins/intel_cpu/src/nodes/executors/graph_emitter.hppindex 6aad18c793c..784ed8bc778 100644--- a/src/plugins/intel_cpu/src/nodes/executors/graph_emitter.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/graph_emitter.hpp@@ -5,12 +5,11 @@#pragma once#include <functional>-#include <vector>#include "graph.h"-#include "memory_desc/cpu_memory_desc.h"#include "node.h"#include "nodes/executors/executor.hpp"+#include "nodes/executors/executor_config.hpp"#include "post_ops.hpp"namespace ov {@@ -72,6 +71,49 @@ public:return graph;}+ static MemoryDescArgs memoryDescsFromMemory(const MemoryArgs& memory) {+ MemoryDescArgs memoryDescs;+ memoryDescs.reserve(memory.size());++ for (const auto& mem : memory) {+ memoryDescs[mem.first] = mem.second->getDescPtr();+ }++ return memoryDescs;+ }++ static executor::Config<Attrs> createConfig(const MemoryArgs& memory,+ const Attrs& attrs,+ const PostOps& postOps) {+ return executor::Config<Attrs>{memoryDescsFromMemory(memory), attrs, postOps};+ }++ static ExecutorPtr fallback(const executor::Config<Attrs>& config,+ const executor::Config<Attrs>& fallbackConfig,+ const MemoryArgs& memory,+ const ExecutorContext::CPtr context,+ const std::string& name) {+ DEBUG_LOG("Falling back to graph executor for ",+ name,+ ". Original config: ",+ config,+ " new config:",+ fallbackConfig);++ GraphEmitter<Attrs> graphEmitter(config.descs, config.attrs, config.postOps, memory, context, name);++ const auto& graphExecutor =+ graphEmitter.createGraph(fallbackConfig.descs, fallbackConfig.attrs, fallbackConfig.postOps, context)+ .ensureAttrsMatch()+ .ensureSrcDescsMatch()+ .ensureDstDescsMatch()+ .ensurePostOpsMatch()+ .emit();+ (void)graphExecutor;++ OPENVINO_THROW("Fallback logic is not implemented yet"); // return graphExecutor;+ }+private:const MemoryDescArgs& descs;const Attrs& attrs;diff --git a/src/plugins/intel_cpu/src/nodes/executors/variable_executor.hpp b/src/plugins/intel_cpu/src/nodes/executors/variable_executor.hppnew file mode 100644index 00000000000..8dfb7a4c63f--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/executors/variable_executor.hpp@@ -0,0 +1,140 @@+// Copyright (C) 2018-2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "executor.hpp"+#include "executor_config.hpp"+#include "executor_implementation.hpp"+#include "nodes/executors/graph_emitter.hpp"++namespace ov {+namespace intel_cpu {++/**+ * A stateful (variable) executor+ * Contains two or more executors.+ * Switches between the executors based on provided Memory (more precisely based on in / out shapes)+ */+template <typename Attrs>+class VariableExecutor : public Executor {+public:+ using ExecutorImplementationRef = std::reference_wrapper<const ExecutorImplementation<Attrs>>;++ VariableExecutor(const MemoryArgs& memory,+ const Attrs& attrs,+ const PostOps& postOps,+ const ExecutorContext::CPtr context,+ std::vector<ExecutorImplementationRef> suitableImplementations)+ : m_attrs(attrs),+ m_postOps(postOps),+ m_context(context),+ m_suitableImplementations(std::move(suitableImplementations)),+ m_implementationRequiresFallback(+ cacheFallbackStatus(m_suitableImplementations,+ GraphEmitter<Attrs>::createConfig(memory, m_attrs, m_postOps))),+ m_executors(m_suitableImplementations.size()) {+ const size_t implId = select(memory, 0);+ m_executors[implId] = create(implId, memory);+ m_implId = implId;+ }++ bool update(const MemoryArgs& memory) override {+ for (auto implId = select(memory, 0); implId < m_suitableImplementations.size();+ implId = select(memory, implId)) {+ if (!m_executors[implId]) {+ m_executors[implId] = create(implId, memory);+ }++ if (m_executors[implId]->update(memory)) {+ m_implId = implId;+ return true;+ }+ }++ return false;+ }++ void execute(const MemoryArgs& memory) override {+ m_executors[m_implId]->execute(memory);+ }++ impl_desc_type implType() const override {+ return m_executors[m_implId]->implType();+ }++ void moveMemToNumaNode(int numaID) override {+ m_executors[m_implId]->moveMemToNumaNode(numaID);+ }++private:+ /**+ * @brief Returns a fallback status for each suitable implementation.+ */+ static std::vector<bool> cacheFallbackStatus(const std::vector<ExecutorImplementationRef>& suitableImplementations,+ const executor::Config<Attrs>& config) {+ std::vector<bool> implementationRequiresFallback(suitableImplementations.size());+ std::transform(suitableImplementations.begin(),+ suitableImplementations.end(),+ implementationRequiresFallback.begin(),+ [&config](const ExecutorImplementationRef& impl) {+ return impl.get().requiresFallback(config);+ });++ return implementationRequiresFallback;+ }++ size_t select(const MemoryArgs& memory, const size_t startIdx) const {+ OPENVINO_ASSERT(startIdx < m_suitableImplementations.size(),+ "Failed to find an implementation since start indx: ",+ startIdx,+ " is out of range of the suitable implementations array: ",+ m_suitableImplementations.size());++ auto startIt = m_suitableImplementations.begin() + startIdx;++ const auto selectedImplementation =+ std::find_if(startIt,+ m_suitableImplementations.end(),+ [&memory](const ExecutorImplementationRef& implementation) {+ return implementation.get().shapeAgnostic() || implementation.get().acceptsShapes(memory);+ });++ OPENVINO_ASSERT(selectedImplementation != m_suitableImplementations.end(), "Failed to select an implemetation");++ return std::distance(m_suitableImplementations.begin(), selectedImplementation);+ }++ ExecutorPtr create(const size_t implId, const MemoryArgs& memory) {+ assert(implId < m_executors.size() && implId < m_suitableImplementations.size());++ auto createWithFallback = [this](const size_t implId, const MemoryArgs& memory) {+ const auto& impl = m_suitableImplementations[implId].get();++ if (m_implementationRequiresFallback[implId]) {+ auto config = GraphEmitter<Attrs>::createConfig(memory, m_attrs, m_postOps);+ if (auto fallbackConfig = impl.requiresFallback(config)) {+ return GraphEmitter<Attrs>::fallback(config, *fallbackConfig, memory, m_context, impl.name());+ }+ }++ return impl.create(m_attrs, m_postOps, memory, m_context);+ };++ return createWithFallback(implId, memory);+ }++ const Attrs& m_attrs;+ const PostOps& m_postOps;+ const ExecutorContext::CPtr m_context;+ std::vector<ExecutorImplementationRef> m_suitableImplementations;+ // stores fallback status to avoid performing the check for every make() call+ std::vector<bool> m_implementationRequiresFallback;+ // executors cache+ std::vector<ExecutorPtr> m_executors;+ size_t m_implId;+};++} // namespace intel_cpu+} // namespace ovdiff --git a/src/plugins/intel_cpu/src/nodes/fullyconnected.cpp b/src/plugins/intel_cpu/src/nodes/fullyconnected.cppindex 307125ef006..31ae4f26cc0 100644--- a/src/plugins/intel_cpu/src/nodes/fullyconnected.cpp+++ b/src/plugins/intel_cpu/src/nodes/fullyconnected.cpp@@ -66,7 +66,7 @@ void FullyConnected::initTensorParallelConfig(const GraphContext::CPtr context)// init tp_cfg.w_rank and tp_cfg.w_sizetp_cfg.w_rank = context->getCPUStreamExecutor()->get_rank()[0];tp_cfg.w_size = ov::threading::message_manager()->get_num_sub_streams();- tp_cfg.enable_tensor_parallel = tp_cfg.w_size > 1 ? true : false;+ tp_cfg.enable_tensor_parallel = tp_cfg.w_size > 1;tp_cfg.sub_memory = context->getSubMemory();}}@@ -119,16 +119,12 @@ void FullyConnected::needPrepareParamsForTensorParallel() {}}-ExecutorPtr FullyConnected::createExecutor() {- const auto& executor = factory->make(memory);- getSelectedPrimitiveDescriptor()->setImplementationType(executor->implType());-- return executor;-}-void FullyConnected::prepareParams() {needPrepareParamsForTensorParallel();- executor = createExecutor();++ executor->update(memory);+ // @todo avoid updating implementation type in scope of every prepareParams call+ getSelectedPrimitiveDescriptor()->setImplementationType(executor->implType());}void FullyConnected::initTensorParallelSync() {@@ -431,7 +427,7 @@ void FullyConnected::initSupportedPrimitiveDescriptors() {needUpdateZeroPointForTensorParallel();auto executionContext = std::make_shared<ExecutorContext>(context, getImplPriority(), privateWeightCache);- factory = std::make_shared<ExecutorFactory<FCAttrs, node::FullyConnected>>(attrs, postOps, executionContext, descs);+ factory = std::make_shared<ExecutorFactory<FCAttrs>>(attrs, postOps, executionContext, descs);const auto nodeDescriptors = factory->getProperMemoryDescriptors(descs);NodeConfig nodeConfig;@@ -496,7 +492,7 @@ void FullyConnected::createPrimitive() {needSplitMemoryForTensorParallel();// @todo should we preconfigure only for dynamic shapes?// Since for static shapes primitive is created in scope of compile_model() anyway- factory->preconfigure(memory);+ executor = factory->make(memory);Node::createPrimitive();}diff --git a/src/plugins/intel_cpu/src/nodes/fullyconnected.h b/src/plugins/intel_cpu/src/nodes/fullyconnected.hindex be29342b851..8c17228e365 100644--- a/src/plugins/intel_cpu/src/nodes/fullyconnected.h+++ b/src/plugins/intel_cpu/src/nodes/fullyconnected.h@@ -16,7 +16,6 @@#include "nodes/executors/memory_arguments.hpp"#include "nodes/executors/fullyconnected_config.hpp"#include "post_ops.hpp"-#include "openvino/runtime/threading/cpu_message.hpp"namespace ov {namespace intel_cpu {@@ -85,7 +84,6 @@ private:static const size_t WEIGHTS_ID = 1;static const size_t BIAS_ID = 2;- ExecutorPtr createExecutor();void fuseDecompressionConstant(const MemoryCPtr& memory, MemoryCPtr& decompressionValuesPtr);void initTensorParallelConfig(const GraphContext::CPtr context);@@ -103,7 +101,7 @@ private:FCAttrs attrs;PostOps postOps;MemoryArgs memory;- ExecutorFactoryPtr<FCAttrs, node::FullyConnected> factory;+ ExecutorFactoryPtr<FCAttrs> factory;ExecutorPtr executor = nullptr;std::string errorPrefix;