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] Enhance Tensor size calculation (#35064)
Tomasz Jankowski972d0994ae0c
diff --git a/src/core/dev_api/openvino/core/memory_util.hpp b/src/core/dev_api/openvino/core/memory_util.hppindex 8ea204bedf1..b383338cc1c 100644--- a/src/core/dev_api/openvino/core/memory_util.hpp+++ b/src/core/dev_api/openvino/core/memory_util.hpp@@ -39,6 +39,17 @@ OPENVINO_API std::optional<size_t> get_memory_size_safe(const element::Type& typ*/OPENVINO_API std::optional<size_t> get_memory_size_safe(const element::Type& type, const ov::Shape& shape);+/**+ * @brief Gets the maximum count of elements that can fit into the given memory size for a specific element type.+ * @note For the returned value @c n, the following holds:+ * get_memory_size(type, n) <= memory_size and get_memory_size(type, n + 1) > memory_size.+ * @param type Element precision.+ * @param memory_size Available memory size in bytes.+ * @return Maximum count of elements that can fit into the given memory size, or 0 if the element type has 0 bitwidth+ * e.g. type is dynamic.+ */+OPENVINO_API size_t get_elements_capacity(const element::Type& type, const size_t memory_size);+/*** @brief Calculates padding size in bytes to align given position to specified alignment.*diff --git a/src/core/include/openvino/runtime/tensor.hpp b/src/core/include/openvino/runtime/tensor.hppindex bb481655e49..bb503d89ce6 100644--- a/src/core/include/openvino/runtime/tensor.hpp+++ b/src/core/include/openvino/runtime/tensor.hpp@@ -311,7 +311,7 @@ using TensorVector = std::vector<Tensor>;/// \brief Read a tensor content from a file. Only raw data is loaded./// \param file_name Path to file to read.-/// \param element_type Element type, when not specified the it is assumed as element::u8.+/// \param element_type Element type, when not specified then it is assumed as element::u8./// \param shape Shape for resulting tensor. If provided shape is static, specified number of elements is read only./// File should contain enough bytes, an exception is raised otherwise./// One of the dimensions can be dynamic. In this case it will be determined automatically based on thediff --git a/src/core/src/memory_util.cpp b/src/core/src/memory_util.cppindex 850ed05c792..6ded091cfc5 100644--- a/src/core/src/memory_util.cpp+++ b/src/core/src/memory_util.cpp@@ -10,21 +10,36 @@namespace ov::util {namespace {-size_t get_split_bit_memory_size(const element::Type& type, const size_t shape_size) {- constexpr size_t storage_unit_size = 24;- const size_t elements_per_storage_unit = storage_unit_size / type.bitwidth();- auto byte_size = shape_size / elements_per_storage_unit;- byte_size += static_cast<size_t>(byte_size * elements_per_storage_unit != shape_size);- return byte_size * 3;+constexpr size_t split_unit_bit_size = 24;+constexpr size_t split_unit_byte_size = split_unit_bit_size / 8;+size_t get_split_bit_memory_size(const element::Type& type, const size_t elements_count) {+ const size_t elements_per_storage_unit = split_unit_bit_size / type.bitwidth();+ auto units_count = elements_count / elements_per_storage_unit;+ units_count += static_cast<size_t>(units_count * elements_per_storage_unit != elements_count);+ return units_count * split_unit_byte_size;+}++size_t get_split_elements_count(const element::Type& type, const size_t memory_size) {+ const size_t elements_per_storage_unit = split_unit_bit_size / type.bitwidth();+ const size_t storage_unit_count = memory_size / split_unit_byte_size;+ size_t elements_count;+ OPENVINO_ASSERT(!mul_overflow<size_t>(storage_unit_count, elements_per_storage_unit, elements_count));+ return elements_count;}size_t get_bit_memory_size(const element::Type& type, const size_t shape_size) {- constexpr size_t storage_unit_size = 8;- const auto elements_per_storage_unit = storage_unit_size / type.bitwidth();- auto byte_size = shape_size / elements_per_storage_unit;- byte_size += static_cast<size_t>((byte_size * elements_per_storage_unit) != shape_size);+ const auto elements_per_byte = 8 / type.bitwidth();+ auto byte_size = shape_size / elements_per_byte;+ byte_size += static_cast<size_t>((byte_size * elements_per_byte) != shape_size);return byte_size;}++size_t get_bit_elements_count(const element::Type& type, const size_t memory_size) {+ const size_t elements_per_byte = 8 / type.bitwidth();+ size_t elements_count;+ OPENVINO_ASSERT(!mul_overflow<size_t>(memory_size, elements_per_byte, elements_count));+ return elements_count;+}} // namespacesize_t get_memory_size(const element::Type& type, const size_t n) {@@ -51,4 +66,17 @@ std::optional<size_t> get_memory_size_safe(const element::Type& type, const ov::auto byte_size = shape_size_safe(shape);return byte_size ? get_memory_size_safe(type, *byte_size) : byte_size;}++size_t get_elements_capacity(const element::Type& type, const size_t memory_size) {+ if (type.bitwidth() == 0) {+ return 0;+ } else if (element::is_split_bit_type(type)) {+ return get_split_elements_count(type, memory_size);+ } else if (element::is_bit_type(type) || element::is_nibble_type(type)) {+ return get_bit_elements_count(type, memory_size);+ } else {+ const size_t bytes_per_element = type.bitwidth() / 8;+ return memory_size / bytes_per_element;+ }+}} // namespace ov::utildiff --git a/src/core/src/runtime/tensor.cpp b/src/core/src/runtime/tensor.cppindex 1058ab242e8..7a5016392bc 100644--- a/src/core/src/runtime/tensor.cpp+++ b/src/core/src/runtime/tensor.cpp@@ -136,57 +136,57 @@ bool Tensor::is_continuous() const {}namespace {-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) {+/**+ * @brief Resolves a static shape from a partial shape and available size in bytes for given element type.+ * @param available_size Size in bytes, must exactly fit the resolved tensor data.+ * @param element_type The element type of the tensor, used to calculate the size of the tensor data.+ * @param partial_shape The partial shape of the tensor. If it has (at most one) dynamic dimension, it will be computed.+ * @return The resolved static shape.+ * @throw ov::Exception if the partial shape has more than one dynamic dimension,+ * or if the available size is inexact to fit the tensor data of resolved static shape,+ * or if the dynamic dimension cannot be resolved to fit the available size.+ */+Shape resolve_static_shape(size_t available_size,+ const element::Type& element_type,+ const PartialShape& partial_shape) {+ Shape static_shape;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 <= max_size,- "Requested space exceeds available bounds: available bytes=",- max_size,- " offset=",- offset,- " requested size=",- memory_size ? std::to_string(*memory_size) : "uncountable");- return static_shape;- }- auto partial_shape_copy = partial_shape;- auto rank = partial_shape_copy.rank();- OPENVINO_ASSERT(rank.is_static(), "Rank cannot be dynamic");- std::vector<size_t> dynamic_dimension_numbers;- typename Dimension::value_type slice_size = 1;- for (size_t id = 0; id < partial_shape_copy.size(); ++id) {- if (partial_shape_copy[id].is_dynamic()) {- dynamic_dimension_numbers.push_back(id);- } else {- slice_size *= partial_shape_copy[id].get_min_length();+ static_shape = partial_shape.get_shape();+ } else {+ OPENVINO_ASSERT(partial_shape.rank().is_static(), "Rank cannot be dynamic");++ std::optional<size_t> dynamic_dimension_index;+ typename Dimension::value_type slice_size = 1;+ for (size_t id = 0; id < partial_shape.size(); ++id) {+ if (partial_shape[id].is_dynamic()) {+ OPENVINO_ASSERT(!dynamic_dimension_index,+ "Only one dynamic dimension in input shape is supported, got ",+ partial_shape);+ dynamic_dimension_index = id;+ } else {+ slice_size *= partial_shape[id].get_min_length();+ }}- }- 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]];+ OPENVINO_ASSERT(slice_size > 0, "Cannot fit available bytes into requested PartialShape");- auto max_size_to_read = max_size - offset;-- OPENVINO_ASSERT((max_size_to_read * 8) % element_type.bitwidth() == 0,- "cannot fit ",- element_type.get_type_name(),- " into ",- max_size_to_read,- " bytes");- auto elements_to_read = max_size_to_read * 8 / element_type.bitwidth();+ const auto elements_to_read = util::get_elements_capacity(element_type, available_size);+ auto new_dimension = Dimension(elements_to_read) / slice_size;+ OPENVINO_ASSERT(partial_shape[*dynamic_dimension_index].compatible(new_dimension),+ "Cannot fit available bytes into requested PartialShape ",+ partial_shape);- auto new_dimension = ov::Dimension(elements_to_read) / slice_size;- OPENVINO_ASSERT(dynamic_dimension.compatible(new_dimension),- "Cannot fit available bytes into requested PartialShape");+ auto new_shape = partial_shape;+ new_shape[*dynamic_dimension_index] = std::move(new_dimension);+ static_shape = new_shape.get_shape();+ }- dynamic_dimension = std::move(new_dimension);- return partial_shape_copy.get_shape();+ const auto requested_size = util::get_memory_size_safe(element_type, static_shape);+ OPENVINO_ASSERT(requested_size && *requested_size <= available_size,+ "Requested space exceeds available bounds: available bytes=",+ available_size,+ " requested size=",+ requested_size ? std::to_string(*requested_size) : "uncountable");+ return static_shape;}void read_tensor_via_ifstream(const std::filesystem::path& file_name, Tensor& tensor, size_t offset) {@@ -213,8 +213,7 @@ 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) {- 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 static_shape = resolve_static_shape(mapped_memory->size(), element_type, partial_shape);const auto shared_buffer =std::make_shared<ov::SharedBuffer<std::shared_ptr<ov::MappedMemory>>>(mapped_memory->data(),mapped_memory->size(),@@ -250,9 +249,15 @@ Tensor read_tensor_data(const std::filesystem::path& file_name,partial_shape,offset_in_bytes);} else {- auto file_size = std::filesystem::file_size(file_name);- auto static_shape = calc_static_shape_for_file(file_size, element_type, partial_shape, offset_in_bytes);- auto tensor = std::make_shared<ov::Tensor>(element_type, static_shape);+ const auto file_size = std::filesystem::file_size(file_name);+ OPENVINO_ASSERT(offset_in_bytes <= file_size,+ "Requested space exceeds available bounds: offset=",+ offset_in_bytes,+ " file size=",+ file_size);+ const auto available_size = static_cast<size_t>(file_size - offset_in_bytes);+ const auto static_shape = resolve_static_shape(available_size, element_type, partial_shape);+ const auto tensor = std::make_shared<ov::Tensor>(element_type, static_shape);read_tensor_via_ifstream(file_name, *tensor.get(), offset_in_bytes);return wrap_obj_to_viewtensor(tensor, tensor->data(), element_type, static_shape);}diff --git a/src/core/tests/memory_util.cpp b/src/core/tests/memory_util.cppindex b19c858af06..4708f7508b7 100644--- a/src/core/tests/memory_util.cpp+++ b/src/core/tests/memory_util.cpp@@ -92,6 +92,98 @@ TEST(GetMemorySizeOverflowTest, zero_number_of_elements) {EXPECT_EQ(ov::util::get_memory_size_safe(element::string, 0), std::optional<size_t>(0));}+// element type, memory size, expected max count of elements+using MaxElementsForMemorySizeParam = std::tuple<element::Type, size_t, size_t>;++class GetMaxElementsForMemorySizeTest : public testing::TestWithParam<MaxElementsForMemorySizeParam> {};++TEST_P(GetMaxElementsForMemorySizeTest, calculate_max_elements) {+ const auto& [type, memory_size, exp_elements] = GetParam();+ EXPECT_EQ(ov::util::get_elements_capacity(type, memory_size), exp_elements);+}++INSTANTIATE_TEST_SUITE_P(bit_type_precision,+ GetMaxElementsForMemorySizeTest,+ testing::Values(std::make_tuple(element::u1, 0, 0),+ std::make_tuple(element::u1, 1, 8),+ std::make_tuple(element::u1, 2, 16),+ std::make_tuple(element::u1, 3, 24),+ std::make_tuple(element::u1, 4, 32),+ std::make_tuple(element::u2, 0, 0),+ std::make_tuple(element::u2, 1, 4),+ std::make_tuple(element::u2, 2, 8),+ std::make_tuple(element::u2, 3, 12),+ std::make_tuple(element::u2, 4, 16)));++INSTANTIATE_TEST_SUITE_P(nibble_type_precision,+ GetMaxElementsForMemorySizeTest,+ testing::Values(std::make_tuple(element::i4, 0, 0),+ std::make_tuple(element::u4, 0, 0),+ std::make_tuple(element::u4, 1, 2),+ std::make_tuple(element::u4, 2, 4),+ std::make_tuple(element::i4, 3, 6),+ std::make_tuple(element::i4, 4, 8)));++INSTANTIATE_TEST_SUITE_P(split_bit_type_precision,+ GetMaxElementsForMemorySizeTest,+ testing::Values(std::make_tuple(element::u3, 0, 0),+ std::make_tuple(element::u3, 1, 0),+ std::make_tuple(element::u3, 2, 0),+ std::make_tuple(element::u3, 3, 8),+ std::make_tuple(element::u3, 5, 8),+ std::make_tuple(element::u3, 6, 16),+ std::make_tuple(element::u3, 11, 24),+ std::make_tuple(element::u3, 12, 32),+ std::make_tuple(element::u6, 0, 0),+ std::make_tuple(element::u6, 1, 0),+ std::make_tuple(element::u6, 2, 0),+ std::make_tuple(element::u6, 3, 4),+ std::make_tuple(element::u6, 4, 4),+ std::make_tuple(element::u6, 5, 4),+ std::make_tuple(element::u6, 6, 8),+ std::make_tuple(element::u6, 11, 12),+ std::make_tuple(element::u6, 12, 16)));++INSTANTIATE_TEST_SUITE_P(byte_type_precision,+ GetMaxElementsForMemorySizeTest,+ testing::Values(std::make_tuple(element::u8, 0, 0),+ std::make_tuple(element::u8, 1, 1),+ std::make_tuple(element::u8, 2, 2),+ std::make_tuple(element::u8, 3, 3),+ std::make_tuple(element::u8, 4, 4),+ std::make_tuple(element::i16, 0, 0),+ std::make_tuple(element::i16, 1, 0),+ std::make_tuple(element::i16, 2, 1),+ std::make_tuple(element::i16, 3, 1),+ std::make_tuple(element::i16, 4, 2),+ std::make_tuple(element::f32, 0, 0),+ std::make_tuple(element::f32, 1, 0),+ std::make_tuple(element::f32, 4, 1),+ std::make_tuple(element::f32, 7, 1),+ std::make_tuple(element::f32, 8, 2),+ std::make_tuple(element::f32, 15, 3),+ std::make_tuple(element::f32, 16, 4),+ std::make_tuple(element::f64, 0, 0),+ std::make_tuple(element::f64, 1, 0),+ std::make_tuple(element::f64, 7, 0),+ std::make_tuple(element::f64, 8, 1),+ std::make_tuple(element::f64, 15, 1),+ std::make_tuple(element::f64, 16, 2),+ std::make_tuple(element::f64, 24, 3),+ std::make_tuple(element::f64, 32, 4),+ std::make_tuple(element::f64, 33, 4)));++INSTANTIATE_TEST_SUITE_P(other_types,+ GetMaxElementsForMemorySizeTest,+ testing::Values(std::make_tuple(element::dynamic, 0, 0),+ std::make_tuple(element::dynamic, 1, 0),+ std::make_tuple(element::dynamic, 100, 0),+ std::make_tuple(element::string, 0, 0),+ std::make_tuple(element::string, sizeof(std::string), 1),+ std::make_tuple(element::string, 2 * sizeof(std::string), 2),+ std::make_tuple(element::string, 3 * sizeof(std::string), 3),+ std::make_tuple(element::string, 4 * sizeof(std::string), 4)));+using AlignTestParam = std::tuple<uintptr_t, size_t, size_t>;class AlignTest : public ::testing::TestWithParam<AlignTestParam> {};diff --git a/src/core/tests/tensor_utils.cpp b/src/core/tests/tensor_utils.cppindex 1ba5f4ae906..c59b891da99 100644--- a/src/core/tests/tensor_utils.cpp+++ b/src/core/tests/tensor_utils.cpp@@ -229,18 +229,14 @@ TEST_F(FunctionalOffloadTensorTest, read_wrong_dynamic_shape) {}}-TEST_F(FunctionalOffloadTensorTest, read_type_doesnt_fit_file_size) {+TEST_F(FunctionalOffloadTensorTest, allow_auto_size_less_than_file_size) {{std::ofstream fout(file_name, std::ios::binary);fout.write(reinterpret_cast<char*>(init_values.data()), data_size - 1);}ASSERT_TRUE(std::filesystem::exists(file_name));-- {- EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov::element::f32), ov::Exception);- EXPECT_THROW(std::ignore = read_tensor_data(file_name, ov::element::f32, PartialShape::dynamic(1), 0, false),- ov::Exception);- }+ EXPECT_NO_THROW(std::ignore = read_tensor_data(file_name, ov::element::f32));+ EXPECT_NO_THROW(std::ignore = read_tensor_data(file_name, ov::element::f32, PartialShape::dynamic(1), 0, false));}TEST_F(FunctionalOffloadTensorTest, read_null_shape) {