Skip to content

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

[CPU] FC node tensor parallel (#25088)

Xiuchuan Zhai72516c375a6e
diff --git a/src/inference/dev_api/openvino/runtime/threading/cpu_message.hpp b/src/inference/dev_api/openvino/runtime/threading/cpu_message.hpp
new file mode 100644
index 00000000000..357ea1fc285
--- /dev/null
+++ b/src/inference/dev_api/openvino/runtime/threading/cpu_message.hpp
@@ -0,0 +1,58 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+/**
+ * @brief OpenVINO Runtime Executor Manager
+ * @file openvino/runtime/threading/executor_manager.hpp
+ */
+
+#pragma once
+
+#include <atomic>
+#include <condition_variable>
+#include <memory>
+#include <mutex>
+#include <queue>
+#include <set>
+#include <thread>
+#include <vector>
+#include <assert.h>
+
+#include "openvino/runtime/common.hpp"
+#include "openvino/runtime/threading/istreams_executor.hpp"
+#include "openvino/runtime/threading/itask_executor.hpp"
+
+
+namespace ov {
+
+namespace threading {
+enum MsgType {CALL_BACK};
+
+struct MessageInfo {
+ MsgType msg_type;
+};
+
+class OPENVINO_RUNTIME_API MessageManager {
+public:
+ MessageManager();
+
+ void send_message(const MessageInfo& msg_info);
+
+ void server_wait();
+
+ ~MessageManager();
+
+ void set_num_sub_streams(int num_sub_streams);
+
+ int get_num_sub_streams();
+private:
+ int _num_sub_streams = 0;
+ std::vector<MessageInfo> _messageQueue;
+ std::mutex _msgMutex;
+ std::condition_variable _msgCondVar;
+};
+
+OPENVINO_RUNTIME_API std::shared_ptr<MessageManager> message_manager();
+} // namespace threading
+} // namespace ov
\ No newline at end of file
diff --git a/src/inference/dev_api/openvino/runtime/threading/cpu_streams_executor.hpp b/src/inference/dev_api/openvino/runtime/threading/cpu_streams_executor.hpp
index eaa54701e2b..ff21eef7089 100644
--- a/src/inference/dev_api/openvino/runtime/threading/cpu_streams_executor.hpp
+++ b/src/inference/dev_api/openvino/runtime/threading/cpu_streams_executor.hpp
@@ -55,7 +55,7 @@ public:
int get_socket_id() override;
- void run_sub_stream(Task task, int id) override;
+ std::vector<int> get_rank() override;
private:
struct Impl;
diff --git a/src/inference/dev_api/openvino/runtime/threading/istreams_executor.hpp b/src/inference/dev_api/openvino/runtime/threading/istreams_executor.hpp
index 7a34ea258c4..3630c2bb5a6 100644
--- a/src/inference/dev_api/openvino/runtime/threading/istreams_executor.hpp
+++ b/src/inference/dev_api/openvino/runtime/threading/istreams_executor.hpp
@@ -38,6 +38,19 @@ public:
*/
using Ptr = std::shared_ptr<IStreamsExecutor>;
+ enum MsgType{
+ TP,
+ START_INFER,
+ CALL_BACK
+ };
+
+ struct MessageInfo{
+ MsgType msg_type;
+ std::vector<int> rank;
+ void* buf;
+ Task task;
+ };
+
/**
* @brief Defines inference thread binding type
*/
@@ -95,6 +108,7 @@ public:
std::vector<std::vector<int>> _streams_info_table = {};
std::vector<std::vector<int>> _stream_processor_ids;
int _sub_streams = 0;
+ std::vector<int> _rank = {};
/**
* @brief Get and reserve cpu ids based on configuration and hardware information,
@@ -124,6 +138,7 @@ public:
* @param[in] cpu_reservation @copybrief Config::_cpu_reservation
* @param[in] cpu_pinning @copybrief Config::_cpu_pinning
* @param[in] streams_info_table @copybrief Config::_streams_info_table
+ * @param[in] rank @copybrief Config::_rank
*/
Config(std::string name = "StreamsExecutor",
int streams = 1,
@@ -131,14 +146,16 @@ public:
ov::hint::SchedulingCoreType thread_preferred_core_type = ov::hint::SchedulingCoreType::ANY_CORE,
bool cpu_reservation = false,
bool cpu_pinning = false,
- std::vector<std::vector<int>> streams_info_table = {})
+ std::vector<std::vector<int>> streams_info_table = {},
+ std::vector<int> rank = {})
: _name{std::move(name)},
_streams{streams},
_threads_per_stream{threads_per_stream},
_thread_preferred_core_type(thread_preferred_core_type),
_cpu_reservation{cpu_reservation},
_cpu_pinning{cpu_pinning},
- _streams_info_table{std::move(streams_info_table)} {
+ _streams_info_table{std::move(streams_info_table)},
+ _rank{rank} {
update_executor_config();
}
@@ -197,6 +214,9 @@ public:
int get_sub_streams() const {
return _sub_streams;
}
+ std::vector<int> get_rank() const {
+ return _rank;
+ }
StreamsMode get_sub_stream_mode() const {
const auto proc_type_table = get_proc_type_table();
int sockets = proc_type_table.size() > 1 ? static_cast<int>(proc_type_table.size()) - 1 : 1;
@@ -250,31 +270,17 @@ public:
virtual int get_socket_id() = 0;
/**
- * @brief Execute the task in the current thread using streams executor configuration and constraints
- * @param task A task to start
+ * @brief Return the rank of current stream
+ * Return {} when current stream has no rank
+ * @return Rank array, or throws exceptions if called not from stream thread
*/
- virtual void execute(Task task) = 0;
+ virtual std::vector<int> get_rank() = 0;
/**
- * @brief Execute ov::Task inside sub stream of task executor context
+ * @brief Execute the task in the current thread using streams executor configuration and constraints
* @param task A task to start
- * @param id Sub stream id
- */
- virtual void run_sub_stream(Task task, int id) = 0;
-
- /**
- * @brief Execute all of the tasks and waits for its completion.
- * Default run_sub_stream_and_wait() method implementation uses run_sub_stream() pure virtual method
- * and higher level synchronization primitives from STL.
- * The task is wrapped into std::packaged_task which returns std::future.
- * std::packaged_task will call the task and signal to std::future that the task is finished
- * or the exception is thrown from task
- * Than std::future is used to wait for task execution completion and
- * task exception extraction
- * @note run_sub_stream_and_wait() does not copy or capture tasks!
- * @param tasks A vector of tasks to execute
*/
- void run_sub_stream_and_wait(const std::vector<Task>& tasks);
+ virtual void execute(Task task) = 0;
};
} // namespace threading
diff --git a/src/inference/src/dev/threading/cpu_message.cpp b/src/inference/src/dev/threading/cpu_message.cpp
new file mode 100644
index 00000000000..75df25d70d5
--- /dev/null
+++ b/src/inference/src/dev/threading/cpu_message.cpp
@@ -0,0 +1,96 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#include "openvino/runtime/threading/cpu_message.hpp"
+
+#include <memory>
+#include <mutex>
+#include <queue>
+#include <set>
+#include <thread>
+#include <vector>
+
+namespace ov {
+namespace threading {
+
+MessageManager::MessageManager() {
+ _num_sub_streams = 0;
+}
+
+MessageManager::~MessageManager() {}
+
+void MessageManager::send_message(const MessageInfo& msg_info) {
+ {
+ std::lock_guard<std::mutex> lock(_msgMutex);
+ _messageQueue.push_back(msg_info);
+ }
+ _msgCondVar.notify_all();
+}
+
+void MessageManager::server_wait() {
+ assert(_num_sub_streams);
+ MsgType msg_type;
+ int count = 0;
+ bool isStopped = false;
+ while (!isStopped) {
+ std::vector<MessageInfo> msgQueue;
+ {
+ std::unique_lock<std::mutex> lock(_msgMutex);
+ _msgCondVar.wait(lock, [&] {
+ return !_messageQueue.empty();
+ });
+ std::swap(_messageQueue, msgQueue);
+ }
+
+ for (auto rec_info : msgQueue) {
+ msg_type = rec_info.msg_type;
+ if (msg_type == CALL_BACK) { // CALL_BACK
+ count++;
+ if (count == _num_sub_streams) {
+ count = 0;
+ isStopped = true;
+ }
+ }
+ }
+ };
+}
+
+void MessageManager::set_num_sub_streams(int num_sub_streams) {
+ _num_sub_streams = num_sub_streams;
+}
+
+int MessageManager::get_num_sub_streams() {
+ return _num_sub_streams;
+}
+
+namespace {
+
+class MessageManageHolder {
+ std::mutex _mutex;
+ std::weak_ptr<MessageManager> _manager;
+
+public:
+ MessageManageHolder(const MessageManageHolder&) = delete;
+ MessageManageHolder& operator=(const MessageManageHolder&) = delete;
+
+ MessageManageHolder() = default;
+
+ std::shared_ptr<ov::threading::MessageManager> get() {
+ std::lock_guard<std::mutex> lock(_mutex);
+ auto manager = _manager.lock();
+ if (!manager) {
+ _manager = manager = std::make_shared<MessageManager>();
+ }
+ return manager;
+ }
+};
+
+} // namespace
+
+std::shared_ptr<MessageManager> message_manager() {
+ static MessageManageHolder message_manage;
+ return message_manage.get();
+}
+
+} // namespace threading
+} // namespace ov
diff --git a/src/inference/src/dev/threading/cpu_streams_executor.cpp b/src/inference/src/dev/threading/cpu_streams_executor.cpp
index 2df59d27cfe..9e55cd2be18 100644
--- a/src/inference/src/dev/threading/cpu_streams_executor.cpp
+++ b/src/inference/src/dev/threading/cpu_streams_executor.cpp
@@ -59,11 +59,6 @@ struct CPUStreamsExecutor::Impl {
_streamId = _impl->_streamIdQueue.front();
_impl->_streamIdQueue.pop();
}
- if (!_impl->_subStreamIdQueue.empty() && _impl->_subStreamsNum < _impl->_config.get_sub_streams()) {
- _sub_stream_id = _impl->_subStreamIdQueue.front();
- _impl->_subStreamIdQueue.pop();
- _impl->_subStreamsNum++;
- }
}
_numaNodeId =
_impl->_config.get_streams()
@@ -176,8 +171,8 @@ struct CPUStreamsExecutor::Impl {
StreamCreateType stream_type;
const auto org_proc_type_table = get_org_proc_type_table();
int streams_num = _impl->_config.get_streams();
- const auto stream_id =
- streams_num == 0 ? 0 : (_sub_stream_id >= 0 ? streams_num + _sub_stream_id : _streamId % streams_num);
+ const auto stream_id = streams_num == 0 ? 0 : _streamId % streams_num;
+ _rank = _impl->_config.get_rank();
get_cur_stream_info(stream_id,
_impl->_config.get_cpu_pinning(),
org_proc_type_table,
@@ -204,7 +199,7 @@ struct CPUStreamsExecutor::Impl {
int _numaNodeId = 0;
int _socketId = 0;
bool _execute = false;
- int _sub_stream_id = -1;
+ std::vector<int> _rank;
std::queue<Task> _taskQueue;
#if OV_THREAD == OV_THREAD_TBB || OV_THREAD == OV_THREAD_TBB_AUTO
std::unique_ptr<custom::task_arena> _taskArena;
@@ -335,7 +330,6 @@ struct CPUStreamsExecutor::Impl {
_exectorMgr = executor_manager();
auto numaNodes = get_available_numa_nodes();
int streams_num = _config.get_streams();
- int sub_streams_num = _config.get_sub_streams();
if (streams_num != 0) {
std::copy_n(std::begin(numaNodes),
std::min<std::size_t>(streams_num, numaNodes.size()),
@@ -343,9 +337,6 @@ struct CPUStreamsExecutor::Impl {
} else {
_usedNumaNodes = std::move(numaNodes);
}
- if (sub_streams_num > 0) {
- _subTaskThread.assign(sub_streams_num, std::make_shared<SubQueue>());
- }
for (auto streamId = 0; streamId < streams_num; ++streamId) {
_threads.emplace_back([this, streamId] {
openvino::itt::threadName(_config.get_name() + "_" + std::to_string(streamId));
@@ -368,31 +359,6 @@ struct CPUStreamsExecutor::Impl {
});
}
_streams.set_thread_ids_map(_threads);
-
- for (auto subId = 0; subId < sub_streams_num; ++subId) {
- _subThreads.emplace_back([this, subId, sub_streams_num] {
- openvino::itt::threadName(_config.get_name() + "_subthreads" + "_" + std::to_string(subId));
- for (bool stopped = false; !stopped;) {
- Task task;
- { _subTaskThread[subId]->que_pop(task, stopped); }
- if (task) {
- {
- std::lock_guard<std::mutex> lock{_streamIdMutex};
- if (_subStreamsNum < sub_streams_num) {
- _subStreamIdQueue.push(subId);
- } else {
- std::queue<int> empty;
- std::swap(_subStreamIdQueue, empty);
- }
- }
- Execute(task, *(_streams.local()));
- }
- }
- });
- }
- if (_subThreads.size() > 0) {
- _streams.set_thread_ids_map(_subThreads);
- }
}
void Enqueue(Task task) {
@@ -403,10 +369,6 @@ struct CPUStreamsExecutor::Impl {
_queueCondVar.notify_one();
}
- void Enqueue_sub(Task task, int id) {
- _subTaskThread[id]->que_push(std::move(task));
- }
-
void Execute(const Task& task, Stream& stream) {
#if OV_THREAD == OV_THREAD_TBB || OV_THREAD == OV_THREAD_TBB_AUTO
auto& arena = stream._taskArena;
@@ -467,52 +429,19 @@ struct CPUStreamsExecutor::Impl {
}
}
- struct SubQueue {
- std::mutex _subMutex;
- std::condition_variable _subQueueCondVar;
- bool _isSubStopped = false;
- std::queue<Task> _subTaskQueue;
-
- SubQueue() {}
-
- void que_push(Task task) {
- {
- std::lock_guard<std::mutex> lock(_subMutex);
- _subTaskQueue.emplace(std::move(task));
- }
- _subQueueCondVar.notify_one();
- }
-
- void que_pop(Task& task, bool& stopped) {
- std::unique_lock<std::mutex> lock(_subMutex);
- _subQueueCondVar.wait(lock, [&] {
- return !_subTaskQueue.empty() || (stopped = _isSubStopped);
- });
- if (!_subTaskQueue.empty()) {
- task = std::move(_subTaskQueue.front());
- _subTaskQueue.pop();
- }
- }
-
- ~SubQueue() {}
- };
-
Config _config;
std::mutex _streamIdMutex;
int _streamId = 0;
std::queue<int> _streamIdQueue;
- std::queue<int> _subStreamIdQueue;
- int _subStreamsNum = 0;
std::vector<std::thread> _threads;
- std::vector<std::thread> _subThreads;
std::mutex _mutex;
std::condition_variable _queueCondVar;
std::queue<Task> _taskQueue;
bool _isStopped = false;
- std::vector<std::shared_ptr<SubQueue>> _subTaskThread;
std::vector<int> _usedNumaNodes;
CustomThreadLocal _streams;
std::shared_ptr<ExecutorManager> _exectorMgr;
+ bool _isExit = false;
};
int CPUStreamsExecutor::get_stream_id() {
@@ -534,6 +463,11 @@ int CPUStreamsExecutor::get_socket_id() {
return stream->_socketId;
}
+std::vector<int> CPUStreamsExecutor::get_rank() {
+ auto stream = _impl->_streams.local();
+ return stream->_rank;
+}
+
CPUStreamsExecutor::CPUStreamsExecutor(const IStreamsExecutor::Config& config) : _impl{new Impl{config}} {}
CPUStreamsExecutor::~CPUStreamsExecutor() {
@@ -547,18 +481,6 @@ CPUStreamsExecutor::~CPUStreamsExecutor() {
thread.join();
}
}
- for (size_t i = 0; i < _impl->_subTaskThread.size(); i++) {
- {
- std::lock_guard<std::mutex> lock(_impl->_subTaskThread[i]->_subMutex);
- _impl->_subTaskThread[i]->_isSubStopped = true;
- }
- _impl->_subTaskThread[i]->_subQueueCondVar.notify_all();
- }
- for (auto& thread : _impl->_subThreads) {
- if (thread.joinable()) {
- thread.join();
- }
- }
}
void CPUStreamsExecutor::execute(Task task) {
@@ -573,9 +495,5 @@ void CPUStreamsExecutor::run(Task task) {
}
}
-void CPUStreamsExecutor::run_sub_stream(Task task, int id) {
- _impl->Enqueue_sub(std::move(task), id);
-}
-
} // namespace threading
} // namespace ov
diff --git a/src/inference/src/dev/threading/cpu_streams_executor_internal.cpp b/src/inference/src/dev/threading/cpu_streams_executor_internal.cpp
index d994b5d40f5..547c149c3fc 100644
--- a/src/inference/src/dev/threading/cpu_streams_executor_internal.cpp
+++ b/src/inference/src/dev/threading/cpu_streams_executor_internal.cpp
@@ -92,8 +92,15 @@ void reserve_cpu_by_streams_info(const std::vector<std::vector<int>> _streams_in
int num_conditions = 0;
int condition_idx = 0;
bool last_all_proc = false;
+ bool sub_stream_enable = false;
for (size_t i = 0; i < _streams_info_table.size(); i++) {
+ if (i > 0 && _streams_info_table[i][NUMBER_OF_STREAMS] < 0 &&
+ _streams_info_table[i - 1][NUMBER_OF_STREAMS] > 0) {
+ stream_pos.clear();
+ num_streams = 0;
+ sub_stream_enable = true;
+ }
if (_streams_info_table[i][NUMBER_OF_STREAMS] != 0) {
stream_pos.push_back(num_streams);
}
@@ -109,11 +116,15 @@ void reserve_cpu_by_streams_info(const std::vector<std::vector<int>> _streams_in
std::string proc_type = "";
std::string numa_node = "";
std::string socket = "";
- if (_streams_info_table[i][NUMBER_OF_STREAMS] != 0) {
+ if ((_streams_info_table[i][NUMBER_OF_STREAMS] > 0 && !sub_stream_enable) ||
+ (_streams_info_table[i][NUMBER_OF_STREAMS] < 0 && sub_stream_enable)) {
streams_table.push_back(_streams_info_table[i]);
if (_streams_info_table[i][NUMBER_OF_STREAMS] < 0) {
- streams_table[streams_table.size() - 1][NUMBER_OF_STREAMS] = 1;
+ streams_table[streams_table.size() - 1][NUMBER_OF_STREAMS] =
+ std::abs(_streams_info_table[i][NUMBER_OF_STREAMS]);
}
+ } else if (_streams_info_table[i][NUMBER_OF_STREAMS] != 0) {
+ continue;
}
if (last_all_proc && _streams_info_table[i][NUMBER_OF_STREAMS] != 0) {
last_all_proc = false;
@@ -135,7 +146,7 @@ void reserve_cpu_by_streams_info(const std::vector<std::vector<int>> _streams_in
std::make_pair(proc_type + numa_node + socket, _streams_info_table[i][THREADS_PER_STREAM]));
threads_status[condition_idx].push_back(0);
}
- if (_streams_info_table[i][PROC_TYPE] > ALL_PROC && _streams_info_table[i][NUMBER_OF_STREAMS] > 0) {
+ if (_streams_info_table[i][PROC_TYPE] > ALL_PROC && _streams_info_table[i][NUMBER_OF_STREAMS] != 0) {
condition_idx++;
}
}
diff --git a/src/inference/src/dev/threading/istreams_executor.cpp b/src/inference/src/dev/threading/istreams_executor.cpp
index 822948e3ef1..53a0c32806c 100644
--- a/src/inference/src/dev/threading/istreams_executor.cpp
+++ b/src/inference/src/dev/threading/istreams_executor.cpp
@@ -332,32 +332,5 @@ void IStreamsExecutor::Config::set_config_zero_stream() {
_cpu_pinning = false;
}
-void IStreamsExecutor::run_sub_stream_and_wait(const std::vector<Task>& tasks) {
- std::vector<std::packaged_task<void()>> packagedTasks;
- std::vector<std::future<void>> futures;
- for (std::size_t i = 0; i < tasks.size(); ++i) {
- packagedTasks.emplace_back([&tasks, i] {
- tasks[i]();
- });
- futures.emplace_back(packagedTasks.back().get_future());
- }
- for (std::size_t i = 0; i < tasks.size(); ++i) {
- run_sub_stream(
- [&packagedTasks, i] {
- packagedTasks[i]();
- },
- static_cast<int>(i));
- }
- // std::future::get will rethrow exception from task.
- // We should wait all tasks before any exception is thrown.
- // So wait() and get() for each future moved to separate loops
- for (auto&& future : futures) {
- future.wait();
- }
- for (auto&& future : futures) {
- future.get();
- }
-}
-
} // namespace threading
} // namespace ov
diff --git a/src/inference/tests/unit/cpu_reserve_test.cpp b/src/inference/tests/unit/cpu_reserve_test.cpp
index 327bcff7499..21c7d374c94 100644
--- a/src/inference/tests/unit/cpu_reserve_test.cpp
+++ b/src/inference/tests/unit/cpu_reserve_test.cpp
@@ -427,7 +427,7 @@ LinuxCpuReserveTestCase _2sockets_72cores_hyper_1streams = {
{68, 1, 1, 68, MAIN_CORE_PROC, 32, -1}, {69, 1, 1, 69, MAIN_CORE_PROC, 33, -1},
{70, 1, 1, 70, MAIN_CORE_PROC, 34, -1}, {71, 1, 1, 71, MAIN_CORE_PROC, 35, -1},
},
- {{1, MAIN_CORE_PROC, 18, 0, 0}, {-1, MAIN_CORE_PROC, 18, 1, 1}},
+ {{1, MAIN_CORE_PROC, 36, -1, -1}, {-1, MAIN_CORE_PROC, 18, 0, 0}, {-1, MAIN_CORE_PROC, 18, 1, 1}},
{
{36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53},
{54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71},
@@ -789,7 +789,8 @@ LinuxCpuReserveTestCase _2sockets_104cores_1streams = {
{204, 3, 1, 102, HYPER_THREADING_PROC, 102, -1}, {205, 3, 1, 102, MAIN_CORE_PROC, 102, -1},
{206, 3, 1, 103, HYPER_THREADING_PROC, 103, -1}, {207, 3, 1, 103, MAIN_CORE_PROC, 103, -1},
},
- {{1, ALL_PROC, 104, -1, 0},
+ {{1, ALL_PROC, 208, -1, -1},
+ {-1, ALL_PROC, 104, -1, 0},
{0, MAIN_CORE_PROC, 26, 0, 0},
{0, MAIN_CORE_PROC, 26, 1, 0},
{0, HYPER_THREADING_PROC, 26, 0, 0},
diff --git a/src/plugins/intel_cpu/src/async_infer_request.cpp b/src/plugins/intel_cpu/src/async_infer_request.cpp
index b77d0059db7..8c5d0c8bc5c 100644
--- a/src/plugins/intel_cpu/src/async_infer_request.cpp
+++ b/src/plugins/intel_cpu/src/async_infer_request.cpp
@@ -4,6 +4,8 @@
#include "async_infer_request.h"
+#include "openvino/runtime/threading/cpu_message.hpp"
+
ov::intel_cpu::AsyncInferRequest::AsyncInferRequest(
const std::shared_ptr<IInferRequest>& request,
const std::shared_ptr<ov::threading::ITaskExecutor>& task_executor,
@@ -13,9 +15,17 @@ ov::intel_cpu::AsyncInferRequest::AsyncInferRequest(
}
ov::intel_cpu::AsyncInferRequest::~AsyncInferRequest() {
+ if (m_has_sub_infers) {
+ m_sub_infer_requests.clear();
+ }
stop_and_wait();
}
void ov::intel_cpu::AsyncInferRequest::throw_if_canceled() const {
check_cancelled_state();
}
+
+void ov::intel_cpu::AsyncInferRequest::setSubInferRequest(
+ const std::vector<std::shared_ptr<IAsyncInferRequest>>& requests) {
+ m_sub_infer_requests = requests;
+}
diff --git a/src/plugins/intel_cpu/src/async_infer_request.h b/src/plugins/intel_cpu/src/async_infer_request.h
index ebf1a210f30..0491bb26a80 100644
--- a/src/plugins/intel_cpu/src/async_infer_request.h
+++ b/src/plugins/intel_cpu/src/async_infer_request.h
@@ -17,7 +17,20 @@ public:
const std::shared_ptr<ov::threading::ITaskExecutor>& callback_executor);
~AsyncInferRequest();
+ void setSubInferRequest(const std::vector<std::shared_ptr<IAsyncInferRequest>>& requests);
+
+ std::vector<std::shared_ptr<ov::IAsyncInferRequest>> getSubInferRequest() const {
+ return m_sub_infer_requests;
+ }
+
+ void setSubInfer(bool has_sub_infer) {
+ m_has_sub_infers = has_sub_infer;
+ }
+
void throw_if_canceled() const;
+
+ std::vector<std::shared_ptr<ov::IAsyncInferRequest>> m_sub_infer_requests;
+ bool m_has_sub_infers = false;
};
} // namespace intel_cpu
diff --git a/src/plugins/intel_cpu/src/compiled_model.cpp b/src/plugins/intel_cpu/src/compiled_model.cpp
index 1a9f7f74099..af8df9657ad 100644
--- a/src/plugins/intel_cpu/src/compiled_model.cpp
+++ b/src/plugins/intel_cpu/src/compiled_model.cpp
@@ -17,6 +17,8 @@
#include "openvino/util/common_util.hpp"
#include "openvino/runtime/threading/cpu_streams_executor.hpp"
#include "transformations/utils/utils.hpp"
+#include "openvino/runtime/threading/cpu_streams_info.hpp"
+#include "openvino/runtime/threading/cpu_message.hpp"
#include "cpu/x64/cpu_isa_traits.hpp"
#include <cstring>
@@ -42,25 +44,33 @@ struct ImmediateSerialExecutor : public ov::threading::ITaskExecutor {
CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
const std::shared_ptr<const ov::IPlugin>& plugin,
const Config& cfg,
- const bool loaded_from_cache)
+ const bool loaded_from_cache,
+ const std::shared_ptr<SubMemoryManager> sub_memory_manager)
: ov::ICompiledModel::ICompiledModel(model, plugin),
m_model(model),
m_plugin(plugin),
m_cfg{cfg},
m_name{model->get_name()},
- m_loaded_from_cache(loaded_from_cache) {
+ m_loaded_from_cache(loaded_from_cache),
+ m_sub_memory_manager(sub_memory_manager) {
m_mutex = std::make_shared<std::mutex>();
const auto& core = m_plugin->get_core();
if (!core)
OPENVINO_THROW("Unable to get API version. Core is unavailable");
- ov::threading::IStreamsExecutor::Ptr stream_executor = nullptr;
+ IStreamsExecutor::Config executor_confg;
if (cfg.exclusiveAsyncRequests) {
// special case when all InferRequests are muxed into a single queue
m_task_executor = m_plugin->get_executor_manager()->get_executor("CPU");
} else {
- stream_executor = m_plugin->get_executor_manager()->get_idle_cpu_streams_executor(m_cfg.streamExecutorConfig);
- m_task_executor = stream_executor;
+ executor_confg = m_cfg.numSubStreams > 0 ? IStreamsExecutor::Config{"CPUMainStreamExecutor",
+ 1,
+ 1,
+ ov::hint::SchedulingCoreType::ANY_CORE,
+ false,
+ true}
+ : m_cfg.streamExecutorConfig;
+ m_task_executor = m_plugin->get_executor_manager()->get_idle_cpu_streams_executor(executor_confg);
}
if (0 != m_cfg.streamExecutorConfig.get_streams()) {
m_callback_executor = m_plugin->get_executor_manager()->get_idle_cpu_streams_executor(
@@ -74,11 +84,11 @@ CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
if (m_callback_executor)
set_callback_executor(m_callback_executor);
- int streams = std::max(1, m_cfg.streamExecutorConfig.get_streams());
+ int streams = std::max(1, executor_confg.get_streams());
std::vector<Task> tasks;
tasks.resize(streams);
m_graphs.resize(streams);
- if (m_cfg.streamExecutorConfig.get_streams() != 0) {
+ if (executor_confg.get_streams() != 0) {
auto all_graphs_ready = [&] {
return std::all_of(m_graphs.begin(), m_graphs.end(), [&](Graph& graph) {
return graph.IsReady();
@@ -102,15 +112,30 @@ CompiledModel::CompiledModel(const std::shared_ptr<ov::Model>& model,
} else {
CompiledModel::get_graph();
}
- // init sub stream threads of executor
- int sub_streams = m_cfg.streamExecutorConfig.get_sub_streams();
- if (sub_streams > 0 && stream_executor != nullptr) {
- std::vector<Task> tasks;
- tasks.resize(sub_streams);
- for (auto&& task : tasks) {
- task = [] {};
+ if (m_cfg.numSubStreams > 0) {
+ m_has_sub_compiled_models = true;
+ auto sub_cfg = m_cfg;
+ sub_cfg.numSubStreams = 0;
+ sub_cfg.enableNodeSplit = true;
+ auto streams_info_table = m_cfg.streamExecutorConfig.get_streams_info_table();
+ auto message = message_manager();
+ m_sub_memory_manager = std::make_shared<SubMemoryManager>(m_cfg.numSubStreams);
+ message->set_num_sub_streams(m_cfg.numSubStreams);
+ for (int i = 0; i < m_cfg.numSubStreams; i++) {
+ std::vector<std::vector<int>> sub_streams_table;
+ sub_streams_table.push_back(streams_info_table[i + 1]);
+ sub_streams_table[0][NUMBER_OF_STREAMS] = 1;
+ sub_cfg.streamExecutorConfig = IStreamsExecutor::Config{"CPUStreamsExecutor",
+ 1,
+ 1,
+ ov::hint::SchedulingCoreType::ANY_CORE,
+ false,
+ true,
+ sub_streams_table,
+ sub_cfg.streamsRankTable[i]};
+ m_sub_compiled_models.push_back(
+ std::make_shared<CompiledModel>(model, plugin, sub_cfg, loaded_from_cache, m_sub_memory_manager));
}
- stream_executor->run_sub_stream_and_wait(tasks);
}
}
@@ -130,11 +155,14 @@ CompiledModel::GraphGuard::Lock CompiledModel::get_graph() const {
GraphContext::Ptr ctx;
{
std::lock_guard<std::mutex> lock{*m_mutex.get()};
- auto isQuantizedFlag =
- (m_cfg.lpTransformsMode == Config::On) &&
- ov::pass::low_precision::LowPrecision::isFunctionQuantized(m_model);
+ auto isQuantizedFlag = (m_cfg.lpTransformsMode == Config::On) &&
+ ov::pass::low_precision::LowPrecision::isFunctionQuantized(m_model);
- ctx = std::make_shared<GraphContext>(m_cfg, m_socketWeights[socketId], isQuantizedFlag, streamsExecutor);
+ ctx = std::make_shared<GraphContext>(m_cfg,
+ m_socketWeights[socketId],
+ isQuantizedFlag,
+ streamsExecutor,
+ m_sub_memory_manager);
}
const std::shared_ptr<const ov::Model> model = m_model;
graphLock._graph.CreateGraph(model, ctx);
@@ -165,6 +193,14 @@ std::shared_ptr<ov::IAsyncInferRequest> CompiledModel::create_infer_request() co
std::make_shared<AsyncInferRequest>(std::static_pointer_cast<SyncInferRequest>(internal_request),
get_task_executor(),
get_callback_executor());
+ if (m_has_sub_compiled_models) {
+ std::vector<std::shared_ptr<IAsyncInferRequest>> requests;
+ for (auto model : m_sub_compiled_models) {
+ requests.push_back(model->create_infer_request());
+ }
+ async_infer_request->setSubInferRequest(requests);
+ async_infer_request->setSubInfer(true);
+ }
return async_infer_request;
}
diff --git a/src/plugins/intel_cpu/src/compiled_model.h b/src/plugins/intel_cpu/src/compiled_model.h
index 64caee60aeb..facd9ef3698 100644
--- a/src/plugins/intel_cpu/src/compiled_model.h
+++ b/src/plugins/intel_cpu/src/compiled_model.h
@@ -14,6 +14,7 @@
#include "openvino/runtime/iplugin.hpp"
#include "openvino/runtime/isync_infer_request.hpp"
#include "openvino/runtime/threading/thread_local.hpp"
+#include "sub_memory_manager.hpp"
namespace ov {
namespace intel_cpu {
@@ -25,7 +26,15 @@ public:
CompiledModel(const std::shared_ptr<ov::Model>& model,
const std::shared_ptr<const ov::IPlugin>& plugin,
const Config& cfg,
- const bool loaded_from_cache);
+ const bool loaded_from_cache,
+ const std::shared_ptr<SubMemoryManager> sub_memory_manager = nullptr);
+
+ ~CompiledModel() {
+ if (m_has_sub_compiled_models) {
+ m_sub_compiled_models.clear();
+ m_sub_memory_manager->_memorys_table.clear();
+ }
+ }
std::shared_ptr<ov::IAsyncInferRequest> create_infer_request() const override;
@@ -73,6 +82,14 @@ private:
* even from main thread
*/
GraphGuard::Lock get_graph() const;
+
+ std::vector<std::shared_ptr<CompiledModel>> get_sub_compiled_models() const {
+ return m_sub_compiled_models;
+ }
+
+ std::vector<std::shared_ptr<CompiledModel>> m_sub_compiled_models;
+ std::shared_ptr<SubMemoryManager> m_sub_memory_manager = nullptr;
+ bool m_has_sub_compiled_models = false;
};
} // namespace intel_cpu
diff --git a/src/plugins/intel_cpu/src/config.h b/src/plugins/intel_cpu/src/config.h
index 4ca6332c25c..e0bcc6786a8 100644
--- a/src/plugins/intel_cpu/src/config.h
+++ b/src/plugins/intel_cpu/src/config.h
@@ -66,6 +66,7 @@ struct Config {
int threadsPerStream = 0;
ov::threading::IStreamsExecutor::ThreadBindingType threadBindingType = ov::threading::IStreamsExecutor::ThreadBindingType::NONE;
ov::hint::PerformanceMode hintPerfMode = ov::hint::PerformanceMode::LATENCY;
+ std::vector<std::vector<int>> streamsRankTable;
bool changedHintPerfMode = false;
ov::log::Level logLevel = ov::log::Level::NO;
uint32_t hintNumRequests = 0;
@@ -73,6 +74,9 @@ struct Config {
bool changedCpuPinning = false;
ov::hint::SchedulingCoreType schedulingCoreType = ov::hint::SchedulingCoreType::ANY_CORE;
std::set<ov::hint::ModelDistributionPolicy> modelDistributionPolicy = {};
+ int streamsRankLevel = 1;
+ int numSubStreams = 0;
+ bool enableNodeSplit = false;
bool enableHyperThreading = true;
bool changedHyperThreading = false;
#if defined(OPENVINO_ARCH_X86) || defined(OPENVINO_ARCH_X86_64)
diff --git a/src/plugins/intel_cpu/src/cpu_memory.cpp b/src/plugins/intel_cpu/src/cpu_memory.cpp
index ab454382f57..fac71e9e5bc 100644
--- a/src/plugins/intel_cpu/src/cpu_memory.cpp
+++ b/src/plugins/intel_cpu/src/cpu_memory.cpp
@@ -6,6 +6,7 @@
#include "memory_desc/cpu_memory_desc_utils.h"
#include <common/memory_desc_wrapper.hpp>
#include "nodes/reorder.h"
+#include "nodes/common/cpu_memcpy.h"
#include "utils/debug_capabilities.h"
#if defined(__linux__)
# include <sys/syscall.h> /* Definition of SYS_* constants */
@@ -657,5 +658,125 @@ bool mbind_move(const dnnl::memory mem, int numaNodeID) {
return mbind_move(data, size, numaNodeID);
}
+MemoryPtr split_horizontal(const dnnl::engine& eng, const MemoryPtr src, int dim, int w_rank, int w_size, bool need_fill) {
+ auto desc = src->getDescPtr();
+ auto shape = src->getShape();
+ auto dims = shape.getDims();
+ auto prec = src->getPrecision();
+ if (dim < 0) {
+ dim += dims.size();
+ }
+ auto split_parts = [](int len, int n) {
+ int average = len / n;
+ std::vector<int> parts(n, average);
+ parts.back() = len - average * (n - 1);
+ return parts;
+ };
+ if (shape.isDynamic()) {
+ // if the dim is dynamic, should return a dynamic dim without any change.
+ // if the dim is static, should split it indeed.
+ const auto& pshape = shape.toPartialShape();
+ if (pshape[dim].is_dynamic()) {
+ return src;
+ }
+ auto new_pshape = pshape;
+ auto splited_dim_vec = split_parts(new_pshape[dim].get_length(), w_size);
+ new_pshape[dim] = splited_dim_vec[w_rank];
+
+ auto new_desc = std::make_shared<CpuBlockedMemoryDesc>(prec, Shape{new_pshape});
+ MemoryPtr ptr = std::make_shared<Memory>(eng, new_desc);
+ return ptr;
+ }
+ assert(dims[dim] >= w_size);
+ auto splited_dim_vec = split_parts(dims[dim], w_size);
+
+ // reference stride
+ VectorDims stride_dims = dims;
+ stride_dims[dim] = splited_dim_vec[0];
+ size_t stride = std::accumulate(stride_dims.begin(), stride_dims.end(), static_cast<size_t>(1), std::multiplies<size_t>()) * prec.size();
+
+ // create new shape for target memory
+ VectorDims new_dims = dims;
+ new_dims[dim] = splited_dim_vec[w_rank];
+
+ auto new_desc = desc->cloneWithNewDims(new_dims, true);
+ if (!need_fill) {
+ MemoryPtr ptr = std::make_shared<Memory>(eng, new_desc, nullptr);
+ return ptr;
+ }
+
+ auto srcPtr = static_cast<uint8_t*>(src->getData());
+ if (prec == ov::element::u4 || prec == ov::element::i4) {
+ stride /= 2;
+ }
+
+ MemoryPtr ptr = std::make_shared<Memory>(eng, new_desc, srcPtr + w_rank * stride);
+ return ptr;
+}
+
+MemoryPtr split_vertical(const dnnl::engine& eng, const MemoryPtr src, int dim, int w_rank, int w_size, bool need_fill) {
+ auto desc = src->getDescPtr();
+ auto shape = src->getShape();
+ auto dims = shape.getDims();
+ auto prec = src->getPrecision();
+ if (dim < 0) {
+ dim += dims.size();
+ }
+ auto split_parts = [](int len, int n) {
+ int average = len / n;
+ std::vector<int> parts(n, average);
+ parts.back() = len - average * (n - 1);
+ return parts;
+ };
+ if (shape.isDynamic()) {
+ const auto& pshape = shape.toPartialShape();
+ if (pshape[dim].is_dynamic()) {
+ OPENVINO_THROW("Can't split data with dynamic shapes");
+ }
+ auto new_pshape = pshape;
+ auto splited_dim_vec = split_parts(new_pshape[dim].get_length(), w_size);
+ new_pshape[dim] = splited_dim_vec[w_rank];
+
+ auto new_desc = std::make_shared<CpuBlockedMemoryDesc>(prec, Shape{new_pshape});
+ MemoryPtr ptr = std::make_shared<Memory>(eng, new_desc);
+ return ptr;
+ }
+ assert(dims[dim] >= w_size);
+ const auto splited_size = dims[dim] * prec.size();
+ auto splited_dim_vec = split_parts(dims[dim], w_size);
+ auto element_size = prec.size();
+
+ VectorDims new_dims = dims;
+ new_dims[dim] = splited_dim_vec[w_rank];
+
+ auto new_desc = desc->cloneWithNewDims(new_dims, true);
+ MemoryPtr ptr = std::make_shared<Memory>(eng, new_desc);
+ if (!need_fill) {
+ return ptr;
+ }
+ // copy
+ auto srcPtr = static_cast<uint8_t*>(src->getData());
+ auto dstPtr = static_cast<uint8_t*>(ptr->getData());
+ // selected dim bytes
+ auto channel_size = dims[dim] * element_size;
+ // total bytes
+ auto mem_size = src->getSize();
+ // the steps need to copy.
+ const int step = (mem_size / channel_size);
+ // bytes of selected dim.
+ auto strideSize = splited_dim_vec[0] * element_size;
+ auto copySize = splited_dim_vec[w_rank] * element_size;
+ if (prec == ov::element::u4 || prec == ov::element::i4) {
+ strideSize /= 2;
+ copySize /= 2;
+ }
+ parallel_for(step, [&](int i){
+ int dst_offset = i * copySize;
+ int src_offset = i * splited_size + w_rank * strideSize;
+ cpu_parallel_memcpy(dstPtr + dst_offset, srcPtr + src_offset, copySize);
+ });
+ return ptr;
+}
+
} // namespace intel_cpu
} // namespace ov
diff --git a/src/plugins/intel_cpu/src/cpu_memory.h b/src/plugins/intel_cpu/src/cpu_memory.h
index 69b70cb6e58..f62c2f05257 100644
--- a/src/plugins/intel_cpu/src/cpu_memory.h
+++ b/src/plugins/intel_cpu/src/cpu_memory.h
@@ -463,5 +463,8 @@ bool mbind_move(void* data, size_t size, int numaNodeID);
bool mbind_move(const MemoryCPtr mem, int numaNodeID);
bool mbind_move(const dnnl::memory mem, int numaNodeID);
+MemoryPtr split_horizontal(const dnnl::engine& eng, const MemoryPtr src, int dim, int w_rank, int w_size, bool need_fill = true);
+MemoryPtr split_vertical(const dnnl::engine& eng, const MemoryPtr src, int dim, int w_rank, int w_size, bool need_fill = true);
+
} // namespace intel_cpu
} // namespace ov
diff --git a/src/plugins/intel_cpu/src/cpu_streams_calculation.cpp b/src/plugins/intel_cpu/src/cpu_streams_calculation.cpp
index 08ba43f9eff..fb8294e5ce2 100644
--- a/src/plugins/intel_cpu/src/cpu_streams_calculation.cpp
+++ b/src/plugins/intel_cpu/src/cpu_streams_calculation.cpp
@@ -22,6 +22,7 @@ using namespace ov;
using namespace ov::threading;
#define INIT_VAL -100
+#define TP_CPU_LIMIT 32
namespace ov {
namespace intel_cpu {
@@ -101,17 +102,24 @@ std::vector<std::vector<int>> get_streams_info_table(const int input_streams,
const std::vector<std::vector<int>>& one_proc_table,
const int num_threads,
const IStreamsExecutor::Config::StreamsMode sub_streams_model) {
+ stream_info[THREADS_PER_STREAM] = sub_streams_model == IStreamsExecutor::Config::StreamsMode::SUB_STREAMS_NULL
+ ? num_threads
+ : std::min(TP_CPU_LIMIT, num_threads);
if ((one_proc_info[PROC_NUMA_NODE_ID] < 0) || (one_proc_info[PROC_SOCKET_ID] < 0) ||
- (((one_proc_info[MAIN_CORE_PROC] > 0) && (one_proc_info[MAIN_CORE_PROC] < num_threads)) ||
+ (((one_proc_info[MAIN_CORE_PROC] > 0) &&
+ (one_proc_info[MAIN_CORE_PROC] < stream_info[THREADS_PER_STREAM])) ||
((one_proc_info[MAIN_CORE_PROC] == 0) && (one_proc_info[EFFICIENT_CORE_PROC] > 0) &&
- (one_proc_info[EFFICIENT_CORE_PROC] < num_threads)))) {
- update_mix_stream_info(one_proc_info, one_proc_table, num_threads, sub_streams_model, ALL_PROC);
+ (one_proc_info[EFFICIENT_CORE_PROC] < stream_info[THREADS_PER_STREAM])))) {
+ update_mix_stream_info(one_proc_info,
+ one_proc_table,
+ stream_info[THREADS_PER_STREAM],
+ sub_streams_model,
+ ALL_PROC);
} else {
stream_info[PROC_TYPE] =
- one_proc_info[MAIN_CORE_PROC] >= num_threads ? MAIN_CORE_PROC : EFFICIENT_CORE_PROC;
+ one_proc_info[MAIN_CORE_PROC] >= stream_info[THREADS_PER_STREAM] ? MAIN_CORE_PROC : EFFICIENT_CORE_PROC;
stream_info[NUMBER_OF_STREAMS] =
sub_streams_model == IStreamsExecutor::Config::StreamsMode::SUB_STREAMS_NULL ? 1 : -1;
- stream_info[THREADS_PER_STREAM] = num_threads;
update_ids_method(one_proc_info);
streams_info_table.push_back(stream_info);
}
@@ -371,7 +379,7 @@ std::vector<std::vector<int>> get_streams_info_table(const int input_streams,
create_one_stream(proc_socket_table[current_socket_id],
proc_type_table,
proc_socket_table[current_socket_id][ALL_PROC],
- IStreamsExecutor::Config::StreamsMode::SUB_STREAMS_NULL);
+ IStreamsExecutor::Config::StreamsMode::SUB_STREAMS_FOR_SOCKET);
for (size_t n_node = 0; n_node < proc_socket_table.size(); n_node++) {
if (n_node != size_t(current_socket_id)) {
create_one_stream(proc_socket_table[n_node],
@@ -380,6 +388,23 @@ std::vector<std::vector<int>> get_streams_info_table(const int input_streams,
IStreamsExecutor::Config::StreamsMode::SUB_STREAMS_FOR_SOCKET);
}
}
+ stream_info = streams_info_table[0];
+ stream_info[NUMBER_OF_STREAMS] = 1;
+ for (size_t n = 1; n < streams_info_table.size(); n++) {
+ if (streams_info_table[n][NUMBER_OF_STREAMS] == -1) {
+ if (stream_info[PROC_TYPE] != streams_info_table[n][PROC_TYPE]) {
+ stream_info[PROC_TYPE] = ALL_PROC;
+ }
+ stream_info[THREADS_PER_STREAM] += streams_info_table[n][THREADS_PER_STREAM];
+ if (stream_info[STREAM_NUMA_NODE_ID] != streams_info_table[n][STREAM_NUMA_NODE_ID]) {
+ stream_info[STREAM_NUMA_NODE_ID] = -1;
+ }
+ if (stream_info[STREAM_SOCKET_ID] != streams_info_table[n][STREAM_SOCKET_ID]) {
+ stream_info[STREAM_SOCKET_ID] = -1;
+ }
+ }
+ }
+ streams_info_table.insert(streams_info_table.begin(), stream_info);
n_streams--;
}
@@ -462,6 +487,33 @@ std::vector<std::vector<int>> get_streams_info_table(const int input_streams,
return streams_info_table;
}
+std::vector<std::vector<int>> get_streams_rank_table(const std::vector<std::vector<int>>& streams_info_table,
+ const int input_rank_level,
+ int& num_sub_streams) {
+ std::vector<std::vector<int>> rank_table = {};
+ num_sub_streams = 0;
+ std::vector<int> init_rank = {};
+ int rank_level = input_rank_level == 0 ? 1 : input_rank_level;
+ init_rank.resize(rank_level, 0);
+
+ for (auto& row : streams_info_table) {
+ if (row[NUMBER_OF_STREAMS] < 0) {
+ for (int i = 0; i < abs(row[NUMBER_OF_STREAMS]); i++) {
+ init_rank[rank_level - 1] = num_sub_streams + i;
+ rank_table.push_back(init_rank);
+ }
+ num_sub_streams -= row[NUMBER_OF_STREAMS];
+ }
+ }
+ if (rank_level == 2) {
+ for (int i = num_sub_streams / 2; i < num_sub_streams; i++) {
+ rank_table[i][0] = 1;
+ rank_table[i][1] -= num_sub_streams / 2;
+ }
+ }
+ return rank_table;
+}
+
int get_model_prefer_threads(const int num_streams,
const std::vector<std::vector<int>> proc_type_table,
const std::shared_ptr<ov::Model>& model,
@@ -608,6 +660,12 @@ std::vector<std::vector<int>> generate_stream_info(const int streams,
ov::util::to_string(config.hintPerfMode),
config.modelDistributionPolicy,
proc_type_table);
+ // streams_info_table = {{1, 1, 56, 1, 1}, {-1, 1, 28, 1, 1}, {-1, 1, 28, 0, 0}};
+ if (config.modelDistributionPolicy.find(ov::hint::ModelDistributionPolicy::TENSOR_PARALLEL) !=
+ config.modelDistributionPolicy.end()) {
+ config.streamsRankTable =
+ get_streams_rank_table(streams_info_table, config.streamsRankLevel, config.numSubStreams);
+ }
auto cpu_pinning =
get_cpu_pinning(config.enableCpuPinning, config.changedCpuPinning, proc_type_table, streams_info_table);
diff --git a/src/plugins/intel_cpu/src/cpu_streams_calculation.hpp b/src/plugins/intel_cpu/src/cpu_streams_calculation.hpp
index 584f9a2d9a0..e362c0373d8 100644
--- a/src/plugins/intel_cpu/src/cpu_streams_calculation.hpp
+++ b/src/plugins/intel_cpu/src/cpu_streams_calculation.hpp
@@ -53,6 +53,18 @@ std::vector<std::vector<int>> get_streams_info_table(const int input_streams,
const std::string input_perf_hint,
const std::set<ov::hint::ModelDistributionPolicy> hint_llm_distribution_policy,
const std::vector<std::vector<int>>& proc_type_table);
+
+/**
+ * @brief Generate streams rank table for tensor parallel according to streams info table.
+ * @param[in] streams_info_table is streams information table for tensor parallel.
+ * @param[in] input_rank_level is depth of rank nesting.
+ * @param[out] num_sub_streams is number of sub streams for tensor parallel.
+ * @return streams rank table which will be used by StreamsExecutor.
+ */
+std::vector<std::vector<int>> get_streams_rank_table(const std::vector<std::vector<int>>& streams_info_table,
+ const int input_rank_level,
+ int& num_sub_streams);
+
/**
* @brief Get model_prefer_threads
* @param[in] num_streams is target streams set by user via NUM_STREAMS or hints.
diff --git a/src/plugins/intel_cpu/src/graph.cpp b/src/plugins/intel_cpu/src/graph.cpp
index bfb28f769b9..898f69fef76 100644
--- a/src/plugins/intel_cpu/src/graph.cpp
+++ b/src/plugins/intel_cpu/src/graph.cpp
@@ -233,30 +233,6 @@ void Graph::Replicate(const std::shared_ptr<const ov::Model> &model) {
}
}
-void Graph::GroupParallelNodes() {
- std::map<std::string, std::vector<NodePtr>> pdomain_nodes;
- for (size_t k = 0; k < graphNodes.size(); k++) {
- auto& node = graphNodes[k];
- auto& domain = node->getParallelDomain();
- if (domain.empty())
- continue;
- if (pdomain_nodes.count(domain) == 0)
- pdomain_nodes[domain] = {};
- pdomain_nodes[domain].push_back(node);
- }
-
- // record valid paralell_nodes
- for (auto& pn : pdomain_nodes) {
- auto& node_ptrs = pn.second;
- if (node_ptrs.size() > 1) {
- // parallelWith includes pointer to itself
- for (auto& pnode : node_ptrs) {
- pnode->parallelWith = node_ptrs;
- }
- }
- }
-}
-
static std::vector<size_t> IdentifySyncPoints(const std::vector<NodePtr>& graphNodes) {
OV_ITT_SCOPE(FIRST_INFERENCE, itt::domains::intel_cpu_LT, "Graph::IdentifySyncPoints");
std::vector<size_t> syncNodesInds;
@@ -352,8 +328,6 @@ void Graph::InitGraph(bool optimize) {
optimizer.ApplyImplSpecificGraphOptimizations(*this);
- GroupParallelNodes();
-
SortTopologically();
const bool hasDynNodes = ProcessDynNodes();
@@ -1382,87 +1356,27 @@ void Graph::InferDynamic(SyncInferRequest* request, UpdateStrategy&& update) {
}
inline void Graph::ExecuteNode(const NodePtr& node, const dnnl::stream& stream) const {
- if (!node->parallelWith.empty()) {
- // run nodes in parallel
- auto& parallelNodes = node->parallelWith;
- if (node == parallelNodes[0]) {
- if (const auto& cpuExecutor = context->getCPUStreamExecutor()) {
- auto num_parallel_nodes = parallelNodes.size();
- ParalleMtNuma(num_parallel_nodes, cpuExecutor, [&](int subStreamID, size_t i) {
- auto& n = parallelNodes[i];
-
- if (n->isDynamicNode()) {
- n->executeDynamic(stream, subStreamID);
- } else {
- n->executeStatic(stream, subStreamID);
- }
- });
- } else {
- // fallback to serialize executor
- for (auto& node : parallelNodes) {
- if (node->isDynamicNode()) {
- node->executeDynamic(stream);
- } else {
- node->executeStatic(stream);
- }
- }
- }
- }
+ DUMP(node, getConfig().debugCaps, infer_count);
+ OV_ITT_SCOPED_TASK(itt::domains::intel_cpu, node->profiling.execute);
+ DEBUG_LOG(*node);
+ // TODO: 132954 workaround for latency
+ int numaID = GetNumaNodeId();
+ if (node->isDynamicNode()) {
+ node->executeDynamic(stream, numaID);
} else {
- DUMP(node, getConfig().debugCaps, infer_count);
- OV_ITT_SCOPED_TASK(itt::domains::intel_cpu, node->profiling.execute);
- DEBUG_LOG(*node);
- // TODO: 132954 workaround for latency
- int subStreamID = -1;
-#if defined(__x86_64__) && defined(__linux__)
- if ((getGraphContext()->getCPUStreamExecutor()) && (getConfig().hintPerfMode == ov::hint::PerformanceMode::LATENCY)) {
- subStreamID = getGraphContext()->getCPUStreamExecutor()->get_numa_node_id();
- }
-#endif
- if (node->isDynamicNode()) {
- node->executeDynamic(stream, subStreamID);
- } else {
- node->executeStatic(stream, subStreamID);
- }
+ node->executeStatic(stream, numaID);
}
}
-void Graph::ParalleMtNuma(size_t num_nodes,
- ov::threading::CPUStreamsExecutor::Ptr executor,
- const std::function<void(size_t, size_t)>& func) const {
- OPENVINO_ASSERT(num_nodes > 1, "Parallel Nodes must be more than 1. But now got ",
- num_nodes,
- " Nodes, which shouldn't invoke multi nodes parallel.");
- std::atomic<int> nodes_remain(num_nodes);
- int cur_numa_id = executor->get_numa_node_id();
- // enqueue (nsockets-1) sub stream tasks
- int sub_stream_id = 0;
- for (size_t socket_id = 0; socket_id < num_nodes; socket_id++) {
- if (socket_id != static_cast<size_t>(cur_numa_id)) {
- size_t i0{0}, i1{0};
- splitter(num_nodes, num_nodes, socket_id, i0, i1);
- executor->run_sub_stream(
- [socket_id, i0, i1, &func, &nodes_remain]() {
- for (size_t i = i0; i < i1; i++) {
- func(socket_id, i);
- nodes_remain--;
- }
- },
- sub_stream_id);
- sub_stream_id++;
- }
- }
- // run in main stream (current socket)
- {
- size_t i0{0}, i1{0};
- splitter(num_nodes, num_nodes, static_cast<size_t>(cur_numa_id), i0, i1);
- for (size_t i = i0; i < i1; i++) {
- func(cur_numa_id, i);
- nodes_remain--;
- }
+int Graph::GetNumaNodeId() const {
+ int numaNodeId = -1;
+#if defined(__x86_64__) && defined(__linux__)
+ if ((getGraphContext()->getCPUStreamExecutor()) &&
+ (getConfig().hintPerfMode == ov::hint::PerformanceMode::LATENCY)) {
+ numaNodeId = getGraphContext()->getCPUStreamExecutor()->get_numa_node_id();
}
- // wait and sync
- while (nodes_remain.load() > 0) {}
+#endif
+ return numaNodeId;
}
void Graph::Infer(SyncInferRequest* request) {
@@ -1504,29 +1418,12 @@ void Graph::SortTopologically() {
if (node->execIndex >= 0)
return; // already visited
- if (!node->parallelWith.empty()) {
- for (auto& n : node->parallelWith) {
- for (size_t i = 0; i < n->getParentEdges().size(); i++) {
- visit(n->getParentEdgeAt(i)->getParent());
- }
- }
-
- // parallel nodes has same execIndex
- // so they can provide correct start/end time point for
- // their input and output memory object
- ++execIndexCnt;
- for (auto& n : node->parallelWith) {
- sorted.push_back(n);
- n->execIndex = execIndexCnt;
- }
- } else {
- for (size_t i = 0; i < node->getParentEdges().size(); i++) {
- visit(node->getParentEdgeAt(i)->getParent());
- }
-
- sorted.push_back(node);
- node->execIndex = ++execIndexCnt;
+ for (size_t i = 0; i < node->getParentEdges().size(); i++) {
+ visit(node->getParentEdgeAt(i)->getParent());
}
+
+ sorted.push_back(node);
+ node->execIndex = ++execIndexCnt;
};
// First execute MemoryInput because it will change the memory pointer of
diff --git a/src/plugins/intel_cpu/src/graph.h b/src/plugins/intel_cpu/src/graph.h
index 6816dcc75c1..f91275f399c 100644
--- a/src/plugins/intel_cpu/src/graph.h
+++ b/src/plugins/intel_cpu/src/graph.h
@@ -223,7 +223,6 @@ protected:
void ResolveEdgeConflicts();
void ResolveComplexInplaceConflicts();
bool ProcessDynNodes();
- void GroupParallelNodes();
void Allocate(const std::vector<size_t>& syncNodesInds);
void AllocateWithReuse(const std::vector<size_t>& syncNodesInds);
void ExecuteNode(const NodePtr& node, const dnnl::stream& stream) const;
@@ -232,9 +231,6 @@ protected:
template<typename UpdateStrategy>
void InferDynamic(SyncInferRequest* request, UpdateStrategy&& update);
- void ParalleMtNuma(size_t num_nodes,
- ov::threading::CPUStreamsExecutor::Ptr executor,
- const std::function<void(size_t, size_t)>& func) const;
friend class intel_cpu::SyncInferRequest;
friend std::shared_ptr<ov::Model> dump_graph_as_ie_ngraph_net(const Graph &graph);
@@ -259,6 +255,7 @@ private:
void EnforceBF16();
void insertReorder(EdgePtr& edge, bool isOptimized, std::unordered_set<std::string>& uniqueLayerNames);
void insertConvert(EdgePtr& edge);
+ int GetNumaNodeId() const;
};
using GraphPtr = std::shared_ptr<Graph>;
diff --git a/src/plugins/intel_cpu/src/graph_context.cpp b/src/plugins/intel_cpu/src/graph_context.cpp
index c06cb614d03..2699a8854af 100644
--- a/src/plugins/intel_cpu/src/graph_context.cpp
+++ b/src/plugins/intel_cpu/src/graph_context.cpp
@@ -11,11 +11,13 @@ namespace intel_cpu {
GraphContext::GraphContext(const Config& config,
WeightsSharing::Ptr w_cache,
bool isGraphQuantized,
- ov::threading::IStreamsExecutor::Ptr streamExecutor)
+ ov::threading::IStreamsExecutor::Ptr streamExecutor,
+ std::shared_ptr<SubMemoryManager> sub_memory_manager)
: config(config),
weightsCache(std::move(w_cache)),
isGraphQuantizedFlag(isGraphQuantized),
streamExecutor(streamExecutor),
+ subMemoryManager(sub_memory_manager),
memoryStatesRegister(std::make_shared<node::MemoryStatesRegister>()) {
rtParamsCache = std::make_shared<MultiCache>(config.rtCacheCapacity);
// primitive/executors can be shared across sub-stream
diff --git a/src/plugins/intel_cpu/src/graph_context.h b/src/plugins/intel_cpu/src/graph_context.h
index 0bca410fca3..138ccebe0f9 100644
--- a/src/plugins/intel_cpu/src/graph_context.h
+++ b/src/plugins/intel_cpu/src/graph_context.h
@@ -5,6 +5,7 @@
#pragma once
#include "openvino/runtime/threading/cpu_streams_executor.hpp"
+#include "sub_memory_manager.hpp"
#include "cache/multi_cache.h"
#include "config.h"
#include "dnnl_scratch_pad.h"
@@ -25,7 +26,8 @@ public:
GraphContext(const Config& config,
WeightsSharing::Ptr w_cache,
bool isGraphQuantized,
- ov::threading::IStreamsExecutor::Ptr streamExecutor = nullptr);
+ ov::threading::IStreamsExecutor::Ptr streamExecutor = nullptr,
+ std::shared_ptr<SubMemoryManager> sub_memory_manager = nullptr);
const Config& getConfig() const {
return config;
@@ -62,6 +64,10 @@ public:
return cpuStreamExecutor;
}
+ std::shared_ptr<SubMemoryManager> getSubMemory() const {
+ return subMemoryManager;
+ }
+
int getNumNumaNodes() const {
return numNumaNodes;
}
@@ -86,6 +92,8 @@ private:
ov::threading::CPUStreamsExecutor::Ptr cpuStreamExecutor; // cpu stream executor for current graph
+ std::shared_ptr<SubMemoryManager> subMemoryManager;
+
int numNumaNodes = 1;
std::shared_ptr<node::MemoryStatesRegister> memoryStatesRegister;
diff --git a/src/plugins/intel_cpu/src/infer_request.cpp b/src/plugins/intel_cpu/src/infer_request.cpp
index 82b72137b6b..2d382c00508 100644
--- a/src/plugins/intel_cpu/src/infer_request.cpp
+++ b/src/plugins/intel_cpu/src/infer_request.cpp
@@ -18,6 +18,7 @@
#include "proxy_mem_mgr.h"
#include "utils/general_utils.h"
#include "utils/ngraph_utils.hpp"
+#include "openvino/runtime/threading/cpu_message.hpp"
using OvString = ov::element_type_traits<ov::element::string>::value_type;
@@ -104,8 +105,15 @@ void SyncInferRequest::infer() {
OV_ITT_SCOPED_TASK(itt::domains::intel_cpu, m_profiling_task);
auto graphLock = m_compiled_model->get_graph();
m_graph = &(graphLock._graph);
+ auto message = ov::threading::message_manager();
throw_if_canceled();
+ if (m_asyncRequest->m_has_sub_infers) {
+ sub_streams_infer();
+ message->server_wait();
+ return;
+ }
+
convert_batched_tensors();
if (m_batched_tensors.size() > 0) {
// batched_tensors will be updated for each infer, external_ptr should be update together
@@ -303,6 +311,15 @@ void SyncInferRequest::change_default_ptr() {
}
std::vector<ov::SoPtr<ov::IVariableState>> SyncInferRequest::query_state() const {
+ if (m_asyncRequest->m_has_sub_infers) {
+ auto requests = m_asyncRequest->getSubInferRequest();
+ std::vector<ov::SoPtr<ov::IVariableState>> states;
+ for (auto request : requests) {
+ auto cur = request->query_state();
+ states.insert(states.end(), cur.begin(), cur.end());
+ }
+ return states;
+ }
return {m_memory_states.begin(), m_memory_states.end()};
}
@@ -600,6 +617,38 @@ SyncInferRequest::OutputControlBlock::OutputControlBlock(const ov::element::Type
m_tensor = std::make_shared<Tensor>(memory);
}
+void SyncInferRequest::sub_streams_infer() {
+ std::map<ov::Output<const ov::Node>, ov::SoPtr<ov::ITensor>> input_tensors;
+ auto message = ov::threading::message_manager();
+ auto requests = m_asyncRequest->getSubInferRequest();
+ auto inputs = get_inputs();
+ auto outputs = get_outputs();
+
+ size_t requests_num = requests.size();
+
+ if (requests.size() > 0) {
+ for (const auto& output : outputs) {
+ auto tensor = requests[0]->get_tensor(output);
+ set_tensor(output, tensor);
+ }
+ for (size_t i = 0; i < requests_num; i++) {
+ for (auto& input : inputs) {
+ auto tensor = get_tensor(input);
+ requests[i]->set_tensor(input, tensor);
+ }
+
+ requests[i]->set_callback([message](const std::exception_ptr& ptr) {
+ ov::threading::MessageInfo msg_info;
+ msg_info.msg_type = ov::threading::MsgType::CALL_BACK;
+ message->send_message(msg_info);
+ });
+ }
+ for (size_t i = 0; i < requests_num; i++) {
+ requests[i]->start_async();
+ }
+ }
+}
+
} // namespace intel_cpu
} // namespace ov
diff --git a/src/plugins/intel_cpu/src/infer_request.h b/src/plugins/intel_cpu/src/infer_request.h
index e3839466f0c..2e097c87673 100644
--- a/src/plugins/intel_cpu/src/infer_request.h
+++ b/src/plugins/intel_cpu/src/infer_request.h
@@ -104,6 +104,8 @@ private:
const ov::Output<const ov::Node>& get_internal_port(const ov::Output<const ov::Node>& port) const;
+ void sub_streams_infer();
+
private:
std::unordered_map<std::size_t, OutputControlBlock> m_outputControlBlocks;
diff --git a/src/plugins/intel_cpu/src/node.h b/src/plugins/intel_cpu/src/node.h
index eb1f84dc8b9..2095907b860 100644
--- a/src/plugins/intel_cpu/src/node.h
+++ b/src/plugins/intel_cpu/src/node.h
@@ -658,7 +658,6 @@ protected:
std::vector <NodePtr> fusedWith;
std::vector <NodePtr> mergedWith;
- std::vector <NodePtr> parallelWith;
int curNumaNode = -1;
void toNumaNode(int numaID);
diff --git a/src/plugins/intel_cpu/src/nodes/fullyconnected.cpp b/src/plugins/intel_cpu/src/nodes/fullyconnected.cpp
index da3dcafa475..d7fbd942e12 100644
--- a/src/plugins/intel_cpu/src/nodes/fullyconnected.cpp
+++ b/src/plugins/intel_cpu/src/nodes/fullyconnected.cpp
@@ -9,6 +9,7 @@
#include <openvino/op/constant.hpp>
#include "common/cpu_convert.h"
+#include "common/cpu_memcpy.h"
#include "dnnl_extension_utils.h"
#include "executors/memory_arguments.hpp"
#include "graph_context.h"
@@ -19,6 +20,7 @@
#include "nodes/executors/executor.hpp"
#include "nodes/executors/fullyconnected_config.hpp"
#include "openvino/core/type/element_type.hpp"
+#include "openvino/runtime/threading/cpu_message.hpp"
#include "post_ops.hpp"
#include "shape_inference/custom/fullyconnected.hpp"
#include "transformations/cpu_opset/common/op/fully_connected.hpp"
@@ -58,10 +60,23 @@ bool FullyConnected::isSupportedOperation(const std::shared_ptr<const ov::Node>&
return true;
}
+void FullyConnected::initTensorParallelConfig(const GraphContext::CPtr context) {
+ if (context->getCPUStreamExecutor()) {
+ if (!context->getCPUStreamExecutor()->get_rank().empty()) {
+ // init tp_cfg.w_rank and tp_cfg.w_size
+ tp_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.sub_memory = context->getSubMemory();
+ }
+ }
+}
+
FullyConnected::FullyConnected(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr context)
: Node(op, context, FCShapeInferFactory(op)),
errorPrefix("FullyConnected node with name '" + getName() + "'") {
std::string errorMessage;
+ initTensorParallelConfig(context);
if (!isSupportedOperation(op, errorMessage))
OPENVINO_THROW_NOT_IMPLEMENTED(errorMessage);
}
@@ -73,6 +88,36 @@ bool FullyConnected::canBeExecutedInInt8() const {
return one_of(srcType, ov::element::u8, ov::element::i8) && weiType == ov::element::i8;
}
+void FullyConnected::needPrepareParamsForTensorParallel() {
+ if (tp_cfg.enable_tensor_parallel) {
+ // must call in dynamic
+ const auto dstMemoryBuffer = getDstMemoryAtPort(0);
+
+ auto split_parts = [](int len, int n) {
+ int average = len / n;
+ std::vector<int> parts(n, average);
+ parts.back() = len - average * (n - 1);
+ return parts;
+ };
+
+ int dim = -1;
+ auto dst_shape = dstMemoryBuffer->getShape();
+ auto dst_desc = dstMemoryBuffer->getDescPtr();
+ auto dims = dst_shape.getDims();
+ if (dim < 0) {
+ dim += dims.size();
+ }
+ assert(dims[dim] >= tp_cfg.w_size);
+ auto splited_dim_vec = split_parts(dims[dim], tp_cfg.w_size);
+
+ VectorDims new_dims = dims;
+ new_dims[dim] = splited_dim_vec[tp_cfg.w_rank];
+ auto memory_desc = dst_desc->cloneWithNewDims(new_dims, true);
+ tp_cfg.cached_dst->redefineDesc(memory_desc);
+ memory[ARG_DST] = tp_cfg.cached_dst;
+ }
+}
+
ExecutorPtr FullyConnected::createExecutor() {
const auto& executor = factory->make(memory);
getSelectedPrimitiveDescriptor()->setImplementationType(executor->implType());
@@ -81,11 +126,108 @@ ExecutorPtr FullyConnected::createExecutor() {
}
void FullyConnected::prepareParams() {
+ needPrepareParamsForTensorParallel();
executor = createExecutor();
}
+void FullyConnected::initTensorParallelSync() {
+ if (tp_cfg.enable_tensor_parallel) {
+ tp_cfg.id = tp_cfg.sub_memory->get_memory_id(tp_cfg.w_rank);
+ tp_cfg.sub_memory->set_memory_used(tp_cfg.id, tp_cfg.w_rank);
+ while (true) {
+ std::lock_guard<std::mutex> lock(tp_cfg.sub_memory->_flagMutex);
+ if (tp_cfg.sub_memory->_use_count[tp_cfg.id] == tp_cfg.w_size) {
+ tp_cfg.sub_memory->_use_count[tp_cfg.id] = 0;
+ for (int i = 0; i < tp_cfg.w_size; i++) {
+ tp_cfg.sub_memory->_memorys_table[tp_cfg.id][i].flag = false;
+ }
+ }
+ if (tp_cfg.sub_memory->_use_count[tp_cfg.id] == 0) {
+ break;
+ }
+ }
+ }
+}
+
+void FullyConnected::execTensorParallelSync() {
+ if (tp_cfg.enable_tensor_parallel) {
+ // dst
+ auto dst = getDstMemoryAtPort(0);
+ auto dst_ptr = static_cast<uint8_t*>(dst->getData());
+
+ auto shape = dst->getShape();
+ auto dims = shape.getDims();
+ auto prec = dst->getPrecision();
+
+ // cur dst
+ auto cur_dst = memory[ARG_DST];
+
+ auto split_parts = [](int len, int n) {
+ int average = len / n;
+ std::vector<int> parts(n, average);
+ parts.back() = len - average * (n - 1);
+ return parts;
+ };
+
+ const int dim = dims.size() - 1;
+ // selected dim bytes
+ auto channel_size = dims[dim] * prec.size();
+ // total bytes
+ auto mem_size = dst->getSize();
+ // the steps need to copy.
+ const size_t count = (mem_size / channel_size);
+
+ auto splited_dim_vec = split_parts(dims[dim], tp_cfg.w_size);
+ const auto strideSize = splited_dim_vec[0] * prec.size();
+
+ tp_cfg.sub_memory->_memorys_table[tp_cfg.id][tp_cfg.w_rank].send_buf = cur_dst->getData();
+ tp_cfg.sub_memory->_memorys_table[tp_cfg.id][tp_cfg.w_rank].flag = true;
+
+ std::vector<int> wait_list(tp_cfg.w_size, 1);
+ while (true) {
+ int wait_size = 0;
+ for (int idx = 0; idx < tp_cfg.w_size; idx++) {
+ if (wait_list[idx] > 0 && tp_cfg.sub_memory->_memorys_table[tp_cfg.id][idx].flag) {
+ auto new_ptr = static_cast<uint8_t*>(tp_cfg.sub_memory->_memorys_table[tp_cfg.id][idx].send_buf);
+ const auto copySize = splited_dim_vec[idx] * prec.size(); // bytes of half selected dim.
+ const size_t unloop = 8;
+ size_t step = count / unloop;
+ parallel_for(step, [&](size_t i){
+ cpu_memcpy(dst_ptr + idx * strideSize + (i * unloop) * channel_size, new_ptr + (i * unloop) * copySize, copySize);
+ cpu_memcpy(dst_ptr + idx * strideSize + (i * unloop + 1) * channel_size, new_ptr + (i * unloop + 1) * copySize, copySize);
+ cpu_memcpy(dst_ptr + idx * strideSize + (i * unloop + 2) * channel_size, new_ptr + (i * unloop + 2) * copySize, copySize);
+ cpu_memcpy(dst_ptr + idx * strideSize + (i * unloop + 3) * channel_size, new_ptr + (i * unloop + 3) * copySize, copySize);
+ cpu_memcpy(dst_ptr + idx * strideSize + (i * unloop + 4) * channel_size, new_ptr + (i * unloop + 4) * copySize, copySize);
+ cpu_memcpy(dst_ptr + idx * strideSize + (i * unloop + 5) * channel_size, new_ptr + (i * unloop + 5) * copySize, copySize);
+ cpu_memcpy(dst_ptr + idx * strideSize + (i * unloop + 6) * channel_size, new_ptr + (i * unloop + 6) * copySize, copySize);
+ cpu_memcpy(dst_ptr + idx * strideSize + (i * unloop + 7) * channel_size, new_ptr + (i * unloop + 7) * copySize, copySize);
+ });
+ size_t tail = count & ~(unloop - 1);
+ for (size_t i = tail; i < count; ++i) {
+ size_t dst_offset = i * channel_size + idx * strideSize;
+ size_t src_offset = i * copySize;
+ cpu_parallel_memcpy(dst_ptr + dst_offset, new_ptr + src_offset, copySize);
+ }
+ wait_list[idx] = 0;
+ }
+ wait_size += wait_list[idx];
+ }
+ if (wait_size == 0) {
+ break;
+ }
+ }
+ {
+ std::lock_guard<std::mutex> lock(tp_cfg.sub_memory->_flagMutex);
+ tp_cfg.sub_memory->_use_count[tp_cfg.id]++;
+ }
+ }
+}
void FullyConnected::execute(dnnl::stream strm) {
+ initTensorParallelSync();
+
executor->execute(memory);
+
+ execTensorParallelSync();
}
void FullyConnected::executeDynamicImpl(dnnl::stream strm) {
@@ -222,9 +364,29 @@ static bool useSparseWeightsDecompression(const NodePtr& weightsInput,
return sparseRate >= minSparseRate;
}
+void FullyConnected::needUpdateDQScaleForTensorParallel(std::vector<float>& dequantizationScales) {
+ if (tp_cfg.enable_tensor_parallel) {
+ auto split_parts = [](int len, int n) {
+ int average = len / n;
+ std::vector<int> parts(n, average);
+ parts.back() = len - average * (n - 1);
+ return parts;
+ };
+ auto DQScales = getDQScales();
+ auto split_lens = split_parts(DQScales.size(), tp_cfg.w_size);
+ auto split_offset = tp_cfg.w_rank * split_lens[0];
+ std::vector<float> newDQScales(split_lens[tp_cfg.w_rank]);
+ std::copy(DQScales.begin() + split_offset, DQScales.begin() + split_offset + split_lens[tp_cfg.w_rank], newDQScales.begin());
+ dequantizationScales = newDQScales;
+ }
+}
+
void FullyConnected::initSupportedPrimitiveDescriptors() {
attrs.withBias = getOriginalInputsNumber() == 3;
+
attrs.dequantizationScales = getDQScales();
+ needUpdateDQScaleForTensorParallel(attrs.dequantizationScales);
+
attrs.sparseWeights = useSparseWeightsDecompression(getParentEdgeAt(WEIGHTS_ID)->getParent(),
getOriginalInputPrecisionAtPort(DATA_ID),
context->getConfig().fcSparseWeiDecompressionRate);
@@ -259,6 +421,9 @@ void FullyConnected::initSupportedPrimitiveDescriptors() {
{ARG_DST, dstDescs[0]},
};
+ needUpdateScaleForTensorParallel();
+ needUpdateZeroPointForTensorParallel();
+
auto executionContext = std::make_shared<ExecutorContext>(context, getImplPriority(), privateWeightCache);
factory = std::make_shared<ExecutorFactory<FCAttrs, node::FullyConnected>>(attrs, postOps, executionContext, descs);
const auto nodeDescriptors = factory->getProperMemoryDescriptors(descs);
@@ -274,11 +439,55 @@ void FullyConnected::initSupportedPrimitiveDescriptors() {
supportedPrimitiveDescriptors.emplace_back(nodeConfig, impl_desc_type::undef);
}
+void FullyConnected::needSplitMemoryForTensorParallel() {
+ if (tp_cfg.enable_tensor_parallel) {
+ auto src = getSrcMemoryAtPort(DATA_ID);
+ auto wgt = getSrcMemoryAtPort(WEIGHTS_ID);
+ auto dst = getDstMemoryAtPort(0);
+ // src
+ memory[ARG_SRC] = getSrcMemoryAtPort(DATA_ID);
+ // wgt
+ // split N direction
+ tp_cfg.cached_splited_weight = attrs.weightsNonTransposed ? split_vertical(context->getEngine(), wgt, 0, tp_cfg.w_rank, tp_cfg.w_size)
+ : split_horizontal(context->getEngine(), wgt, 0, tp_cfg.w_rank, tp_cfg.w_size);
+ memory[ARG_WEI] = tp_cfg.cached_splited_weight;
+ // bias
+ if (attrs.withBias) {
+ auto bias = getSrcMemoryAtPort(BIAS_ID);
+ auto select_bias = split_horizontal(context->getEngine(), bias, 0, tp_cfg.w_rank, tp_cfg.w_size);
+ tp_cfg.cached_splited_bias = select_bias;
+ } else {
+ tp_cfg.cached_splited_bias = MemoryDescUtils::makeEmptyMemory(context);
+ }
+ memory[ARG_BIAS] = tp_cfg.cached_splited_bias;
+ // dst
+ memory[ARG_DST] = getDstMemoryAtPort(0);
+ tp_cfg.cached_dst = split_horizontal(context->getEngine(), dst, -1, tp_cfg.w_rank, tp_cfg.w_size, false);
+ }
+}
+
+void FullyConnected::needUpdateTensorParalelConfig() {
+ // tensor parallel should be disabled in two conditions.
+ // 1. weight shape is dynamic
+ // 2. last dim can be splited.
+ if (tp_cfg.enable_tensor_parallel) {
+ auto shape = getSrcMemoryAtPort(WEIGHTS_ID)->getShape();
+ if (shape.isDynamic()) {
+ tp_cfg.enable_tensor_parallel = false;
+ } else if (shape.getDims()[0] < static_cast<size_t>(tp_cfg.w_size)) {
+ tp_cfg.enable_tensor_parallel = false;
+ }
+ }
+}
void FullyConnected::createPrimitive() {
+ needUpdateTensorParalelConfig();
+
memory[ARG_SRC] = getSrcMemoryAtPort(DATA_ID);
memory[ARG_WEI] = getSrcMemoryAtPort(WEIGHTS_ID);
memory[ARG_BIAS] = attrs.withBias ? getSrcMemoryAtPort(BIAS_ID) : MemoryDescUtils::makeEmptyMemory(context);
memory[ARG_DST] = getDstMemoryAtPort(0);
+
+ 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);
@@ -302,12 +511,47 @@ ov::element::Type FullyConnected::getRuntimePrecision() const {
return getMaxPrecision(srcTypes);
}
+void FullyConnected::needUpdateScaleForTensorParallel() {
+ if (tp_cfg.enable_tensor_parallel && tp_cfg.cached_scale) {
+ attrs.decompressionMultiplyPtr = tp_cfg.cached_scale;
+ }
+}
+
+void FullyConnected::needSplitScaleForTensorParallel(const MemoryCPtr& memory) {
+ if (tp_cfg.enable_tensor_parallel && !tp_cfg.cached_scale) {
+ auto scale_mem = std::const_pointer_cast<IMemory>(memory);
+ tp_cfg.cached_scale = attrs.weightsNonTransposed ? split_vertical(context->getEngine(), scale_mem, 0, tp_cfg.w_rank, tp_cfg.w_size)
+ : split_horizontal(context->getEngine(), scale_mem, 0, tp_cfg.w_rank, tp_cfg.w_size);
+ }
+}
+
+void FullyConnected::needUpdateZeroPointForTensorParallel() {
+ if (tp_cfg.enable_tensor_parallel && tp_cfg.cached_zeropoint) {
+ attrs.decompressionSubtractPtr = tp_cfg.cached_zeropoint;
+ }
+}
+
+void FullyConnected::needSplitZeroPointForTensorParallel(const MemoryCPtr& memory) {
+ if (tp_cfg.enable_tensor_parallel && !tp_cfg.cached_zeropoint) {
+ auto zeropoint_mem = std::const_pointer_cast<IMemory>(memory);
+ auto element_num = memory->getSize() / memory->getPrecision().size();
+ if (element_num == 1) {
+ tp_cfg.cached_zeropoint = zeropoint_mem;
+ } else {
+ tp_cfg.cached_zeropoint = attrs.weightsNonTransposed ? split_vertical(context->getEngine(), zeropoint_mem, 0, tp_cfg.w_rank, tp_cfg.w_size)
+ : split_horizontal(context->getEngine(), zeropoint_mem, 0, tp_cfg.w_rank, tp_cfg.w_size);
+ }
+ }
+}
+
void FullyConnected::fuseDecompressionMultiply(const MemoryCPtr& memory) {
attrs.decompressionMultiplyPtr = memory;
+ needSplitScaleForTensorParallel(memory);
}
void FullyConnected::fuseDecompressionSubtract(const MemoryCPtr& memory) {
attrs.decompressionSubtractPtr = memory;
+ needSplitZeroPointForTensorParallel(memory);
}
} // namespace node
diff --git a/src/plugins/intel_cpu/src/nodes/fullyconnected.h b/src/plugins/intel_cpu/src/nodes/fullyconnected.h
index 06b83d6a784..be29342b851 100644
--- a/src/plugins/intel_cpu/src/nodes/fullyconnected.h
+++ b/src/plugins/intel_cpu/src/nodes/fullyconnected.h
@@ -16,11 +16,26 @@
#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 {
namespace node {
+// tensor parallel config
+struct FCTensorParallelConfig {
+ int w_rank = -1;
+ int w_size = -1;
+ int id = 0;
+ bool enable_tensor_parallel = false;
+ std::shared_ptr<SubMemoryManager> sub_memory = nullptr;
+ MemoryPtr cached_splited_weight = nullptr;
+ MemoryPtr cached_splited_bias = nullptr;
+ MemoryPtr cached_scale = nullptr;
+ MemoryPtr cached_zeropoint = nullptr;
+ MemoryPtr cached_dst = nullptr;
+};
+
class FullyConnected : public Node {
public:
FullyConnected(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr context);
@@ -73,12 +88,26 @@ private:
ExecutorPtr createExecutor();
void fuseDecompressionConstant(const MemoryCPtr& memory, MemoryCPtr& decompressionValuesPtr);
+ void initTensorParallelConfig(const GraphContext::CPtr context);
+ void needUpdateTensorParalelConfig();
+ void needPrepareParamsForTensorParallel();
+ void initTensorParallelSync();
+ void execTensorParallelSync();
+ void needSplitMemoryForTensorParallel();
+ void needSplitScaleForTensorParallel(const MemoryCPtr& memory);
+ void needUpdateScaleForTensorParallel();
+ void needSplitZeroPointForTensorParallel(const MemoryCPtr& memory);
+ void needUpdateZeroPointForTensorParallel();
+ void needUpdateDQScaleForTensorParallel(std::vector<float>& dequantizationScales);
+
FCAttrs attrs;
PostOps postOps;
MemoryArgs memory;
ExecutorFactoryPtr<FCAttrs, node::FullyConnected> factory;
ExecutorPtr executor = nullptr;
std::string errorPrefix;
+
+ FCTensorParallelConfig tp_cfg;
};
} // namespace node
diff --git a/src/plugins/intel_cpu/src/plugin.cpp b/src/plugins/intel_cpu/src/plugin.cpp
index c251f8c619e..276502a0f62 100644
--- a/src/plugins/intel_cpu/src/plugin.cpp
+++ b/src/plugins/intel_cpu/src/plugin.cpp
@@ -131,11 +131,13 @@ Plugin::Plugin() : deviceFullName(getDeviceFullName()), specialSetup(new CPUSpec
});
auto& ov_version = ov::get_openvino_version();
m_compiled_model_runtime_properties["OV_VERSION"] = std::string(ov_version.buildNumber);
+ m_msg_manager = ov::threading::message_manager();
}
Plugin::~Plugin() {
executor_manager()->clear("CPU");
executor_manager()->clear("CPUStreamsExecutor");
+ executor_manager()->clear("CPUMainStreamExecutor");
executor_manager()->clear("CPUCallbackExecutor");
}
@@ -290,16 +292,11 @@ std::shared_ptr<ov::ICompiledModel> Plugin::compile_model(const std::shared_ptr<
conf.readProperties(config, modelType);
calculate_streams(conf, cloned_model);
- if (conf.streamExecutorConfig.get_sub_stream_mode() ==
- IStreamsExecutor::Config::StreamsMode::SUB_STREAMS_FOR_SOCKET) {
- int num_sub_streams = conf.streamExecutorConfig.get_sub_streams();
- transformations.SetSubStreamNum(num_sub_streams);
- }
-
transformations.PostLpt();
transformations.Snippets();
transformations.CpuSpecificOpSet();
+
DEBUG_LOG(PrintableModel(*cloned_model, "cpu_"));
if ((cloned_model->inputs().size() != model->inputs().size()) ||
diff --git a/src/plugins/intel_cpu/src/plugin.h b/src/plugins/intel_cpu/src/plugin.h
index 3332d873fdc..c2d24e98ee6 100644
--- a/src/plugins/intel_cpu/src/plugin.h
+++ b/src/plugins/intel_cpu/src/plugin.h
@@ -6,6 +6,7 @@
#include "compiled_model.h"
#include "cpu_streams_calculation.hpp"
+#include "openvino/runtime/threading/cpu_message.hpp"
namespace ov {
namespace intel_cpu {
@@ -43,6 +44,8 @@ public:
OPENVINO_THROW_NOT_IMPLEMENTED("Not Implemented get_default_context is not supported by CPU plugin!");
};
+ std::shared_ptr<ov::threading::MessageManager> m_msg_manager;
+
private:
ov::Any get_ro_property(const std::string& name, const ov::AnyMap& options) const;
diff --git a/src/plugins/intel_cpu/src/sub_memory_manager.hpp b/src/plugins/intel_cpu/src/sub_memory_manager.hpp
new file mode 100644
index 00000000000..4a0fd7ea0a2
--- /dev/null
+++ b/src/plugins/intel_cpu/src/sub_memory_manager.hpp
@@ -0,0 +1,57 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <string>
+#include <vector>
+#include <mutex>
+#include <memory>
+#include <assert.h>
+#include "cpu_memory.h"
+
+namespace ov {
+namespace intel_cpu {
+class SubMemoryManager {
+public:
+ struct MemoryInfo {
+ void* send_buf;
+ bool flag;
+ bool last_used;
+ };
+
+ SubMemoryManager(int num_sub_streams) {
+ assert(num_sub_streams);
+ _num_sub_streams = num_sub_streams;
+ MemoryInfo memory_info;
+ memory_info.flag = false;
+ memory_info.last_used = false;
+ std::vector<MemoryInfo> memorys;
+ memorys.assign(_num_sub_streams, memory_info);
+ _memorys_table.assign(2, memorys);
+ _use_count.assign(2, 0);
+ }
+
+ int get_memory_id(int sub_stream_id) {
+ for (int i = 0; i < 2; i++) {
+ if (!_memorys_table[i][sub_stream_id].last_used) {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ void set_memory_used(int memory_id, int sub_stream_id) {
+ _memorys_table[memory_id][sub_stream_id].last_used = true;
+ _memorys_table[(memory_id + 1) % 2][sub_stream_id].last_used = false;
+ }
+
+ int _num_sub_streams;
+ std::vector<std::vector<MemoryInfo>> _memorys_table;
+ std::vector<int> _use_count;
+ std::mutex _flagMutex;
+};
+} // namespace intel_cpu
+
+} // namespace ov
\ No newline at end of file
diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/convert_to_cpu_specific_opset.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/convert_to_cpu_specific_opset.hpp
index 703df1d26cb..20502f67d36 100644
--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/convert_to_cpu_specific_opset.hpp
+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/convert_to_cpu_specific_opset.hpp
@@ -26,7 +26,7 @@
namespace ov {
namespace intel_cpu {
-inline void ConvertToCPUSpecificOpset(std::shared_ptr<ov::Model> &model, int subStreamNum) {
+inline void ConvertToCPUSpecificOpset(std::shared_ptr<ov::Model> &model) {
RUN_ON_FUNCTION_SCOPE(ConvertToCPUSpecificOpset);
ov::pass::Manager manager("CPU:ConvertToCPUSpecificOpset");
@@ -34,10 +34,6 @@ inline void ConvertToCPUSpecificOpset(std::shared_ptr<ov::Model> &model, int sub
CPU_REGISTER_PASS_COMMON(manager, ConvertMatMulToFC);
CPU_REGISTER_PASS_X64(manager, MoveFCReshapeToWeights);
CPU_REGISTER_PASS_X64(manager, ov::pass::Validate);
- if (subStreamNum >= 1) {
- CPU_REGISTER_PASS_COMMON(manager, SplitFC, subStreamNum);
- CPU_REGISTER_PASS_COMMON(manager, ov::pass::Validate);
- }
CPU_REGISTER_PASS_COMMON(manager, AlignMatMulInputRanks);
CPU_REGISTER_PASS_COMMON(manager, ConvertTileToSeqTiles);
CPU_REGISTER_PASS_COMMON(manager, ConvertToPowerStatic);
diff --git a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
index 726a416fe1c..98da1be4c74 100644
--- a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
+++ b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp
@@ -296,14 +296,10 @@ void Transformations::UpToLpt() {
Lpt(defaultPrecisions);
}
-void Transformations::SetSubStreamNum(int SubStreams) {
- subStreamNum = SubStreams;
-}
-
void Transformations::CpuSpecificOpSet(void) {
CPU_DEBUG_CAP_TRANSFORMATION_SCOPE(this, Specific);
- ConvertToCPUSpecificOpset(model, subStreamNum);
+ ConvertToCPUSpecificOpset(model);
}
void Transformations::PreLpt(const std::vector<ov::element::Type>& defaultPrecisions) {
diff --git a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.h b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.h
index 2c66d3abf1d..420cf102f38 100644
--- a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.h
+++ b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.h
@@ -37,7 +37,6 @@ public:
void CpuSpecificOpSet();
void PostLpt();
void Snippets(void);
- void SetSubStreamNum(int);
private:
std::shared_ptr<ov::Model> model;
@@ -45,7 +44,6 @@ private:
const ov::element::Type inferencePrecision;
const Config::SnippetsMode snippetsMode;
const Config& config;
- int subStreamNum = -1;
void PreLpt(const std::vector<ov::element::Type>& defaultPrecisions);
diff --git a/src/plugins/intel_cpu/tests/unit/streams_info/streams_e2e_test.cpp b/src/plugins/intel_cpu/tests/unit/streams_info/streams_e2e_test.cpp
index 15d9098e9fa..7fd491e934f 100644
--- a/src/plugins/intel_cpu/tests/unit/streams_info/streams_e2e_test.cpp
+++ b/src/plugins/intel_cpu/tests/unit/streams_info/streams_e2e_test.cpp
@@ -411,7 +411,7 @@ StreamGenerateionTestCase generation_latency_2sockets_48cores_10 = {
false,
ov::hint::PerformanceMode::LATENCY,
{{48, 48, 0, 0, -1, -1}, {24, 24, 0, 0, 0, 0}, {24, 24, 0, 0, 1, 1}},
- {{1, MAIN_CORE_PROC, 24, 0, 0}, {-1, MAIN_CORE_PROC, 24, 1, 1}},
+ {{1, MAIN_CORE_PROC, 48, -1, -1}, {-1, MAIN_CORE_PROC, 24, 0, 0}, {-1, MAIN_CORE_PROC, 24, 1, 1}},
};
StreamGenerateionTestCase generation_latency_2sockets_48cores_11 = {
@@ -434,7 +434,7 @@ StreamGenerateionTestCase generation_latency_2sockets_48cores_11 = {
false,
ov::hint::PerformanceMode::LATENCY,
{{48, 48, 0, 0, -1, -1}, {24, 24, 0, 0, 0, 0}, {24, 24, 0, 0, 1, 1}},
- {{1, MAIN_CORE_PROC, 24, 0, 0}, {-1, MAIN_CORE_PROC, 24, 1, 1}},
+ {{1, MAIN_CORE_PROC, 48, -1, -1}, {-1, MAIN_CORE_PROC, 24, 0, 0}, {-1, MAIN_CORE_PROC, 24, 1, 1}},
};
StreamGenerateionTestCase generation_tput_1sockets_14cores_2 = {
diff --git a/src/plugins/intel_cpu/tests/unit/streams_info/streams_info_table_test.cpp b/src/plugins/intel_cpu/tests/unit/streams_info/streams_info_table_test.cpp
index 73869074bf9..4cc795eeaf2 100644
--- a/src/plugins/intel_cpu/tests/unit/streams_info/streams_info_table_test.cpp
+++ b/src/plugins/intel_cpu/tests/unit/streams_info/streams_info_table_test.cpp
@@ -58,17 +58,14 @@ StreamsCalculationTestCase _2sockets_104cores_latency_auto_1 = {
0, // param[in]: the current socket id of the running thread in this simulation
"LATENCY", // param[in]: the performance hint in this simulation
{ov::hint::ModelDistributionPolicy::TENSOR_PARALLEL}, // param[in]: the hint of max threads per stream in this
- // simulation
+ // simulation
{{208, 104, 0, 104, -1, -1},
{104, 52, 0, 52, 0, 0},
{104, 52, 0, 52, 1, 1}}, // param[in]: the proc_type_table in this simulation
- {{1, ALL_PROC, 104, 0, 0},
- {0, MAIN_CORE_PROC, 52, 0, 0},
- {0, HYPER_THREADING_PROC, 52, 0, 0},
- {-1, ALL_PROC, 104, 1, 1},
- {0, MAIN_CORE_PROC, 52, 1, 1},
- {0, HYPER_THREADING_PROC, 52, 1, 1}}, // param[expected out]: the expected result of streams_info_table in this
- // simulation
+ {{1, MAIN_CORE_PROC, 64, -1, -1},
+ {-1, MAIN_CORE_PROC, 32, 0, 0},
+ {-1, MAIN_CORE_PROC, 32, 1, 1}}, // param[expected out]: the expected result of streams_info_table in this
+ // simulation
};
StreamsCalculationTestCase _2sockets_104cores_latency_auto_2 = {
@@ -81,7 +78,7 @@ StreamsCalculationTestCase _2sockets_104cores_latency_auto_2 = {
"LATENCY",
{ov::hint::ModelDistributionPolicy::TENSOR_PARALLEL},
{{104, 104, 0, 0, -1, -1}, {52, 52, 0, 0, 0, 0}, {52, 52, 0, 0, 1, 1}},
- {{1, MAIN_CORE_PROC, 52, 0, 0}, {-1, MAIN_CORE_PROC, 52, 1, 1}},
+ {{1, MAIN_CORE_PROC, 64, -1, -1}, {-1, MAIN_CORE_PROC, 32, 0, 0}, {-1, MAIN_CORE_PROC, 32, 1, 1}},
};
StreamsCalculationTestCase _2sockets_104cores_latency_auto_3 = {
1,
@@ -97,16 +94,13 @@ StreamsCalculationTestCase _2sockets_104cores_latency_auto_3 = {
{52, 26, 0, 26, 1, 0},
{52, 26, 0, 26, 2, 1},
{52, 26, 0, 26, 3, 1}},
- {{1, ALL_PROC, 104, -1, 0},
+ {{1, ALL_PROC, 64, -1, -1},
+ {-1, ALL_PROC, 32, -1, 0},
{0, MAIN_CORE_PROC, 26, 0, 0},
- {0, MAIN_CORE_PROC, 26, 1, 0},
- {0, HYPER_THREADING_PROC, 26, 0, 0},
- {0, HYPER_THREADING_PROC, 26, 1, 0},
- {-1, ALL_PROC, 104, -1, 1},
+ {0, MAIN_CORE_PROC, 6, 1, 0},
+ {-1, ALL_PROC, 32, -1, 1},
{0, MAIN_CORE_PROC, 26, 2, 1},
- {0, MAIN_CORE_PROC, 26, 3, 1},
- {0, HYPER_THREADING_PROC, 26, 2, 1},
- {0, HYPER_THREADING_PROC, 26, 3, 1}},
+ {0, MAIN_CORE_PROC, 6, 3, 1}},
};
StreamsCalculationTestCase _2sockets_104cores_latency_auto_4 = {
1,
@@ -118,12 +112,13 @@ StreamsCalculationTestCase _2sockets_104cores_latency_auto_4 = {
"LATENCY",
{ov::hint::ModelDistributionPolicy::TENSOR_PARALLEL},
{{104, 104, 0, 0, -1, -1}, {26, 26, 0, 0, 0, 0}, {26, 26, 0, 0, 1, 0}, {26, 26, 0, 0, 2, 1}, {26, 26, 0, 0, 3, 1}},
- {{1, ALL_PROC, 52, -1, 0},
+ {{1, ALL_PROC, 64, -1, -1},
+ {-1, ALL_PROC, 32, -1, 0},
{0, MAIN_CORE_PROC, 26, 0, 0},
- {0, MAIN_CORE_PROC, 26, 1, 0},
- {-1, ALL_PROC, 52, -1, 1},
+ {0, MAIN_CORE_PROC, 6, 1, 0},
+ {-1, ALL_PROC, 32, -1, 1},
{0, MAIN_CORE_PROC, 26, 2, 1},
- {0, MAIN_CORE_PROC, 26, 3, 1}},
+ {0, MAIN_CORE_PROC, 6, 3, 1}},
};
StreamsCalculationTestCase _2sockets_104cores_latency_platform_1 = {
1,
@@ -2295,9 +2290,10 @@ StreamsCalculationTestCase _2sockets_mock_latency_22 = {
"LATENCY",
{ov::hint::ModelDistributionPolicy::TENSOR_PARALLEL},
{{60, 30, 0, 30, -1, -1}, {40, 20, 0, 20, 0, 0}, {20, 10, 0, 10, 1, 1}},
- {{1, ALL_PROC, 40, 0, 0},
+ {{1, ALL_PROC, 52, -1, -1},
+ {-1, ALL_PROC, 32, 0, 0},
{0, MAIN_CORE_PROC, 20, 0, 0},
- {0, HYPER_THREADING_PROC, 20, 0, 0},
+ {0, HYPER_THREADING_PROC, 12, 0, 0},
{-1, ALL_PROC, 20, 1, 1},
{0, MAIN_CORE_PROC, 10, 1, 1},
{0, HYPER_THREADING_PROC, 10, 1, 1}},
@@ -2340,16 +2336,13 @@ StreamsCalculationTestCase _2sockets_mock_latency_25 = {
{60, 30, 0, 30, 1, 0},
{40, 20, 0, 20, 2, 1},
{20, 10, 0, 10, 3, 1}},
- {{1, ALL_PROC, 140, -1, 0},
- {0, MAIN_CORE_PROC, 40, 0, 0},
- {0, MAIN_CORE_PROC, 30, 1, 0},
- {0, HYPER_THREADING_PROC, 40, 0, 0},
- {0, HYPER_THREADING_PROC, 30, 1, 0},
- {-1, ALL_PROC, 60, -1, 1},
+ {{1, ALL_PROC, 64, -1, -1},
+ {-1, ALL_PROC, 32, -1, 0},
+ {0, MAIN_CORE_PROC, 32, 0, 0},
+ {-1, ALL_PROC, 32, -1, 1},
{0, MAIN_CORE_PROC, 20, 2, 1},
{0, MAIN_CORE_PROC, 10, 3, 1},
- {0, HYPER_THREADING_PROC, 20, 2, 1},
- {0, HYPER_THREADING_PROC, 10, 3, 1}},
+ {0, HYPER_THREADING_PROC, 2, 2, 1}},
};
StreamsCalculationTestCase _2sockets_mock_latency_26 = {
1,
@@ -2405,16 +2398,13 @@ StreamsCalculationTestCase _2sockets_mock_latency_28 = {
{60, 30, 0, 30, 1, 0},
{40, 20, 0, 20, 2, 1},
{20, 10, 0, 10, 3, 1}},
- {{1, ALL_PROC, 140, -1, 0},
- {0, MAIN_CORE_PROC, 40, 0, 0},
- {0, MAIN_CORE_PROC, 30, 1, 0},
- {0, HYPER_THREADING_PROC, 40, 0, 0},
- {0, HYPER_THREADING_PROC, 30, 1, 0},
- {-1, ALL_PROC, 60, -1, 1},
+ {{1, ALL_PROC, 64, -1, -1},
+ {-1, ALL_PROC, 32, -1, 0},
+ {0, MAIN_CORE_PROC, 32, 0, 0},
+ {-1, ALL_PROC, 32, -1, 1},
{0, MAIN_CORE_PROC, 20, 2, 1},
{0, MAIN_CORE_PROC, 10, 3, 1},
- {0, HYPER_THREADING_PROC, 20, 2, 1},
- {0, HYPER_THREADING_PROC, 10, 3, 1}},
+ {0, HYPER_THREADING_PROC, 2, 2, 1}},
};
StreamsCalculationTestCase _2sockets_mock_latency_29 = {
1,
@@ -2518,7 +2508,7 @@ StreamsCalculationTestCase _2sockets_mock_latency_34 = {
"LATENCY",
{ov::hint::ModelDistributionPolicy::TENSOR_PARALLEL},
{{48, 48, 0, 0, -1, -1}, {24, 24, 0, 0, 0, 0}, {24, 24, 0, 0, 1, 1}},
- {{1, MAIN_CORE_PROC, 24, 0, 0}, {-1, MAIN_CORE_PROC, 24, 1, 1}},
+ {{1, MAIN_CORE_PROC, 48, -1, -1}, {-1, MAIN_CORE_PROC, 24, 0, 0}, {-1, MAIN_CORE_PROC, 24, 1, 1}},
};
StreamsCalculationTestCase _1sockets_mock_latency_1 = {
1,
@@ -2642,7 +2632,7 @@ StreamsCalculationTestCase _2sockets_mock_latency_37 = {
"LATENCY",
{ov::hint::ModelDistributionPolicy::TENSOR_PARALLEL},
{{48, 48, 0, 0, -1, -1}, {24, 24, 0, 0, 0, 0}, {24, 24, 0, 0, 1, 1}},
- {{1, MAIN_CORE_PROC, 24, 1, 1}, {-1, MAIN_CORE_PROC, 24, 0, 0}},
+ {{1, MAIN_CORE_PROC, 48, -1, -1}, {-1, MAIN_CORE_PROC, 24, 1, 1}, {-1, MAIN_CORE_PROC, 24, 0, 0}},
};
TEST_P(StreamsCalculationTests, StreamsCalculation) {}
diff --git a/src/plugins/intel_cpu/tests/unit/streams_info/streams_rank_table_test.cpp b/src/plugins/intel_cpu/tests/unit/streams_info/streams_rank_table_test.cpp
new file mode 100644
index 00000000000..ce2dcb324d6
--- /dev/null
+++ b/src/plugins/intel_cpu/tests/unit/streams_info/streams_rank_table_test.cpp
@@ -0,0 +1,125 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <gtest/gtest.h>
+
+#include "common_test_utils/test_common.hpp"
+#include "cpu_streams_calculation.hpp"
+
+using namespace testing;
+using namespace ov;
+
+namespace {
+
+struct StreamsRankTestCase {
+ std::vector<std::vector<int>> stream_info_table;
+ int rank_level;
+ int num_sub_streams;
+ std::vector<std::vector<int>> stream_rank_table;
+};
+
+class StreamsRankTests : public ov::test::TestsCommon,
+ public testing::WithParamInterface<std::tuple<StreamsRankTestCase>> {
+public:
+ void SetUp() override {
+ const auto& test_data = std::get<0>(GetParam());
+
+ int test_num_sub_streams;
+ std::vector<std::vector<int>> test_stream_rank_table =
+ ov::intel_cpu::get_streams_rank_table(test_data.stream_info_table,
+ test_data.rank_level,
+ test_num_sub_streams);
+
+ ASSERT_EQ(test_data.stream_rank_table, test_stream_rank_table);
+ ASSERT_EQ(test_data.num_sub_streams, test_num_sub_streams);
+ }
+};
+
+StreamsRankTestCase _2sockets_mock_1 = {
+ {{1, ALL_PROC, 208, -1, -1},
+ {-1, ALL_PROC, 104, 0, 0},
+ {0, MAIN_CORE_PROC, 52, 0, 0},
+ {0, HYPER_THREADING_PROC, 52, 0, 0},
+ {-1, ALL_PROC, 104, 1, 1},
+ {0, MAIN_CORE_PROC, 52, 1, 1},
+ {0, HYPER_THREADING_PROC, 52, 1, 1}}, // param[in]: the expected result of streams_info_table in this simulation
+ 1, // param[in]: the number of rank level in this simulation
+ 2, // param[expected out]: the number of sub stream in this simulation
+ {{0}, {1}}, // param[expected out]: the expected result of streams_rank_table in thissimulation
+};
+StreamsRankTestCase _2sockets_mock_2 = {
+ {{1, MAIN_CORE_PROC, 104, -1, -1}, {-1, MAIN_CORE_PROC, 52, 0, 0}, {-1, MAIN_CORE_PROC, 52, 1, 1}},
+ 1,
+ 2,
+ {{0}, {1}},
+};
+StreamsRankTestCase _2sockets_mock_3 = {
+ {{1, ALL_PROC, 208, -1, -1},
+ {-1, ALL_PROC, 104, -1, 0},
+ {0, MAIN_CORE_PROC, 26, 0, 0},
+ {0, MAIN_CORE_PROC, 26, 1, 0},
+ {0, HYPER_THREADING_PROC, 26, 0, 0},
+ {0, HYPER_THREADING_PROC, 26, 1, 0},
+ {-1, ALL_PROC, 104, -1, 1},
+ {0, MAIN_CORE_PROC, 26, 2, 1},
+ {0, MAIN_CORE_PROC, 26, 3, 1},
+ {0, HYPER_THREADING_PROC, 26, 2, 1},
+ {0, HYPER_THREADING_PROC, 26, 3, 1}},
+ 1,
+ 2,
+ {{0}, {1}},
+};
+StreamsRankTestCase _2sockets_mock_4 = {
+ {{1, MAIN_CORE_PROC, 104, -1, -1},
+ {-1, MAIN_CORE_PROC, 26, 0, 0},
+ {-1, MAIN_CORE_PROC, 26, 1, 0},
+ {-1, MAIN_CORE_PROC, 26, 2, 1},
+ {-1, MAIN_CORE_PROC, 26, 3, 1}},
+ 1,
+ 4,
+ {{0}, {1}, {2}, {3}},
+};
+StreamsRankTestCase _2sockets_mock_5 = {
+ {{1, MAIN_CORE_PROC, 104, -1, -1},
+ {-1, MAIN_CORE_PROC, 26, 0, 0},
+ {-1, MAIN_CORE_PROC, 26, 1, 0},
+ {-1, MAIN_CORE_PROC, 26, 2, 1},
+ {-1, MAIN_CORE_PROC, 26, 3, 1}},
+ 2,
+ 4,
+ {{0, 0}, {0, 1}, {1, 0}, {1, 1}},
+};
+StreamsRankTestCase _1sockets_mock_1 = {
+ {{1, MAIN_CORE_PROC, 16, 0, 0}, {-4, MAIN_CORE_PROC, 4, 0, 0}},
+ 1,
+ 4,
+ {{0}, {1}, {2}, {3}},
+};
+StreamsRankTestCase _1sockets_mock_2 = {
+ {{1, MAIN_CORE_PROC, 16, 0, 0}, {-4, MAIN_CORE_PROC, 4, 0, 0}},
+ 2,
+ 4,
+ {{0, 0}, {0, 1}, {1, 0}, {1, 1}},
+};
+StreamsRankTestCase _1sockets_mock_3 = {
+ {{1, MAIN_CORE_PROC, 32, 0, 0}, {-8, MAIN_CORE_PROC, 4, 0, 0}},
+ 2,
+ 8,
+ {{0, 0}, {0, 1}, {0, 2}, {0, 3}, {1, 0}, {1, 1}, {1, 2}, {1, 3}},
+};
+
+TEST_P(StreamsRankTests, StreamsRankTest) {}
+
+INSTANTIATE_TEST_SUITE_P(StreamsRankTable,
+ StreamsRankTests,
+ testing::Values(_2sockets_mock_1,
+ _2sockets_mock_2,
+ _2sockets_mock_3,
+ _2sockets_mock_4,
+ _2sockets_mock_5,
+ _1sockets_mock_1,
+ _1sockets_mock_2,
+ _1sockets_mock_3));
+
+} // namespace