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
Add Windows impl for async mmap prefetch (#37063)
Oleg Pipikinafdb243cd0c6
diff --git a/src/common/util/CMakeLists.txt b/src/common/util/CMakeLists.txtindex bdd0c2dd58a..e818f38f40b 100644--- a/src/common/util/CMakeLists.txt+++ b/src/common/util/CMakeLists.txt@@ -69,7 +69,7 @@ target_sources(${TARGET_NAME}${CMAKE_CURRENT_SOURCE_DIR}/src/file_path.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/file_util.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/log.cpp- ${CMAKE_CURRENT_SOURCE_DIR}/src/memory.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/src/memory_prefetch.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/memory_prefetch.hpp${CMAKE_CURRENT_SOURCE_DIR}/src/native_stream.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/native_streambuf.cppdiff --git a/src/common/util/src/memory.cpp b/src/common/util/src/memory.cppdeleted file mode 100644index 11d509709c3..00000000000--- a/src/common/util/src/memory.cpp+++ /dev/null@@ -1,34 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#include "openvino/util/memory.hpp"--#include <algorithm>-#include <cstdint>-#include <thread>-#include <vector>--#include "memory_prefetch.hpp"-#include "openvino/util/math_util.hpp"-#include "openvino/util/mmap_object.hpp"--namespace ov::util {-void populate_pages(void* ptr, size_t size, size_t num_threads) noexcept;--void populate_pages(void* ptr, size_t size, size_t num_threads) noexcept {- const auto page_size = static_cast<size_t>(get_system_page_size());- const auto chunk_size = std::max<size_t>(align_size_up(size / num_threads, page_size), one_mib);-- std::vector<std::thread> threads;- threads.reserve(ceil_div(size, chunk_size));-- for (auto first = reinterpret_cast<const uint8_t*>(ptr), last = first + size; first < last; first += chunk_size) {- threads.emplace_back(PageToucher{first, std::min(first + chunk_size, last), page_size});- }- for (auto& t : threads) {- t.join();- }-}--} // namespace ov::utildiff --git a/src/common/util/src/memory_prefetch.cpp b/src/common/util/src/memory_prefetch.cppnew file mode 100644index 00000000000..c93b45a23a4--- /dev/null+++ b/src/common/util/src/memory_prefetch.cpp@@ -0,0 +1,153 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "memory_prefetch.hpp"++#include <condition_variable>+#include <cstdint>+#include <functional>+#include <future>+#include <list>+#include <mutex>+#include <new>+#include <stdexcept>+#include <thread>+#include <vector>++#include "openvino/util/math_util.hpp"+#include "openvino/util/memory.hpp"++namespace ov::util {++namespace {++// FIFO job queue feeding the shared page-toucher pool: a small pool of long-lived worker threads+// is reused across calls instead of spawning/joining threads per prefetch request. Shared by both+// the Linux and Windows vm_prefetch_async() implementations (see submit_page_toucher_tasks()+// below).+class TaskQueue {+public:+ void push(std::list<std::function<void()>>&& batch) noexcept {+ {+ std::lock_guard lock(m_mutex);+ m_queue.splice(m_queue.end(), batch);+ }+ m_cv.notify_all();+ }++ // Blocks until a job is available, or returns false once the queue is stopped and drained.+ bool wait_and_pop(std::function<void()>& job) noexcept {+ std::unique_lock<std::mutex> lock(m_mutex);+ m_cv.wait(lock, [this] {+ return m_stop || !m_queue.empty();+ });+ if (m_queue.empty()) {+ return false;+ }+ job = std::move(m_queue.front());+ m_queue.pop_front();+ return true;+ }++ void stop() noexcept {+ {+ std::lock_guard<std::mutex> lock(m_mutex);+ m_stop = true;+ }+ m_cv.notify_all();+ }++private:+ std::mutex m_mutex;+ std::condition_variable m_cv;+ std::list<std::function<void()>> m_queue;+ bool m_stop = false;+};++class ThreadPool {+public:+ static ThreadPool& instance() {+ static ThreadPool pool;+ return pool;+ }++ ThreadPool(const ThreadPool&) = delete;+ ThreadPool& operator=(const ThreadPool&) = delete;+ ThreadPool(ThreadPool&&) = delete;+ ThreadPool& operator=(ThreadPool&&) = delete;++ std::vector<std::future<void>> submit(std::vector<std::function<void()>>&& jobs) {+ std::vector<std::future<void>> futures;+ futures.reserve(jobs.size());+ std::list<std::function<void()>> pending;+ for (auto& job : jobs) {+ auto task = std::make_shared<std::packaged_task<void()>>(std::move(job));+ futures.push_back(task->get_future());+ pending.emplace_back([task]() {+ (*task)();+ });+ }+ m_queue.push(std::move(pending));+ return futures;+ }++private:+ ThreadPool() {+ const auto workers_count =+ std::max<size_t>(1, std::min<size_t>(max_prefetch_threads, std::thread::hardware_concurrency()));+ m_workers.reserve(workers_count);+ for (size_t i = 0; i < workers_count; ++i) {+ m_workers.emplace_back([this]() {+ worker_loop();+ });+ }+ }++ ~ThreadPool() {+ m_queue.stop();+ for (auto& worker : m_workers) {+ if (worker.joinable()) {+ worker.join();+ }+ }+ }++ void worker_loop() noexcept {+ std::function<void()> job;+ while (m_queue.wait_and_pop(job)) {+ job();+ }+ }++ TaskQueue m_queue;+ std::vector<std::thread> m_workers;+};++} // namespace++std::vector<std::future<void>> submit_page_toucher_tasks(void* ptr, size_t size, size_t num_threads) noexcept {+ try {+ const auto page_size = static_cast<size_t>(get_system_page_size());+ const auto chunk_size =+ std::max<size_t>(align_size_up(size / num_threads, page_size), default_parallel_io_min_chunk);++ std::vector<std::function<void()>> jobs;+ jobs.reserve(ceil_div(size, chunk_size));++ for (auto first = reinterpret_cast<const uint8_t*>(ptr), last = first + size; first < last;+ first += chunk_size) {+ jobs.emplace_back(PageToucher{first, std::min(first + chunk_size, last), page_size});+ }+ return ThreadPool::instance().submit(std::move(jobs));+ } catch (const std::bad_alloc&) {+ // Job/future/packaged_task allocation failed under memory pressure.+ return {};+ } catch (const std::length_error&) {+ // vector::reserve()'s requested capacity exceeded max_size() (e.g. a pathological+ // ptr/size/num_threads combination producing an absurd chunk count).+ return {};+ }+}++} // namespace ov::utildiff --git a/src/common/util/src/memory_prefetch.hpp b/src/common/util/src/memory_prefetch.hppindex d0363a8dbbd..2517cdfc621 100644--- a/src/common/util/src/memory_prefetch.hpp+++ b/src/common/util/src/memory_prefetch.hpp@@ -115,13 +115,21 @@ private:};/**- * @brief Clamps [offset, offset + size) to [0, mapping_size) and page-aligns the result. Returns an- * empty region (m_length == 0) for a null/empty mapping, an offset at or past the end, or a- * sub-page request.+ * @brief Submits page-population jobs for [ptr, ptr + size) to the shared background thread pool,+ * splitting the range into up to @p num_threads chunks.*- * @note This is a self-contained helper for @ref make_prefetch_plan / hint_prefetch_async() only.- * It intentionally does not replace the pre-existing per-platform region helpers used by- * hint_evict()/hint_prefetch(), so those call sites remain untouched.+ * @param ptr Page-aligned base address of the range.+ * @param size Multiple of the system page size.+ * @param num_threads Number of population jobs to split the range into.+ *+ * Returns an empty vector if the work could not be scheduled (e.g. an allocation failure).+ */+std::vector<std::future<void>> submit_page_toucher_tasks(void* ptr, size_t size, size_t num_threads) noexcept;++/**+ * @brief Clamps [offset, offset + size) to [0, mapping_size) and page-aligns the result, rounding+ * the length up so it is always a page multiple (both ends page-aligned). Returns an empty region+ * (m_length == 0) for a null/empty mapping, an offset at or past the end, or a sub-page request.*/inline AlignedRegion clamp_align_region(const void* data, size_t mapping_size, size_t offset, size_t size) noexcept {const auto page_size = static_cast<size_t>(get_system_page_size());@@ -130,26 +138,9 @@ inline AlignedRegion clamp_align_region(const void* data, size_t mapping_size, s}const auto available = mapping_size - offset;const auto raw_len = (size == auto_size) ? available : std::min(size, available);- return align_region(reinterpret_cast<uintptr_t>(data) + offset, raw_len, page_size);-}--/** @brief Aligned region and page-aligned size for a hint_prefetch_async() call. */-struct PrefetchPlan {- uintptr_t m_address = 0;- size_t m_aligned_size = 0;-};--/**- * @brief Computes the region and page-aligned size for a hint_prefetch_async() call, or an empty- * plan (m_aligned_size == 0) when the region is below the parallel-I/O threshold (a real- * population pass would not be worth it).- */-inline PrefetchPlan make_prefetch_plan(const void* data, size_t mapping_size, size_t offset, size_t size) noexcept {- if (const auto region = clamp_align_region(data, mapping_size, offset, size);- region.m_length > default_parallel_io_threshold) {- return {region.m_address, align_size_up(region.m_length, static_cast<size_t>(get_system_page_size()))};- }- return {};+ auto region = align_region(reinterpret_cast<uintptr_t>(data) + offset, raw_len, page_size);+ region.m_length = align_size_up(region.m_length, page_size);+ return region;}/** @brief Upper bound on the shared page-population pool's worker threads. */diff --git a/src/common/util/src/os/lin/lin_memory.cpp b/src/common/util/src/os/lin/lin_memory.cppindex 50a8b3a835b..ff1dd7b5bc0 100644--- a/src/common/util/src/os/lin/lin_memory.cpp+++ b/src/common/util/src/os/lin/lin_memory.cpp@@ -4,26 +4,16 @@#include <sys/mman.h>-#include <algorithm>#include <cassert>#include <cerrno>-#include <condition_variable>#include <cstddef>#include <cstdint>#include <cstdlib>-#include <functional>-#include <future>-#include <list>-#include <mutex>-#include <thread>#include <tuple>-#include <vector>#include "memory_prefetch.hpp"-#include "openvino/util/math_util.hpp"#include "openvino/util/memory.hpp"#include "openvino/util/mmap_object.hpp"-#include "openvino/util/parallel_io.hpp"namespace ov::util {@@ -34,122 +24,6 @@ void madvise_hint(void* ptr, size_t size) noexcept {madvise(ptr, size, MADV_WILLNEED);}-class TaskQueue {-public:- void push(std::list<std::function<void()>>&& batch) noexcept {- {- std::lock_guard<std::mutex> lock(m_mutex);- m_queue.splice(m_queue.end(), batch);- }- m_cv.notify_all();- }-- // Blocks until a job is available, or returns false once the queue is stopped and drained.- bool wait_and_pop(std::function<void()>& job) noexcept {- std::unique_lock<std::mutex> lock(m_mutex);- m_cv.wait(lock, [this] {- return m_stop || !m_queue.empty();- });- if (m_queue.empty()) {- return false;- }- job = std::move(m_queue.front());- m_queue.pop_front();- return true;- }-- void stop() noexcept {- {- std::lock_guard<std::mutex> lock(m_mutex);- m_stop = true;- }- m_cv.notify_all();- }--private:- std::mutex m_mutex;- std::condition_variable m_cv;- std::list<std::function<void()>> m_queue;- bool m_stop = false;-};--class ThreadPool {-public:- static ThreadPool& instance() {- static ThreadPool pool;- return pool;- }-- ThreadPool(const ThreadPool&) = delete;- ThreadPool& operator=(const ThreadPool&) = delete;- ThreadPool(ThreadPool&&) = delete;- ThreadPool& operator=(ThreadPool&&) = delete;-- std::vector<std::future<void>> submit(std::vector<std::function<void()>>&& jobs) {- std::vector<std::future<void>> futures;- futures.reserve(jobs.size());- std::list<std::function<void()>> pending;- for (auto& job : jobs) {- auto task = std::make_shared<std::packaged_task<void()>>(std::move(job));- futures.push_back(task->get_future());- pending.emplace_back([task]() {- (*task)();- });- }- m_queue.push(std::move(pending));- return futures;- }--private:- ThreadPool() {- const auto workers_count =- std::max<size_t>(1, std::min<size_t>(max_prefetch_threads, std::thread::hardware_concurrency()));- m_workers.reserve(workers_count);- for (size_t i = 0; i < workers_count; ++i) {- m_workers.emplace_back([this]() {- worker_loop();- });- }- }-- ~ThreadPool() {- m_queue.stop();- for (auto& worker : m_workers) {- if (worker.joinable()) {- worker.join();- }- }- }-- void worker_loop() noexcept {- std::function<void()> job;- while (m_queue.wait_and_pop(job)) {- job();- }- }-- TaskQueue m_queue;- std::vector<std::thread> m_workers;-};--std::vector<std::future<void>> submit_page_toucher_tasks(void* ptr, size_t size, size_t num_threads) noexcept {- try {- const auto page_size = static_cast<size_t>(get_system_page_size());- const auto chunk_size =- std::max<size_t>(align_size_up(size / num_threads, page_size), default_parallel_io_min_chunk);-- std::vector<std::function<void()>> jobs;- jobs.reserve(ceil_div(size, chunk_size));-- for (auto first = reinterpret_cast<const uint8_t*>(ptr), last = first + size; first < last;- first += chunk_size) {- jobs.emplace_back(PageToucher{first, std::min(first + chunk_size, last), page_size});- }- return ThreadPool::instance().submit(std::move(jobs));- } catch (...) {- return {};- }-}} // namespacevoid* aligned_alloc(size_t size, size_t alignment) noexcept {diff --git a/src/common/util/src/os/lin/lin_mmap_object.cpp b/src/common/util/src/os/lin/lin_mmap_object.cppindex 33baacb425d..b1a43bc0596 100644--- a/src/common/util/src/os/lin/lin_mmap_object.cpp+++ b/src/common/util/src/os/lin/lin_mmap_object.cpp@@ -218,10 +218,11 @@ public:}void hint_prefetch_async(size_t offset, size_t size) override {- if (const auto plan = util::make_prefetch_plan(m_data, m_size, offset, size); plan.m_aligned_size) {- auto token = util::vm_prefetch_async(reinterpret_cast<void*>(plan.m_address),- plan.m_aligned_size,- util::prefetch_thread_count(plan.m_aligned_size));+ if (const auto region = util::clamp_align_region(m_data, m_size, offset, size);+ region.m_length > util::default_parallel_io_threshold) {+ auto token = util::vm_prefetch_async(reinterpret_cast<void*>(region.m_address),+ region.m_length,+ util::prefetch_thread_count(region.m_length));adopt_pending_prefetch(token.detach());}}diff --git a/src/common/util/src/os/win/win_memory.cpp b/src/common/util/src/os/win/win_memory.cppindex 3c5f33bbe73..f898114fde5 100644--- a/src/common/util/src/os/win/win_memory.cpp+++ b/src/common/util/src/os/win/win_memory.cpp@@ -9,11 +9,9 @@#include <malloc.h>#include <windows.h>-#include <algorithm>#include <cassert>#include <cstddef>#include <cstring>-#include <thread>#include <tuple>#include "memory_prefetch.hpp"@@ -21,8 +19,6 @@namespace ov::util {-void populate_pages(void* ptr, size_t size, size_t num_threads) noexcept;-void* aligned_alloc(size_t size, size_t alignment) noexcept {if (alignment == 0) {alignment = alignof(std::max_align_t);@@ -68,13 +64,18 @@ void vm_prefetch(void* ptr, size_t size, size_t num_threads) noexcept {WIN32_MEMORY_RANGE_ENTRY entry{ptr, size};::PrefetchVirtualMemory(::GetCurrentProcess(), 1, &entry, 0);} else {- // blocks until every page has been faulted in.- populate_pages(ptr, size, num_threads);+ PrefetchToken(submit_page_toucher_tasks(ptr, size, num_threads)).wait();}}-PrefetchToken vm_prefetch_async(void* /*ptr*/, size_t /*size*/, size_t /*num_threads*/) noexcept {- return {};+PrefetchToken vm_prefetch_async(void* ptr, size_t size, size_t num_threads) noexcept {+ assert(ptr != nullptr && size > 0);+ if (num_threads == 0) {+ WIN32_MEMORY_RANGE_ENTRY entry{ptr, size};+ ::PrefetchVirtualMemory(::GetCurrentProcess(), 1, &entry, 0);+ return {};+ }+ return PrefetchToken(submit_page_toucher_tasks(ptr, size, num_threads));}} // namespace ov::utildiff --git a/src/common/util/src/os/win/win_mmap_object.cpp b/src/common/util/src/os/win/win_mmap_object.cppindex 1d7fdab912d..c78fd40c24d 100644--- a/src/common/util/src/os/win/win_mmap_object.cpp+++ b/src/common/util/src/os/win/win_mmap_object.cpp@@ -3,7 +3,9 @@//#include <algorithm>+#include <chrono>#include <cstring>+#include <future>#include <map>#include <mutex>#include <shared_mutex>@@ -306,9 +308,19 @@ public:void hint_prefetch(size_t offset, size_t size) override;- void hint_prefetch_async(size_t /*offset*/, size_t /*size*/) override {}+ void hint_prefetch_async(size_t offset, size_t size) override;private:+ /**+ * @brief Adopts futures detached from a util::PrefetchToken, reaping already-finished ones so+ * the pending list doesn't grow unbounded across repeated hint_prefetch_async() calls.+ */+ void adopt_pending_prefetch(std::vector<std::future<void>>&& tasks);++ /** @brief Joins all outstanding background prefetch tasks. Must run before any teardown that+ * unmaps or frees the view, since a detached task may still be touching those pages. */+ void wait_for_pending_prefetch() noexcept;+/*** @brief Remaps a placeholder region by replacing it with a file-backed view.*@@ -378,6 +390,10 @@ private:* the lock, so the VEH cannot fire on the same thread and re-enter try_remap_slot.*/std::mutex m_slot_mutex;++ // Tasks adopted from hint_prefetch_async()'s token; joined before unmapping (see ~MapHolder).+ std::mutex m_pending_prefetch_mutex;+ std::vector<std::future<void>> m_pending_prefetch;};LONG NTAPI MmapVehRegistry::veh(PEXCEPTION_POINTERS ep) {@@ -398,6 +414,10 @@ LONG NTAPI MmapVehRegistry::veh(PEXCEPTION_POINTERS ep) {}MapHolder::~MapHolder() {+ // Detached prefetch tasks may still be touching this mapping's pages; join them first,+ // before any view is unmapped or VA space is released.+ wait_for_pending_prefetch();+if (m_view_base && m_total_va_size != 0) {// Placeholder path: unregister VEH, unmap all views, free all VA allocations.const auto& api = PlaceholderAPI::instance();@@ -764,6 +784,32 @@ util::AlignedRegion clamp_align_region(const void* data, size_t mapping_size, si} // namespace+void MapHolder::adopt_pending_prefetch(std::vector<std::future<void>>&& tasks) {+ std::lock_guard<std::mutex> lock(m_pending_prefetch_mutex);+ // Reap already-finished futures so the vector doesn't grow without bound across repeated+ // hint_prefetch_async() calls over this mapping's lifetime.+ m_pending_prefetch.erase(std::remove_if(m_pending_prefetch.begin(),+ m_pending_prefetch.end(),+ [](std::future<void>& task) {+ return !task.valid() || task.wait_for(std::chrono::seconds(0)) ==+ std::future_status::ready;+ }),+ m_pending_prefetch.end());+ m_pending_prefetch.insert(m_pending_prefetch.end(),+ std::make_move_iterator(tasks.begin()),+ std::make_move_iterator(tasks.end()));+}++void MapHolder::wait_for_pending_prefetch() noexcept {+ std::lock_guard<std::mutex> lock(m_pending_prefetch_mutex);+ for (auto& task : m_pending_prefetch) {+ if (task.valid()) {+ task.wait();+ }+ }+ m_pending_prefetch.clear();+}+void MapHolder::hint_prefetch(size_t offset, size_t size) {// Below 4 MiB the overhead of spawning threads exceeds the benefit; skip.if (const auto region = clamp_align_region(m_data, m_size, offset, size); region.m_length > 4 * util::one_mib) {@@ -774,6 +820,16 @@ void MapHolder::hint_prefetch(size_t offset, size_t size) {}}+void MapHolder::hint_prefetch_async(size_t offset, size_t size) {+ if (const auto region = util::clamp_align_region(m_data, m_size, offset, size);+ region.m_length > util::default_parallel_io_threshold) {+ auto token = util::vm_prefetch_async(reinterpret_cast<void*>(region.m_address),+ region.m_length,+ util::prefetch_thread_count(region.m_length));+ adopt_pending_prefetch(token.detach());+ }+}+std::pair<char*, char*> MapHolder::compute_evict_range(size_t offset, size_t size) const noexcept {// Require placeholder path, API availability, and a live VEH (eviction without VEH// would leave inaccessible placeholders on the next access).