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] Align constant offsets to element size in .bin serialization (#36733)
Leo89adf0d7465b
diff --git a/src/core/src/xml_util/constant_writer.cpp b/src/core/src/xml_util/constant_writer.cppindex 49c93cb4b8e..167bafea4e3 100644--- a/src/core/src/xml_util/constant_writer.cpp+++ b/src/core/src/xml_util/constant_writer.cpp@@ -4,7 +4,11 @@#include "openvino/xml_util/constant_writer.hpp"+#include <algorithm>+#include <iterator>+#include "openvino/core/except.hpp"+#include "openvino/core/memory_util.hpp"#include "openvino/reference/convert.hpp"#include "openvino/runtime/compute_hash.hpp"#include "openvino/util/hash_util.hpp"@@ -20,25 +24,34 @@ ConstantWriter::ConstantWriter(std::ostream& bin_data, bool enable_compression)ConstantWriter::~ConstantWriter() = default;+namespace {+void pad_to_alignment(std::ostream& stream, size_t alignment) {+ const ConstantWriter::FilePosition write_pos = stream.tellp();+ if (write_pos >= 0) {+ const auto pad = align_padding_size(alignment, static_cast<size_t>(write_pos));+ std::fill_n(std::ostream_iterator<char>(stream), pad, 0);+ }+}+} // namespace+ConstantWriter::FilePosition ConstantWriter::write(const char* ptr,size_t size,size_t& new_size,bool compress_to_fp16,ov::element::Type src_type,bool ptr_is_temporary) {- const FilePosition write_pos = m_binary_output.get().tellp();- const auto offset = write_pos - m_blob_offset;new_size = size;const auto fp16_data = compress_to_fp16 ? compress_data_to_fp16(ptr, size, src_type, new_size) : nullptr;const auto data_ptr = compress_to_fp16 ? fp16_data.get() : ptr;+ HashValue hash = 0;if (m_enable_compression) {// This hash is weak (but efficient). For example current hash algorithms gives// the same hash for {2, 2} and {0, 128} arrays.// But even strong hashing algorithms sometimes give collisions.// Therefore we always have to compare values when finding a match in the hash multimap.- const HashValue hash = ov::runtime::compute_hash(data_ptr, new_size);+ hash = ov::runtime::compute_hash(data_ptr, new_size);const auto found = m_hash_to_file_positions.equal_range(hash);// iterate over all matches of the key in the multimap@@ -47,6 +60,13 @@ ConstantWriter::FilePosition ConstantWriter::write(const char* ptr,return it->second.offset;}}+ }++ pad_to_alignment(m_binary_output.get(), compress_to_fp16 ? element::f16.size() : src_type.size());+ const FilePosition aligned_pos = m_binary_output.get().tellp();+ const FilePosition offset = aligned_pos - m_blob_offset;++ if (m_enable_compression) {if (!ptr_is_temporary) {// Since fp16_compressed data will be disposed at exit point and since we cannot reread it from the// ostream, we store pointer to the original uncompressed blob.diff --git a/src/core/src/xml_util/xml_serialize_util.cpp b/src/core/src/xml_util/xml_serialize_util.cppindex 0cef0158fed..fda1db70cb9 100644--- a/src/core/src/xml_util/xml_serialize_util.cpp+++ b/src/core/src/xml_util/xml_serialize_util.cpp@@ -1109,10 +1109,13 @@ void XmlSerializer::serialize(pugi::xml_node& net_xml, const ov::Model& model) {// <layers/data> general attributes{bool compress_to_fp16 = false;- ov::element::Type output_element_type = ov::element::dynamic;+ // ConstantWriter uses this as the fp16 conversion source and to align the write.+ // dynamic disables the alignment, so a real type is needed without compression too.+ // Empty Constants are written as a 1-byte AlignedBuffer and get the same padding.+ ov::element::Type output_element_type =+ node->get_output_size() > 0 ? node->get_output_element_type(0) : ov::element::dynamic;if (is_fp16_compression_postponed(node->get_rt_info())) {compress_to_fp16 = true;- output_element_type = node->get_output_element_type(0);}// Backward compatibility: clear padding values for nodes with auto_padPaddingsFixer fixed_node(node);diff --git a/src/core/tests/pass/serialization/const_compression.cpp b/src/core/tests/pass/serialization/const_compression.cppindex 1cef829551b..f2a6f2d4471 100644--- a/src/core/tests/pass/serialization/const_compression.cpp+++ b/src/core/tests/pass/serialization/const_compression.cpp@@ -357,7 +357,6 @@ TEST_F(SerializationConstantCompressionTest, EmptyAndNotEmptyConstantSameValues)}TEST_F(SerializationConstantCompressionTest, EmptyAndNotEmptyConstantsDifferentValues) {- constexpr int unique_const_count = 2;auto A = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{0}, std::vector<int32_t>{});auto B = ov::op::v0::Constant::create(ov::element::i8, ov::Shape{1}, std::vector<int8_t>{1});@@ -365,14 +364,20 @@ TEST_F(SerializationConstantCompressionTest, EmptyAndNotEmptyConstantsDifferentVov::pass::Serialize(m_out_xml_path_1, m_out_bin_path_1).run_on_model(model_initial);- std::ifstream xml_1(m_out_xml_path_1, std::ios::binary);- std::ifstream bin_1(m_out_bin_path_1, std::ios::binary);-- ASSERT_EQ(file_size(bin_1), unique_const_count * sizeof(int8_t));-+ // No exact .bin size assertion: A is an empty i32 constant with a 1 B placeholder allocation+ // (see Constant::allocate_buffer), so its alignment padding can vary with traversal order.ov::Core core;auto model_imported = core.read_model(m_out_xml_path_1, m_out_bin_path_1);+ // Verify the two constants were not deduplicated (different data, different pointers)+ std::vector<const void*> ptrs;+ for (auto& node : model_imported->get_ops()) {+ if (auto c = ov::as_type_ptr<ov::op::v0::Constant>(node))+ ptrs.push_back(c->get_data_ptr());+ }+ ASSERT_EQ(ptrs.size(), 2);+ ASSERT_NE(ptrs[0], ptrs[1]);+const auto& [success, message] = compare_functions(model_initial, model_imported, true, true, false, true, true);ASSERT_TRUE(success) << message;}diff --git a/src/core/tests/pass/serialization/serialize.cpp b/src/core/tests/pass/serialization/serialize.cppindex f859b753a36..0f65f4d3a31 100644--- a/src/core/tests/pass/serialization/serialize.cpp+++ b/src/core/tests/pass/serialization/serialize.cpp@@ -15,6 +15,7 @@#include "openvino/core/graph_util.hpp"#include "openvino/core/version.hpp"#include "openvino/op/add.hpp"+#include "openvino/op/convert.hpp"#include "openvino/pass/serialize.hpp"#include "openvino/runtime/core.hpp"#include "openvino/runtime/tensor.hpp"@@ -917,4 +918,27 @@ TEST_F(UndefinedTypeDynamicTypeSerializationTests, compare_dynamic_type_undefineASSERT_TRUE(files_equal(m_dynamic_type_out_xml_path, m_undefined_type_out_xml_path))<< "Serialized XML files are different: dynamic type vs undefined type";}+TEST_P(SerializePassTestP, constant_data_pointer_is_aligned) {+ // A 1 B u8 spacer precedes the constant under test, so missing alignment padding would+ // leave it at an unaligned offset.+ const auto& precision = GetParam();+ auto param = std::make_shared<Parameter>(element::f32, Shape{1});+ auto spacer = std::make_shared<Constant>(element::u8, Shape{1}, std::vector<uint8_t>{7});+ auto c = std::make_shared<Constant>(precision, Shape{1}, std::vector{1});++ auto a1 = std::make_shared<Add>(param, std::make_shared<op::v0::Convert>(spacer, element::f32));+ auto a2 = std::make_shared<Add>(a1, std::make_shared<op::v0::Convert>(c, element::f32));+ m_model = std::make_shared<Model>(OutputVector{a2}, ParameterVector{param});++ OV_ASSERT_NO_THROW(ov::serialize(m_model, m_out_xml_path, m_out_bin_path));++ const auto reloaded = test::readModel(m_out_xml_path.string(), m_out_bin_path.string());+ const auto alignment = precision.size();+ for (auto& node : reloaded->get_ops()) {+ if (const auto& constant = ov::as_type_ptr<Constant>(node);+ constant && constant->get_element_type() == precision) {+ EXPECT_EQ(reinterpret_cast<uintptr_t>(constant->get_data_ptr()) % alignment, 0) << *constant;+ }+ }+}} // namespace ov::testdiff --git a/src/core/tests/xml_util/constant_writer_test.cpp b/src/core/tests/xml_util/constant_writer_test.cppindex 111c3380e6f..ea4f2a15ded 100644--- a/src/core/tests/xml_util/constant_writer_test.cpp+++ b/src/core/tests/xml_util/constant_writer_test.cpp@@ -89,4 +89,53 @@ TEST(ConstantWriterTest, identical_constants_are_deduplicated) {EXPECT_EQ(static_cast<size_t>(bin.tellp()), a.size()) << "duplicate constant must not be re-written";}+// Alignment padding inserted before each write() matches the element type's own size.+TEST(ConstantWriterTest, alignment_padding_matches_element_size) {+ std::stringstream bin;+ ov::util::ConstantWriter writer(bin, /*enable_compression=*/false);+ size_t new_size = 0;++ // u8 never needs padding: b starts right after a, at offset 3.+ constexpr std::array<uint8_t, 3> u8_a = {1, 2, 3};+ constexpr std::array<uint8_t, 5> u8_b = {4, 5, 6, 7, 8};+ writer.write(reinterpret_cast<const char*>(u8_a.data()), u8_a.size(), new_size, false, element::u8);+ const auto off_u8_b =+ writer.write(reinterpret_cast<const char*>(u8_b.data()), u8_b.size(), new_size, false, element::u8);+ EXPECT_EQ(off_u8_b, static_cast<int64_t>(u8_a.size()));++ // Stream is at offset 8 now, already 4-aligned: i32 needs no padding either.+ constexpr std::array<uint8_t, 4> i32_data = {};+ const auto off_i32 =+ writer.write(reinterpret_cast<const char*>(i32_data.data()), i32_data.size(), new_size, false, element::i32);+ EXPECT_EQ(off_i32, 8);++ // A 1 B spacer leaves the stream at offset 13: the i64 write must pad 3 B to reach 16.+ constexpr std::array<uint8_t, 1> spacer = {0xAB};+ constexpr std::array<uint8_t, 8> i64_data = {};+ writer.write(reinterpret_cast<const char*>(spacer.data()), spacer.size(), new_size, false, element::u8);+ const auto off_i64 =+ writer.write(reinterpret_cast<const char*>(i64_data.data()), i64_data.size(), new_size, false, element::i64);+ EXPECT_EQ(off_i64, 16);+}++// StreamSerialize embeds the constants blob after an unpadded, arbitrary-length custom-data+// section, so the blob can start at a non-aligned absolute position. Padding must target the+// absolute stream position, not the offset relative to that (possibly unaligned) blob start.+TEST(ConstantWriterTest, padding_targets_absolute_stream_position) {+ std::stringstream bin;+ bin.write("XXXXX", 5);+ const auto blob_offset = static_cast<size_t>(bin.tellp());++ ov::util::ConstantWriter writer(bin, /*enable_compression=*/false);+ size_t new_size = 0;++ constexpr std::array<uint8_t, 1> u8_data = {0xAB};+ constexpr std::array<uint8_t, 4> i32_data = {1, 2, 3, 4};+ writer.write(reinterpret_cast<const char*>(u8_data.data()), u8_data.size(), new_size, false, element::u8);+ const auto off_i32 =+ writer.write(reinterpret_cast<const char*>(i32_data.data()), i32_data.size(), new_size, false, element::i32);++ EXPECT_EQ((blob_offset + static_cast<size_t>(off_i32)) % 4, 0u);+}+} // namespace ov::test