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
Async mmap population (#36668)
Oleg Pipikin350e28672445
diff --git a/src/common/util/CMakeLists.txt b/src/common/util/CMakeLists.txtindex da7305dd89b..f032f62ff7e 100644--- a/src/common/util/CMakeLists.txt+++ b/src/common/util/CMakeLists.txt@@ -70,6 +70,7 @@ target_sources(${TARGET_NAME}${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.hpp${CMAKE_CURRENT_SOURCE_DIR}/src/native_stream.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/native_streambuf.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/parallel_read_streambuf.cpp@@ -93,7 +94,9 @@ if (WIN32)target_link_libraries(${TARGET_NAME} PRIVATE Shlwapi)endif()-target_include_directories(${TARGET_NAME} PUBLIC $<BUILD_INTERFACE:${UTIL_INCLUDE_DIR}>)+target_include_directories(${TARGET_NAME}+ PUBLIC $<BUILD_INTERFACE:${UTIL_INCLUDE_DIR}>+ PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)ov_add_clang_format_target(${TARGET_NAME}_clang FOR_TARGETS ${TARGET_NAME})ov_ncc_naming_style(FOR_TARGET ${TARGET_NAME}diff --git a/src/common/util/include/openvino/util/memory.hpp b/src/common/util/include/openvino/util/memory.hppindex 351ca2df028..da1f1b1f54d 100644--- a/src/common/util/include/openvino/util/memory.hpp+++ b/src/common/util/include/openvino/util/memory.hpp@@ -116,18 +116,4 @@ void vm_decommit(void* ptr, size_t size) noexcept;* @pre ptr != nullptr && size > 0; violated preconditions are a programming error (assert fires in debug).*/void vm_release(void* ptr, size_t size) noexcept;--/**- * @brief Pre-fetch a committed VM range into physical memory.- *- * Works with both anonymous (@ref vm_commit) and file-backed (mmap) regions.- *- * @param ptr Base address of the range. Must be page-aligned.- * @param size Number of bytes to pre-fetch. Must be a multiple of the system page size.- * @param num_threads Strategy selector:- * - @c 0 (default) → OS advisory hint (async, low overhead).- * - @c N >= 1 → parallel touch with N threads (synchronous).- */-void vm_prefetch(void* ptr, size_t size, size_t num_threads = 0) noexcept;-} // namespace ov::utildiff --git a/src/common/util/include/openvino/util/mmap_object.hpp b/src/common/util/include/openvino/util/mmap_object.hppindex 56e0567ac7f..93a5803ffe3 100644--- a/src/common/util/include/openvino/util/mmap_object.hpp+++ b/src/common/util/include/openvino/util/mmap_object.hpp@@ -16,6 +16,7 @@#include <string>#include "openvino/util/file_util.hpp"+#include "openvino/util/memory.hpp"namespace ov {@@ -48,6 +49,17 @@ public:* mapping when set to auto_size.*/virtual void hint_prefetch(size_t offset = 0, size_t size = auto_size) = 0;++ /**+ * @brief Asynchronous variant of @ref hint_prefetch: starts populating the given region in the+ * background and returns immediately. Any background work is joined before this object is+ * destroyed.+ *+ * @param offset Offset within the mapping where prefetching starts.+ * @param size Number of bytes to prefetch. Defaults to the rest of the+ * mapping when set to auto_size.+ */+ virtual void hint_prefetch_async(size_t offset = 0, size_t size = auto_size) = 0;};/**diff --git a/src/common/util/include/openvino/util/parallel_io.hpp b/src/common/util/include/openvino/util/parallel_io.hppindex 1911cf3b8d2..3e162652b46 100644--- a/src/common/util/include/openvino/util/parallel_io.hpp+++ b/src/common/util/include/openvino/util/parallel_io.hpp@@ -9,6 +9,7 @@#pragma once+#include <algorithm>#include <cstddef>#include <filesystem>diff --git a/src/common/util/src/memory.cpp b/src/common/util/src/memory.cppindex 612945e5a86..11d509709c3 100644--- a/src/common/util/src/memory.cpp+++ b/src/common/util/src/memory.cpp@@ -5,41 +5,18 @@#include "openvino/util/memory.hpp"#include <algorithm>-#include <cassert>#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;-namespace {--/**- * @brief Functor that touches one byte per page over [m_begin, m_end) to force the pages resident.- *- * The volatile accumulator prevents the compiler from optimizing the read loop away.- */-struct PageToucher {- const uint8_t* m_begin;- const uint8_t* m_end;- const size_t m_page_size;-- void operator()() const noexcept {- volatile uint8_t local = 0; // prevents the compiler from optimizing the loop away- for (auto begin = m_begin; begin < m_end; begin += m_page_size) {- local += *begin;- }- }-};--} // namespace-void populate_pages(void* ptr, size_t size, size_t num_threads) noexcept {- // ptr and size are guaranteed page-aligned by vm_prefetch's precondition.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);diff --git a/src/common/util/src/memory_prefetch.hpp b/src/common/util/src/memory_prefetch.hppnew file mode 100644index 00000000000..d0363a8dbbd--- /dev/null+++ b/src/common/util/src/memory_prefetch.hpp@@ -0,0 +1,177 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <algorithm>+#include <cstddef>+#include <cstdint>+#include <future>+#include <thread>+#include <vector>++#include "openvino/util/memory.hpp"+#include "openvino/util/mmap_object.hpp"+#include "openvino/util/parallel_io.hpp"++namespace ov::util {++// Touches one byte per page over [m_begin, m_end) to force the pages resident. The volatile+// accumulator keeps the compiler from eliminating the read loop.+struct PageToucher {+ const uint8_t* m_begin;+ const uint8_t* m_end;+ const size_t m_page_size;++ void operator()() const noexcept {+ volatile uint8_t local = 0;+ for (auto begin = m_begin; begin < m_end; begin += m_page_size) {+ local += *begin;+ }+ }+};++class PrefetchToken;++/**+ * @brief Pre-fetches a page-aligned, committed VM range into physical memory, blocking until every+ * page is resident.+ *+ * @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; @c 0 requests only a+ * lightweight advisory OS hint instead of touching pages.+ */+void vm_prefetch(void* ptr, size_t size, size_t num_threads) noexcept;++/**+ * @brief Asynchronous variant of @ref vm_prefetch: submits page-population to the shared pool and+ * returns immediately with a @ref PrefetchToken to wait on.+ *+ * @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; @c 0 requests only a+ * lightweight advisory OS hint instead of touching pages and returns an empty+ * token.+ *+ * Returns an empty token if the work could not be scheduled.+ */+PrefetchToken vm_prefetch_async(void* ptr, size_t size, size_t num_threads) noexcept;++/**+ * @brief Move-only RAII handle for background page-population started by @ref vm_prefetch_async.+ *+ * Destruction (or an explicit @ref wait) joins the outstanding work, so nothing is ever left+ * running uncontrolled. The token does not keep the populated memory alive: the caller must keep+ * that memory valid until the token completes, is destroyed, or its futures are @ref detach "detached".+ */+class PrefetchToken {+public:+ PrefetchToken() noexcept = default;+ explicit PrefetchToken(std::vector<std::future<void>>&& tasks) noexcept : m_tasks(std::move(tasks)) {}++ PrefetchToken(const PrefetchToken&) = delete;+ PrefetchToken& operator=(const PrefetchToken&) = delete;+ PrefetchToken(PrefetchToken&&) noexcept = default;++ PrefetchToken& operator=(PrefetchToken&& other) noexcept {+ if (this != &other) {+ wait();+ m_tasks = std::move(other.m_tasks);+ }+ return *this;+ }++ ~PrefetchToken() {+ wait();+ }++ void wait() noexcept {+ for (auto& task : m_tasks) {+ if (task.valid()) {+ task.wait();+ }+ }+ m_tasks.clear();+ }++ std::vector<std::future<void>> detach() noexcept {+ auto tasks = std::move(m_tasks);+ m_tasks.clear();+ return tasks;+ }++ bool valid() const noexcept {+ return !m_tasks.empty();+ }++ explicit operator bool() const noexcept {+ return valid();+ }++private:+ std::vector<std::future<void>> m_tasks;+};++/**+ * @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.+ *+ * @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.+ */+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());+ if (data == nullptr || mapping_size == 0 || offset >= mapping_size || size < page_size) {+ return {};+ }+ 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 {};+}++/** @brief Upper bound on the shared page-population pool's worker threads. */+inline constexpr size_t max_prefetch_threads = 8;++/**+ * @brief Number of parallel chunks a @p size byte job should be split into: at least one, at most+ * @p max_chunks, targeting roughly one chunk per @p min_chunk bytes.+ */+constexpr size_t split_chunk_count(size_t size, size_t min_chunk, size_t max_chunks) noexcept {+ const size_t by_size = (min_chunk == 0) ? max_chunks : size / min_chunk;+ return std::max<size_t>(1, std::min<size_t>(max_chunks, by_size));+}++/**+ * @brief Number of page-population jobs a @p size byte region is split into, honoring the shared+ * parallel-I/O minimum chunk size and the pool worker cap.+ */+inline size_t prefetch_thread_count(size_t size) noexcept {+ const auto pool_cap =+ std::max<size_t>(1, std::min<size_t>(max_prefetch_threads, std::thread::hardware_concurrency()));+ return split_chunk_count(size, default_parallel_io_min_chunk, pool_cap);+}++} // namespace ov::utildiff --git a/src/common/util/src/os/lin/lin_memory.cpp b/src/common/util/src/os/lin/lin_memory.cppindex 6ad74c2c6d7..50a8b3a835b 100644--- a/src/common/util/src/os/lin/lin_memory.cpp+++ b/src/common/util/src/os/lin/lin_memory.cpp@@ -4,14 +4,26 @@#include <sys/mman.h>+#include <algorithm>#include <cassert>#include <cerrno>+#include <condition_variable>#include <cstddef>+#include <cstdint>#include <cstdlib>-#include <cstring>+#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 {@@ -22,9 +34,123 @@ void madvise_hint(void* ptr, size_t size) noexcept {madvise(ptr, size, MADV_WILLNEED);}-} // namespace+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 populate_pages(void* ptr, size_t size, size_t num_threads) noexcept;+ 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 {if (alignment == 0) {@@ -79,9 +205,17 @@ void vm_prefetch(void* ptr, size_t size, size_t num_threads) noexcept {if (num_threads == 0) {madvise_hint(ptr, size);} 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 {+ assert(ptr != nullptr && size > 0);+ if (num_threads == 0) {+ madvise_hint(ptr, size);+ return {};}+ return PrefetchToken(submit_page_toucher_tasks(ptr, size, num_threads));}} // namespace ov::utildiff --git a/src/common/util/src/os/lin/lin_mmap_object.cpp b/src/common/util/src/os/lin/lin_mmap_object.cppindex 763c01175fb..33baacb425d 100644--- a/src/common/util/src/os/lin/lin_mmap_object.cpp+++ b/src/common/util/src/os/lin/lin_mmap_object.cpp@@ -9,14 +9,19 @@#include <algorithm>#include <atomic>+#include <chrono>#include <cstring>+#include <future>+#include <mutex>#include <thread>#include <tuple>+#include "memory_prefetch.hpp"#include "openvino/util/file_util.hpp"#include "openvino/util/hash_util.hpp"#include "openvino/util/memory.hpp"#include "openvino/util/mmap_object.hpp"+#include "openvino/util/parallel_io.hpp"namespace ov {namespace util {@@ -103,6 +108,35 @@ class MapHolder final : public MappedMemory {size_t m_size = 0;uint64_t m_id = std::numeric_limits<uint64_t>::max();HandleHolder m_handle;+ // 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;++ void 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 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();+ }public:MapHolder() = default;@@ -150,6 +184,8 @@ public:}~MapHolder() {+ // Detached prefetch tasks may still be touching this mapping's pages; join them first.+ wait_for_pending_prefetch();if (m_mapped_view != MAP_FAILED) {munmap(m_mapped_view, m_mapped_view_size);}@@ -180,6 +216,15 @@ public:util::vm_prefetch(reinterpret_cast<void*>(region.m_address), aligned_size, num_threads);}}++ 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));+ adopt_pending_prefetch(token.detach());+ }+ }};std::shared_ptr<MappedMemory> load_mmap_object(const std::filesystem::path& path,diff --git a/src/common/util/src/os/win/win_memory.cpp b/src/common/util/src/os/win/win_memory.cppindex f0b5d7cdd68..3c5f33bbe73 100644--- a/src/common/util/src/os/win/win_memory.cpp+++ b/src/common/util/src/os/win/win_memory.cpp@@ -9,11 +9,14 @@#include <malloc.h>#include <windows.h>+#include <algorithm>#include <cassert>#include <cstddef>#include <cstring>+#include <thread>#include <tuple>+#include "memory_prefetch.hpp"#include "openvino/util/memory.hpp"namespace ov::util {@@ -70,4 +73,8 @@ void vm_prefetch(void* ptr, size_t size, size_t num_threads) noexcept {}}+PrefetchToken vm_prefetch_async(void* /*ptr*/, size_t /*size*/, size_t /*num_threads*/) noexcept {+ return {};+}+} // 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 c1f637968aa..1d7fdab912d 100644--- a/src/common/util/src/os/win/win_mmap_object.cpp+++ b/src/common/util/src/os/win/win_mmap_object.cpp@@ -11,6 +11,7 @@#include <thread>#include <vector>+#include "memory_prefetch.hpp"#include "openvino/util/file_util.hpp"#include "openvino/util/hash_util.hpp"#include "openvino/util/memory.hpp"@@ -305,6 +306,8 @@ public:void hint_prefetch(size_t offset, size_t size) override;+ void hint_prefetch_async(size_t /*offset*/, size_t /*size*/) override {}+private:/*** @brief Remaps a placeholder region by replacing it with a file-backed view.diff --git a/src/core/tests/file_load_benchmark.cpp b/src/core/tests/file_load_benchmark.cppindex d14bd1bf9bf..63af1443fc1 100644--- a/src/core/tests/file_load_benchmark.cpp+++ b/src/core/tests/file_load_benchmark.cpp@@ -17,7 +17,6 @@#include <numeric>#include <string>#include <string_view>-#include <thread>#include <tuple>#include <vector>@@ -205,7 +204,7 @@ namespace strategy {// Note: the mmap destructor (munmap + close) runs inside the timed window;void sync_vm_prefetch_mem_lock(const std::filesystem::path& path, size_t /*file_size*/) {auto mapped = load_mmap_object(path);- util::vm_prefetch(mapped->data(), mapped->size(), std::thread::hardware_concurrency());+ mapped->hint_prefetch();ensure_memory_resident(mapped); // should be near no-op and just lock/unlock resident pages}diff --git a/src/core/tests/mmap_object.cpp b/src/core/tests/mmap_object.cppindex d5974e39e80..468912428e3 100644--- a/src/core/tests/mmap_object.cpp+++ b/src/core/tests/mmap_object.cpp@@ -8,10 +8,14 @@#include <gtest/gtest.h>#include <algorithm>+#include <chrono>#include <filesystem>#include <iostream>#include <numeric>+#include <random>#include <sstream>+#include <thread>+#include <utility>#include "common_test_utils/common_utils.hpp"#include "common_test_utils/file_utils.hpp"@@ -473,4 +477,189 @@ TEST_F(HintPrefetchTest, hint_prefetch_sequential_eviction_check) {EXPECT_EQ(pages_after, pages_before) << "hint_prefetch evicted pages.";}+class HintPrefetchAsyncTest : public ::testing::Test {+protected:+ std::filesystem::path m_file_path;++ void TearDown() override {+ if (!m_file_path.empty()) {+ std::filesystem::remove(m_file_path);+ }+ }++ static std::vector<uint8_t> read_mapped(MappedMemory& mm) {+ return {reinterpret_cast<uint8_t*>(mm.data()), reinterpret_cast<uint8_t*>(mm.data()) + mm.size()};+ }++ static std::vector<uint8_t> make_pattern(size_t size) {+ std::vector<uint8_t> data(size);+ for (size_t i = 0; i < size; ++i)+ data[i] = static_cast<uint8_t>(i % 251);+ return data;+ }++ void write_file(const std::vector<uint8_t>& data) {+ std::ofstream f(m_file_path, std::ios::binary);+ f.write(reinterpret_cast<const char*>(data.data()), data.size());+ }++ // hint_prefetch_async() no longer returns a token to wait on: completion is tracked and+ // joined internally by the MappedMemory implementation. To observe residency in tests we+ // simply poll until the background population catches up (or a generous timeout elapses).+ static size_t wait_for_resident_pages(const char* addr,+ size_t size,+ size_t expected_pages,+ std::chrono::milliseconds timeout = std::chrono::seconds(10)) {+ const auto deadline = std::chrono::steady_clock::now() + timeout;+ size_t pages_resident = 0;+ do {+ pages_resident = utils::count_resident_pages(addr, size);+ if (pages_resident >= expected_pages)+ break;+ std::this_thread::sleep_for(std::chrono::milliseconds(10));+ } while (std::chrono::steady_clock::now() < deadline);+ return pages_resident;+ }+};++TEST_F(HintPrefetchAsyncTest, pages_resident_eventually) {+#ifndef __linux__+ GTEST_SKIP() << "utils::count_resident_pages is not implemented on this platform yet CVS-186579";+#endif+ m_file_path = std::filesystem::path(utils::generateTestFilePrefix() + "_prefetch_async_wait.bin");+ constexpr size_t file_size = 8 * 1024 * 1024; // 8 MiB (above 4 MiB threshold)+ const auto data = make_pattern(file_size);+ write_file(data);++ auto mapped = load_mmap_object(m_file_path);+ ASSERT_NE(mapped, nullptr);++ const size_t page = static_cast<size_t>(util::get_system_page_size());+ const size_t total_pages = (file_size + page - 1) / page;++ mapped->hint_prefetch_async();++ const size_t pages_resident = wait_for_resident_pages(mapped->data(), file_size, total_pages);+ EXPECT_EQ(pages_resident, total_pages) << "Expected all pages resident after hint_prefetch_async().";+}++TEST_F(HintPrefetchAsyncTest, prefetch_then_immediate_destruction_is_safe) {+ // Regression test: hint_prefetch_async() must never leave background page-touching tasks+ // racing with this object's destruction. Dropping the last reference to the mapping right+ // after kicking off the prefetch (with zero waiting) must not crash / use-after-free, since+ // the implementation is required to join any in-flight tasks before unmapping.+ m_file_path = std::filesystem::path(utils::generateTestFilePrefix() + "_prefetch_async_destroy.bin");+ constexpr size_t file_size = 8 * 1024 * 1024; // 8 MiB (above 4 MiB threshold)+ const auto data = make_pattern(file_size);+ write_file(data);++ auto mapped = load_mmap_object(m_file_path);+ ASSERT_NE(mapped, nullptr);++ mapped->hint_prefetch_async();+ mapped.reset(); // must not crash, regardless of whether the background tasks finished yet+}++TEST_F(HintPrefetchAsyncTest, partial_region_populated_and_correct) {+#ifndef __linux__+ GTEST_SKIP() << "utils::count_resident_pages is not implemented on this platform yet CVS-186579";+#endif+ m_file_path = std::filesystem::path(utils::generateTestFilePrefix() + "_prefetch_async_partial.bin");+ constexpr size_t file_size = 8 * 1024 * 1024; // 8 MiB+ constexpr size_t prefetch_offset = 1 * 1024 * 1024;+ constexpr size_t prefetch_size = 5 * 1024 * 1024;+ const auto data = make_pattern(file_size);+ write_file(data);++ auto mapped = load_mmap_object(m_file_path);+ ASSERT_NE(mapped, nullptr);++ const size_t page = static_cast<size_t>(util::get_system_page_size());+ const size_t region_pages = (prefetch_size + page - 1) / page;++ mapped->hint_prefetch_async(prefetch_offset, prefetch_size);++ const size_t pages_resident =+ wait_for_resident_pages(mapped->data() + prefetch_offset, prefetch_size, region_pages);+ EXPECT_EQ(pages_resident, region_pages) << "Expected the requested region to be fully resident.";++ EXPECT_EQ(read_mapped(*mapped), data);+}++TEST_F(HintPrefetchAsyncTest, below_threshold_is_safe_noop) {+ m_file_path = std::filesystem::path(utils::generateTestFilePrefix() + "_prefetch_async_small.bin");+ constexpr size_t file_size = 1024; // 1 KiB - below the 4 MiB threshold+ const auto data = make_pattern(file_size);+ write_file(data);++ auto mapped = load_mmap_object(m_file_path);+ ASSERT_NE(mapped, nullptr);++ EXPECT_NO_THROW(mapped->hint_prefetch_async());+ EXPECT_EQ(read_mapped(*mapped), data);+}++TEST_F(HintPrefetchAsyncTest, data_correct_immediately_after_call) {+ m_file_path = std::filesystem::path(utils::generateTestFilePrefix() + "_prefetch_async_alive.bin");+ constexpr size_t file_size = 8 * 1024 * 1024; // 8 MiB (above 4 MiB threshold)+ const auto data = make_pattern(file_size);+ write_file(data);++ auto mapped = load_mmap_object(m_file_path);+ ASSERT_NE(mapped, nullptr);++ mapped->hint_prefetch_async();+ // The mapping is always readable/correct regardless of prefetch completion; background+ // threads only accelerate residency.+ EXPECT_EQ(read_mapped(*mapped), data);+}++TEST_F(HintPrefetchAsyncTest, random_access_after_async_is_correct) {+ // Reading pages in a shuffled order concurrently with in-flight background population must+ // always return the correct bytes, whether or not a given page has been faulted in yet.+ m_file_path = std::filesystem::path(utils::generateTestFilePrefix() + "_prefetch_async_random.bin");+ constexpr size_t file_size = 8 * 1024 * 1024; // 8 MiB (above the parallel-I/O threshold)+ const auto data = make_pattern(file_size);+ write_file(data);++ auto mapped = load_mmap_object(m_file_path);+ ASSERT_NE(mapped, nullptr);++ mapped->hint_prefetch_async();++ const size_t page = static_cast<size_t>(util::get_system_page_size());+ const size_t total_pages = (file_size + page - 1) / page;+ std::vector<size_t> order(total_pages);+ std::iota(order.begin(), order.end(), size_t{0});+ std::shuffle(order.begin(), order.end(), std::mt19937{12345});++ const auto* base = reinterpret_cast<const uint8_t*>(mapped->data());+ for (const size_t idx : order) {+ const size_t begin = idx * page;+ const size_t end = std::min(begin + page, file_size);+ for (size_t i = begin; i < end; ++i) {+ ASSERT_EQ(base[i], data[i]) << "mismatch at offset " << i;+ }+ }+}++TEST_F(HintPrefetchAsyncTest, backward_access_after_async_is_correct) {+ // Reading the mapping back-to-front (opposite the population's forward stride) concurrently+ // with in-flight background population must still return the correct bytes.+ m_file_path = std::filesystem::path(utils::generateTestFilePrefix() + "_prefetch_async_backward.bin");+ constexpr size_t file_size = 8 * 1024 * 1024; // 8 MiB (above the parallel-I/O threshold)+ const auto data = make_pattern(file_size);+ write_file(data);++ auto mapped = load_mmap_object(m_file_path);+ ASSERT_NE(mapped, nullptr);++ mapped->hint_prefetch_async();++ const auto* base = reinterpret_cast<const uint8_t*>(mapped->data());+ for (size_t i = file_size; i-- > 0;) {+ ASSERT_EQ(base[i], data[i]) << "mismatch at offset " << i;+ }+}+} // namespace ov::testdiff --git a/src/core/tests/shared_buffer.cpp b/src/core/tests/shared_buffer.cppindex 89a26bd2b6c..c4bb9abcccf 100644--- a/src/core/tests/shared_buffer.cpp+++ b/src/core/tests/shared_buffer.cpp@@ -541,6 +541,8 @@ public:MOCK_METHOD(void, hint_prefetch, (size_t offset, size_t size), (override));+ MOCK_METHOD(void, hint_prefetch_async, (size_t offset, size_t size), (override));+private:std::vector<char> m_data;uint64_t m_id;diff --git a/src/tests/test_utils/common_test_utils/tests/memory_test.cpp b/src/tests/test_utils/common_test_utils/tests/memory_test.cppindex ce21086ff61..00dbb4762f2 100644--- a/src/tests/test_utils/common_test_utils/tests/memory_test.cpp+++ b/src/tests/test_utils/common_test_utils/tests/memory_test.cpp@@ -18,8 +18,6 @@namespace ov::test {-using testing::ElementsAreArray;-// Verify the constexpr contract at compile time for the most common alignments.static_assert(ov::util::align_size_up(0, 64) == 0);static_assert(ov::util::align_size_up(1, 64) == 64);@@ -157,33 +155,4 @@ TEST_F(AlignedAllocTest, free_nullptr_is_noop) {EXPECT_NO_FATAL_FAILURE(util::aligned_free(nullptr));}-class VmPrefetchMappedFileTest : public testing::TestWithParam<size_t> {-protected:- std::filesystem::path m_file_path;-- void TearDown() override {- std::filesystem::remove(m_file_path);- }-};--TEST_P(VmPrefetchMappedFileTest, prefetch_faults_in_mapped_file_and_preserves_data) {- const size_t num_threads = GetParam();- const size_t size = 64 * util::min_page_alignment;-- const auto expected = utils::make_modulo_sequence_pattern(size);-- m_file_path = utils::generateTestFilePrefix() + "_vm_prefetch.bin";- ov::util::save_binary(m_file_path, expected.data(), expected.size());-- auto mapped = load_mmap_object(m_file_path);- ASSERT_NE(mapped, nullptr);- ASSERT_EQ(mapped->size(), size);-- EXPECT_NO_FATAL_FAILURE(util::vm_prefetch(mapped->data(), mapped->size(), num_threads));-- EXPECT_THAT(expected, ElementsAreArray(reinterpret_cast<const uint8_t*>(mapped->data()), mapped->size()));-}--INSTANTIATE_TEST_SUITE_P(NumThreads, VmPrefetchMappedFileTest, testing::Values(0u, 5u, 10u));-} // namespace ov::test