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
[core] Allow ranged file view mapping (#34687)
Tomasz Jankowskiea616886410b
diff --git a/src/common/util/CMakeLists.txt b/src/common/util/CMakeLists.txtindex 9560103c325..01f453b6839 100644--- a/src/common/util/CMakeLists.txt+++ b/src/common/util/CMakeLists.txt@@ -31,7 +31,6 @@ set_source_files_properties(source_group("src" FILES ${LIBRARY_SRC})source_group("include" FILES ${PUBLIC_HEADERS})-# Create shared libraryadd_library(${TARGET_NAME} STATIC ${LIBRARY_SRC} ${PUBLIC_HEADERS})add_library(openvino::util ALIAS ${TARGET_NAME})diff --git a/src/common/util/include/openvino/util/mmap_object.hpp b/src/common/util/include/openvino/util/mmap_object.hppindex 6067584a1c7..dd5e95d2b14 100644--- a/src/common/util/include/openvino/util/mmap_object.hpp+++ b/src/common/util/include/openvino/util/mmap_object.hpp@@ -16,6 +16,10 @@namespace ov {+namespace util {+int64_t get_system_page_size();+} // namespace util+#ifdef _WIN32// Windows uses HANDLE (void*) for file handlesusing FileHandle = void*;@@ -37,15 +41,24 @@ public:virtual ~MappedMemory() = default;};+/**+ * @brief Generic constant to indicate automatic size calculation is required.+ */+inline constexpr auto auto_size = std::numeric_limits<size_t>::max();+/*** @brief Returns mapped memory for a file from provided path.* Instead of reading files, we can map the memory via mmap for Linux* in order to avoid time-consuming reading and reduce memory consumption.** @param path Path to a file which memory will be mmaped.+ * @param offset Offset in the file where the mapping starts.+ * @param size Size of the mapping. If size is std::numeric_limits<size_t>::max(), maps from offset to EOF.* @return MappedMemory shared ptr object which keep mmaped memory and control the lifetime.*/-std::shared_ptr<ov::MappedMemory> load_mmap_object(const std::filesystem::path& path);+std::shared_ptr<ov::MappedMemory> load_mmap_object(const std::filesystem::path& path,+ size_t offset = 0,+ size_t size = auto_size);/*** @brief Returns mapped memory for a file from provided file handle (cross-platform).@@ -54,12 +67,16 @@ std::shared_ptr<ov::MappedMemory> load_mmap_object(const std::filesystem::path&* Do not call load_mmap_object_from_handle directly, use the template wrapper instead.** @param handle Platform-specific file handle (int fd on Linux, HANDLE on Windows).+ * @param offset Offset in the file where the mapping starts.+ * @param size Size of the mapping. If size is std::numeric_limits<size_t>::max(), maps from offset to EOF.* @return MappedMemory shared ptr object which keep mmaped memory and control the lifetime.*/-std::shared_ptr<ov::MappedMemory> load_mmap_object_from_handle(FileHandle handle);+std::shared_ptr<ov::MappedMemory> load_mmap_object_from_handle(FileHandle handle,+ size_t offset = 0,+ size_t size = auto_size);template <typename T, std::enable_if_t<std::is_same<T, FileHandle>::value, int> = 0>-std::shared_ptr<ov::MappedMemory> load_mmap_object(T handle) {- return load_mmap_object_from_handle(static_cast<FileHandle>(handle));+std::shared_ptr<ov::MappedMemory> load_mmap_object(T handle, size_t offset = 0, size_t size = auto_size) {+ return load_mmap_object_from_handle(static_cast<FileHandle>(handle), offset, size);}} // namespace ovdiff --git a/src/common/util/src/os/lin/lin_mmap_object.cpp b/src/common/util/src/os/lin/lin_mmap_object.cppindex d3d974458d5..62c63a52245 100644--- a/src/common/util/src/os/lin/lin_mmap_object.cpp+++ b/src/common/util/src/os/lin/lin_mmap_object.cpp@@ -12,10 +12,17 @@#include <iostream>#include <sstream>+#include "openvino/util/common_util.hpp"#include "openvino/util/file_util.hpp"#include "openvino/util/mmap_object.hpp"namespace ov {+namespace util {+int64_t get_system_page_size() {+ static auto page_size = static_cast<int64_t>(sysconf(_SC_PAGE_SIZE));+ return page_size;+}+} // namespace utilclass HandleHolder {int m_handle = -1;@@ -56,7 +63,9 @@ public:};class MapHolder final : public MappedMemory {- void* m_data = MAP_FAILED;+ void* m_mapped_view = MAP_FAILED;+ size_t m_mapped_view_size = 0;+ void* m_data = nullptr;size_t m_size = 0;uint64_t m_id = std::numeric_limits<uint64_t>::max();HandleHolder m_handle;@@ -64,33 +73,44 @@ class MapHolder final : public MappedMemory {public:MapHolder() = default;- void set(const std::filesystem::path& path) {+ void set(const std::filesystem::path& path, const size_t offset, const size_t size) {int mode = O_RDONLY;int fd = open(path.c_str(), mode);if (fd == -1) {throw std::runtime_error("Can not open file " + util::path_to_string(path) +- " for mapping. Ensure that file exists and has appropriate permissions");+ " for mapping. Ensure that file exists and has appropriate permissions.");}- set_from_fd(fd);- m_id = std::hash<std::string>{}(path.native());+ set_from_fd(fd, offset, size);+ m_id = util::u64_hash_combine(offset, size);+ m_id = util::u64_hash_combine(std::hash<std::filesystem::path::string_type>{}(path.native()), m_id);}- void set_from_fd(const int fd) {- int prot = PROT_READ;- struct stat sb = {};+ void set_from_fd(const int fd, const size_t offset, const size_t size) {+ if (fd == -1) {+ throw std::runtime_error("Invalid file descriptor provided for mapping.");+ }m_handle = HandleHolder(fd);++ struct stat sb = {};if (fstat(fd, &sb) == -1) {throw std::runtime_error("Can not get file size for fd=" + std::to_string(fd));}- m_size = sb.st_size;+ const auto file_size = static_cast<size_t>(sb.st_size);+ m_size = (size == auto_size) ? file_size - offset : size;+ if (offset + m_size > file_size || offset + m_size < offset) {+ throw std::runtime_error("Requested mapping range exceeds file size for fd=" + std::to_string(fd));+ }+if (m_size > 0) {- m_data = mmap(nullptr, m_size, prot, MAP_SHARED, fd, 0);- if (m_data == MAP_FAILED) {+ const auto page_size = util::get_system_page_size();+ const auto aligned_offset = (offset / page_size) * page_size;+ m_mapped_view_size = offset + m_size - aligned_offset;+ m_mapped_view = mmap(nullptr, m_mapped_view_size, PROT_READ, MAP_SHARED, fd, aligned_offset);+ if (m_mapped_view == MAP_FAILED) {throw std::runtime_error("Can not create file mapping for " + std::to_string(fd) +", err=" + std::strerror(errno));}- } else {- m_data = MAP_FAILED;+ m_data = static_cast<char*>(m_mapped_view) + (offset - aligned_offset);}}@@ -99,8 +119,8 @@ public:}~MapHolder() {- if (m_data != MAP_FAILED) {- munmap(m_data, m_size);+ if (m_mapped_view != MAP_FAILED) {+ munmap(m_mapped_view, m_mapped_view_size);}}@@ -113,17 +133,15 @@ public:}};-std::shared_ptr<ov::MappedMemory> load_mmap_object(const std::filesystem::path& path) {+std::shared_ptr<MappedMemory> load_mmap_object(const std::filesystem::path& path, size_t offset, size_t size) {auto holder = std::make_shared<MapHolder>();- holder->set(path);+ holder->set(path, offset, size);return holder;}-std::shared_ptr<ov::MappedMemory> load_mmap_object_from_handle(FileHandle handle) {- // On Linux, FileHandle is int (file descriptor)+std::shared_ptr<ov::MappedMemory> load_mmap_object_from_handle(FileHandle handle, size_t offset, size_t size) {auto holder = std::make_shared<MapHolder>();- holder->set_from_fd(static_cast<int>(handle));+ holder->set_from_fd(handle, offset, size);return holder;}-} // namespace ovdiff --git a/src/common/util/src/os/win/win_mmap_object.cpp b/src/common/util/src/os/win/win_mmap_object.cppindex 6eecefab2fa..6155e0f4f33 100644--- a/src/common/util/src/os/win/win_mmap_object.cpp+++ b/src/common/util/src/os/win/win_mmap_object.cpp@@ -4,6 +4,7 @@#include <stdexcept>+#include "openvino/util/common_util.hpp"#include "openvino/util/file_util.hpp"#include "openvino/util/mmap_object.hpp"@@ -15,6 +16,16 @@// clang-format-onnamespace ov {+namespace util {+int64_t get_system_page_size() {+ static auto page_size = []() {+ SYSTEM_INFO sysInfo;+ GetSystemInfo(&sysInfo);+ return static_cast<int64_t>(sysInfo.dwPageSize);+ }();+ return page_size;+}+} // namespace utilclass HandleHolder {HANDLE m_handle = INVALID_HANDLE_VALUE;@@ -56,21 +67,22 @@ public:MapHolder() = default;~MapHolder() {- if (m_data) {- ::UnmapViewOfFile(m_data);+ if (m_mapped_view) {+ ::UnmapViewOfFile(m_mapped_view);}}- void set(const std::filesystem::path& path) {+ void set(const std::filesystem::path& path, size_t offset, size_t size) {// Note that file can't be changed (renamed/deleted) until it's unmapped. FILE_SHARE_DELETE flag allow// rename/deletion, but it doesn't work with FAT32 filesystem (works on NTFS)auto h = ::CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);- map(path, h);- m_id = std::hash<std::wstring>{}(path.native());+ map(path, h, offset, size);+ m_id = util::u64_hash_combine(offset, size);+ m_id = util::u64_hash_combine(std::hash<std::filesystem::path::string_type>{}(path.native()), m_id);}- void set_from_handle(HANDLE h) {- map("<external_handle>", h);+ void set_from_handle(HANDLE h, size_t offset, size_t size) {+ map("<external_handle>", h, offset, size);}char* data() noexcept override {@@ -85,43 +97,50 @@ public:}private:- void map(const std::filesystem::path& path, HANDLE h) {+ void map(const std::filesystem::path& path, HANDLE h, const size_t offset, const size_t size) {if (h == INVALID_HANDLE_VALUE) {throw std::runtime_error("Can not open file " + util::path_to_string(path) +" for mapping. Ensure that file exists and has appropriate permissions");}m_handle = HandleHolder(h);- DWORD map_mode = FILE_MAP_READ;- DWORD access = PAGE_READONLY;-LARGE_INTEGER file_size_large;if (::GetFileSizeEx(m_handle.get(), &file_size_large) == 0) {- throw std::runtime_error("Can not get file size for " + util::path_to_string(path));+ throw std::runtime_error("Can not get file size for " + util::path_to_string(path) + ". Error " ++ std::to_string(::GetLastError()));+ }+ const auto file_size = static_cast<size_t>(file_size_large.QuadPart);+ m_size = (size == auto_size) ? file_size - offset : size;+ if (offset + m_size > file_size || offset + m_size < offset) {+ throw std::runtime_error("Requested mapping range exceeds file size for " + util::path_to_string(path));}- m_size = static_cast<uint64_t>(file_size_large.QuadPart);if (m_size > 0) {- m_mapping =- HandleHolder(::CreateFileMapping(m_handle.get(), 0, access, m_size >> 32, m_size & 0xffffffff, 0));+ m_mapping = HandleHolder(::CreateFileMapping(m_handle.get(), 0, PAGE_READONLY, 0, 0, 0));if (m_mapping.get() == INVALID_HANDLE_VALUE) {throw std::runtime_error("Can not create file mapping for " + util::path_to_string(path));}- m_data = ::MapViewOfFile(m_mapping.get(),- map_mode,- 0, // offset_align >> 32,- 0, // offset_align & 0xffffffff,- m_size);- if (!m_data) {- throw std::runtime_error("Can not create map view for " + util::path_to_string(path));+ SYSTEM_INFO system_info;+ ::GetSystemInfo(&system_info);+ const auto aligned_offset =+ (offset / system_info.dwAllocationGranularity) * system_info.dwAllocationGranularity;+ const auto aligned_size = offset + m_size - aligned_offset;+ m_mapped_view = ::MapViewOfFile(m_mapping.get(),+ FILE_MAP_READ,+ aligned_offset >> 32,+ aligned_offset & 0xffffffff,+ aligned_size);+ if (!m_mapped_view) {+ throw std::runtime_error("Can not create map view for " + util::path_to_string(path) + ". Error " ++ std::to_string(::GetLastError()));}- } else {- m_data = nullptr;+ m_data = reinterpret_cast<char*>(m_mapped_view) + (offset - aligned_offset);}}private:+ void* m_mapped_view = nullptr;void* m_data = nullptr;size_t m_size = 0;uint64_t m_id = std::numeric_limits<uint64_t>::max();@@ -129,22 +148,18 @@ private:HandleHolder m_mapping;};-std::shared_ptr<ov::MappedMemory> load_mmap_object(const std::filesystem::path& path) {+std::shared_ptr<MappedMemory> load_mmap_object(const std::filesystem::path& path, size_t offset, size_t size) {auto holder = std::make_shared<MapHolder>();- holder->set(path);+ holder->set(path, offset, size);return holder;}-std::shared_ptr<ov::MappedMemory> load_mmap_object_from_handle(FileHandle handle) {- // On Windows, FileHandle is void* (HANDLE)- HANDLE h = static_cast<HANDLE>(handle);- if (h == INVALID_HANDLE_VALUE || h == nullptr) {+std::shared_ptr<ov::MappedMemory> load_mmap_object_from_handle(FileHandle handle, size_t offset, size_t size) {+ if (handle == INVALID_HANDLE_VALUE || handle == nullptr) {throw std::runtime_error("Invalid handle provided to load_mmap_object");}-auto holder = std::make_shared<MapHolder>();- holder->set_from_handle(h);+ holder->set_from_handle(handle, offset, size);return holder;}-} // namespace ovdiff --git a/src/core/src/runtime/tensor.cpp b/src/core/src/runtime/tensor.cppindex 65b2f5fe6f2..1058ab242e8 100644--- a/src/core/src/runtime/tensor.cpp+++ b/src/core/src/runtime/tensor.cpp@@ -136,16 +136,16 @@ bool Tensor::is_continuous() const {}namespace {-ov::Shape calc_static_shape_for_file(size_t file_size,+ov::Shape calc_static_shape_for_file(size_t max_size,const ov::element::Type& element_type,const ov::PartialShape& partial_shape,size_t offset) {if (partial_shape.is_static()) {auto static_shape = partial_shape.get_shape();const auto memory_size = ov::util::get_memory_size_safe(element_type, static_shape);- OPENVINO_ASSERT(memory_size && *memory_size + offset <= file_size,- "Requested space exceeds file bounds: file size=",- file_size,+ OPENVINO_ASSERT(memory_size && *memory_size + offset <= max_size,+ "Requested space exceeds available bounds: available bytes=",+ max_size," offset=",offset," requested size=",@@ -164,25 +164,26 @@ ov::Shape calc_static_shape_for_file(size_t file_size,slice_size *= partial_shape_copy[id].get_min_length();}}- OPENVINO_ASSERT(slice_size > 0, "Cannot fit file size into requested PartialShape");+ OPENVINO_ASSERT(slice_size > 0, "Cannot fit available bytes into requested PartialShape");OPENVINO_ASSERT(dynamic_dimension_numbers.size() == 1,"Only one dynamic dimension in input shape is supported but got: ",dynamic_dimension_numbers.size());auto& dynamic_dimension = partial_shape_copy[dynamic_dimension_numbers[0]];- auto file_size_to_read = file_size - offset;+ auto max_size_to_read = max_size - offset;- OPENVINO_ASSERT((file_size_to_read * 8) % element_type.bitwidth() == 0,+ OPENVINO_ASSERT((max_size_to_read * 8) % element_type.bitwidth() == 0,"cannot fit ",element_type.get_type_name()," into ",- file_size_to_read,+ max_size_to_read," bytes");- auto elements_to_read = file_size_to_read * 8 / element_type.bitwidth();+ auto elements_to_read = max_size_to_read * 8 / element_type.bitwidth();auto new_dimension = ov::Dimension(elements_to_read) / slice_size;- OPENVINO_ASSERT(dynamic_dimension.compatible(new_dimension), "Cannot fit file size into requested PartialShape");+ OPENVINO_ASSERT(dynamic_dimension.compatible(new_dimension),+ "Cannot fit available bytes into requested PartialShape");dynamic_dimension = std::move(new_dimension);return partial_shape_copy.get_shape();@@ -212,14 +213,28 @@ Tensor read_tensor_data_mmap_impl(std::shared_ptr<ov::MappedMemory> mapped_memorconst ov::element::Type& element_type,const ov::PartialShape& partial_shape,size_t offset_in_bytes) {- auto static_shape = calc_static_shape_for_file(mapped_memory->size(), element_type, partial_shape, offset_in_bytes);- auto shared_buffer =- std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::MappedMemory>>>(mapped_memory->data() + offset_in_bytes,- mapped_memory->size() - offset_in_bytes,+ const auto max_size = offset_in_bytes + mapped_memory->size();+ const auto static_shape = calc_static_shape_for_file(max_size, element_type, partial_shape, offset_in_bytes);+ const auto shared_buffer =+ std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::MappedMemory>>>(mapped_memory->data(),+ mapped_memory->size(),mapped_memory);-return wrap_obj_to_viewtensor(shared_buffer, shared_buffer->get_ptr(), element_type, static_shape);}++size_t get_size_for_mapping(const ov::element::Type& element_type, const ov::PartialShape& partial_shape) {+ if (partial_shape.is_static()) {+ const auto memory_size = ov::util::get_memory_size_safe(element_type, partial_shape.get_shape());+ OPENVINO_ASSERT(memory_size,+ "Cannot calculate memory size for provided element type ",+ element_type,+ " and shape ",+ partial_shape);+ return *memory_size;+ } else {+ return auto_size;+ }+}} // namespaceTensor read_tensor_data(const std::filesystem::path& file_name,@@ -229,7 +244,8 @@ Tensor read_tensor_data(const std::filesystem::path& file_name,bool mmap) {OPENVINO_ASSERT(element_type != ov::element::string);if (mmap) {- return read_tensor_data_mmap_impl(ov::load_mmap_object(file_name),+ const auto size = get_size_for_mapping(element_type, partial_shape);+ return read_tensor_data_mmap_impl(load_mmap_object(file_name, offset_in_bytes, size),element_type,partial_shape,offset_in_bytes);@@ -247,6 +263,10 @@ Tensor read_tensor_data(ov::FileHandle file_handle,const ov::PartialShape& partial_shape,size_t offset_in_bytes) {OPENVINO_ASSERT(element_type != ov::element::string);- return read_tensor_data_mmap_impl(ov::load_mmap_object(file_handle), element_type, partial_shape, offset_in_bytes);+ const auto size = get_size_for_mapping(element_type, partial_shape);+ return read_tensor_data_mmap_impl(load_mmap_object(file_handle, offset_in_bytes, size),+ element_type,+ partial_shape,+ offset_in_bytes);}} // namespace ovdiff --git a/src/core/tests/mmap_object.cpp b/src/core/tests/mmap_object.cppnew file mode 100644index 00000000000..374bf44eec6--- /dev/null+++ b/src/core/tests/mmap_object.cpp@@ -0,0 +1,232 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/util/mmap_object.hpp"++#include <gtest/gtest.h>++#include <algorithm>+#include <filesystem>+#include <iostream>+#include <sstream>++#include "common_test_utils/common_utils.hpp"+#include "common_test_utils/file_utils.hpp"++namespace ov::test {+TEST(MappedMemory, get_id_unique_per_file) {+ // Create two temporary files+ std::filesystem::path file1 = utils::generateTestFilePrefix() + "_file1";+ std::filesystem::path file2 = utils::generateTestFilePrefix() + "_file2";++ const char test_data[] = "Test data for MappedMemory";++ // Write same data to both files+ {+ std::ofstream os1(file1, std::ios::binary);+ os1.write(test_data, sizeof(test_data));++ std::ofstream os2(file2, std::ios::binary);+ os2.write(test_data, sizeof(test_data));+ }++ {+ // Load both files+ auto mapped1 = load_mmap_object(file1);+ auto mapped2 = load_mmap_object(file2);++ ASSERT_NE(mapped1, nullptr);+ ASSERT_NE(mapped2, nullptr);++ // IDs should be different even though content is the same (ID is hash of file path)+ EXPECT_NE(mapped1->get_id(), mapped2->get_id());+ }+ // Clean up+ std::filesystem::remove(file1);+ std::filesystem::remove(file2);+}++TEST(MappedMemory, get_id_same_for_same_file) {+ std::filesystem::path file_path = utils::generateTestFilePrefix() + "_same_file";+ const char test_data[] = "Test data for same file";++ // Create file+ {+ std::ofstream os(file_path, std::ios::binary);+ os.write(test_data, sizeof(test_data));+ }++ {+ // Load the same file twice+ auto mapped1 = load_mmap_object(file_path);+ auto mapped2 = load_mmap_object(file_path);++ ASSERT_NE(mapped1, nullptr);+ ASSERT_NE(mapped2, nullptr);++ // IDs should be the same for the same file path+ EXPECT_EQ(mapped1->get_id(), mapped2->get_id());+ }+ // Clean up+ std::filesystem::remove(file_path);+}++struct RangedMappingTestRegions {+ size_t offset_1;+ size_t size_1;+ size_t offset_2;+ size_t size_2;+ size_t file_size;+};+// regions, use file path (true) or file handle (false)+using RangedMappingTestParams = std::tuple<RangedMappingTestRegions, bool>;++namespace {+size_t calc_sector_actual_size(size_t offset, size_t size, size_t file_actual_size) {+ return size == auto_size ? file_actual_size - offset : size;+}+} // namespace++class RangedMappingTest : public ::testing::TestWithParam<RangedMappingTestParams> {+protected:+ std::filesystem::path m_file_path;+ std::vector<char> m_sector_1, m_sector_2;++ void SetUp() override {+ const auto& [regions, use_file_path] = GetParam();+ const auto& [offset_1, size_1, offset_2, size_2, file_size] = regions;++ const auto actual_size_1 = calc_sector_actual_size(offset_1, size_1, file_size);+ const auto actual_size_2 = calc_sector_actual_size(offset_2, size_2, file_size);+ ASSERT_GT(file_size, 0);+ ASSERT_LE(offset_1 + actual_size_1, file_size);+ ASSERT_LE(offset_2 + actual_size_2, file_size);++ m_file_path = utils::generateTestFilePrefix();+ std::fstream s(m_file_path, std::ios::binary | std::ios::in | std::ios::out | std::ios::trunc);+ ASSERT_TRUE(s.is_open());+ for (size_t i = 0; i < file_size; ++i) {+ s.put('_');+ }+ ASSERT_TRUE(s.good());+ s.seekp(offset_1);+ for (size_t i = 0; i < actual_size_1; ++i) {+ s.put('A' + i % 26);+ }+ s.seekp(offset_2);+ for (size_t i = 0; i < actual_size_2; ++i) {+ s.put('a' + i % 26);+ }+ // sectors may overlap, so read these after all+ m_sector_1.resize(actual_size_1);+ m_sector_2.resize(actual_size_2);+ s.seekg(offset_1);+ s.read(m_sector_1.data(), actual_size_1);+ s.seekg(offset_2);+ s.read(m_sector_2.data(), actual_size_2);+ ASSERT_TRUE(s.good());+ }++ void TearDown() override {+ std::filesystem::remove(m_file_path);+ }++public:+ static std::string test_name(const testing::TestParamInfo<RangedMappingTestParams>& info) {+ const auto& [regions, use_file_path] = info.param;+ const auto& [offset_1, size_1, offset_2, size_2, file_size] = regions;+ const auto actual_size_1 = calc_sector_actual_size(offset_1, size_1, file_size);+ const auto actual_size_2 = calc_sector_actual_size(offset_2, size_2, file_size);+ std::ostringstream ss;+ ss << "offset1_" << offset_1 << "_size1_" << std::to_string(actual_size_1) << "_offset2_" << offset_2+ << "_size2_" << std::to_string(actual_size_2) << "_file_size_" << std::to_string(file_size)+ << (use_file_path ? "_file_path" : "_file_handle");+ return ss.str();+ }+};++TEST_P(RangedMappingTest, compare_data) {+ const auto& [regions, use_file_path] = GetParam();+ const auto& [offset_1, size_1, offset_2, size_2, file_size] = regions;+ std::shared_ptr<MappedMemory> mm_1, mm_2;++ if (use_file_path) {+ mm_1 = load_mmap_object(m_file_path, offset_1, size_1);+ mm_2 = load_mmap_object(m_file_path, offset_2, size_2);+ } else {+ const auto handle_1 = utils::open_ro_file(m_file_path);+ const auto handle_2 = utils::open_ro_file(m_file_path);+ mm_1 = load_mmap_object_from_handle(handle_1, offset_1, size_1);+ mm_2 = load_mmap_object_from_handle(handle_2, offset_2, size_2);+ }+ ASSERT_NE(mm_1, nullptr);+ ASSERT_NE(mm_2, nullptr);++ EXPECT_EQ(mm_1->size(), m_sector_1.size());+ EXPECT_EQ(mm_2->size(), m_sector_2.size());+ EXPECT_EQ(m_sector_1, std::vector<char>(mm_1->data(), mm_1->data() + mm_1->size()));+ EXPECT_EQ(m_sector_2, std::vector<char>(mm_2->data(), mm_2->data() + mm_2->size()));+}++TEST_P(RangedMappingTest, compare_id) {+ const auto& [regions, use_file_path] = GetParam();+ if (!use_file_path) {+ GTEST_SKIP(); // CVS-182260+ }+ const auto& [offset_1, size_1, offset_2, size_2, file_size] = regions;++ std::filesystem::path other_file_path = utils::generateTestFilePrefix();+ std::error_code ec;+ std::filesystem::copy_file(m_file_path, other_file_path, ec);+ ASSERT_FALSE(ec) << "Failed to copy file \"" << m_file_path << "\" for test setup: " << ec.message();++ std::shared_ptr<MappedMemory> mm_1, mm_2, other_mm_1, other_mm_2, mm_1_;+ if (use_file_path) {+ mm_1 = load_mmap_object(m_file_path, offset_1, size_1);+ mm_2 = load_mmap_object(m_file_path, offset_2, size_2);+ other_mm_1 = load_mmap_object(other_file_path, offset_1, size_1);+ other_mm_2 = load_mmap_object(other_file_path, offset_2, size_2);+ mm_1_ = load_mmap_object(m_file_path, offset_1, size_1);+ } else {+ const auto handle_1 = utils::open_ro_file(m_file_path);+ const auto handle_2 = utils::open_ro_file(m_file_path);+ const auto other_handle = utils::open_ro_file(other_file_path);+ mm_1 = load_mmap_object_from_handle(handle_1, offset_1, size_1);+ mm_2 = load_mmap_object_from_handle(handle_2, offset_2, size_2);+ other_mm_1 = load_mmap_object_from_handle(other_handle, offset_1, size_1);+ other_mm_2 = load_mmap_object_from_handle(other_handle, offset_2, size_2);+ mm_1_ = load_mmap_object_from_handle(handle_1, offset_1, size_1);+ }++ ASSERT_NE(mm_1, nullptr);+ ASSERT_NE(mm_2, nullptr);+ ASSERT_NE(other_mm_1, nullptr);+ ASSERT_NE(other_mm_2, nullptr);+ ASSERT_NE(mm_1_, nullptr);++ EXPECT_NE(mm_1->get_id(), mm_2->get_id());+ EXPECT_NE(mm_1->get_id(), other_mm_1->get_id());+ EXPECT_NE(mm_2->get_id(), other_mm_2->get_id());+ EXPECT_EQ(mm_1->get_id(), mm_1_->get_id());+}++static const auto pg_sz = []() {+ const auto sz = util::get_system_page_size();+ return sz > 0 ? static_cast<size_t>(sz) : size_t{4096};+}();+INSTANTIATE_TEST_SUITE_P(MappedMemory,+ RangedMappingTest,+ ::testing::Combine(::testing::ValuesIn(std::vector<RangedMappingTestRegions>{+ {pg_sz, 127, 2 * pg_sz, 101, (2 * pg_sz + 101)},+ {0, 3 * pg_sz, 7 * pg_sz, 1024, (7 * pg_sz + 1024)},+ {0, pg_sz, pg_sz, pg_sz, (2 * pg_sz)},+ {100, 50, 150, 30, 180},+ {1, auto_size, 0, auto_size, pg_sz},+ {0, 40, 0, 41, 42},+ {11, auto_size, 17, 80, 101},+ {10, auto_size, 0, 90, 100}}),+ ::testing::ValuesIn(std::vector<bool>{true, false})),+ RangedMappingTest::test_name);++} // namespace ov::testdiff --git a/src/core/tests/shared_buffer.cpp b/src/core/tests/shared_buffer.cppindex 164702fc576..0686263fd25 100644--- a/src/core/tests/shared_buffer.cpp+++ b/src/core/tests/shared_buffer.cpp@@ -345,65 +345,6 @@ TEST_F(SharedBufferTest, aligned_buffer_interface) {EXPECT_EQ(aligned->get_ptr(), test_data);}-// ==================== MappedMemory get_id Tests ====================--TEST(MappedMemory, get_id_unique_per_file) {- // Create two temporary files- std::filesystem::path file1 = ov::test::utils::generateTestFilePrefix() + "_file1";- std::filesystem::path file2 = ov::test::utils::generateTestFilePrefix() + "_file2";-- const char test_data[] = "Test data for MappedMemory";-- // Write same data to both files- {- std::ofstream os1(file1, std::ios::binary);- os1.write(test_data, sizeof(test_data));-- std::ofstream os2(file2, std::ios::binary);- os2.write(test_data, sizeof(test_data));- }-- {- // Load both files- auto mapped1 = ov::load_mmap_object(file1);- auto mapped2 = ov::load_mmap_object(file2);-- ASSERT_NE(mapped1, nullptr);- ASSERT_NE(mapped2, nullptr);-- // IDs should be different even though content is the same (ID is hash of file path)- EXPECT_NE(mapped1->get_id(), mapped2->get_id());- }- // Clean up- std::filesystem::remove(file1);- std::filesystem::remove(file2);-}--TEST(MappedMemory, get_id_same_for_same_file) {- std::filesystem::path file_path = ov::test::utils::generateTestFilePrefix() + "_same_file";- const char test_data[] = "Test data for same file";-- // Create file- {- std::ofstream os(file_path, std::ios::binary);- os.write(test_data, sizeof(test_data));- }-- {- // Load the same file twice- auto mapped1 = ov::load_mmap_object(file_path);- auto mapped2 = ov::load_mmap_object(file_path);-- ASSERT_NE(mapped1, nullptr);- ASSERT_NE(mapped2, nullptr);-- // IDs should be the same for the same file path- EXPECT_EQ(mapped1->get_id(), mapped2->get_id());- }- // Clean up- std::filesystem::remove(file_path);-}-// ==================== SharedBuffer with explicit descriptor Tests ====================TEST_F(SharedBufferTest, shared_ptr_void_with_explicit_descriptor) {diff --git a/src/core/tests/tensor_utils.cpp b/src/core/tests/tensor_utils.cppindex 52cc782610d..1ba5f4ae906 100644--- a/src/core/tests/tensor_utils.cpp+++ b/src/core/tests/tensor_utils.cpp@@ -4,6 +4,7 @@#include "common_test_utils/common_utils.hpp"#include "common_test_utils/data_utils.hpp"+#include "common_test_utils/test_assertions.hpp"#include "openvino/core/type/element_iterator.hpp"#include "openvino/op/constant.hpp"#include "openvino/reference/convert.hpp"@@ -146,22 +147,38 @@ TEST_F(FunctionalOffloadTensorTest, read_small_file) {auto new_shape = shape;new_shape[0] = 10;{- EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, new_shape, 0), ov::Exception);- EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, new_shape, 0, false), ov::Exception);+ OV_EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, new_shape, 0),+ std::runtime_error,+ ::testing::HasSubstr("Requested mapping range exceeds"));+ OV_EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, new_shape, 0, false),+ AssertFailure,+ ::testing::HasSubstr("Requested space exceeds available bounds"));}}TEST_F(FunctionalOffloadTensorTest, read_too_big_offset) {{// offset + data_size > file_size- EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, shape, 1), ov::Exception);- EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, shape, 1, false), ov::Exception);+ OV_EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, shape, 1),+ std::runtime_error,+ ::testing::HasSubstr("Requested mapping range exceeds"));+ OV_EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, shape, 1, false),+ AssertFailure,+ ::testing::HasSubstr("Requested space exceeds available bounds"));// offset == file_size- EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, shape, data_size), ov::Exception);- EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, shape, data_size, false), ov::Exception);+ OV_EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, shape, data_size),+ std::runtime_error,+ ::testing::HasSubstr("Requested mapping range exceeds"));+ OV_EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, shape, data_size, false),+ AssertFailure,+ ::testing::HasSubstr("Requested space exceeds available bounds"));// offset > file_size- EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, shape, data_size + 1), ov::Exception);- EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, shape, data_size + 1, false), ov::Exception);+ OV_EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, shape, data_size + 1),+ std::runtime_error,+ ::testing::HasSubstr("Requested mapping range exceeds"));+ OV_EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov_type, shape, data_size + 1, false),+ AssertFailure,+ ::testing::HasSubstr("Requested space exceeds available bounds"));}}diff --git a/src/inference/dev_api/openvino/runtime/single_file_storage.hpp b/src/inference/dev_api/openvino/runtime/single_file_storage.hppindex f9c01f56838..3b917390282 100644--- a/src/inference/dev_api/openvino/runtime/single_file_storage.hpp+++ b/src/inference/dev_api/openvino/runtime/single_file_storage.hpp@@ -63,6 +63,8 @@ public:using DataIdType = uint64_t;using PadSizeType = uint64_t;+ static const size_t blob_alignment;+private:std::filesystem::path m_file_path;diff --git a/src/inference/src/single_file_storage.cpp b/src/inference/src/single_file_storage.cppindex 0cf903597d9..c97291c7cd5 100644--- a/src/inference/src/single_file_storage.cpp+++ b/src/inference/src/single_file_storage.cpp@@ -4,12 +4,6 @@#include "openvino/runtime/single_file_storage.hpp"-#ifdef _WIN32-# include <windows.h>-#else-# include <unistd.h>-#endif-#include "openvino/runtime/aligned_buffer.hpp"#include "openvino/util/file_util.hpp"#include "openvino/util/mmap_object.hpp"@@ -47,16 +41,6 @@ void write_tlv_string(std::ostream& stream, const std::string& str) {write_tlv_record(stream, static_cast<TLVTraits::TagType>(SingleFileStorage::Tag::String), str.size(), str.data());}-static const uint64_t alignment = []() {-#ifdef _WIN32- SYSTEM_INFO sysInfo;- GetSystemInfo(&sysInfo);- return static_cast<uint64_t>(sysInfo.dwPageSize);-#else- return static_cast<uint64_t>(sysconf(_SC_PAGE_SIZE));-#endif-}();-bool read_tlv_string(std::istream& stream, std::string& str) {TLVTraits::TagType tag;TLVTraits::LengthType size;@@ -83,6 +67,11 @@ void write_padding(std::ostream& stream, uint64_t alignment) {}} // namespace+const size_t SingleFileStorage::blob_alignment = []() {+ const auto sz = util::get_system_page_size();+ return sz > 0 ? static_cast<size_t>(sz) : size_t{1};+}();+SingleFileStorage::SingleFileStorage(const std::filesystem::path& path): m_file_path{path},m_blob_index{},@@ -235,7 +224,7 @@ void SingleFileStorage::write_blob_entry(std::ofstream& stream, BlobIdType blob_const auto blob_writer = [&](std::ostream& s) {s.write(reinterpret_cast<const char*>(&blob_id), sizeof(blob_id));- write_padding(s, alignment);+ write_padding(s, blob_alignment);blob_pos = s.tellp();writer(s);blob_size = s.tellp() - blob_pos;@@ -335,7 +324,7 @@ void SingleFileStorage::write_context(const weight_sharing::Context& context) {const auto device_id = static_cast<uint64_t>(std::strtoul(weight_buffer.m_device.c_str(), nullptr, 10));s.write(reinterpret_cast<const char*>(&device_id), sizeof(device_id));s.write(reinterpret_cast<const char*>(&source_id), sizeof(source_id));- write_padding(s, alignment);+ write_padding(s, blob_alignment);s.write(reinterpret_cast<const char*>(buf->get_ptr()), buf->size());}diff --git a/src/inference/tests/unit/single_file_storage.cpp b/src/inference/tests/unit/single_file_storage.cppindex 1c427da1888..c839c2ea0d3 100644--- a/src/inference/tests/unit/single_file_storage.cpp+++ b/src/inference/tests/unit/single_file_storage.cpp@@ -6,16 +6,11 @@#include <gtest/gtest.h>-#ifdef _WIN32-# include <windows.h>-#else-# include <unistd.h>-#endif-#include "common_test_utils/common_utils.hpp"#include "common_test_utils/file_utils.hpp"#include "common_test_utils/test_assertions.hpp"#include "openvino/runtime/aligned_buffer.hpp"+#include "openvino/util/mmap_object.hpp"namespace ov::test {@@ -25,16 +20,6 @@ namespace {constexpr uint64_t version_size() {return 3 * sizeof(uint16_t); // major, minor, patch}--std::streamoff get_system_page_size() {-#ifdef _WIN32- SYSTEM_INFO sysInfo;- GetSystemInfo(&sysInfo);- return static_cast<std::streamoff>(sysInfo.dwPageSize);-#else- return static_cast<std::streamoff>(sysconf(_SC_PAGE_SIZE));-#endif-}} // namespaceclass SingleFileStorageTest : public ::testing::Test {@@ -135,8 +120,6 @@ TEST_F(SingleFileStorageTest, BlobAlignment) {const auto stream_end = stream.tellg();stream.seekg(version_size(), std::ios::beg);- const auto alignment = get_system_page_size();-while (stream.good() && stream.tellg() < stream_end) {SingleFileStorage::Tag tag;runtime::TLVTraits::LengthType length;@@ -155,7 +138,8 @@ TEST_F(SingleFileStorageTest, BlobAlignment) {stream.seekg(padding_size, std::ios::cur);const auto blob_data_pos = stream.tellg();- EXPECT_EQ(blob_data_pos % alignment, 0) << "Blob with id " << id << " is not properly aligned";+ EXPECT_EQ(blob_data_pos % SingleFileStorage::blob_alignment, 0)+ << "Blob with id " << id << " is not properly aligned";const auto expected_pos = blob_id_pos + static_cast<std::streamoff>(length);stream.seekg(test_blobs.at(id).size(), std::ios::cur);@@ -270,8 +254,6 @@ TEST_F(SingleFileStorageTest, ContextWeightSourceWrite) {const auto stream_end = stream.tellg();stream.seekg(version_size(), std::ios::beg);- const auto alignment = get_system_page_size();-while (stream.good() && stream.tellg() < stream_end) {SingleFileStorage::Tag tag;runtime::TLVTraits::LengthType length;@@ -289,7 +271,7 @@ TEST_F(SingleFileStorageTest, ContextWeightSourceWrite) {stream.seekg(padding_size, std::ios::cur);const auto weight_pos = stream.tellg();- ASSERT_EQ(weight_pos % alignment, 0);+ ASSERT_EQ(weight_pos % SingleFileStorage::blob_alignment, 0);const auto weight_size =length - sizeof(device_id) - sizeof(source_id) - sizeof(padding_size) - padding_size;ASSERT_EQ(weight_size, buffer->size());diff --git a/src/tests/test_utils/common_test_utils/include/common_test_utils/file_utils.hpp b/src/tests/test_utils/common_test_utils/include/common_test_utils/file_utils.hppindex 4bb26053bdd..da860ebb392 100644--- a/src/tests/test_utils/common_test_utils/include/common_test_utils/file_utils.hpp+++ b/src/tests/test_utils/common_test_utils/include/common_test_utils/file_utils.hpp@@ -349,4 +349,11 @@ using StringPathVariant = std::variant<std::string, std::u16string, std::u32stristd::filesystem::path to_fs_path(const StringPathVariant& param);+/**+ * @brief Opens file in read-only mode+ * @param path file path+ * @return file handle+ */+FileHandle open_ro_file(const std::filesystem::path& path);+} // namespace ov::test::utilsdiff --git a/src/tests/test_utils/common_test_utils/src/file_utils.cpp b/src/tests/test_utils/common_test_utils/src/file_utils.cppindex 883ac1943cc..ff7f95105f5 100644--- a/src/tests/test_utils/common_test_utils/src/file_utils.cpp+++ b/src/tests/test_utils/common_test_utils/src/file_utils.cpp@@ -17,6 +17,7 @@# include <windows.h>#else# include <dlfcn.h>+# include <fcntl.h># include <limits.h># include <unistd.h>#endif@@ -247,4 +248,18 @@ std::filesystem::path to_fs_path(const StringPathVariant& param) {}},param);}++FileHandle open_ro_file(const std::filesystem::path& path) {+#ifdef _WIN32+ return ::CreateFileW(path.c_str(),+ GENERIC_READ,+ FILE_SHARE_READ,+ nullptr,+ OPEN_EXISTING,+ FILE_ATTRIBUTE_NORMAL,+ nullptr);+#else+ return ::open(path.c_str(), O_RDONLY);+#endif+}} // namespace ov::test::utils