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
[NPU] Make zero mem pool global per core and not per process (#35121)
Bogdan Pereanueeddd2be154d
diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_init.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_init.hppindex 0b88f4487f0..766efc2cc8c 100644--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_init.hpp+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_init.hpp@@ -12,9 +12,15 @@#include "intel_npu/utils/logger/logger.hpp"#include "intel_npu/utils/zero/zero_api.hpp"+#include "intel_npu/utils/zero/zero_mem_pool.hpp"#include "intel_npu/utils/zero/zero_types.hpp"namespace intel_npu {++namespace zero_mem {+class ZeroMemPoolManager;+} // namespace zero_mem+/*** Holder for the level zero structures which must be initialized via call to the driver once zero backend is loaded,* and de-initialized after their last use is over.@@ -85,11 +91,17 @@ public:uint32_t getCompilerVersion();private:+ friend class zero_mem::ZeroMemPoolManager;+void initNpuDriver();void initCompilerPropertiesLocked();void getExtensionFunctionAddress(const std::string& name, const uint32_t version, void** function_address);void setContextProperties();+ inline ZeroMemPool& getZeroMemPool() {+ return _zero_mem_pool;+ }+// keep zero_api alive until context is destroyedstd::shared_ptr<ZeroApi> _zero_api;@@ -120,6 +132,12 @@ private:uint32_t _command_queue_group_ordinal = 0;+ // Per-context global registry for ZeroMem tracking.+ // The pool object lives in the context holder, while all create/import/look-up operations+ // are performed through zero_mem helper APIs (and their manager), which also synchronize+ // updates and cleanup.+ ZeroMemPool _zero_mem_pool;+std::mutex _mutex;};diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_mem.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_mem.hppindex 48f78b63a38..44c95e475e7 100644--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_mem.hpp+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_mem.hpp@@ -4,12 +4,16 @@#pragma once+#include <memory>+#include "intel_npu/utils/logger/logger.hpp"#include "intel_npu/utils/zero/zero_init.hpp"namespace intel_npu {-class ZeroMemPool;+namespace zero_mem {+class ZeroMemPoolManager;+} // namespace zero_memclass ZeroMem final {public:@@ -26,7 +30,7 @@ public:size_t size();private:- friend class intel_npu::ZeroMemPool;+ friend class zero_mem::ZeroMemPoolManager;/*** @brief Allocates a new memory region in the level zero context provided through init_structs.diff --git a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_mem_pool.hpp b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_mem_pool.hppindex 5140e4e19cf..fdbc29a2baa 100644--- a/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_mem_pool.hpp+++ b/src/plugins/intel_npu/src/utils/include/intel_npu/utils/zero/zero_mem_pool.hpp@@ -4,89 +4,78 @@#pragma once+#include <cstdint>#include <future>+#include <memory>#include <mutex>--#include "intel_npu/utils/logger/logger.hpp"-#include "intel_npu/utils/zero/zero_init.hpp"-#include "intel_npu/utils/zero/zero_mem.hpp"+#include <unordered_map>namespace intel_npu {+class ZeroInitStructsHolder;+class ZeroMem;+/**- * @brief ZeroMemPool API used to keep track of all allocations and memory imports performed in the level zero context.- * @details Provides methods to either allocate or import memory in the level zero context. Such method will also add an- * entry into the pool for the tracking ID that corresponds to that allocation. Provides a method to check if a given- * memory range was previously allocated or imported.+ * @brief Per-context registry of tracked Level Zero memory objects.+ * @details Stores weak references to imported and allocated ZeroMem instances together with the synchronization+ * primitives used to serialize pool updates and coordinate pool entry removal with re-import attempts.+ * The pool is owned by ZeroInitStructsHolder to make it global for a given Level Zero context, while memory+ * allocation/import/look-up is intentionally mediated by zero_mem helper APIs.*/-class ZeroMemPool final {-public:- ZeroMemPool(const ZeroMemPool& other) = delete;- ZeroMemPool(ZeroMemPool&& other) = delete;- void operator=(const ZeroMemPool&) = delete;- void operator=(ZeroMemPool&&) = delete;-- /**- * @brief Get static instance.- */- static ZeroMemPool& get_instance();-- /**- * @brief Returns a new memory region allocated in the level zero context and adds it to the pool.- * @param init_structs Holder for the level zero structures.- * @param bytes Size in bytes of the memory that must be allocated.- * @param alignment Alignment needed for the memory; it must be a multiple of the standard page size.- * @param is_input Memory is used only as input or not.- */- std::shared_ptr<ZeroMem> allocate_zero_memory(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,- const size_t bytes,- const size_t alignment,- const bool is_input = false);-- /**- * @brief Returns an imported shared(CMX-DMA in case of Linux, NT handle in case of Windows) memory in the level- * zero and adds it to the pool.- * @param init_structs Holder for the level zero structures.- * @param data Memory to be imported.- * @param bytes Size in bytes of the memory that must be allocated.- */- std::shared_ptr<ZeroMem> import_shared_memory(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,- const void* data,- const size_t bytes);-- /**- * @brief Performs a look-up in the pool to check if the entire range given by [data, data + bytes] was previously- * allocated or imported. Returns a reference to the ZeroMem object stored in the pool in case the check is- * successful, or tries to import memory in the level zero context, adds it to the pool, and returns it.- * @param init_structs Holder for the level zero structures.- * @param data User memory to be checked.- * @param bytes Size in bytes of the memory.- * @param is_input Memory is used only as input or not.- */- std::shared_ptr<ZeroMem> import_standard_allocation_memory(- const std::shared_ptr<ZeroInitStructsHolder>& init_structs,- const void* data,- const size_t bytes,- const bool is_input = false);+struct ZeroMemPool {+ // Tracks Level Zero allocations and imported memory by allocation ID without extending their lifetime.+ std::unordered_map<uint64_t, std::weak_ptr<ZeroMem>> mem_pool;+ // Signals completion of asynchronous pool entry removal before a standard allocation is imported again.+ std::unordered_map<uint64_t, std::promise<void>> notify_mem_pool;+ // Serializes pool lookups and mutations.+ std::mutex mem_pool_mutex;+ // Coordinates custom deleters with standard-allocation import paths.+ std::mutex mem_pool_deleter_mutex;+};-private:- ZeroMemPool();+/**+ * @details Provides helpers to either allocate or import memory in the level zero context. Such method will also add an+ * entry into the pool for the tracking ID that corresponds to that allocation. Provides a helper to check if a given+ * memory range was previously allocated or imported.+ */+namespace zero_mem {- std::shared_ptr<ZeroMem> import_standard_allocation(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,- const void* data,- const size_t bytes,- const bool is_input);- void update_pool(const std::shared_ptr<intel_npu::ZeroMem>& zero_memory);- void delete_pool_entry(ZeroMem* ptr);+/**+ * @brief Returns a new memory region allocated in the level zero context and adds it to the pool.+ * @param init_structs Holder for the level zero structures.+ * @param bytes Size in bytes of the memory that must be allocated.+ * @param alignment Alignment needed for the memory; it must be a multiple of the standard page size.+ * @param is_input Memory is used only as input or not.+ */+std::shared_ptr<ZeroMem> allocate_memory(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,+ const size_t bytes,+ const size_t alignment,+ const bool is_input = false);- std::unordered_map<uint64_t, std::weak_ptr<ZeroMem>> _pool;- // pool to synchronize shared_ptr<ZeroMem> deleter and import_standard_allocation_memory method- std::unordered_map<uint64_t, std::promise<void>> _notify_pool;+/**+ * @brief Returns an imported shared(CMX-DMA in case of Linux, NT handle in case of Windows) memory in the level+ * zero and adds it to the pool.+ * @param init_structs Holder for the level zero structures.+ * @param data Memory to be imported.+ * @param bytes Size in bytes of the memory that must be allocated.+ */+std::shared_ptr<ZeroMem> import_shared_memory(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,+ const void* data,+ const size_t bytes);- // mutex to synchronize memory pool- std::mutex _mutex;- // mutex to synchronize shared_ptr<ZeroMem> deleter and import_standard_allocation_memory method- std::mutex _deleter_mutex;-};+/**+ * @brief Performs a look-up in the pool to check if the entire range given by [data, data + bytes] was previously+ * allocated or imported. Returns a reference to the ZeroMem object stored in the pool in case the check is+ * successful, or tries to import memory in the level zero context, adds it to the pool, and returns it.+ * @param init_structs Holder for the level zero structures.+ * @param data User memory to be checked.+ * @param bytes Size in bytes of the memory.+ * @param is_input Memory is used only as input or not.+ */+std::shared_ptr<ZeroMem> import_standard_allocation_memory(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,+ const void* data,+ const size_t bytes,+ const bool is_input = false);+} // namespace zero_mem} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/utils/src/zero/zero_mem_pool.cpp b/src/plugins/intel_npu/src/utils/src/zero/zero_mem_pool.cppindex cc0394fae74..1d5b8dac27d 100644--- a/src/plugins/intel_npu/src/utils/src/zero/zero_mem_pool.cpp+++ b/src/plugins/intel_npu/src/utils/src/zero/zero_mem_pool.cpp@@ -4,135 +4,179 @@#include "intel_npu/utils/zero/zero_mem_pool.hpp"-#include "intel_npu/utils/utils.hpp"+#ifdef NPU_PLUGIN_DEVELOPER_BUILD+# include <cstdlib>+#endif++#include "intel_npu/utils/logger/logger.hpp"+#include "intel_npu/utils/zero/zero_init.hpp"+#include "intel_npu/utils/zero/zero_mem.hpp"#include "intel_npu/utils/zero/zero_utils.hpp"namespace intel_npu {+namespace zero_mem {++class ZeroMemPoolManager final {+public:+ ZeroMemPoolManager() = default;+ ~ZeroMemPoolManager() = default;++ static std::shared_ptr<ZeroMem> allocate_memory(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,+ const size_t bytes,+ const size_t alignment,+ const bool is_input) {+ auto zero_memory = std::shared_ptr<ZeroMem>(new ZeroMem(init_structs, bytes, alignment, is_input),+ [init_structs](ZeroMem* ptr) {+ ZeroMemPoolManager::delete_pool_entry(init_structs, ptr);+ });++ std::lock_guard<std::mutex> lock(init_structs->getZeroMemPool().mem_pool_mutex);+ {+ // lock the deleter_lock only for this scope+ std::lock_guard<std::mutex> deleter_lock(init_structs->getZeroMemPool().mem_pool_deleter_mutex);+ ZeroMemPoolManager::update_pool(init_structs, zero_memory);+ }-ZeroMemPool::ZeroMemPool() {}--ZeroMemPool& ZeroMemPool::get_instance() {- static ZeroMemPool instance;- return instance;-}--std::shared_ptr<ZeroMem> ZeroMemPool::allocate_zero_memory(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,- const size_t bytes,- const size_t alignment,- const bool is_input) {- auto zero_memory =- std::shared_ptr<ZeroMem>(new ZeroMem(init_structs, bytes, alignment, is_input), [this](ZeroMem* ptr) {- delete_pool_entry(ptr);- });-- std::lock_guard<std::mutex> lock(_mutex);- {- // lock the deleter_lock only for this scope- std::lock_guard<std::mutex> deleter_lock(_deleter_mutex);- update_pool(zero_memory);- }-- return zero_memory;-}--std::shared_ptr<ZeroMem> ZeroMemPool::import_shared_memory(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,- const void* data,- const size_t bytes) {- auto zero_memory =- std::shared_ptr<ZeroMem>(new ZeroMem(init_structs, data, bytes, false, false), [this](ZeroMem* ptr) {- delete_pool_entry(ptr);- });-- std::lock_guard<std::mutex> lock(_mutex);- {- // lock the deleter_lock only for this scope- std::lock_guard<std::mutex> deleter_lock(_deleter_mutex);- update_pool(zero_memory);+ return zero_memory;}- return zero_memory;-}+ static std::shared_ptr<ZeroMem> import_shared_memory(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,+ const void* data,+ const size_t bytes) {+ auto zero_memory = std::shared_ptr<ZeroMem>(new ZeroMem(init_structs, data, bytes, false, false),+ [init_structs](ZeroMem* ptr) {+ ZeroMemPoolManager::delete_pool_entry(init_structs, ptr);+ });++ std::lock_guard<std::mutex> lock(init_structs->getZeroMemPool().mem_pool_mutex);+ {+ // lock the deleter_lock only for this scope+ std::lock_guard<std::mutex> deleter_lock(init_structs->getZeroMemPool().mem_pool_deleter_mutex);+ ZeroMemPoolManager::update_pool(init_structs, zero_memory);+ }-std::shared_ptr<ZeroMem> ZeroMemPool::import_standard_allocation_memory(- const std::shared_ptr<ZeroInitStructsHolder>& init_structs,- const void* data,- const size_t bytes,- const bool is_input) {- std::lock_guard<std::mutex> lock(_mutex);- std::unique_lock<std::mutex> deleter_lock(_deleter_mutex);-- auto memory_id = zeroUtils::get_l0_context_memory_allocation_id(init_structs->getContext(), data);- if (memory_id == 0) {- // try to import memory if it isn't part of the same zero context- return import_standard_allocation(init_structs, data, bytes, is_input);+ return zero_memory;}- if (_pool.find(memory_id) != _pool.end()) {- // found one weak pointer in the pool; check it if it's valid- auto obj = _pool.at(memory_id).lock();- if (obj) {- auto user_addr_end = static_cast<uint8_t*>(const_cast<void*>(data)) + bytes;- auto host_addr_end = static_cast<uint8_t*>(obj->data()) + obj->size();- if (user_addr_end > host_addr_end) {- throw ZeroMemException("Tensor memory range is out of bounds of the allocated host memory");- }-- return obj;- } else {- // shared_ptr counter is 0, we can not lock memory; wait until the deleter frees the memory- std::shared_future<void> done_future = _notify_pool[memory_id].get_future().share();- // allow (any) deleter to be executed. it will remove the pool entry and deallocate the level zero memory- deleter_lock.unlock();- // waiting for the corresponding deleter to be executed- done_future.wait();- deleter_lock.lock();- _notify_pool.erase(memory_id);-- // import again memory after make sure it is destroyed+ static std::shared_ptr<ZeroMem> import_standard_allocation_memory(+ const std::shared_ptr<ZeroInitStructsHolder>& init_structs,+ const void* data,+ const size_t bytes,+ const bool is_input) {+ std::lock_guard<std::mutex> lock(init_structs->getZeroMemPool().mem_pool_mutex);+ std::unique_lock<std::mutex> deleter_lock(init_structs->getZeroMemPool().mem_pool_deleter_mutex);++ auto memory_id = zeroUtils::get_l0_context_memory_allocation_id(init_structs->getContext(), data);+ if (memory_id == 0) {+ // try to import memory if it isn't part of the same zero contextreturn import_standard_allocation(init_structs, data, bytes, is_input);}- }-- throw ZeroMemException("Unexpected error");-}-std::shared_ptr<ZeroMem> ZeroMemPool::import_standard_allocation(- const std::shared_ptr<ZeroInitStructsHolder>& init_structs,- const void* data,- const size_t bytes,- const bool is_input) {- auto zero_memory =- std::shared_ptr<ZeroMem>(new ZeroMem(init_structs, data, bytes, is_input, true), [this](ZeroMem* ptr) {- auto memory_id = ptr->id();- delete_pool_entry(ptr);- if (_notify_pool.find(memory_id) != _notify_pool.end()) {- _notify_pool.at(memory_id).set_value();+ auto& zero_mem_pool = init_structs->getZeroMemPool().mem_pool;+ auto& notify_zero_mem_pool = init_structs->getZeroMemPool().notify_mem_pool;++ if (zero_mem_pool.find(memory_id) != zero_mem_pool.end()) {+ // found one weak pointer in the pool; check it if it's valid+ auto obj = zero_mem_pool.at(memory_id).lock();+ if (obj) {+ auto user_addr_end = static_cast<uint8_t*>(const_cast<void*>(data)) + bytes;+ auto host_addr_end = static_cast<uint8_t*>(obj->data()) + obj->size();+ if (user_addr_end > host_addr_end) {+ throw ZeroMemException("Tensor memory range is out of bounds of the allocated host memory");+ }++ return obj;+ } else {+ // shared_ptr counter is 0, we can not lock memory; wait until the deleter frees the memory+ std::shared_future<void> done_future = notify_zero_mem_pool[memory_id].get_future().share();+ // allow (any) deleter to be executed. it will remove the pool entry and deallocate the level zero+ // memory+ deleter_lock.unlock();+ // waiting for the corresponding deleter to be executed+ done_future.wait();+ deleter_lock.lock();+ notify_zero_mem_pool.erase(memory_id);++ // import again memory after make sure it is destroyed+ return ZeroMemPoolManager::import_standard_allocation(init_structs, data, bytes, is_input);}- });+ }- update_pool(zero_memory);+ throw ZeroMemException("Unexpected error");+ }- return zero_memory;-}+private:+ static std::shared_ptr<ZeroMem> import_standard_allocation(+ const std::shared_ptr<ZeroInitStructsHolder>& init_structs,+ const void* data,+ const size_t bytes,+ const bool is_input) {+ auto zero_memory = std::shared_ptr<ZeroMem>(+ new ZeroMem(init_structs, data, bytes, is_input, true),+ [init_structs](ZeroMem* ptr) {+ auto memory_id = ptr->id();+ auto& notify_zero_mem_pool = init_structs->getZeroMemPool().notify_mem_pool;+ ZeroMemPoolManager::delete_pool_entry(init_structs, ptr);++ std::unique_lock<std::mutex> deleter_lock(init_structs->getZeroMemPool().mem_pool_deleter_mutex);+ if (notify_zero_mem_pool.find(memory_id) != notify_zero_mem_pool.end()) {+ notify_zero_mem_pool.at(memory_id).set_value();+ }+ });++ ZeroMemPoolManager::update_pool(init_structs, zero_memory);+ return zero_memory;+ }-void ZeroMemPool::update_pool(const std::shared_ptr<intel_npu::ZeroMem>& zero_memory) {- auto pair = std::make_pair(zero_memory->id(), zero_memory);+ static void update_pool(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,+ const std::shared_ptr<ZeroMem>& zero_memory) {+ auto& zero_mem_pool = init_structs->getZeroMemPool().mem_pool;+ auto pair = std::make_pair(zero_memory->id(), zero_memory);#ifdef NPU_PLUGIN_DEVELOPER_BUILD- if (_pool.find(zero_memory->id()) != _pool.end()) {- if (_pool.at(zero_memory->id()).lock()) {- OPENVINO_THROW("Memory exists, at this point id shall not be used!");+ if (zero_mem_pool.find(zero_memory->id()) != zero_mem_pool.end()) {+ if (zero_mem_pool.at(zero_memory->id()).lock()) {+ // Abort instead of throw: this is a programming-error invariant violation.+ // Throwing here could cause a deadlock if the caller holds+ // _zero_mem_pool_deleter_mutex, because stack unwinding would destroy+ // zero_memory whose custom deleter re-acquires the same mutex.+ Logger log("ZeroMemPool", Logger::global().level());+ log.error("Memory exists, at this point id shall not be used!");+ std::abort();+ }}- }#endif- _pool.emplace(pair);+ zero_mem_pool.emplace(pair);+ }++ static void delete_pool_entry(const std::shared_ptr<ZeroInitStructsHolder>& init_structs, ZeroMem* zero_memory) {+ auto& zero_mem_pool = init_structs->getZeroMemPool().mem_pool;+ std::unique_lock<std::mutex> deleter_lock(init_structs->getZeroMemPool().mem_pool_deleter_mutex);+ zero_mem_pool.erase(zero_memory->id());+ delete zero_memory;+ }+};++std::shared_ptr<ZeroMem> allocate_memory(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,+ const size_t bytes,+ const size_t alignment,+ const bool is_input) {+ return ZeroMemPoolManager::allocate_memory(init_structs, bytes, alignment, is_input);}-void ZeroMemPool::delete_pool_entry(ZeroMem* zero_memory) {- std::unique_lock lock(_deleter_mutex);- _pool.erase(zero_memory->id());- delete zero_memory;+std::shared_ptr<ZeroMem> import_shared_memory(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,+ const void* data,+ const size_t bytes) {+ return ZeroMemPoolManager::import_shared_memory(init_structs, data, bytes);+}++std::shared_ptr<ZeroMem> import_standard_allocation_memory(const std::shared_ptr<ZeroInitStructsHolder>& init_structs,+ const void* data,+ const size_t bytes,+ const bool is_input) {+ return ZeroMemPoolManager::import_standard_allocation_memory(init_structs, data, bytes, is_input);}+} // namespace zero_mem} // namespace intel_npudiff --git a/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp b/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cppindex f636fe58084..ed03cad91df 100644--- a/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp+++ b/src/plugins/intel_npu/src/utils/src/zero/zero_remote_tensor.cpp@@ -321,10 +321,10 @@ void ZeroRemoteTensor::copy_file_data_to_level_zero_memory(const size_t size_to_fin.seekg(offset, std::ios::beg);- _host_memory = ZeroMemPool::get_instance().allocate_zero_memory(_init_structs,- size_to_read,- utils::STANDARD_PAGE_SIZE,- _tensor_type == TensorType::INPUT ? true : false);+ _host_memory = zero_mem::allocate_memory(_init_structs,+ size_to_read,+ utils::STANDARD_PAGE_SIZE,+ _tensor_type == TensorType::INPUT ? true : false);_data = _host_memory->data();std::streamoff bytes_to_read = static_cast<std::streamoff>(size_to_read);@@ -339,17 +339,16 @@ void ZeroRemoteTensor::copy_file_data_to_level_zero_memory(const size_t size_to_void ZeroRemoteTensor::allocate(const size_t bytes) {switch (_mem_type) {case MemType::L0_INTERNAL_BUF: {- _host_memory =- ZeroMemPool::get_instance().allocate_zero_memory(_init_structs,- bytes,- utils::STANDARD_PAGE_SIZE,- _tensor_type == TensorType::INPUT ? true : false);+ _host_memory = zero_mem::allocate_memory(_init_structs,+ bytes,+ utils::STANDARD_PAGE_SIZE,+ _tensor_type == TensorType::INPUT ? true : false);_data = _host_memory->data();break;}case MemType::SHARED_BUF: {// set up the request to import the external memory handle- _host_memory = ZeroMemPool::get_instance().import_shared_memory(_init_structs, _mem, bytes);+ _host_memory = zero_mem::import_shared_memory(_init_structs, _mem, bytes);_data = _host_memory->data();break;}@@ -384,11 +383,11 @@ void ZeroRemoteTensor::allocate(const size_t bytes) {try {size_t aligned_size = utils::align_size_to_standard_page_size(bytes);- _host_memory = ZeroMemPool::get_instance().import_standard_allocation_memory(- _init_structs,- std::as_const(_mmap_tensor).data(),- aligned_size,- _tensor_type == TensorType::INPUT ? true : false);+ _host_memory =+ zero_mem::import_standard_allocation_memory(_init_structs,+ std::as_const(_mmap_tensor).data(),+ aligned_size,+ _tensor_type == TensorType::INPUT ? true : false);_data = _host_memory->data();} catch (const ZeroMemException&) {_logger.info("Failed to import mmaped memory. File data will be copied to the level zero memory");@@ -398,11 +397,10 @@ void ZeroRemoteTensor::allocate(const size_t bytes) {break;}case MemType::CPU_VA: {- _host_memory = ZeroMemPool::get_instance().import_standard_allocation_memory(- _init_structs,- _mem,- bytes,- _tensor_type == TensorType::INPUT ? true : false);+ _host_memory = zero_mem::import_standard_allocation_memory(_init_structs,+ _mem,+ bytes,+ _tensor_type == TensorType::INPUT ? true : false);_data = _host_memory->data();break;}diff --git a/src/plugins/intel_npu/src/utils/src/zero/zero_tensor.cpp b/src/plugins/intel_npu/src/utils/src/zero/zero_tensor.cppindex 4975c1bf091..d3bcd024b81 100644--- a/src/plugins/intel_npu/src/utils/src/zero/zero_tensor.cpp+++ b/src/plugins/intel_npu/src/utils/src/zero/zero_tensor.cpp@@ -46,10 +46,7 @@ ZeroTensor::ZeroTensor(const std::shared_ptr<ZeroInitStructsHolder>& init_struct_bytes_capacity = get_byte_size();- _mem_ref = ZeroMemPool::get_instance().allocate_zero_memory(_init_structs,- byte_size.value(),- utils::STANDARD_PAGE_SIZE,- _is_input);+ _mem_ref = zero_mem::allocate_memory(_init_structs, byte_size.value(), utils::STANDARD_PAGE_SIZE, _is_input);auto data = _mem_ref->data();OPENVINO_ASSERT(byte_size.value() == 0 || data != nullptr, "Failed to allocate zero memory");_ptr = data;@@ -97,7 +94,7 @@ ZeroTensor::ZeroTensor(const std::shared_ptr<ZeroInitStructsHolder>& init_struct// _mem_ref will keep a reference to that allocation. Otherwise the function will try to import it into the level// zero context._logger.debug("ZeroTensor::ZeroTensor - get tensor from pool or import it");- _mem_ref = ZeroMemPool::get_instance().import_standard_allocation_memory(_init_structs, _ptr, _bytes_capacity);+ _mem_ref = zero_mem::import_standard_allocation_memory(_init_structs, _ptr, _bytes_capacity);}// Note: Override data() members to not used OpenVINO library code to improve performance@@ -208,10 +205,7 @@ void ZeroTensor::set_shape(ov::Shape new_shape) {// allocate buffer and initialize objects from scratchconst auto byte_size = ov::util::get_memory_size_safe(_element_type, _shape);OPENVINO_ASSERT(byte_size, "Cannot allocate memory for type: ", _element_type, " and shape: ", _shape);- _mem_ref = ZeroMemPool::get_instance().allocate_zero_memory(_init_structs,- byte_size.value(),- utils::STANDARD_PAGE_SIZE,- _is_input);+ _mem_ref = zero_mem::allocate_memory(_init_structs, byte_size.value(), utils::STANDARD_PAGE_SIZE, _is_input);_ptr = _mem_ref->data();OPENVINO_ASSERT(byte_size.value() == 0 || _ptr != nullptr, "Failed to allocate zero memory");_bytes_capacity = get_byte_size();@@ -242,7 +236,7 @@ bool ZeroTensor::can_be_reused() {void ZeroTensor::allocate_data() {_logger.debug("ZeroTensor::allocate_data - import the tensor data");_ptr = _user_tensor->data();- _mem_ref = ZeroMemPool::get_instance().import_standard_allocation_memory(_init_structs, _ptr, _bytes_capacity);+ _mem_ref = zero_mem::import_standard_allocation_memory(_init_structs, _ptr, _bytes_capacity);}void ZeroTensor::detach_imported_allocation_for_custom_tensor() {diff --git a/src/plugins/intel_npu/tests/functional/internal/compiler_adapter/zero_graph.hpp b/src/plugins/intel_npu/tests/functional/internal/compiler_adapter/zero_graph.hppindex a50e9baaeb2..44be378a849 100644--- a/src/plugins/intel_npu/tests/functional/internal/compiler_adapter/zero_graph.hpp+++ b/src/plugins/intel_npu/tests/functional/internal/compiler_adapter/zero_graph.hpp@@ -164,10 +164,8 @@ TEST_P(ZeroGraphCompilationTests, GetInitSetArgsDestroyGraphAlignedMemoryIR) {size_t totalSize = 1 * 3 * 24 * 24 * sizeof(float);std::shared_ptr<ZeroMem> buffer;- OV_ASSERT_NO_THROW(buffer = ZeroMemPool::get_instance().allocate_zero_memory(zeroInitStruct,- totalSize,- ::utils::STANDARD_PAGE_SIZE,- false));+ OV_ASSERT_NO_THROW(+ buffer = ::intel_npu::zero_mem::allocate_memory(zeroInitStruct, totalSize, ::utils::STANDARD_PAGE_SIZE, false));OV_ASSERT_NO_THROW(zeGraphExt->setGraphArgumentValue(graphDescriptor, 0, buffer->data()));}@@ -221,10 +219,9 @@ TEST_P(ZeroGraphTest, GetInitSetArgsDestroyGraphAlignedMemoryMallocBlob) {OV_ASSERT_NO_THROW(zeGraphExt->initializeGraph(graphDescriptor));std::shared_ptr<ZeroMem> buffer;- OV_ASSERT_NO_THROW(buffer = ZeroMemPool::get_instance().allocate_zero_memory(zeroInitStruct,- alignedSize,- ::utils::STANDARD_PAGE_SIZE,- false));+ OV_ASSERT_NO_THROW(+ buffer =+ ::intel_npu::zero_mem::allocate_memory(zeroInitStruct, alignedSize, ::utils::STANDARD_PAGE_SIZE, false));OV_ASSERT_NO_THROW(zeGraphExt->setGraphArgumentValue(graphDescriptor, 0, buffer->data()));}@@ -237,10 +234,9 @@ TEST_P(ZeroGraphTest, GetInitSetArgsDestroyGraphNotAlignedMemoryMallocBlob) {OV_ASSERT_NO_THROW(zeGraphExt->initializeGraph(graphDescriptor));std::shared_ptr<ZeroMem> buffer;- OV_ASSERT_NO_THROW(buffer = ZeroMemPool::get_instance().allocate_zero_memory(zeroInitStruct,- alignedSize,- ::utils::STANDARD_PAGE_SIZE,- false));+ OV_ASSERT_NO_THROW(+ buffer =+ ::intel_npu::zero_mem::allocate_memory(zeroInitStruct, alignedSize, ::utils::STANDARD_PAGE_SIZE, false));OV_ASSERT_NO_THROW(zeGraphExt->setGraphArgumentValue(graphDescriptor, 0, static_cast<char*>(buffer->data()) + 1));}diff --git a/src/plugins/intel_npu/tests/functional/internal/compiler_adapter/zero_init_mock.hpp b/src/plugins/intel_npu/tests/functional/internal/compiler_adapter/zero_init_mock.hppindex 1751b671541..e95d95c4dfa 100644--- a/src/plugins/intel_npu/tests/functional/internal/compiler_adapter/zero_init_mock.hpp+++ b/src/plugins/intel_npu/tests/functional/internal/compiler_adapter/zero_init_mock.hpp@@ -12,6 +12,7 @@#include "intel_npu/utils/logger/logger.hpp"#include "intel_npu/utils/zero/zero_api.hpp"+#include "intel_npu/utils/zero/zero_mem_pool.hpp"#include "intel_npu/utils/zero/zero_types.hpp"namespace intel_npu {@@ -25,7 +26,9 @@ inline constexpr uint32_t TARGET_ZE_CONTEXT_NPU_EXT_VERSION = ZE_CONTEXT_NPU_EXTinline constexpr uint32_t TARGET_ZE_MUTABLE_COMMAND_LIST_EXT_VERSION = ZE_MUTABLE_COMMAND_LIST_EXP_VERSION_1_1;inline constexpr uint32_t TARGET_ZE_EXTERNAL_MEMMAP_SYSMEM_EXT_VERSION = ZE_EXTERNAL_MEMMAP_SYSMEM_EXT_VERSION_1_0;} // namespace test_constants+struct ZeroInitStructsMock {+public:ZeroInitStructsMock(uint32_t zeDriverNpuExtVersion = intel_npu::test_constants::TARGET_ZE_DRIVER_NPU_EXT_VERSION,uint32_t zeGraphNpuExtVersion = intel_npu::test_constants::TARGET_ZE_GRAPH_NPU_EXT_VERSION,@@ -38,6 +41,11 @@ struct ZeroInitStructsMock {~ZeroInitStructsMock();+ inline ZeroMemPool& getZeroMemPool() {+ return _zero_mem_pool;+ }++private:void initNpuDriver();void getExtensionFunctionAddress(const std::string& name, const uint32_t version, void** function_address);@@ -70,6 +78,8 @@ struct ZeroInitStructsMock {uint32_t _command_queue_group_ordinal = 0;+ ZeroMemPool _zero_mem_pool;+std::mutex _mutex;};diff --git a/src/plugins/intel_npu/tests/functional/internal/utils/zero/zero_mem_pool_tests.hpp b/src/plugins/intel_npu/tests/functional/internal/utils/zero/zero_mem_pool_tests.hppindex 49752d72c84..6962c3f8d89 100644--- a/src/plugins/intel_npu/tests/functional/internal/utils/zero/zero_mem_pool_tests.hpp+++ b/src/plugins/intel_npu/tests/functional/internal/utils/zero/zero_mem_pool_tests.hpp@@ -25,6 +25,7 @@#include "intel_npu/utils/zero/zero_mem.hpp"#include "intel_npu/utils/zero/zero_mem_pool.hpp"#include "intel_npu/utils/zero/zero_utils.hpp"+#include "internal/compiler_adapter/zero_init_mock.hpp"#include "openvino/core/any.hpp"#include "openvino/runtime/core.hpp"#include "shared_test_classes/base/ov_behavior_test_utils.hpp"@@ -102,15 +103,12 @@ TEST_P(ZeroMemPoolTests, GetZeroMemoryData) {std::shared_ptr<::intel_npu::ZeroMem> get_zero_mem;if (init_struct->isExternalMemoryStandardAllocationSupported()) {- OV_ASSERT_NO_THROW(- get_zero_mem =- ::intel_npu::ZeroMemPool::get_instance().import_standard_allocation_memory(init_struct, data, 4096));+ OV_ASSERT_NO_THROW(get_zero_mem =+ ::intel_npu::zero_mem::import_standard_allocation_memory(init_struct, data, 4096));ASSERT_TRUE(::intel_npu::zeroUtils::get_l0_context_memory_allocation_id(init_struct->getContext(), data));} else {- ASSERT_THROW(- get_zero_mem =- ::intel_npu::ZeroMemPool::get_instance().import_standard_allocation_memory(init_struct, data, 4096),- ::intel_npu::ZeroMemException);+ ASSERT_THROW(get_zero_mem = ::intel_npu::zero_mem::import_standard_allocation_memory(init_struct, data, 4096),+ ::intel_npu::ZeroMemException);ASSERT_FALSE(::intel_npu::zeroUtils::get_l0_context_memory_allocation_id(init_struct->getContext(), data));}@@ -132,21 +130,19 @@ TEST_P(ZeroMemPoolTests, MultiThreadingReUseAlreadyAllocatedImportedMemory) {// Prep: add few entries in the poolfor (int i = 0; i < 3; i++) {data[i] = ::operator new(4096, std::align_val_t(4096));- zero_mem[i] =- ::intel_npu::ZeroMemPool::get_instance().import_standard_allocation_memory(init_struct, data[i], 4096);+ zero_mem[i] = ::intel_npu::zero_mem::import_standard_allocation_memory(init_struct, data[i], 4096);}- zero_mem[3] = ::intel_npu::ZeroMemPool::get_instance().allocate_zero_memory(init_struct, 4096, 4096);- zero_mem[4] = ::intel_npu::ZeroMemPool::get_instance().allocate_zero_memory(init_struct, 4096, 4096);+ zero_mem[3] = ::intel_npu::zero_mem::allocate_memory(init_struct, 4096, 4096);+ zero_mem[4] = ::intel_npu::zero_mem::allocate_memory(init_struct, 4096, 4096);for (int i = 0; i < threads_no; ++i) {threads[i] = std::thread([this, &zero_mem, i]() -> void {for (int j = 0; j < 256; j++) {std::shared_ptr<::intel_npu::ZeroMem> get_zero_mem;- OV_ASSERT_NO_THROW(get_zero_mem =- ::intel_npu::ZeroMemPool::get_instance().import_standard_allocation_memory(- init_struct,- zero_mem[i % 5]->data(),- 4096));+ OV_ASSERT_NO_THROW(+ get_zero_mem = ::intel_npu::zero_mem::import_standard_allocation_memory(init_struct,+ zero_mem[i % 5]->data(),+ 4096));SLEEP_MS(0);}});@@ -180,11 +176,10 @@ TEST_P(ZeroMemPoolTests, MultiThreadingImportMemoryReUseAndDestroyIt) {threads[i] = std::thread([&]() -> void {std::shared_ptr<::intel_npu::ZeroMem> zero_mem;for (int j = 0; j < threads_no; j++) {- OV_ASSERT_NO_THROW(zero_mem =- ::intel_npu::ZeroMemPool::get_instance().import_standard_allocation_memory(- init_struct,- data[j % no_of_buffers],- 4096));+ OV_ASSERT_NO_THROW(+ zero_mem = ::intel_npu::zero_mem::import_standard_allocation_memory(init_struct,+ data[j % no_of_buffers],+ 4096));SLEEP_MS(0);if (j % 2 == 0) {zero_mem = {};@@ -205,6 +200,173 @@ TEST_P(ZeroMemPoolTests, MultiThreadingImportMemoryReUseAndDestroyIt) {}}+TEST_P(ZeroMemPoolTests, GetPoolReturnsSamePoolForSameInitStruct) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED()++ auto zero_init_mock = std::make_shared<::intel_npu::ZeroInitStructsMock>();+ auto local_init_struct_0 = std::reinterpret_pointer_cast<::intel_npu::ZeroInitStructsHolder>(zero_init_mock);+ auto local_init_struct_1 = std::reinterpret_pointer_cast<::intel_npu::ZeroInitStructsHolder>(zero_init_mock);++ auto mem0 = ::intel_npu::zero_mem::allocate_memory(local_init_struct_0, 4096, 4096);+ auto mem1 = ::intel_npu::zero_mem::allocate_memory(local_init_struct_1, 4096, 4096);+ ASSERT_EQ(zero_init_mock->getZeroMemPool().mem_pool.size(), 2u);++ mem0 = {};+ mem1 = {};+ ASSERT_EQ(zero_init_mock->getZeroMemPool().mem_pool.size(), 0u);+}++TEST_P(ZeroMemPoolTests, CheckDifferentZeroStructsHolderPools) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED()++ auto zero_init_mock_0 = std::make_shared<::intel_npu::ZeroInitStructsMock>();+ auto zero_init_mock_1 = std::make_shared<::intel_npu::ZeroInitStructsMock>();+ auto zero_init_mock_2 = std::make_shared<::intel_npu::ZeroInitStructsMock>();++ auto local_init_struct_0 = std::reinterpret_pointer_cast<::intel_npu::ZeroInitStructsHolder>(zero_init_mock_0);+ auto local_init_struct_1 = std::reinterpret_pointer_cast<::intel_npu::ZeroInitStructsHolder>(zero_init_mock_1);+ auto local_init_struct_2 = std::reinterpret_pointer_cast<::intel_npu::ZeroInitStructsHolder>(zero_init_mock_2);++ auto& pool_init_0 = zero_init_mock_0->getZeroMemPool().mem_pool;+ auto& pool_init_1 = zero_init_mock_1->getZeroMemPool().mem_pool;+ auto& pool_init_2 = zero_init_mock_2->getZeroMemPool().mem_pool;++ auto mem0_struct_global = ::intel_npu::zero_mem::allocate_memory(local_init_struct_0, 4096, 4096);+ auto mem0_struct_1 = ::intel_npu::zero_mem::allocate_memory(local_init_struct_1, 4096, 4096);+ auto mem0_struct_2 = ::intel_npu::zero_mem::allocate_memory(local_init_struct_2, 4096, 4096);+ auto mem1_struct_2 = ::intel_npu::zero_mem::allocate_memory(local_init_struct_2, 4096, 4096);++ ASSERT_TRUE(::intel_npu::zeroUtils::get_l0_context_memory_allocation_id(local_init_struct_0->getContext(),+ mem0_struct_global->data()));+ ASSERT_FALSE(::intel_npu::zeroUtils::get_l0_context_memory_allocation_id(local_init_struct_2->getContext(),+ mem0_struct_1->data()));+ ASSERT_FALSE(::intel_npu::zeroUtils::get_l0_context_memory_allocation_id(local_init_struct_0->getContext(),+ mem1_struct_2->data()));++ ASSERT_EQ(pool_init_0.size(), 1u);+ ASSERT_EQ(pool_init_1.size(), 1u);+ ASSERT_EQ(pool_init_2.size(), 2u);++ mem0_struct_2 = {};+ ASSERT_EQ(pool_init_2.size(), 1u);+ local_init_struct_2 = {};+ zero_init_mock_2 = {};+ ASSERT_EQ(pool_init_2.size(), 1u);+}++TEST_P(ZeroMemPoolTests, MultiThreadingDifferentZeroInitStructsHaveIsolatedPools) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED()++ constexpr size_t threads_per_pool = 32;+ constexpr size_t total_threads = threads_per_pool * 3;++ auto zero_init_mock_0 = std::make_shared<::intel_npu::ZeroInitStructsMock>();+ auto zero_init_mock_1 = std::make_shared<::intel_npu::ZeroInitStructsMock>();+ auto zero_init_mock_2 = std::make_shared<::intel_npu::ZeroInitStructsMock>();++ auto local_init_struct_0 = std::reinterpret_pointer_cast<::intel_npu::ZeroInitStructsHolder>(zero_init_mock_0);+ auto local_init_struct_1 = std::reinterpret_pointer_cast<::intel_npu::ZeroInitStructsHolder>(zero_init_mock_1);+ auto local_init_struct_2 = std::reinterpret_pointer_cast<::intel_npu::ZeroInitStructsHolder>(zero_init_mock_2);++ std::array<std::thread, total_threads> threads;+ std::array<std::shared_ptr<::intel_npu::ZeroMem>, threads_per_pool> mem_pool_0;+ std::array<std::shared_ptr<::intel_npu::ZeroMem>, threads_per_pool> mem_pool_1;+ std::array<std::shared_ptr<::intel_npu::ZeroMem>, threads_per_pool> mem_pool_2;++ for (size_t i = 0; i < threads_per_pool; ++i) {+ threads[i] = std::thread([&, i]() -> void {+ OV_ASSERT_NO_THROW(mem_pool_0[i] = ::intel_npu::zero_mem::allocate_memory(local_init_struct_0, 4096, 4096));+ });+ threads[i + threads_per_pool] = std::thread([&, i]() -> void {+ OV_ASSERT_NO_THROW(mem_pool_1[i] = ::intel_npu::zero_mem::allocate_memory(local_init_struct_1, 4096, 4096));+ });+ threads[i + (threads_per_pool * 2)] = std::thread([&, i]() -> void {+ OV_ASSERT_NO_THROW(mem_pool_2[i] = ::intel_npu::zero_mem::allocate_memory(local_init_struct_2, 4096, 4096));+ });+ }++ for (auto& t : threads) {+ t.join();+ }++ ASSERT_EQ(zero_init_mock_0->getZeroMemPool().mem_pool.size(), threads_per_pool);+ ASSERT_EQ(zero_init_mock_1->getZeroMemPool().mem_pool.size(), threads_per_pool);+ ASSERT_EQ(zero_init_mock_2->getZeroMemPool().mem_pool.size(), threads_per_pool);++ for (size_t i = 0; i < threads_per_pool; ++i) {+ mem_pool_0[i] = {};+ mem_pool_1[i] = {};+ mem_pool_2[i] = {};+ }++ ASSERT_EQ(zero_init_mock_0->getZeroMemPool().mem_pool.size(), 0u);+ ASSERT_EQ(zero_init_mock_1->getZeroMemPool().mem_pool.size(), 0u);+ ASSERT_EQ(zero_init_mock_2->getZeroMemPool().mem_pool.size(), 0u);+}++TEST_P(ZeroMemPoolTests, MultiThreadingImportMemoryReUseAndDestroyItWithMultipleInitStructs) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED()++ if (!init_struct->isExternalMemoryStandardAllocationSupported()) {+ GTEST_SKIP() << "Test requires support for importing standard allocated memory as external memory, which is "+ "not available on this platform.";+ }++ constexpr size_t init_structs_no = 3;+ constexpr size_t threads_per_pool = 32;+ constexpr size_t no_of_buffers = 5;++ auto zero_init_mock_0 = std::make_shared<::intel_npu::ZeroInitStructsMock>();+ auto zero_init_mock_1 = std::make_shared<::intel_npu::ZeroInitStructsMock>();+ auto zero_init_mock_2 = std::make_shared<::intel_npu::ZeroInitStructsMock>();++ std::array<std::shared_ptr<::intel_npu::ZeroInitStructsHolder>, init_structs_no> init_structs = {+ std::reinterpret_pointer_cast<::intel_npu::ZeroInitStructsHolder>(zero_init_mock_0),+ std::reinterpret_pointer_cast<::intel_npu::ZeroInitStructsHolder>(zero_init_mock_1),+ std::reinterpret_pointer_cast<::intel_npu::ZeroInitStructsHolder>(zero_init_mock_2)};++ std::array<std::array<void*, no_of_buffers>, init_structs_no> data = {};+ for (size_t s = 0; s < init_structs_no; ++s) {+ for (size_t i = 0; i < no_of_buffers; ++i) {+ data[s][i] = ::operator new(4096, std::align_val_t(4096));+ }+ }++ std::array<std::thread, threads_per_pool * init_structs_no> threads;+ for (size_t s = 0; s < init_structs_no; ++s) {+ for (size_t i = 0; i < threads_per_pool; ++i) {+ threads[s * threads_per_pool + i] = std::thread([&, s]() -> void {+ std::shared_ptr<::intel_npu::ZeroMem> zero_mem;+ for (size_t j = 0; j < threads_per_pool; ++j) {+ OV_ASSERT_NO_THROW(+ zero_mem = ::intel_npu::zero_mem::import_standard_allocation_memory(init_structs[s],+ data[s][j % no_of_buffers],+ 4096));+ SLEEP_MS(0);+ if (j % 2 == 0) {+ zero_mem = {};+ }+ }+ zero_mem = {};+ });+ }+ }++ for (auto& t : threads) {+ t.join();+ }++ ASSERT_EQ(zero_init_mock_0->getZeroMemPool().mem_pool.size(), 0u);+ ASSERT_EQ(zero_init_mock_1->getZeroMemPool().mem_pool.size(), 0u);+ ASSERT_EQ(zero_init_mock_2->getZeroMemPool().mem_pool.size(), 0u);++ for (size_t s = 0; s < init_structs_no; ++s) {+ for (size_t i = 0; i < no_of_buffers; ++i) {+ ::operator delete(data[s][i], std::align_val_t(4096));+ }+ }+}+} // namespace behavior} // namespace test} // namespace ov