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
[GPU] use parallel ifstream to boost file reading latency (#34679)
River Li27e83577936c
diff --git a/src/common/util/include/openvino/util/parallel_io.hpp b/src/common/util/include/openvino/util/parallel_io.hppnew file mode 100644index 00000000000..234a23af23c--- /dev/null+++ b/src/common/util/include/openvino/util/parallel_io.hpp@@ -0,0 +1,85 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++/**+ * @brief A header file for definition of platform-specific parallel I/O primitives.+ * @file parallel_io.hpp+ */++#pragma once++#include <cstddef>+#include <filesystem>++#include "openvino/util/mmap_object.hpp"++namespace ov::util {++#ifndef _WIN32+inline constexpr FileHandle INVALID_HANDLE_VALUE = -1;+#endif++inline constexpr size_t default_parallel_io_threshold = 4UL * 1024 * 1024; ///< 4 MB default threshold for parallel I/O+inline constexpr size_t default_parallel_io_min_chunk = 2UL * 1024 * 1024; ///< 2 MB minimum chunk size per thread++/**+ * @brief Open a file for reading and retrieve its size.+ *+ * On Linux, uses open(O_RDONLY | O_CLOEXEC) + fstat.+ * On Windows, uses CreateFileW(GENERIC_READ) + GetFileSizeEx.+ *+ * @param path Path to the file to open.+ * @param file_offset Header offset to validate (must be within [0, file_size]).+ * @param out_handle [out] The opened file handle / descriptor.+ * @param out_size [out] Total size of the file in bytes.+ * @throws std::runtime_error If the file cannot be opened or its size cannot be queried.+ * @throws std::out_of_range If file_offset is outside [0, file_size].+ */+void get_file_handle_and_size(const std::filesystem::path& path,+ std::streamoff file_offset,+ FileHandle& out_handle,+ std::streamoff& out_size);++/**+ * @brief Close a platform file handle.+ *+ * On Linux, calls close(fd). On Windows, calls CloseHandle(handle).+ * Safe to call with an invalid handle (no-op).+ *+ * @param handle The file handle to close.+ */+void close_file_handle(FileHandle handle);++/**+ * @brief Open a file for reading (lightweight, for per-thread file handles).+ *+ * Each worker thread in a parallel read should open its own file handle so that+ * the OS readahead state is independent per thread.+ *+ * On Linux, uses open(O_RDONLY | O_CLOEXEC).+ * On Windows, uses CreateFileW(GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE).+ *+ * @param path Path to the file.+ * @return A valid file handle, or the platform-specific invalid value on failure.+ */+FileHandle open_file_for_read(const std::filesystem::path& path);++/**+ * @brief Read bytes from a file at a given absolute offset (single-threaded).+ *+ * On Linux, uses pread() in a loop.+ * On Windows, uses SetFilePointerEx + ReadFile in a loop.+ *+ * @note This function is @b not thread-safe for a given handle. Callers that+ * perform parallel reads must open a separate handle per thread (see+ * open_file_for_read).+ *+ * @param handle File handle / descriptor.+ * @param dst Destination buffer.+ * @param size Number of bytes to read.+ * @param file_offset Absolute byte offset in the file.+ * @return true if all bytes were read successfully, false on I/O error.+ */+bool positional_read(FileHandle handle, char* dst, size_t size, size_t file_offset);+} // namespace ov::util\ No newline at end of filediff --git a/src/common/util/include/openvino/util/parallel_read_streambuf.hpp b/src/common/util/include/openvino/util/parallel_read_streambuf.hppnew file mode 100644index 00000000000..2d3c94e8218--- /dev/null+++ b/src/common/util/include/openvino/util/parallel_read_streambuf.hpp@@ -0,0 +1,76 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++/**+ * @brief A header file for definition of a parallel I/O streambuf for file-based reads.+ * @file parallel_read_streambuf.hpp+ */++#pragma once++#include <filesystem>+#include <memory>+#include <streambuf>++#include "openvino/util/parallel_io.hpp"++namespace ov::util {++/**+ * @brief A std::streambuf that reads from a file using parallel I/O for large+ * reads, bypassing the OS page cache pressure that mmap+memcpy incurs.+ *+ * For reads >= threshold bytes, the read is split across N threads where each+ * thread issues its own independent positional read operation using+ * platform-specific APIs. Smaller reads fall through to a single positional call.+ *+ * Usage:+ * @code+ * ParallelReadStreamBuf buf(cache_path, blob_offset_in_file);+ * std::istream stream(&buf);+ * cldnn::BinaryInputBuffer ib(stream, engine);+ * ib >> ...;+ * @endcode+ */+class ParallelReadStreamBuf : public std::streambuf {+public:+ /**+ * @param path Path to the file to read.+ * @param header_offset Initial file position (absolute offset from the start+ * of the file; the stream starts reading from here).+ * @param threshold Minimum read size to trigger parallel I/O.+ */+ explicit ParallelReadStreamBuf(const std::filesystem::path& path,+ std::streamoff header_offset = 0,+ size_t threshold = default_parallel_io_threshold);++ ~ParallelReadStreamBuf() override;++ ParallelReadStreamBuf(const ParallelReadStreamBuf&) = delete;+ ParallelReadStreamBuf& operator=(const ParallelReadStreamBuf&) = delete;++protected:+ std::streamsize xsgetn(char_type* dst, std::streamsize n) override;+ int_type underflow() override;+ pos_type seekoff(off_type off, std::ios_base::seekdir way, std::ios_base::openmode which) override;+ pos_type seekpos(pos_type pos, std::ios_base::openmode which) override;+ std::streamsize showmanyc() override;++private:+ bool single_read(char* dst, size_t size, size_t file_offset);+ bool parallel_read(char* dst, size_t size, size_t file_offset);++ static constexpr size_t UNDERFLOW_BUF = 8192; ///< batch size for char-by-char reads++ std::filesystem::path m_path;+ FileHandle m_handle; ///< platform file handle++ std::streamoff m_file_offset = 0; ///< absolute file offset of next byte to read+ std::streamoff m_header_offset = 0; ///< absolute file offset of logical stream start+ std::streamoff m_file_size = 0;+ size_t m_threshold = default_parallel_io_threshold;+ std::unique_ptr<char_type[]> m_underflow_buf; ///< lazily allocated buffer for underflow()+};++} // namespace ov::util\ No newline at end of filediff --git a/src/common/util/src/os/lin/parallel_io.cpp b/src/common/util/src/os/lin/parallel_io.cppnew file mode 100644index 00000000000..0c42d1597d9--- /dev/null+++ b/src/common/util/src/os/lin/parallel_io.cpp@@ -0,0 +1,69 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/util/parallel_io.hpp"++#include <fcntl.h>+#include <sys/mman.h>+#include <sys/stat.h>+#include <unistd.h>++#include <cstdint>+#include <fstream>+#include <sstream>+#include <stdexcept>++#include "openvino/util/file_util.hpp"++namespace ov::util {++void get_file_handle_and_size(const std::filesystem::path& path,+ std::streamoff file_offset,+ FileHandle& out_handle,+ std::streamoff& out_size) {+ out_handle = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);+ if (out_handle == -1) {+ throw std::runtime_error("Cannot open file: " + ov::util::path_to_string(path));+ }+ struct stat st = {};+ if (::fstat(out_handle, &st) != 0) {+ ::close(out_handle);+ out_handle = -1;+ throw std::runtime_error("Cannot stat file: " + ov::util::path_to_string(path));+ }+ out_size = static_cast<std::streamoff>(st.st_size);+ if (file_offset < 0 || file_offset > out_size) {+ ::close(out_handle);+ out_handle = -1;+ throw std::out_of_range("header_offset is out of range for file: " + ov::util::path_to_string(path));+ }+}++void close_file_handle(FileHandle handle) {+ if (handle != -1) {+ ::close(handle);+ }+}++FileHandle open_file_for_read(const std::filesystem::path& path) {+ return ::open(path.c_str(), O_RDONLY | O_CLOEXEC);+}++bool positional_read(FileHandle handle, char* dst, size_t size, size_t file_offset) {+ char* cur = dst;+ size_t remaining = size;+ off_t cur_offset = static_cast<off_t>(file_offset);+ while (remaining > 0) {+ const ssize_t n = ::pread(handle, cur, remaining, cur_offset);+ if (n <= 0) {+ return false;+ }+ cur += n;+ cur_offset += n;+ remaining -= static_cast<size_t>(n);+ }+ return true;+}++} // namespace ov::utildiff --git a/src/common/util/src/os/win/parallel_io.cpp b/src/common/util/src/os/win/parallel_io.cppnew file mode 100644index 00000000000..fd5bf2f6b20--- /dev/null+++ b/src/common/util/src/os/win/parallel_io.cpp@@ -0,0 +1,92 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/util/parallel_io.hpp"++// clang-format off+#ifndef NOMINMAX+# define NOMINMAX+#endif+#include <windows.h>+// clang-format on++#include <cstdint>+#include <stdexcept>++#include "openvino/util/file_util.hpp"++namespace ov::util {++void get_file_handle_and_size(const std::filesystem::path& path,+ std::streamoff file_offset,+ FileHandle& out_handle,+ std::streamoff& out_size) {+ out_handle = CreateFileW(path.c_str(),+ GENERIC_READ,+ FILE_SHARE_READ | FILE_SHARE_WRITE,+ nullptr,+ OPEN_EXISTING,+ FILE_ATTRIBUTE_NORMAL,+ nullptr);+ if (out_handle == INVALID_HANDLE_VALUE) {+ throw std::runtime_error("Cannot open file: " + ov::util::path_to_string(path));+ }+ LARGE_INTEGER file_size = {};+ if (!GetFileSizeEx(out_handle, &file_size)) {+ CloseHandle(out_handle);+ out_handle = INVALID_HANDLE_VALUE;+ throw std::runtime_error("Cannot get file size: " + ov::util::path_to_string(path));+ }+ out_size = static_cast<std::streamoff>(file_size.QuadPart);+ if (file_offset < 0 || file_offset > out_size) {+ CloseHandle(out_handle);+ out_handle = INVALID_HANDLE_VALUE;+ throw std::out_of_range("header_offset is out of range for file: " + ov::util::path_to_string(path));+ }+}++void close_file_handle(FileHandle handle) {+ if (handle != INVALID_HANDLE_VALUE) {+ CloseHandle(handle);+ }+}++FileHandle open_file_for_read(const std::filesystem::path& path) {+ return CreateFileW(path.native().c_str(),+ GENERIC_READ,+ FILE_SHARE_READ | FILE_SHARE_WRITE,+ nullptr,+ OPEN_EXISTING,+ FILE_ATTRIBUTE_NORMAL,+ nullptr);+}++bool positional_read(FileHandle handle, char* dst, size_t size, size_t file_offset) {+ char* cur = dst;+ size_t remaining = size;+ size_t cur_offset = file_offset;+ while (remaining > 0) {+ const DWORD to_read = static_cast<DWORD>((std::min)(remaining, static_cast<size_t>(UINT_MAX - 1024u)));+ // Use OVERLAPPED to specify the file offset directly, making the read+ // positional and independent of the file pointer. This is the Windows+ // equivalent of Linux pread() and is safe for concurrent use on+ // separate handles (no TOCTOU between SetFilePointerEx + ReadFile).+ OVERLAPPED ov = {};+ ov.Offset = static_cast<DWORD>(cur_offset & 0xFFFFFFFFULL);+ ov.OffsetHigh = static_cast<DWORD>((cur_offset >> 32) & 0xFFFFFFFFULL);+ DWORD bytes_read = 0;+ if (!ReadFile(handle, cur, to_read, &bytes_read, &ov)) {+ return false;+ }+ if (bytes_read == 0) {+ return false;+ }+ cur += bytes_read;+ cur_offset += bytes_read;+ remaining -= bytes_read;+ }+ return true;+}++} // namespace ov::util\ No newline at end of filediff --git a/src/common/util/src/parallel_read_streambuf.cpp b/src/common/util/src/parallel_read_streambuf.cppnew file mode 100644index 00000000000..0ab43588763--- /dev/null+++ b/src/common/util/src/parallel_read_streambuf.cpp@@ -0,0 +1,241 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/util/parallel_read_streambuf.hpp"++#ifdef _WIN32+# ifndef NOMINMAX+# define NOMINMAX+# endif+# include <windows.h>+#endif++#include <algorithm>+#include <atomic>+#include <cstring>+#include <limits>+#include <stdexcept>+#include <thread>+#include <vector>++#include "openvino/util/file_util.hpp"+#include "openvino/util/parallel_io.hpp"++namespace ov::util {++ParallelReadStreamBuf::ParallelReadStreamBuf(const std::filesystem::path& path,+ std::streamoff header_offset,+ size_t threshold)+ : m_path(path),+ m_file_offset(header_offset),+ m_header_offset(header_offset),+ m_threshold(threshold) {+ get_file_handle_and_size(path, m_file_offset, m_handle, m_file_size);+}++ParallelReadStreamBuf::~ParallelReadStreamBuf() {+ close_file_handle(m_handle);+}++// xsgetn: main hot path - called by sgetn() for all bulk reads+std::streamsize ParallelReadStreamBuf::xsgetn(char_type* dst, std::streamsize n) {+ if (n <= 0)+ return 0;++ std::streamsize total = 0;++ // Drain any chars previously buffered by underflow()+ if (gptr() != nullptr && gptr() < egptr()) {+ const std::streamsize avail = static_cast<std::streamsize>(egptr() - gptr());+ const std::streamsize from_buf = (std::min)(n, avail);+ std::memcpy(dst, gptr(), static_cast<size_t>(from_buf));+ // Safe: from_buf <= UNDERFLOW_BUF (8192), always fits in int.+ static_assert(UNDERFLOW_BUF <= static_cast<size_t>((std::numeric_limits<int>::max)()),+ "UNDERFLOW_BUF must fit in int for gbump()");+ gbump(static_cast<int>(from_buf));+ total += from_buf;+ dst += from_buf;+ n -= from_buf;+ }++ if (n <= 0 || m_file_offset >= m_file_size) {+ return total;+ }++ const std::streamoff remaining = m_file_size - m_file_offset;+ const std::streamsize to_read = static_cast<std::streamsize>((std::min)(static_cast<std::streamoff>(n), remaining));++ const size_t bytes = static_cast<size_t>(to_read);+ const size_t offset = static_cast<size_t>(m_file_offset);++ bool ok = (bytes >= m_threshold) ? parallel_read(dst, bytes, offset) : single_read(dst, bytes, offset);++ if (ok) {+ m_file_offset += to_read;+ total += to_read;+ }++ return total;+}++// underflow: called for single-char peek / non-bulk reads (e.g. std::getline)+ParallelReadStreamBuf::int_type ParallelReadStreamBuf::underflow() {+ if (m_file_offset >= m_file_size) {+ return traits_type::eof();+ }+ if (!m_underflow_buf) {+ m_underflow_buf = std::make_unique<char_type[]>(UNDERFLOW_BUF);+ }+ // Read a batch of up to UNDERFLOW_BUF bytes so that character-by-character+ // consumers (std::getline, operator>>) don't issue one pread per char.+ const size_t to_read =+ static_cast<size_t>((std::min)(static_cast<std::streamoff>(UNDERFLOW_BUF), m_file_size - m_file_offset));+ if (!single_read(m_underflow_buf.get(), to_read, static_cast<size_t>(m_file_offset))) {+ return traits_type::eof();+ }+ // Advance m_file_offset past the bytes we just read into the get area.+ // m_file_offset now points to the byte after egptr(), consistent with+ // the seekoff(0, cur) formula: logical_pos = m_file_offset - (egptr - gptr).+ m_file_offset += static_cast<std::streamoff>(to_read);+ setg(m_underflow_buf.get(), m_underflow_buf.get(), m_underflow_buf.get() + to_read);+ return traits_type::to_int_type(m_underflow_buf[0]);+}++ParallelReadStreamBuf::pos_type ParallelReadStreamBuf::seekoff(off_type off,+ std::ios_base::seekdir way,+ std::ios_base::openmode /* which */) {+ // All internal positions (m_file_offset, m_file_size, m_header_offset) are+ // absolute byte offsets from the start of the file. The public-facing+ // stream positions are *logical* offsets: 0 == header_offset in the file.+ std::streamoff new_pos = 0;+ if (way == std::ios_base::beg) {+ // off is a logical offset; translate to absolute file offset.+ new_pos = m_header_offset + off;+ } else if (way == std::ios_base::cur) {+ // Account for the buffered chars from underflow() not yet consumed.+ const std::streamsize ahead = (gptr() != nullptr) ? static_cast<std::streamsize>(egptr() - gptr()) : 0;+ new_pos = m_file_offset - ahead + off; // stays absolute+ // Pure tell (off == 0): return current position without any side effects+ // on the get area or m_file_offset. Discarding the underflow buffer on a+ // tell would force the next read to re-issue a pread for data that is+ // already buffered, breaking interleaved getline()+tellg() patterns.+ if (off == 0) {+ if (new_pos < m_header_offset || new_pos > m_file_size)+ return pos_type(off_type(-1));+ return pos_type(new_pos - m_header_offset);+ }+ } else {+ new_pos = m_file_size + off; // stays absolute+ }++ // Reject seeks before the logical stream start or past the file end.+ if (new_pos < m_header_offset || new_pos > m_file_size) {+ return pos_type(off_type(-1));+ }++ setg(nullptr, nullptr, nullptr); // invalidate get-area+ m_file_offset = new_pos;+ // Return the logical position (0 == start of exposed stream).+ return pos_type(m_file_offset - m_header_offset);+}++ParallelReadStreamBuf::pos_type ParallelReadStreamBuf::seekpos(pos_type pos, std::ios_base::openmode /* which */) {+ return seekoff(off_type(pos), std::ios_base::beg, std::ios_base::in);+}++std::streamsize ParallelReadStreamBuf::showmanyc() {+ // Report both buffered characters (in the get area) and remaining+ // bytes in the underlying file.+ // Per [streambuf.virt.get]/6: return -1 when the next call to+ // underflow() would return traits_type::eof() (i.e. stream truly+ // exhausted). Return 0 when availability is unknown. Here both+ // the file and the get-area are fully accounted for, so -1 at+ // total==0 is correct — underflow() would indeed return EOF.+ std::streamsize buffered = 0;+ if (gptr() != nullptr && egptr() != nullptr && egptr() > gptr()) {+ buffered = static_cast<std::streamsize>(egptr() - gptr());+ }+ std::streamoff remaining_off = m_file_size - m_file_offset;+ if (remaining_off < 0) {+ remaining_off = 0;+ }+ const std::streamsize remaining = remaining_off > 0 ? static_cast<std::streamsize>(remaining_off) : 0;+ const std::streamsize total = buffered + remaining;+ return total > 0 ? total : static_cast<std::streamsize>(-1);+}++// Single-threaded positional read+bool ParallelReadStreamBuf::single_read(char* dst, size_t size, size_t file_offset) {+ return positional_read(m_handle, dst, size, file_offset);+}++// Parallel positional read+bool ParallelReadStreamBuf::parallel_read(char* dst, size_t size, size_t file_offset) {+ const size_t hw_threads = (std::max)(size_t{1}, static_cast<size_t>(std::thread::hardware_concurrency()));+ const size_t max_by_size = size / (1024 * 1024); // 1 thread per MB+ const size_t num_threads = (std::max)(size_t{1}, (std::min)(hw_threads, max_by_size));++ if (num_threads == 1) {+ return single_read(dst, size, file_offset);+ }++ // Round chunk_size UP to the next 4 KiB boundary so that every thread's+ // start offset is page-aligned (better I/O coalescing on NVMe/direct I/O).+ // Because rounding up means num_threads * chunk_size >= size, two extra+ // guards are required:+ // 1. Non-last threads: cap read to min(chunk_size, size - cur_offset) so+ // they never stride past EOF when the aligned chunk extends beyond it.+ // 2. Last thread: use (size - cur_offset) to capture every remaining byte+ // including the fragment that lies beyond (num_threads-1) * chunk_size+ // but before size. Using chunk_size here would silently drop those bytes.+ size_t chunk_size = size / num_threads;+ chunk_size = (chunk_size + 4095u) & ~size_t{4095u};++ std::atomic<bool> success{true};+ // Each worker opens its own file descriptor so that Linux's per-file-+ // description readahead state (file_ra_state / f_ra) is independent per+ // thread. Sharing a single fd causes concurrent pread() calls to corrupt+ // each other's sequential readahead prediction, collapsing throughput from+ // ~3.5 GB/s sequential to ~0.5 GB/s.+ std::vector<std::thread> workers;+ workers.reserve(num_threads);+ for (size_t ithr = 0; ithr < num_threads; ++ithr) {+ try {+ workers.emplace_back([&, ithr]() {+ const size_t cur_offset = ithr * chunk_size;+ if (cur_offset >= size) {+ return; // page-alignment rounding created a surplus worker slot+ }+ // Last thread: read everything remaining (includes the fragment that+ // falls between (num_threads-1)*chunk_size and size).+ // Non-last threads: cap to min(chunk_size, size - cur_offset) so we+ // never read past eof when alignment pushed the chunk boundary beyond it.+ const size_t read_size =+ (ithr == num_threads - 1) ? (size - cur_offset) : (std::min)(chunk_size, size - cur_offset);+ char* const ptr = dst + cur_offset;+ const size_t thread_file_offset = file_offset + cur_offset;++ FileHandle t_handle = open_file_for_read(m_path);+ if (t_handle == INVALID_HANDLE_VALUE) {+ success = false;+ return;+ }++ if (!positional_read(t_handle, ptr, read_size, thread_file_offset)) {+ success = false;+ }+ close_file_handle(t_handle);+ }); // workers.emplace_back+ } catch (...) {+ success = false;+ break;+ }+ }+ for (auto& t : workers) {+ t.join();+ }+ return success.load();+}++} // namespace ov::utildiff --git a/src/inference/src/cache_manager.hpp b/src/inference/src/cache_manager.hppindex 54f8d0e8d4b..ff4cdc5d9ae 100644--- a/src/inference/src/cache_manager.hpp+++ b/src/inference/src/cache_manager.hpp@@ -20,6 +20,7 @@#include "openvino/runtime/tensor.hpp"#include "openvino/util/file_util.hpp"#include "openvino/util/mmap_object.hpp"+#include "openvino/util/parallel_read_streambuf.hpp"namespace ov {@@ -75,7 +76,8 @@ private:CompiledBlobVariant compiled_blob{std::in_place_index<0>, ov::read_tensor_data(blob_path)};reader(compiled_blob);} else {- std::ifstream stream(blob_path, std::ios_base::binary);+ ov::util::ParallelReadStreamBuf par_buf(blob_path);+ std::istream stream(&par_buf);CompiledBlobVariant compiled_blob{std::in_place_index<1>, std::ref(stream)};reader(compiled_blob);}diff --git a/src/inference/src/single_file_storage.cpp b/src/inference/src/single_file_storage.cppindex 6c846a055d2..e9171ac7c55 100644--- a/src/inference/src/single_file_storage.cpp+++ b/src/inference/src/single_file_storage.cpp@@ -7,6 +7,7 @@#include "openvino/runtime/aligned_buffer.hpp"#include "openvino/util/file_util.hpp"#include "openvino/util/mmap_object.hpp"+#include "openvino/util/parallel_read_streambuf.hpp"#include "openvino/util/variant_visitor.hpp"namespace ov::runtime {@@ -259,8 +260,9 @@ void SingleFileStorage::read_cache_entry(const std::string& blob_id, bool enableblob_pos)};reader(compiled_blob);} else {- std::ifstream stream(m_file_path, std::ios::binary);- stream.seekg(blob_pos);+ // Use parallel file I/O to saturate NVMe bandwidth instead of single-threaded ifstream.+ ov::util::ParallelReadStreamBuf par_buf(m_file_path, static_cast<std::streamoff>(blob_pos));+ std::istream stream(&par_buf);CompiledBlobVariant compiled_blob{std::in_place_index<1>, std::ref(stream)};reader(compiled_blob);}diff --git a/src/inference/tests/unit/parallel_read_streambuf_test.cpp b/src/inference/tests/unit/parallel_read_streambuf_test.cppnew file mode 100644index 00000000000..40c21e801ae--- /dev/null+++ b/src/inference/tests/unit/parallel_read_streambuf_test.cpp@@ -0,0 +1,525 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/util/parallel_read_streambuf.hpp"++#include <gtest/gtest.h>++#include <cstring>+#include <filesystem>+#include <fstream>+#include <thread>+#include <vector>++#include "common_test_utils/common_utils.hpp"++namespace ov::test {++namespace {++/**+ * @brief Fill a vector with a deterministic pattern unique per byte position.+ *+ * byte[i] = (i % 251) -- 251 is prime so the period never aligns with any+ * power-of-two chunk/page size.+ */+void fill_pattern(std::vector<char>& buf, size_t start_index = 0) {+ for (size_t i = 0; i < buf.size(); ++i) {+ buf[i] = static_cast<char>((start_index + i) % 251u);+ }+}++/**+ * @brief Write data to a file, preceded by prefix_size bytes of 0xFF garbage+ * so that non-zero-offset tests can verify the header bytes are never+ * surfaced through the streambuf.+ */+// ASSERT_* macros expand to `return` (void), so they cannot be used directly+// in a non-void function. The canonical GTest pattern is to delegate to a+// void helper, then check HasFatalFailure() before continuing.+void write_temp_file_impl(const std::filesystem::path& path, const std::vector<char>& data, size_t prefix_size) {+ std::ofstream ofs(path, std::ios::binary | std::ios::trunc);+ ASSERT_TRUE(ofs.is_open()) << "Cannot create temp file: " << path;+ if (prefix_size > 0) {+ std::vector<char> prefix(prefix_size, static_cast<char>(0xFFu));+ ofs.write(prefix.data(), static_cast<std::streamsize>(prefix_size));+ }+ ofs.write(data.data(), static_cast<std::streamsize>(data.size()));+}++} // namespace++// Test fixture – creates a temporary file and removes it in TearDown+class ParallelReadStreamBufTest : public ::testing::Test {+protected:+ std::filesystem::path m_tmp_path;++ void SetUp() override {+ m_tmp_path = ov::test::utils::generateTestFilePrefix() + "_par_read.bin";+ }++ void setup_temp_file(const std::vector<char>& data, size_t prefix_size = 0) {+ ASSERT_FALSE(m_tmp_path.empty());+ write_temp_file_impl(m_tmp_path, data, prefix_size);+ }++ void TearDown() override {+ if (!m_tmp_path.empty() && std::filesystem::exists(m_tmp_path)) {+ std::filesystem::remove(m_tmp_path);+ }+ }+};++// 1. Full sequential read – threshold=1 forces parallel_read() to be called;+// num_threads collapses to 1 for < 1 MB so single_read() is used, but the+// dispatch code path (chunk math, atomic success flag) is exercised.+TEST_F(ParallelReadStreamBufTest, FullReadSmallThreshold) {+ constexpr size_t k_size = 16 * 1024; // 16 KB+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ util::ParallelReadStreamBuf buf(m_tmp_path, /*header_offset=*/0, /*threshold=*/1);+ std::istream stream(&buf);++ std::vector<char> got(k_size);+ ASSERT_TRUE(stream.read(got.data(), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(got, expected);+}++// 2. Non-zero header_offset: the file starts with a "garbage" prefix that+// must never appear in reads made through the streambuf.+TEST_F(ParallelReadStreamBufTest, NonZeroHeaderOffsetSmallData) {+ constexpr size_t k_prefix_size = 512;+ constexpr size_t k_payload_size = 4 * 1024;++ std::vector<char> payload(k_payload_size);+ fill_pattern(payload);+ setup_temp_file(payload, k_prefix_size);++ util::ParallelReadStreamBuf buf(m_tmp_path,+ static_cast<std::streamoff>(k_prefix_size),+ /*threshold=*/1);+ std::istream stream(&buf);++ std::vector<char> got(k_payload_size);+ ASSERT_TRUE(stream.read(got.data(), static_cast<std::streamsize>(k_payload_size)));+ EXPECT_EQ(got, payload);+}++// 3. Multiple consecutive reads – each partial read must pick up exactly+// where the previous one left off.+TEST_F(ParallelReadStreamBufTest, ChunkedReads) {+ constexpr size_t k_size = 8 * 1024;+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/1);+ std::istream stream(&buf);++ std::vector<char> got(k_size);+ constexpr size_t k_chunk = 1000; // intentionally not a power-of-2+ size_t offset = 0;+ while (offset < k_size) {+ const size_t n = std::min(k_chunk, k_size - offset);+ ASSERT_TRUE(stream.read(got.data() + offset, static_cast<std::streamsize>(n)));+ offset += n;+ }+ EXPECT_EQ(got, expected);+}++// 4. underflow() path: reading character-by-character exercises the internal+// 8 KB underflow buffer and the get-area bookkeeping.+TEST_F(ParallelReadStreamBufTest, CharByCharUnderflow) {+ constexpr size_t k_size = 300; // small enough to fit in a single underflow fill+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/SIZE_MAX); // force all reads via underflow+ std::istream stream(&buf);++ std::vector<char> got;+ got.reserve(k_size);+ int ch;+ while ((ch = stream.get()) != std::char_traits<char>::eof()) {+ got.push_back(static_cast<char>(ch));+ }+ ASSERT_EQ(got.size(), k_size);+ EXPECT_EQ(got, expected);+}++// 5. seekg(pos, beg): absolute seek then read must return bytes at that+// logical position (relative to the start exposed by the streambuf, i.e.+// after the header_offset).+TEST_F(ParallelReadStreamBufTest, SeekFromBeginning) {+ constexpr size_t k_size = 2 * 1024;+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/1);+ std::istream stream(&buf);++ // Seek to byte 500 and read 16 bytes+ constexpr std::streamoff k_seek_pos = 500;+ constexpr size_t k_read_len = 16;+ stream.seekg(k_seek_pos, std::ios::beg);+ ASSERT_TRUE(stream.good());++ std::vector<char> got(k_read_len);+ ASSERT_TRUE(stream.read(got.data(), static_cast<std::streamsize>(k_read_len)));++ std::vector<char> slice(expected.begin() + k_seek_pos, expected.begin() + k_seek_pos + k_read_len);+ EXPECT_EQ(got, slice);+}++// 6. seekg(off, cur): seek relative to current position.+TEST_F(ParallelReadStreamBufTest, SeekFromCurrent) {+ constexpr size_t k_size = 2 * 1024;+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/1);+ std::istream stream(&buf);++ // Read 100 bytes, skip 200 forward, read another 50+ constexpr size_t k_first_read = 100;+ constexpr std::streamoff k_skip = 200;+ constexpr size_t k_second_read = 50;++ std::vector<char> first(k_first_read);+ ASSERT_TRUE(stream.read(first.data(), static_cast<std::streamsize>(k_first_read)));+ EXPECT_EQ(first, std::vector<char>(expected.begin(), expected.begin() + k_first_read));++ stream.seekg(k_skip, std::ios::cur);+ ASSERT_TRUE(stream.good());++ std::vector<char> second(k_second_read);+ ASSERT_TRUE(stream.read(second.data(), static_cast<std::streamsize>(k_second_read)));++ const size_t expected_start = k_first_read + static_cast<size_t>(k_skip);+ std::vector<char> expected_slice(expected.begin() + expected_start,+ expected.begin() + expected_start + k_second_read);+ EXPECT_EQ(second, expected_slice);+}++// 7. seekg(off, end): seek backward from end-of-file.+TEST_F(ParallelReadStreamBufTest, SeekFromEnd) {+ constexpr size_t k_size = 2 * 1024;+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/1);+ std::istream stream(&buf);++ constexpr std::streamoff k_from_end = 64;+ stream.seekg(-k_from_end, std::ios::end);+ ASSERT_TRUE(stream.good());++ std::vector<char> got(static_cast<size_t>(k_from_end));+ ASSERT_TRUE(stream.read(got.data(), k_from_end));++ std::vector<char> tail(expected.end() - k_from_end, expected.end());+ EXPECT_EQ(got, tail);+}++// 8. seekg(0, end) then tellg() should equal the file (payload) size.+TEST_F(ParallelReadStreamBufTest, TellgAtEnd) {+ constexpr size_t k_size = 1024;+ std::vector<char> data(k_size, static_cast<char>(0xAA));+ setup_temp_file(data);++ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/1);+ std::istream stream(&buf);++ stream.seekg(0, std::ios::end);+ ASSERT_TRUE(stream.good());+ EXPECT_EQ(static_cast<size_t>(stream.tellg()), k_size);+}++// 9. Seek with non-zero header_offset: logical pos 0 == file offset (prefix).+// seeking to the end should give the payload size, not the whole file size.+TEST_F(ParallelReadStreamBufTest, SeekRespectsHeaderOffset) {+ constexpr size_t k_prefix_size = 256;+ constexpr size_t k_payload_size = 1024;++ std::vector<char> payload(k_payload_size);+ fill_pattern(payload);+ setup_temp_file(payload, k_prefix_size);++ util::ParallelReadStreamBuf buf(m_tmp_path,+ static_cast<std::streamoff>(k_prefix_size),+ /*threshold=*/1);+ std::istream stream(&buf);++ // tellg at start should be 0 (relative to payload start)+ EXPECT_EQ(static_cast<size_t>(stream.tellg()), 0u);++ // seekg to end, tellg should equal payload size+ stream.seekg(0, std::ios::end);+ ASSERT_TRUE(stream.good());+ EXPECT_EQ(static_cast<size_t>(stream.tellg()), k_payload_size);++ // Seek to byte 100 and read 8 bytes+ constexpr std::streamoff k_pos = 100;+ stream.seekg(k_pos, std::ios::beg);+ std::vector<char> got(8);+ ASSERT_TRUE(stream.read(got.data(), 8));+ std::vector<char> expected(payload.begin() + k_pos, payload.begin() + k_pos + 8);+ EXPECT_EQ(got, expected);+}++// 10. Out-of-range seek returns pos_type(-1) and leaves stream in a fail state.+TEST_F(ParallelReadStreamBufTest, OutOfRangeSeekFails) {+ constexpr size_t k_size = 64;+ std::vector<char> data(k_size, static_cast<char>(0x55));+ setup_temp_file(data);++ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/1);+ std::istream stream(&buf);++ // Seek before start+ const auto pos = stream.seekg(-1, std::ios::beg).tellg();+ EXPECT_EQ(pos, std::streampos(-1));+}++// 11. Reading exactly at EOF: request more bytes than remain – stream.read()+// must return false and gcount() must equal the bytes that were available.+TEST_F(ParallelReadStreamBufTest, ReadAtEof) {+ constexpr size_t k_size = 100;+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/SIZE_MAX); // use underflow path+ std::istream stream(&buf);++ // Read all but last 10 bytes+ std::vector<char> buf1(k_size - 10);+ ASSERT_TRUE(stream.read(buf1.data(), static_cast<std::streamsize>(k_size - 10)));++ // Now try to read 20 bytes when only 10 remain+ std::vector<char> buf2(20, 0);+ const bool ok = static_cast<bool>(stream.read(buf2.data(), 20));+ EXPECT_FALSE(ok);+ EXPECT_TRUE(stream.eof());+ ASSERT_EQ(stream.gcount(), 10);+ EXPECT_TRUE(std::equal(buf2.begin(), buf2.begin() + 10, expected.end() - 10));+}++// 12. PARALLEL PATH CORRECTNESS – large read (>= 2 MB) with threshold=1 so+// parallel_read() is always invoked. On ≥ 2-core machines the actual+// parallel dispatch fires; on single-core machines num_threads==1 still+// exercises the chunk-boundary math via single_read().+//+// The test verifies:+// a) The full buffer is byte-exact after a parallel read.+// b) A second consecutive parallel read immediately following also+// produces the correct data (no state corruption between calls).+TEST_F(ParallelReadStreamBufTest, ParallelDispatchFullReadCorrectness) {+ // Use hw_threads * 1 MB + 1 byte so that on any N-core machine,+ // min(hw, size/1MB) > 1 whenever hw >= 2. To avoid excessive memory / I/O+ // on very high-core CI runners, cap the effective hw used for sizing.+ constexpr size_t k_max_hw_for_size = 16;+ const size_t raw_hw = std::max(size_t{2}, static_cast<size_t>(std::thread::hardware_concurrency()));+ const size_t hw = std::min(k_max_hw_for_size, raw_hw);+ const size_t k_size = hw * 1024 * 1024 + 1;++ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/1);+ std::istream stream(&buf);++ // a) First parallel read: the full buffer must be byte-exact.+ std::vector<char> got(k_size);+ ASSERT_TRUE(stream.read(got.data(), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(got, expected) << "First parallel read produced incorrect data";++ // b) Seek back to start and do a second full parallel read immediately.+ // Verifies no state corruption (m_file_offset, fd, etc.) between calls.+ stream.clear();+ stream.seekg(0, std::ios::beg);+ ASSERT_TRUE(stream.good());++ std::vector<char> got2(k_size);+ ASSERT_TRUE(stream.read(got2.data(), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(got2, expected) << "Second consecutive parallel read produced incorrect data";+}++// 13. PARALLEL PATH with NON-ZERO header_offset and a seek in the middle:+// file = 4-KB header + (hw*1 MB) payload. After reading half the payload,+// seek back to position 0 (start of payload), read the whole payload again.+TEST_F(ParallelReadStreamBufTest, ParallelDispatchNonZeroOffset_AndSeek) {+ constexpr size_t k_prefix_size = 4 * 1024;+ constexpr size_t k_max_hw_for_size = 16;+ const size_t hw =+ std::min(k_max_hw_for_size, std::max(size_t{2}, static_cast<size_t>(std::thread::hardware_concurrency())));+ const size_t k_payload_size = hw * 1024 * 1024;++ std::vector<char> payload(k_payload_size);+ fill_pattern(payload);+ setup_temp_file(payload, k_prefix_size);++ util::ParallelReadStreamBuf buf(m_tmp_path,+ static_cast<std::streamoff>(k_prefix_size),+ /*threshold=*/1);+ std::istream stream(&buf);++ // First pass: read the first half+ const size_t k_half = k_payload_size / 2;+ std::vector<char> first_half(k_half);+ ASSERT_TRUE(stream.read(first_half.data(), static_cast<std::streamsize>(k_half)));+ EXPECT_TRUE(std::equal(first_half.begin(), first_half.end(), payload.begin()))+ << "First-half read produced incorrect data";++ // Seek back to the logical start of the payload+ stream.seekg(0, std::ios::beg);+ ASSERT_TRUE(stream.good());++ // Second pass: read the whole payload+ std::vector<char> full_read(k_payload_size);+ ASSERT_TRUE(stream.read(full_read.data(), static_cast<std::streamsize>(k_payload_size)));+ EXPECT_EQ(full_read, payload) << "Full read after seek produced incorrect data";+}++// 14. Mixed underflow + xsgetn: read a few chars via get() (exercises the+// underflow buffer), then read a large block via read() which triggers+// xsgetn to flush the underflow remainder.+TEST_F(ParallelReadStreamBufTest, MixedUnderflowAndBulkRead) {+ constexpr size_t k_size = 10 * 1024;+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ // threshold > k_size so all reads go through underflow() first, but we mix+ // with a large stream.read() to exercise the drain-from-get-area code in xsgetn.+ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/SIZE_MAX);+ std::istream stream(&buf);++ // Read 5 chars individually – this fills the 8 KB underflow buffer+ std::vector<char> prefix;+ for (int i = 0; i < 5; ++i) {+ const int ch = stream.get();+ ASSERT_NE(ch, std::char_traits<char>::eof());+ prefix.push_back(static_cast<char>(ch));+ }+ EXPECT_EQ(prefix, std::vector<char>(expected.begin(), expected.begin() + 5));++ // Now do a bulk read for the rest of the file.+ std::vector<char> rest(k_size - 5);+ ASSERT_TRUE(stream.read(rest.data(), static_cast<std::streamsize>(k_size - 5)));+ EXPECT_EQ(rest, std::vector<char>(expected.begin() + 5, expected.end()))+ << "Bulk read after char-by-char prefix produced incorrect data";+}++// 15. seekg(0, cur) used as tellg() must reflect the current logical position+// correctly after both underflow-buffered reads and bulk reads.+TEST_F(ParallelReadStreamBufTest, TellgIsConsistent) {+ constexpr size_t k_size = 512;+ std::vector<char> data(k_size, static_cast<char>(0xBB));+ setup_temp_file(data);++ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/SIZE_MAX);+ std::istream stream(&buf);++ EXPECT_EQ(stream.tellg(), std::streampos(0));++ // After reading 100 bytes via bulk read+ std::vector<char> tmp(100);+ stream.read(tmp.data(), 100);+ EXPECT_EQ(stream.tellg(), std::streampos(100));++ // After reading 10 more chars individually+ for (int i = 0; i < 10; ++i) {+ stream.get();+ }+ EXPECT_EQ(stream.tellg(), std::streampos(110));++ // After seekg+ stream.seekg(200, std::ios::beg);+ EXPECT_EQ(stream.tellg(), std::streampos(200));+}++// 16. showmanyc() / in_avail() reports remaining bytes accurately, including+// both buffered characters (from the underflow buffer) and unbuffered+// bytes still in the underlying file.+TEST_F(ParallelReadStreamBufTest, ShowmanycReflectsRemainingBytes) {+ constexpr size_t k_size = 256;+ std::vector<char> data(k_size, static_cast<char>(0x77u));+ setup_temp_file(data);++ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/SIZE_MAX);+ std::istream stream(&buf);++ // Before any read, in_avail() should report the full file size.+ EXPECT_EQ(stream.rdbuf()->in_avail(), static_cast<std::streamsize>(k_size));++ // After a bulk read of 100 bytes (via xsgetn, no underflow buffer involved)+ std::vector<char> tmp(100);+ stream.read(tmp.data(), 100);+ EXPECT_EQ(stream.rdbuf()->in_avail(), static_cast<std::streamsize>(k_size - 100));++ // After a single get() which triggers underflow() and fills the 8 KB+ // internal buffer with the remaining 156 bytes, in_avail() should still+ // reflect the correct total: buffered chars minus the one consumed by get().+ stream.get();+ // The underflow buffer now holds min(UNDERFLOW_BUF, 156) = 156 bytes.+ // get() consumed 1, so 155 remain in the buffer. m_file_offset+ // advanced past the buffer, so file_remaining == 0.+ // Total = 155 + 0 = 155.+ EXPECT_EQ(stream.rdbuf()->in_avail(), static_cast<std::streamsize>(k_size - 100 - 1));++ // Consume everything that remains+ std::vector<char> rest(k_size - 101);+ stream.read(rest.data(), static_cast<std::streamsize>(k_size - 101));+ // Now exhausted+ EXPECT_EQ(stream.rdbuf()->in_avail(), -1);+}++// 17. Backward seek from current position: read some bytes, seek backward+// relative to current, verify the re-read returns the correct earlier+// bytes. Also verifies that the underflow buffer is properly invalidated.+TEST_F(ParallelReadStreamBufTest, BackwardSeekFromCurrent) {+ constexpr size_t k_size = 2 * 1024;+ std::vector<char> expected(k_size);+ fill_pattern(expected);+ setup_temp_file(expected);++ // Use SIZE_MAX threshold so reads go through underflow + xsgetn drain,+ // making the backward seek invalidate a non-empty underflow buffer.+ util::ParallelReadStreamBuf buf(m_tmp_path, 0, /*threshold=*/SIZE_MAX);+ std::istream stream(&buf);++ // Read 200 bytes+ constexpr size_t k_first_read = 200;+ std::vector<char> first(k_first_read);+ ASSERT_TRUE(stream.read(first.data(), static_cast<std::streamsize>(k_first_read)));+ EXPECT_EQ(stream.tellg(), std::streampos(k_first_read));++ // Read 5 chars individually to populate the underflow buffer+ for (int i = 0; i < 5; ++i) {+ ASSERT_NE(stream.get(), std::char_traits<char>::eof());+ }+ EXPECT_EQ(stream.tellg(), std::streampos(205));++ // Seek backward 100 bytes from current position+ stream.seekg(-100, std::ios::cur);+ ASSERT_TRUE(stream.good());+ EXPECT_EQ(stream.tellg(), std::streampos(105));++ // Read 50 bytes; they must match expected[105..154]+ constexpr size_t k_reread = 50;+ std::vector<char> got(k_reread);+ ASSERT_TRUE(stream.read(got.data(), static_cast<std::streamsize>(k_reread)));+ std::vector<char> slice(expected.begin() + 105, expected.begin() + 105 + k_reread);+ EXPECT_EQ(got, slice);+}++} // namespace ov::testdiff --git a/src/inference/tests/unit/single_file_storage.cpp b/src/inference/tests/unit/single_file_storage.cppindex 955990cf49c..919caabf817 100644--- a/src/inference/tests/unit/single_file_storage.cpp+++ b/src/inference/tests/unit/single_file_storage.cpp@@ -193,6 +193,49 @@ TEST_F(SingleFileStorageTest, AppendOnlyCacheEntry) {EXPECT_TRUE(read_called);}+// Large blob test: write >= 4 MB so that the real DEFAULT_THRESHOLD (4 MB) in+// ParallelReadStreamBuf is crossed on the non-mmap read path. This exercises+// the SingleFileStorage → ParallelReadStreamBuf integration end-to-end,+// including the blob alignment padding before the data and the non-zero+// header_offset passed to the streambuf constructor.+TEST_F(SingleFileStorageTest, WriteReadLargeBlob_ParallelPath) {+ // 5 MB + 1 byte so that even after padding the blob data itself exceeds the+ // 4 MB parallel threshold.+ constexpr size_t k_blob_size = 5UL * 1024 * 1024 + 1;+ const std::string blob_id = "999";++ // Build a deterministic pattern so byte-exact comparison is possible.+ std::vector<uint8_t> expected(k_blob_size);+ for (size_t i = 0; i < k_blob_size; ++i) {+ expected[i] = static_cast<uint8_t>(i % 251u);+ }++ m_storage->write_cache_entry(blob_id, [&](std::ostream& s) {+ s.write(reinterpret_cast<const char*>(expected.data()), static_cast<std::streamsize>(k_blob_size));+ });++ // --- non-mmap path (ParallelReadStreamBuf) ---+ m_storage->read_cache_entry(blob_id, /*enable_mmap=*/false, [&](const ICacheManager::CompiledBlobVariant& cv) {+ auto& stream = std::get<std::reference_wrapper<std::istream>>(cv).get();++ std::vector<uint8_t> got(k_blob_size);+ ASSERT_TRUE(stream.read(reinterpret_cast<char*>(got.data()), static_cast<std::streamsize>(k_blob_size)));+ EXPECT_EQ(got, expected) << "Parallel read returned incorrect data for large blob";+ });++ // Reset and re-open to ensure the content survives a round-trip through+ // build_content_index (re-scans the file and rebuilds m_blob_index).+ m_storage.reset();+ SingleFileStorage reopened(m_file_path);+ reopened.read_cache_entry(blob_id, /*enable_mmap=*/false, [&](const ICacheManager::CompiledBlobVariant& cv) {+ auto& stream = std::get<std::reference_wrapper<std::istream>>(cv).get();++ std::vector<uint8_t> got(k_blob_size);+ ASSERT_TRUE(stream.read(reinterpret_cast<char*>(got.data()), static_cast<std::streamsize>(k_blob_size)));+ EXPECT_EQ(got, expected) << "Parallel read after re-open returned incorrect data for large blob";+ });+}+TEST_F(SingleFileStorageTest, ContextMetaWriteRead) {weight_sharing::Context test_context;test_context.m_weight_registry[1][11] = {100, 200, element::Type_t::f32};diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/data.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/data.hppindex 61d52dc2885..178b3448b2b 100644--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/data.hpp+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/data.hpp@@ -422,13 +422,65 @@ struct data : public primitive_base<data> {if (is_alloc_host_accessible(_allocation_type)) {ib >> make_data(mem->buffer_ptr(), data_size);} else {- const size_t DATA_BLOCK_SIZE = 2 * 1024 * 1024;- auto& strm = ib.get_engine().get_service_stream();+ const size_t DATA_BLOCK_SIZE = 4 * 1024 * 1024;+ auto& eng = ib.get_engine();+ auto& strm = eng.get_service_stream();if (data_size < DATA_BLOCK_SIZE || output_layout.format.is_image_2d()) {std::vector<uint8_t> _buf(data_size);ib >> make_data(_buf.data(), data_size);mem->copy_from(strm, _buf.data());+ } else if (eng.supports_allocation(allocation_type::usm_host)) {+ // Use USM host staging buffers so the driver can DMA directly+ // from pinned host memory to device, avoiding the hidden+ // pageable-to-pinned bounce copy that std::vector staging incurs.+ // The pipeline is the same ping-pong as the fallback below:+ // CPU reads into host_bufA while GPU copies from host_bufB+ // Safety: each staging buffer is reused every other iteration;+ // the wait() before re-submitting a copy ensures the previous+ // GPU read from that buffer has finished before the CPU writes+ // new data into it (the OTHER buffer's event is waited, but that+ // event was submitted after waiting for THIS buffer's previous+ // event, so this buffer is always free by the time we reuse it).+ const layout staging_layout{{static_cast<int64_t>(DATA_BLOCK_SIZE)},+ data_types::u8, format::bfyx};+ auto host_buf1 = eng.allocate_memory(staging_layout, allocation_type::usm_host, false);+ auto host_buf2 = eng.allocate_memory(staging_layout, allocation_type::usm_host, false);+ bool buf_flag = true;+ event::ptr ev1, ev2;+ ev1 = ev2 = nullptr;+ size_t dst_offset = 0;+ while (dst_offset < data_size) {+ const bool is_blocking = false;+ const size_t src_offset = 0;+ size_t copy_size =+ (data_size > (dst_offset + DATA_BLOCK_SIZE)) ? DATA_BLOCK_SIZE : (data_size - dst_offset);+ if (buf_flag) {+ ib >> make_data(static_cast<uint8_t*>(host_buf1->buffer_ptr()), copy_size);+ if (ev2 != nullptr) {+ ev2->wait();+ ev2 = nullptr;+ }+ ev1 = mem->copy_from(strm, *host_buf1, src_offset, dst_offset, copy_size, is_blocking);+ } else {+ ib >> make_data(static_cast<uint8_t*>(host_buf2->buffer_ptr()), copy_size);+ if (ev1 != nullptr) {+ ev1->wait();+ ev1 = nullptr;+ }+ ev2 = mem->copy_from(strm, *host_buf2, src_offset, dst_offset, copy_size, is_blocking);+ }+ dst_offset += DATA_BLOCK_SIZE;+ buf_flag = !buf_flag;+ }+ if (ev2 != nullptr) {+ ev2->wait();+ }+ if (ev1 != nullptr) {+ ev1->wait();+ }} else {+ // Fallback for devices that do not support USM host allocation:+ // use pageable std::vector staging buffers (original behaviour).std::vector<uint8_t> _buf1(DATA_BLOCK_SIZE);std::vector<uint8_t> _buf2(DATA_BLOCK_SIZE);bool buf_flag = true;diff --git a/src/plugins/intel_gpu/src/graph/common_utils/parallel_mem_streambuf.cpp b/src/plugins/intel_gpu/src/graph/common_utils/parallel_mem_streambuf.cppnew file mode 100644index 00000000000..246af70806f--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/common_utils/parallel_mem_streambuf.cpp@@ -0,0 +1,284 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "parallel_mem_streambuf.hpp"++#include <algorithm>+#include <cstdint>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <sstream>+#include <string>+#include <thread>+#include <vector>++#ifdef _WIN32+// clang-format off+#ifndef NOMINMAX+# define NOMINMAX+#endif+#include <cwchar>+#include <windows.h>+#include <psapi.h>+// clang-format on+#else+# include <sys/mman.h>+#endif++#include "openvino/util/parallel_io.hpp"++namespace ov::intel_gpu {++#ifdef _WIN32+// Convert a kernel device path (\Device\HarddiskVolume3\foo\bar) to a+// Win32 drive path (C:\foo\bar).+static bool resolve_device_path(const wchar_t* dev_path, wchar_t* out, DWORD out_len) {+ const size_t MAX_DRIVES_LEN = 512;+ wchar_t drives[MAX_DRIVES_LEN] = {};+ if (!GetLogicalDriveStringsW(MAX_DRIVES_LEN, drives))+ return false;+ for (const wchar_t* d = drives; *d; d += wcslen(d) + 1) {+ wchar_t drive[3] = {d[0], d[1], L'\0'};+ wchar_t dev_name[MAX_PATH] = {};+ if (!QueryDosDeviceW(drive, dev_name, MAX_PATH))+ continue;+ const size_t dev_name_len = wcslen(dev_name);+ if (wcsncmp(dev_path, dev_name, dev_name_len) == 0 && (dev_path[dev_name_len] == L'\\' || dev_path[dev_name_len] == L'\0')) {+ swprintf_s(out, out_len, L"%s%s", drive, dev_path + dev_name_len);+ return true;+ }+ }+ return false;+}+#endif++// Detect whether a memory address is backed by a file-based mmap.+// On Linux, parses /proc/self/maps.+// On Windows, uses VirtualQuery + GetMappedFileNameW + drive letter resolution.+// param addr The memory address to inspect.+// param out_path [out] Path to the backing file (only set on success).+// param out_offset [out] Absolute byte offset within the file corresponding to addr.+// return true if the address is file-backed, false otherwise.+static bool get_mmap_file_info(const void* addr, std::filesystem::path& out_path, std::streamoff& out_offset) {+#ifdef _WIN32+ MEMORY_BASIC_INFORMATION mbi{};+ if (!VirtualQuery(addr, &mbi, sizeof(mbi)) || mbi.Type != MEM_MAPPED) {+ return false;+ }+ void* query_addr = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(addr));+ wchar_t dev_path[MAX_PATH] = {};+ if (GetMappedFileNameW(GetCurrentProcess(), query_addr, dev_path, MAX_PATH) == 0) {+ return false;+ }+ wchar_t win32_path[MAX_PATH] = {};+ if (!resolve_device_path(dev_path, win32_path, MAX_PATH)) {+ return false;+ }+ out_path = std::filesystem::path(win32_path);+ out_offset = reinterpret_cast<const char*>(addr) - reinterpret_cast<const char*>(mbi.AllocationBase);+ return true;+#else+ std::ifstream maps_file("/proc/self/maps");+ if (!maps_file.is_open())+ return false;+ const auto addr_val = reinterpret_cast<uintptr_t>(addr);+ std::string line;+ while (std::getline(maps_file, line)) {+ // Format: start-end perms offset dev inode [pathname]+ std::istringstream iss(line);+ std::string addr_range, perms, offset_str, dev, inode_str;+ if (!(iss >> addr_range >> perms >> offset_str >> dev >> inode_str))+ continue;+ const auto dash = addr_range.find('-');+ if (dash == std::string::npos)+ continue;+ uintptr_t range_start = 0, range_end = 0;+ try {+ range_start = static_cast<uintptr_t>(std::stoull(addr_range.substr(0, dash), nullptr, 16));+ range_end = static_cast<uintptr_t>(std::stoull(addr_range.substr(dash + 1), nullptr, 16));+ } catch (...) {+ continue;+ }+ if (addr_val < range_start || addr_val >= range_end)+ continue;+ // Skip whitespace after inode to reach the optional pathname field.+ // Use getline instead of operator>> to handle paths that contain spaces.+ std::string pathname;+ std::getline(iss >> std::ws, pathname);+ if (pathname.empty())+ return false; // anonymous mapping (no pathname)+ std::filesystem::path path(pathname);+ if (!path.is_absolute())+ return false; // special region like [heap], [stack], [vdso]+ out_path = path;+ std::streamoff map_offset = 0;+ try {+ map_offset = static_cast<std::streamoff>(std::stoull(offset_str, nullptr, 16));+ } catch (...) {+ return false;+ }+ out_offset = map_offset + static_cast<std::streamoff>(addr_val - range_start);+ return true;+ }+ return false;+#endif+}++// Issue an asynchronous prefetch hint for a memory region.+// On Linux, calls madvise(MADV_WILLNEED) (with page-aligned address).+// On Windows, calls PrefetchVirtualMemory.+// addr Start of the memory region.+// size Size of the region in bytes.+static void prefetch_memory(const void* addr, size_t size) {+#ifdef _WIN32+ void* prefetch_addr = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(addr));+ WIN32_MEMORY_RANGE_ENTRY prefetch_range{prefetch_addr, size};+ PrefetchVirtualMemory(GetCurrentProcess(), 1, &prefetch_range, 0);+#else+ // madvise(2) requires addr to be page-aligned; round down and extend size.+ const uintptr_t base = reinterpret_cast<uintptr_t>(addr);+ const uintptr_t aligned_base = base & ~uintptr_t{4095};+ // madvise is advisory — failure is non-fatal; the read path will still work.+ (void)madvise(reinterpret_cast<void*>(aligned_base), size + (base - aligned_base), MADV_WILLNEED);+#endif+}++ParallelMemStreamBuf::ParallelMemStreamBuf(const void* data, size_t size, size_t threshold)+ : m_begin(static_cast<const char*>(data)),+ m_end(static_cast<const char*>(data) + size),+ m_current(static_cast<const char*>(data)),+ m_threshold(threshold) {+ // Detect whether this memory is a file-backed mmap region.+ // If so, build a ParallelReadStreamBuf over the same file+offset so+ // direct reads are used instead of mmap+memcpy. This avoids 2x RAM+ // pressure (mmap working-set + destination buffer) that causes+ // working-set thrashing for multi-GB models.+ if (size >= threshold) {+ std::filesystem::path file_path;+ std::streamoff file_off = 0;+ if (get_mmap_file_info(data, file_path, file_off)) {+ try {+ m_file_buf = std::make_unique<ov::util::ParallelReadStreamBuf>(file_path, file_off, threshold);+ } catch (...) {+ // File became inaccessible after mmap detection; fall through to memcpy path.+ }+ }+ }+ // For non-file-backed memory (anonymous mmap, USM host buffers, etc.)+ // fall back to async prefetch + parallel memcpy.+ if (!m_file_buf) {+ prefetch_memory(data, size);+ }+}++std::streamsize ParallelMemStreamBuf::xsgetn(char_type* dst, std::streamsize n) {+ if (m_file_buf) {+ return m_file_buf->sgetn(dst, n);+ }+ if (n <= 0 || m_current >= m_end) {+ return 0;+ }+ const std::streamsize avail = static_cast<std::streamsize>(m_end - m_current);+ const std::streamsize to_copy = std::min(n, avail);++ if (static_cast<size_t>(to_copy) >= m_threshold) {+ parallel_copy(dst, m_current, static_cast<size_t>(to_copy));+ } else {+ std::memcpy(dst, m_current, static_cast<size_t>(to_copy));+ }++ m_current += to_copy;+ return to_copy;+}++ParallelMemStreamBuf::int_type ParallelMemStreamBuf::underflow() {+ if (m_file_buf) {+ return m_file_buf->sgetc();+ }+ if (m_current >= m_end) {+ return traits_type::eof();+ }+ return traits_type::to_int_type(*m_current);+}++ParallelMemStreamBuf::int_type ParallelMemStreamBuf::uflow() {+ if (m_file_buf) {+ return m_file_buf->sbumpc();+ }+ if (m_current >= m_end) {+ return traits_type::eof();+ }+ return traits_type::to_int_type(*m_current++);+}++ParallelMemStreamBuf::pos_type ParallelMemStreamBuf::seekoff(off_type off, std::ios_base::seekdir way, std::ios_base::openmode which) {+ if (m_file_buf) {+ return m_file_buf->pubseekoff(off, way, which);+ }+ const char* new_pos = nullptr;+ if (way == std::ios_base::beg) {+ new_pos = m_begin + off;+ } else if (way == std::ios_base::cur) {+ new_pos = m_current + off;+ } else {+ new_pos = m_end + off;+ }++ if (new_pos < m_begin || new_pos > m_end) {+ return pos_type(off_type(-1));+ }++ m_current = new_pos;+ return pos_type(static_cast<off_type>(m_current - m_begin));+}++ParallelMemStreamBuf::pos_type ParallelMemStreamBuf::seekpos(pos_type pos, std::ios_base::openmode which) {+ if (m_file_buf) {+ return m_file_buf->pubseekpos(pos, which);+ }+ return seekoff(off_type(pos), std::ios_base::beg, std::ios_base::in);+}++std::streamsize ParallelMemStreamBuf::showmanyc() {+ if (m_file_buf) {+ return m_file_buf->in_avail();+ }+ const std::streamsize avail = static_cast<std::streamsize>(m_end - m_current);+ return avail > 0 ? avail : -1;+}++void ParallelMemStreamBuf::parallel_copy(char* dst, const char* src, size_t size) {+ // Cap threads: too many concurrent threads cause OS scheduling overhead+ // (Linux) or PFN-lock contention (Windows). Use hardware_concurrency as+ // the upper bound, consistent with parallel_read.+ const size_t hw_conc = std::max(size_t{1}, static_cast<size_t>(std::thread::hardware_concurrency()));+ const size_t num_chunks = std::max(size_t{1}, std::min(size / ov::util::default_parallel_io_min_chunk, hw_conc));+ const size_t chunk_size = (size + num_chunks - 1) / num_chunks;+ prefetch_memory(src, size);++ std::vector<std::thread> workers;+ workers.reserve(num_chunks);+ for (size_t i = 0; i < num_chunks; ++i) {+ try {+ workers.emplace_back([&, i]() {+ const size_t offset = i * chunk_size;+ const size_t copy_size = (i + 1 == num_chunks) ? (size - offset) : std::min(chunk_size, size - offset);+ std::memcpy(dst + offset, src + offset, copy_size);+ });+ } catch (...) {+ for (auto& t : workers)+ t.join();+ const size_t done = i * chunk_size;+ if (done < size)+ std::memcpy(dst + done, src + done, size - done);+ return;+ }+ }+ for (auto& t : workers) {+ t.join();+ }+}++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/graph/common_utils/parallel_mem_streambuf.hpp b/src/plugins/intel_gpu/src/graph/common_utils/parallel_mem_streambuf.hppnew file mode 100644index 00000000000..4fcec9d34ed--- /dev/null+++ b/src/plugins/intel_gpu/src/graph/common_utils/parallel_mem_streambuf.hpp@@ -0,0 +1,49 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <memory>+#include <streambuf>++#include "openvino/util/parallel_read_streambuf.hpp"++namespace ov::intel_gpu {++// A temporary solution to improve SSD reading bandwidth and avoid the 2x-RAM cost of mmap+memcpy for mmap files.+// Once L0 handle SSD reading bandwidth issue, this can be removed and the original mmap+memcpy path can be restored.+//+// A std::streambuf that reads from an in-memory buffer using parallel+// memcpy for large reads. When the source is a file-backed mmap, the+// constructor detects this and delegates to ParallelReadStreamBuf so that+// direct pread/ReadFile calls replace the 2x-RAM mmap+memcpy path.+class ParallelMemStreamBuf : public std::streambuf {+public:+ explicit ParallelMemStreamBuf(const void* data, size_t size, size_t threshold = ov::util::default_parallel_io_threshold);++ ~ParallelMemStreamBuf() override = default;++ ParallelMemStreamBuf(const ParallelMemStreamBuf&) = delete;+ ParallelMemStreamBuf& operator=(const ParallelMemStreamBuf&) = delete;++protected:+ std::streamsize xsgetn(char_type* dst, std::streamsize n) override;+ int_type underflow() override;+ int_type uflow() override;+ pos_type seekoff(off_type off, std::ios_base::seekdir way, std::ios_base::openmode which) override;+ pos_type seekpos(pos_type pos, std::ios_base::openmode which) override;+ std::streamsize showmanyc() override;++private:+ void parallel_copy(char* dst, const char* src, size_t size);++ const char* m_begin;+ const char* m_end;+ const char* m_current;+ size_t m_threshold;+ std::unique_ptr<ov::util::ParallelReadStreamBuf> m_file_buf;+};++} // namespace ov::intel_gpudiff --git a/src/plugins/intel_gpu/src/graph/data.cpp b/src/plugins/intel_gpu/src/graph/data.cppindex 68a9b414267..ce82565e6c5 100644--- a/src/plugins/intel_gpu/src/graph/data.cpp+++ b/src/plugins/intel_gpu/src/graph/data.cpp@@ -1,14 +1,19 @@// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0//+#include "data_inst.h"+#include "json_object.h"#include "primitive_type_base.h"+#include "intel_gpu/runtime/memory.hpp"+#include "openvino/core/parallel.hpp"+#include "openvino/util/parallel_io.hpp"-#include "json_object.h"-#include <string>-#include <memory>#include <algorithm>+#include <cstring>+#include <memory>+#include <string>namespace cldnn {GPU_DEFINE_PRIMITIVE_TYPE_ID(data)@@ -22,7 +27,21 @@ memory::ptr attach_or_copy_data(network& network, memory::ptr mem) {memory::ptr result = engine.allocate_memory(mem->get_layout(), false);mem_lock<char, mem_lock_type::read> src(mem, network.get_stream());mem_lock<char, mem_lock_type::write> dst(result, network.get_stream());- std::copy(src.begin(), src.end(), dst.begin());+ const size_t data_size = src.size();+ if (data_size >= ov::util::default_parallel_io_threshold) {+ char* src_ptr = src.data();+ char* dst_ptr = dst.data();+ const size_t max_threads = static_cast<size_t>(parallel_get_max_threads());+ const size_t num_chunks = std::max(size_t{1}, std::min(data_size / ov::util::default_parallel_io_min_chunk, max_threads));+ const size_t chunk_size = (data_size + num_chunks - 1) / num_chunks;+ ov::parallel_for(num_chunks, [src_ptr, dst_ptr, chunk_size, data_size, num_chunks](size_t i) {+ const size_t offset = i * chunk_size;+ const size_t copy_size = (i + 1 == num_chunks) ? (data_size - offset) : std::min(chunk_size, data_size - offset);+ std::memcpy(dst_ptr + offset, src_ptr + offset, copy_size);+ });+ } else {+ std::copy(src.begin(), src.end(), dst.begin());+ }return result;}} // namespacediff --git a/src/plugins/intel_gpu/src/plugin/plugin.cpp b/src/plugins/intel_gpu/src/plugin/plugin.cppindex b503b089de3..15d6d9202fc 100644--- a/src/plugins/intel_gpu/src/plugin/plugin.cpp+++ b/src/plugins/intel_gpu/src/plugin/plugin.cpp@@ -38,6 +38,7 @@#include "openvino/runtime/plugin_config.hpp"#include "openvino/runtime/properties.hpp"#include "openvino/runtime/shared_buffer.hpp"+#include "common_utils/parallel_mem_streambuf.hpp"#include "openvino/runtime/weightless_properties_utils.hpp"#include "openvino/util/file_util.hpp"#include "openvino/util/weights_path.hpp"@@ -459,8 +460,8 @@ std::shared_ptr<ov::ICompiledModel> Plugin::import_model(const ov::Tensor& modelstd::shared_ptr<ov::ICompiledModel> Plugin::import_model(const ov::Tensor& model,const ov::SoPtr<ov::IRemoteContext>& context,const ov::AnyMap& config) const{- SharedStreamBuffer buf{model.data(), model.get_byte_size()};- std::istream stream(&buf);+ ov::intel_gpu::ParallelMemStreamBuf par_buf(model.data(), model.get_byte_size());+ std::istream stream(&par_buf);return import_model(stream, context, config);}diff --git a/src/plugins/intel_gpu/tests/unit/test_utils/parallel_mem_streambuf_test.cpp b/src/plugins/intel_gpu/tests/unit/test_utils/parallel_mem_streambuf_test.cppnew file mode 100644index 00000000000..7c02b8a7152--- /dev/null+++ b/src/plugins/intel_gpu/tests/unit/test_utils/parallel_mem_streambuf_test.cpp@@ -0,0 +1,497 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "common_utils/parallel_mem_streambuf.hpp"++#include <gtest/gtest.h>++#include <cstring>+#include <filesystem>+#include <fstream>+#include <thread>+#include <vector>++#ifdef _WIN32+# ifndef NOMINMAX+# define NOMINMAX+# endif+# include <windows.h>+#else+# include <fcntl.h>+# include <sys/mman.h>+# include <unistd.h>+#endif++namespace {++void fill_pattern(std::vector<char>& buf, size_t start_index = 0) {+ for (size_t i = 0; i < buf.size(); ++i) {+ buf[i] = static_cast<char>((start_index + i) % 251u);+ }+}++} // namespace++// 1. Small read – threshold=SIZE_MAX forces the single memcpy path.+TEST(ParallelMemStreamBufTest, FullReadSingleMemcpyPath) {+ constexpr size_t k_size = 4 * 1024;+ std::vector<char> src(k_size);+ fill_pattern(src);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/SIZE_MAX);+ std::istream stream(&buf);++ std::vector<char> got(k_size);+ ASSERT_TRUE(stream.read((got.data()), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(got, src);+}++// 2. threshold=1 forces parallel_copy() to be called on every bulk read.+TEST(ParallelMemStreamBufTest, FullReadParallelMemcpyPath) {+ constexpr size_t k_size = 8 * 1024;+ std::vector<char> src(k_size);+ fill_pattern(src);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/1);+ std::istream stream(&buf);++ std::vector<char> got(k_size);+ ASSERT_TRUE(stream.read((got.data()), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(got, src);+}++// 3. Non-zero logical start: construct on a sub-span of a larger allocation.+TEST(ParallelMemStreamBufTest, NonZeroPointerOffset) {+ constexpr size_t k_prefix_size = 512;+ constexpr size_t k_payload_size = 2 * 1024;+ std::vector<char> backing(k_prefix_size + k_payload_size);+ std::fill(backing.begin(), backing.begin() + k_prefix_size, 0xFFu);+ std::vector<char> payload(k_payload_size);+ fill_pattern(payload);+ std::memcpy(backing.data() + k_prefix_size, payload.data(), k_payload_size);++ const char* payload_ptr = (backing.data() + k_prefix_size);+ ov::intel_gpu::ParallelMemStreamBuf buf(payload_ptr, k_payload_size, /*threshold=*/1);+ std::istream stream(&buf);++ std::vector<char> got(k_payload_size);+ ASSERT_TRUE(stream.read((got.data()), static_cast<std::streamsize>(k_payload_size)));+ EXPECT_EQ(got, payload);+}++// 4. Multiple consecutive partial reads consume bytes in order.+TEST(ParallelMemStreamBufTest, ChunkedReads) {+ constexpr size_t k_size = 8 * 1024;+ constexpr size_t k_chunk = 1000;+ std::vector<char> src(k_size);+ fill_pattern(src);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/1);+ std::istream stream(&buf);++ std::vector<char> got(k_size);+ size_t offset = 0;+ while (offset < k_size) {+ const size_t n = std::min(k_chunk, k_size - offset);+ ASSERT_TRUE(stream.read((got.data() + offset), static_cast<std::streamsize>(n)));+ offset += n;+ }+ EXPECT_EQ(got, src);+}++// 5. underflow() + uflow() – char-by-char consumption via stream.get().+TEST(ParallelMemStreamBufTest, CharByCharRead) {+ constexpr size_t k_size = 200;+ std::vector<char> src(k_size);+ fill_pattern(src);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/SIZE_MAX);+ std::istream stream(&buf);++ std::vector<char> got;+ got.reserve(k_size);+ int ch;+ while ((ch = stream.get()) != std::char_traits<char>::eof()) {+ got.push_back(static_cast<char>(ch));+ }+ ASSERT_EQ(got.size(), k_size);+ EXPECT_EQ(got, src);+}++// 6. seekg(pos, beg) then read returns bytes at that logical position.+TEST(ParallelMemStreamBufTest, SeekFromBeginning) {+ constexpr size_t k_size = 1024;+ std::vector<char> src(k_size);+ fill_pattern(src);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/1);+ std::istream stream(&buf);++ constexpr std::streamoff k_seek_pos = 300;+ constexpr size_t k_read_len = 20;+ stream.seekg(k_seek_pos, std::ios::beg);+ ASSERT_TRUE(stream.good());++ std::vector<char> got(k_read_len);+ ASSERT_TRUE(stream.read((got.data()), static_cast<std::streamsize>(k_read_len)));++ std::vector<char> expected(src.begin() + k_seek_pos, src.begin() + k_seek_pos + k_read_len);+ EXPECT_EQ(got, expected);+}++// 7. seekg(off, cur) – relative forward seek after an initial read.+TEST(ParallelMemStreamBufTest, SeekFromCurrent) {+ constexpr size_t k_size = 1024;+ std::vector<char> src(k_size);+ fill_pattern(src);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/1);+ std::istream stream(&buf);++ constexpr size_t k_first_read = 100;+ constexpr std::streamoff k_skip = 150;+ constexpr size_t k_second_read = 30;++ std::vector<char> first(k_first_read);+ ASSERT_TRUE(stream.read((first.data()), static_cast<std::streamsize>(k_first_read)));+ EXPECT_EQ(first, std::vector<char>(src.begin(), src.begin() + k_first_read));++ stream.seekg(k_skip, std::ios::cur);+ ASSERT_TRUE(stream.good());++ std::vector<char> second(k_second_read);+ ASSERT_TRUE(stream.read((second.data()), static_cast<std::streamsize>(k_second_read)));++ const size_t expected_start = k_first_read + static_cast<size_t>(k_skip);+ std::vector<char> expected_slice(src.begin() + expected_start, src.begin() + expected_start + k_second_read);+ EXPECT_EQ(second, expected_slice);+}++// 8. seekg(off, end) – backward seek from the end.+TEST(ParallelMemStreamBufTest, SeekFromEnd) {+ constexpr size_t k_size = 1024;+ std::vector<char> src(k_size);+ fill_pattern(src);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/1);+ std::istream stream(&buf);++ constexpr std::streamoff k_from_end = 48;+ stream.seekg(-k_from_end, std::ios::end);+ ASSERT_TRUE(stream.good());++ std::vector<char> got(static_cast<size_t>(k_from_end));+ ASSERT_TRUE(stream.read((got.data()), k_from_end));++ std::vector<char> expected(src.end() - k_from_end, src.end());+ EXPECT_EQ(got, expected);+}++// 9. seekg(0, end) then tellg() must equal the buffer size.+TEST(ParallelMemStreamBufTest, TellgAtEnd) {+ constexpr size_t k_size = 512;+ std::vector<char> src(k_size, 0xAAu);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/1);+ std::istream stream(&buf);++ stream.seekg(0, std::ios::end);+ ASSERT_TRUE(stream.good());+ EXPECT_EQ(static_cast<size_t>(stream.tellg()), k_size);+}++// 10. tellg() reflects the current position accurately after mixed reads/seeks.+TEST(ParallelMemStreamBufTest, TellgIsConsistent) {+ constexpr size_t k_size = 512;+ std::vector<char> src(k_size, 0xBBu);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/SIZE_MAX);+ std::istream stream(&buf);++ EXPECT_EQ(stream.tellg(), std::streampos(0));++ std::vector<char> tmp(100);+ stream.read(tmp.data(), 100);+ EXPECT_EQ(stream.tellg(), std::streampos(100));++ for (int i = 0; i < 10; ++i) {+ stream.get();+ }+ EXPECT_EQ(stream.tellg(), std::streampos(110));++ stream.seekg(200, std::ios::beg);+ EXPECT_EQ(stream.tellg(), std::streampos(200));+}++// 11. Out-of-range seek returns pos_type(-1).+TEST(ParallelMemStreamBufTest, OutOfRangeSeekFails) {+ constexpr size_t k_size = 64;+ std::vector<char> src(k_size, 0x55u);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/1);+ std::istream stream(&buf);++ const auto pos = stream.seekg(-1, std::ios::beg).tellg();+ EXPECT_EQ(pos, std::streampos(-1));+}++// 12. Partial read at EOF.+TEST(ParallelMemStreamBufTest, ReadAtEof) {+ constexpr size_t k_size = 80;+ std::vector<char> src(k_size);+ fill_pattern(src);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/SIZE_MAX);+ std::istream stream(&buf);++ std::vector<char> discard(k_size - 10);+ ASSERT_TRUE(stream.read((discard.data()), static_cast<std::streamsize>(k_size - 10)));++ std::vector<char> tail(20, 0xFFu);+ const bool ok = static_cast<bool>(stream.read((tail.data()), 20));+ EXPECT_FALSE(ok);+ EXPECT_TRUE(stream.eof());+ ASSERT_EQ(stream.gcount(), 10);+ EXPECT_TRUE(std::equal(tail.begin(), tail.begin() + 10, src.end() - 10));+}++// 13. showmanyc() / in_avail().+TEST(ParallelMemStreamBufTest, ShowmanycReflectsRemainingBytes) {+ constexpr size_t k_size = 256;+ std::vector<char> src(k_size, 0x77u);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/SIZE_MAX);+ std::istream stream(&buf);++ EXPECT_EQ(stream.rdbuf()->in_avail(), static_cast<std::streamsize>(k_size));++ std::vector<char> tmp(100);+ stream.read(tmp.data(), 100);+ EXPECT_EQ(stream.rdbuf()->in_avail(), static_cast<std::streamsize>(k_size - 100));++ std::vector<char> rest(k_size - 100);+ stream.read(rest.data(), static_cast<std::streamsize>(k_size - 100));+ EXPECT_EQ(stream.rdbuf()->in_avail(), -1);+}++// 14. Mixed underflow + bulk read.+TEST(ParallelMemStreamBufTest, MixedCharAndBulkRead) {+ constexpr size_t k_size = 1024;+ std::vector<char> src(k_size);+ fill_pattern(src);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/SIZE_MAX);+ std::istream stream(&buf);++ for (int i = 0; i < 8; ++i) {+ const int ch = stream.get();+ ASSERT_NE(ch, std::char_traits<char>::eof());+ EXPECT_EQ(static_cast<char>(ch), src[static_cast<size_t>(i)]);+ }++ std::vector<char> rest(k_size - 8);+ ASSERT_TRUE(stream.read((rest.data()), static_cast<std::streamsize>(k_size - 8)));+ EXPECT_EQ(rest, std::vector<char>(src.begin() + 8, src.end()));+}++// 15. Seek back to position 0 and re-read.+TEST(ParallelMemStreamBufTest, SeekToZeroAndReread) {+ constexpr size_t k_size = 1024;+ std::vector<char> src(k_size);+ fill_pattern(src);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/1);+ std::istream stream(&buf);++ std::vector<char> first(k_size);+ ASSERT_TRUE(stream.read((first.data()), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(first, src);++ stream.clear();+ stream.seekg(0, std::ios::beg);+ ASSERT_TRUE(stream.good());++ std::vector<char> second(k_size);+ ASSERT_TRUE(stream.read((second.data()), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(second, src);+}++// 16. Parallel path correctness with large buffer.+TEST(ParallelMemStreamBufTest, ParallelDispatchFullReadCorrectness) {+ const size_t k_max_hw = 16;+ const size_t hw_raw = std::max(size_t{2}, static_cast<size_t>(std::thread::hardware_concurrency()));+ const size_t hw = hw_raw > k_max_hw ? k_max_hw : hw_raw;+ const size_t k_size = 2u * hw * 2u * 1024u * 1024u + 1u;++ std::vector<char> src(k_size);+ fill_pattern(src);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/1);+ std::istream stream(&buf);++ std::vector<char> got(k_size);+ ASSERT_TRUE(stream.read((got.data()), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(got, src) << "Parallel memcpy produced incorrect data";+}++// 17. Parallel path with mid-stream seek.+TEST(ParallelMemStreamBufTest, ParallelDispatchSeekAndReread) {+ const size_t k_max_hw = 16;+ const size_t hw_raw = std::max(size_t{2}, static_cast<size_t>(std::thread::hardware_concurrency()));+ const size_t hw = hw_raw > k_max_hw ? k_max_hw : hw_raw;+ const size_t k_size = 2u * hw * 2u * 1024u * 1024u;++ std::vector<char> src(k_size);+ fill_pattern(src);++ ov::intel_gpu::ParallelMemStreamBuf buf(src.data(), k_size, /*threshold=*/1);+ std::istream stream(&buf);++ const size_t k_half = k_size / 2;+ std::vector<char> first_half(k_half);+ ASSERT_TRUE(stream.read((first_half.data()), static_cast<std::streamsize>(k_half)));+ EXPECT_TRUE(std::equal(first_half.begin(), first_half.end(), src.begin()));++ stream.seekg(0, std::ios::beg);+ ASSERT_TRUE(stream.good());++ std::vector<char> full(k_size);+ ASSERT_TRUE(stream.read((full.data()), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(full, src) << "Full read after seek produced incorrect data";+}++// 18. File-backed mmap detection: create a file, mmap it, pass the mmap+// pointer to ParallelMemStreamBuf, and verify correct data is returned.+// This exercises the get_mmap_file_info() detection + delegation to+// ParallelReadStreamBuf that is otherwise untested by in-memory tests.+#ifndef _WIN32+TEST(ParallelMemStreamBufTest, FileBackedMmapDetection) {+ constexpr size_t k_size = 16 * 1024; // 16 KB+ std::vector<char> expected(k_size);+ fill_pattern(expected);++ auto tmp_path = std::filesystem::temp_directory_path() / "par_mem_mmap_test.bin";+ {+ std::ofstream ofs(tmp_path, std::ios::binary | std::ios::trunc);+ ASSERT_TRUE(ofs.is_open()) << "Cannot create temp file: " << tmp_path;+ ofs.write(expected.data(), static_cast<std::streamsize>(k_size));+ }++ int fd = ::open(tmp_path.c_str(), O_RDONLY);+ ASSERT_NE(fd, -1) << "Cannot open temp file for mmap";+ void* mapped = ::mmap(nullptr, k_size, PROT_READ, MAP_PRIVATE, fd, 0);+ ::close(fd);+ ASSERT_NE(mapped, MAP_FAILED) << "mmap failed";++ {+ // threshold=1 so the constructor attempts mmap file detection on any size+ ov::intel_gpu::ParallelMemStreamBuf buf(mapped, k_size, /*threshold=*/1);+ std::istream stream(&buf);++ std::vector<char> got(k_size);+ ASSERT_TRUE(stream.read(got.data(), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(got, expected);++ // Verify seek + re-read works through the delegated ParallelReadStreamBuf+ stream.clear();+ stream.seekg(0, std::ios::beg);+ ASSERT_TRUE(stream.good());++ std::vector<char> got2(k_size);+ ASSERT_TRUE(stream.read(got2.data(), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(got2, expected);+ }++ ::munmap(mapped, k_size);+ std::filesystem::remove(tmp_path);+}++// 19. File-backed mmap with non-zero offset: mmap a file at a page-aligned+// offset and verify the detection correctly computes the file offset.+TEST(ParallelMemStreamBufTest, FileBackedMmapNonZeroOffset) {+ const size_t page_size = static_cast<size_t>(sysconf(_SC_PAGESIZE));+ const size_t k_prefix = page_size; // one page of prefix+ const size_t k_payload = 8 * 1024;+ const size_t k_total = k_prefix + k_payload;++ std::vector<char> file_content(k_total);+ // Fill prefix with 0xFF, payload with deterministic pattern+ std::memset(file_content.data(), 0xFF, k_prefix);+ for (size_t i = 0; i < k_payload; ++i) {+ file_content[k_prefix + i] = static_cast<char>((i) % 251u);+ }++ auto tmp_path = std::filesystem::temp_directory_path() / "par_mem_mmap_offset_test.bin";+ {+ std::ofstream ofs(tmp_path, std::ios::binary | std::ios::trunc);+ ASSERT_TRUE(ofs.is_open());+ ofs.write(file_content.data(), static_cast<std::streamsize>(k_total));+ }++ int fd = ::open(tmp_path.c_str(), O_RDONLY);+ ASSERT_NE(fd, -1);+ // mmap the entire file, then pass a pointer into the payload region+ void* mapped = ::mmap(nullptr, k_total, PROT_READ, MAP_PRIVATE, fd, 0);+ ::close(fd);+ ASSERT_NE(mapped, MAP_FAILED);++ const void* payload_ptr = static_cast<const char*>(mapped) + k_prefix;++ {+ ov::intel_gpu::ParallelMemStreamBuf buf(payload_ptr, k_payload, /*threshold=*/1);+ std::istream stream(&buf);++ std::vector<char> got(k_payload);+ ASSERT_TRUE(stream.read(got.data(), static_cast<std::streamsize>(k_payload)));+ // Verify we got the payload, not the prefix+ std::vector<char> expected_payload(file_content.begin() + k_prefix, file_content.end());+ EXPECT_EQ(got, expected_payload);+ }++ ::munmap(mapped, k_total);+ std::filesystem::remove(tmp_path);+}+#else // _WIN32+TEST(ParallelMemStreamBufTest, FileBackedMmapDetection) {+ constexpr size_t k_size = 16 * 1024;+ std::vector<char> expected(k_size);+ fill_pattern(expected);++ auto tmp_path = std::filesystem::temp_directory_path() / L"par_mem_mmap_test.bin";+ {+ std::ofstream ofs(tmp_path, std::ios::binary | std::ios::trunc);+ ASSERT_TRUE(ofs.is_open()) << "Cannot create temp file";+ ofs.write(expected.data(), static_cast<std::streamsize>(k_size));+ }++ HANDLE hFile = CreateFileW(tmp_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);+ ASSERT_NE(hFile, INVALID_HANDLE_VALUE) << "Cannot open temp file";+ HANDLE hMapping = CreateFileMappingW(hFile, nullptr, PAGE_READONLY, 0, 0, nullptr);+ ASSERT_NE(hMapping, nullptr) << "CreateFileMapping failed";+ void* mapped = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);+ ASSERT_NE(mapped, nullptr) << "MapViewOfFile failed";++ {+ ov::intel_gpu::ParallelMemStreamBuf buf(mapped, k_size, /*threshold=*/1);+ std::istream stream(&buf);++ std::vector<char> got(k_size);+ ASSERT_TRUE(stream.read(got.data(), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(got, expected);++ stream.clear();+ stream.seekg(0, std::ios::beg);+ ASSERT_TRUE(stream.good());++ std::vector<char> got2(k_size);+ ASSERT_TRUE(stream.read(got2.data(), static_cast<std::streamsize>(k_size)));+ EXPECT_EQ(got2, expected);+ }++ UnmapViewOfFile(mapped);+ CloseHandle(hMapping);+ CloseHandle(hFile);+ std::filesystem::remove(tmp_path);+}+#endif