Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

Delayed constant serialization (#29106)

Oleg Pipikin8427701008bd
diff --git a/src/bindings/python/src/openvino/__init__.py b/src/bindings/python/src/openvino/__init__.py
index 0f19b7bfc9b..d5594ee4227 100644
--- a/src/bindings/python/src/openvino/__init__.py
+++ b/src/bindings/python/src/openvino/__init__.py
@@ -52,12 +52,12 @@ from openvino._pyopenvino import RemoteContext
from openvino._pyopenvino import RemoteTensor
# Import public classes from _ov_api
+from openvino._op_base import Op
from openvino._ov_api import Model
from openvino._ov_api import Core
from openvino._ov_api import CompiledModel
from openvino._ov_api import InferRequest
from openvino._ov_api import AsyncInferQueue
-from openvino._ov_api import Op
# Import all public modules
from openvino.package_utils import LazyLoader
diff --git a/src/bindings/python/src/openvino/_op_base.py b/src/bindings/python/src/openvino/_op_base.py
new file mode 100644
index 00000000000..ad49b59c856
--- /dev/null
+++ b/src/bindings/python/src/openvino/_op_base.py
@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2018-2025 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+from typing import Union, Optional, Tuple, List
+
+from openvino._pyopenvino import Op as OpBase
+from openvino._pyopenvino import Node, Output
+
+
+class Op(OpBase):
+ def __init__(self, py_obj: "Op", inputs: Optional[Union[List[Union[Node, Output]], Tuple[Union[Node, Output, List[Union[Node, Output]]]]]] = None) -> None:
+ super().__init__(py_obj)
+ self._update_type_info()
+ if isinstance(inputs, tuple):
+ inputs = None if len(inputs) == 0 else list(inputs)
+ if inputs is not None and len(inputs) == 1 and isinstance(inputs[0], list):
+ inputs = inputs[0]
+ if inputs is not None:
+ self.set_arguments(inputs)
+ self.constructor_validate_and_infer_types()
diff --git a/src/bindings/python/src/openvino/_ov_api.py b/src/bindings/python/src/openvino/_ov_api.py
index 1bbcdac8d96..48d229949e2 100644
--- a/src/bindings/python/src/openvino/_ov_api.py
+++ b/src/bindings/python/src/openvino/_ov_api.py
@@ -4,7 +4,7 @@
import io
from types import TracebackType
-from typing import Any, Iterable, Union, Optional, Dict, Tuple, List
+from typing import Any, Iterable, Union, Optional, Dict
from typing import Type as TypingType
from pathlib import Path
@@ -13,8 +13,7 @@ from openvino._pyopenvino import Model as ModelBase
from openvino._pyopenvino import Core as CoreBase
from openvino._pyopenvino import CompiledModel as CompiledModelBase
from openvino._pyopenvino import AsyncInferQueue as AsyncInferQueueBase
-from openvino._pyopenvino import Op as OpBase
-from openvino._pyopenvino import Node, Output, Tensor, Type
+from openvino._pyopenvino import Node, Tensor, Type
from openvino.utils.data_helpers import (
OVDict,
@@ -25,19 +24,6 @@ from openvino.utils.data_helpers import (
from openvino.package_utils import deprecatedclassproperty
-class Op(OpBase):
- def __init__(self, py_obj: "Op", inputs: Optional[Union[List[Union[Node, Output]], Tuple[Union[Node, Output, List[Union[Node, Output]]]]]] = None) -> None:
- super().__init__(py_obj)
- self._update_type_info()
- if isinstance(inputs, tuple):
- inputs = None if len(inputs) == 0 else list(inputs)
- if inputs is not None and len(inputs) == 1 and isinstance(inputs[0], list):
- inputs = inputs[0]
- if inputs is not None:
- self.set_arguments(inputs)
- self.constructor_validate_and_infer_types()
-
-
class ModelMeta(type):
def __dir__(cls) -> list:
return list(set(cls.__dict__.keys()) | set(dir(ModelBase)))
diff --git a/src/bindings/python/src/openvino/utils/__init__.py b/src/bindings/python/src/openvino/utils/__init__.py
index eb0a4f12803..06dc996f6c4 100644
--- a/src/bindings/python/src/openvino/utils/__init__.py
+++ b/src/bindings/python/src/openvino/utils/__init__.py
@@ -10,3 +10,4 @@ from openvino.package_utils import get_cmake_path
from openvino.package_utils import deprecated
from openvino.package_utils import classproperty
from openvino.package_utils import deprecatedclassproperty
+from openvino.utils.postponed_constant import make_postponed_constant
diff --git a/src/bindings/python/src/openvino/utils/postponed_constant.py b/src/bindings/python/src/openvino/utils/postponed_constant.py
new file mode 100644
index 00000000000..20fb74b79fd
--- /dev/null
+++ b/src/bindings/python/src/openvino/utils/postponed_constant.py
@@ -0,0 +1,38 @@
+# -*- coding: utf-8 -*-
+# Copyright (C) 2018-2025 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+
+from typing import Callable, List, Optional
+from openvino import Op, Type, Shape, Tensor, PartialShape
+
+
+class PostponedConstant(Op):
+ """Postponed Constant is a way to materialize a big constant only when it is going to be serialized to IR and then immediately dispose."""
+ def __init__(self, element_type: Type, shape: Shape, maker: Callable[[Tensor], None], name: Optional[str] = None) -> None:
+ super().__init__(self)
+ self.get_rt_info()["postponed_constant"] = True # value doesn't matter
+ self.m_element_type = element_type
+ self.m_shape = shape
+ self.m_maker = maker
+ if name is not None:
+ self.friendly_name = name
+ self.constructor_validate_and_infer_types()
+
+ def evaluate(self, outputs: List[Tensor], _: List[Tensor]) -> bool:
+ self.m_maker(outputs[0])
+ return True
+
+ def validate_and_infer_types(self) -> None:
+ self.set_output_type(0, self.m_element_type, PartialShape(self.m_shape))
+
+ def clone_with_new_inputs(self, new_inputs: List[Tensor]) -> Op:
+ return PostponedConstant(self.m_element_type, self.m_shape, self.m_maker, self.friendly_name)
+
+ def has_evaluate(self) -> bool:
+ return True
+
+
+# `maker` is a function that returns ov.Tensor that represents a target Constant
+def make_postponed_constant(element_type: Type, shape: Shape, maker: Callable[[Tensor], None], name: Optional[str] = None) -> Op:
+ return PostponedConstant(element_type, shape, maker, name)
diff --git a/src/bindings/python/tests/test_utils/test_utils.py b/src/bindings/python/tests/test_utils/test_utils.py
index 4735b923522..678e5f7e7e1 100644
--- a/src/bindings/python/tests/test_utils/test_utils.py
+++ b/src/bindings/python/tests/test_utils/test_utils.py
@@ -4,9 +4,11 @@
import pytest
import os
+import numpy as np
+import openvino as ov
from pathlib import Path
-from openvino.utils import deprecated, get_cmake_path
-from tests.utils.helpers import compare_models, get_relu_model
+from openvino.utils import deprecated, get_cmake_path, make_postponed_constant
+from tests.utils.helpers import compare_models, get_relu_model, create_filenames_for_ir
def test_compare_functions():
@@ -94,3 +96,95 @@ def test_cmake_file_not_found(monkeypatch):
result = get_cmake_path()
assert result == ""
+
+
+class Maker:
+ def __init__(self):
+ self.calls_count = 0
+
+ def __call__(self, tensor: ov.Tensor) -> None:
+ self.calls_count += 1
+ tensor_data = np.array([2, 2, 2, 2], dtype=np.float32).reshape(1, 1, 2, 2)
+ ov.Tensor(tensor_data).copy_to(tensor)
+
+ def called_times(self):
+ return self.calls_count
+
+
+def create_model(maker):
+ input_shape = ov.Shape([1, 2, 1, 2])
+ param_node = ov.opset13.parameter(input_shape, ov.Type.f32, name="data")
+
+ postponned_constant = make_postponed_constant(ov.Type.f32, input_shape, maker)
+
+ add_1 = ov.opset13.add(param_node, postponned_constant)
+
+ const_2 = ov.op.Constant(ov.Type.f32, input_shape, [1, 2, 3, 4])
+ add_2 = ov.opset13.add(add_1, const_2)
+
+ return ov.Model(add_2, [param_node], "test_model")
+
+
+def prepare_ir_paths(request, tmp_path):
+ xml_path, bin_path = create_filenames_for_ir(request.node.name, tmp_path)
+
+ yield xml_path, bin_path
+
+ # IR Files deletion should be done after `Model` is destructed.
+ # It may be achieved by splitting scopes (`Model` will be destructed
+ # just after test scope finished), or by calling `del Model`
+ os.remove(xml_path)
+ os.remove(bin_path)
+
+
+def test_save_postponned_constant(prepare_ir_paths):
+ maker = Maker()
+ model = create_model(maker)
+ assert maker.called_times() == 0
+
+ model_export_file_name, weights_export_file_name = prepare_ir_paths
+ ov.save_model(model, model_export_file_name, compress_to_fp16=False)
+
+ assert maker.called_times() == 1
+
+
+def test_save_postponned_constant_twice(prepare_ir_paths):
+ maker = Maker()
+ model = create_model(maker)
+ assert maker.called_times() == 0
+
+ model_export_file_name, weights_export_file_name = prepare_ir_paths
+ ov.save_model(model, model_export_file_name, compress_to_fp16=False)
+ assert maker.called_times() == 1
+ ov.save_model(model, model_export_file_name, compress_to_fp16=False)
+ assert maker.called_times() == 2
+
+
+def test_serialize_postponned_constant(prepare_ir_paths):
+ maker = Maker()
+ model = create_model(maker)
+ assert maker.called_times() == 0
+
+ model_export_file_name, weights_export_file_name = prepare_ir_paths
+ ov.serialize(model, model_export_file_name, weights_export_file_name)
+ assert maker.called_times() == 1
+
+
+def test_infer_postponned_constant():
+ maker = Maker()
+ model = create_model(maker)
+ assert maker.called_times() == 0
+
+ compiled_model = ov.compile_model(model, "CPU")
+ assert isinstance(compiled_model, ov.CompiledModel)
+
+ request = compiled_model.create_infer_request()
+ input_data = np.ones([1, 2, 1, 2], dtype=np.float32)
+ input_tensor = ov.Tensor(input_data)
+
+ results = request.infer({"data": input_tensor})
+ assert maker.called_times() == 1
+
+ expected_output = np.array([4, 5, 6, 7], dtype=np.float32).reshape(1, 2, 1, 2)
+ assert np.allclose(results[list(results)[0]], expected_output, 1e-4, 1e-4)
diff --git a/src/core/src/pass/serialize.cpp b/src/core/src/pass/serialize.cpp
index 6f81b503717..a169090963d 100644
--- a/src/core/src/pass/serialize.cpp
+++ b/src/core/src/pass/serialize.cpp
@@ -19,6 +19,7 @@
#include "openvino/core/model.hpp"
#include "openvino/core/parallel.hpp"
#include "openvino/core/type/float16.hpp"
+#include "openvino/op/constant.hpp"
#include "openvino/op/util/framework_node.hpp"
#include "openvino/opsets/opset1.hpp"
#include "openvino/pass/constant_folding.hpp"
@@ -100,7 +101,9 @@ public:
size_t size,
size_t& new_size,
bool compress_to_fp16 = false,
- ov::element::Type src_type = ov::element::dynamic) {
+ ov::element::Type src_type = ov::element::dynamic,
+ bool ptr_is_temporary = false) { // when true, do not rely on ptr after this function call, data
+ // is temporary allocated
const FilePosition write_pos = m_binary_output.tellp();
const auto offset = write_pos - m_blob_offset;
new_size = size;
@@ -133,17 +136,18 @@ public:
// Therefore we always have to compare values when finding a match in the hash multimap.
const HashValue hash = ov::runtime::compute_hash(ptr_to_write, new_size);
- auto found = m_hash_to_file_positions.find(hash);
+ auto found = m_hash_to_file_positions.equal_range(hash);
// iterate over all matches of the key in the multimap
- while (found != m_hash_to_file_positions.end()) {
- if (memcmp(ptr, found->second.second, size) == 0) {
- return found->second.first;
+ for (auto it = found.first; it != found.second; ++it) {
+ if (memcmp(ptr, it->second.second, size) == 0) {
+ return it->second.first;
}
- found++;
}
- // 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.
- m_hash_to_file_positions.insert({hash, {offset, static_cast<void const*>(ptr)}});
+ 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.
+ m_hash_to_file_positions.insert({hash, {offset, static_cast<void const*>(ptr)}});
+ }
if (m_write_hash_value) {
m_binary_output.write(reinterpret_cast<const char*>(&hash), sizeof(uint64_t));
} else {
@@ -314,6 +318,7 @@ class XmlSerializer : public ov::AttributeVisitor {
bool m_deterministic;
bool m_compress_to_fp16;
ov::element::Type m_output_element_type;
+ bool m_data_is_temporary;
template <typename T>
std::string create_atribute_list(ov::ValueAccessor<std::vector<T>>& adapter) {
@@ -432,14 +437,16 @@ public:
int64_t version,
bool deterministic = false,
bool compress_to_fp16 = false,
- ov::element::Type output_element_type = ov::element::dynamic)
+ ov::element::Type output_element_type = ov::element::dynamic,
+ bool data_is_temporary = false)
: m_xml_node(data),
m_node_type_name(node_type_name),
m_constant_write_handler(constant_write_handler),
m_version(version),
m_deterministic(deterministic),
m_compress_to_fp16(compress_to_fp16),
- m_output_element_type(output_element_type) {}
+ m_output_element_type(output_element_type),
+ m_data_is_temporary(data_is_temporary) {}
void on_adapter(const std::string& name, ov::ValueAccessor<void>& adapter) override {
using BodyTargetNames = std::tuple<std::string, std::string, std::vector<std::string>>;
@@ -535,11 +542,13 @@ public:
a2->get_header(header_ptr, header_size);
}
- int64_t offset = m_constant_write_handler.write(reinterpret_cast<const char*>(header_ptr.get()),
- header_size,
- inter_size,
- m_compress_to_fp16,
- m_output_element_type);
+ int64_t offset = m_constant_write_handler.write(
+ reinterpret_cast<const char*>(header_ptr.get()),
+ header_size,
+ inter_size,
+ m_compress_to_fp16,
+ m_output_element_type,
+ true); // header_ptr is allocated in AttributeAdapter that has limited life time
new_size += inter_size;
// write raw strings part
@@ -562,7 +571,9 @@ public:
raw_string_size,
inter_size,
m_compress_to_fp16,
- m_output_element_type);
+ m_output_element_type,
+ m_data_is_temporary);
+
new_size += inter_size;
}
m_xml_node.append_attribute("offset").set_value(static_cast<unsigned long long>(offset));
@@ -576,7 +587,8 @@ public:
size,
new_size,
m_compress_to_fp16,
- m_output_element_type);
+ m_output_element_type,
+ m_data_is_temporary);
m_xml_node.append_attribute("offset").set_value(static_cast<unsigned long long>(offset));
m_xml_node.append_attribute("size").set_value(static_cast<unsigned long long>(new_size));
@@ -891,6 +903,36 @@ public:
}
};
+// Substitute a Constant node instead of a node by calling node->constant_fold if 'postponed_constant' rt_info attribute
+// is present in the node
+class PostponedConstantReplacer {
+private:
+ ov::Node* m_node;
+ std::shared_ptr<ov::Node> m_constant;
+
+public:
+ ov::Node* get_node() {
+ return m_node;
+ }
+
+ bool data_is_temporary() const {
+ return m_constant != nullptr;
+ }
+
+ PostponedConstantReplacer(ov::Node* node) : m_node(node), m_constant() {
+ if (node->get_rt_info().count("postponed_constant")) {
+ OPENVINO_ASSERT(node->get_output_size() == 1);
+ ov::OutputVector outputs(1);
+ OPENVINO_ASSERT(
+ node->constant_fold(outputs, node->input_values()),
+ "Node with set `postponed_constant` attribute cannot be fold to constant when saving model to IR file");
+ m_constant = outputs[0].get_node_shared_ptr();
+ m_node = m_constant.get();
+ m_node->set_friendly_name(node->get_friendly_name());
+ }
+ }
+};
+
bool is_correct_tag_name(const std::string& name) {
if (name.length() == 0) {
return false;
@@ -993,12 +1035,20 @@ void ngfunction_2_ir(pugi::xml_node& netXml,
for (const auto& n : sorted_ops) {
ov::Node* node = n.get();
+ int node_id{};
+ {
+ auto it = layer_ids.find(node);
+ OPENVINO_ASSERT(it != layer_ids.end(), "Internal error");
+ node_id = it->second;
+ }
+ PostponedConstantReplacer modified_node(node);
+ node = modified_node.get_node();
+
const std::string& node_type_name{node->get_type_name()};
- OPENVINO_ASSERT(layer_ids.find(node) != layer_ids.end(), "Internal error");
// <layers>
pugi::xml_node layer = layers.append_child("layer");
- layer.append_attribute("id").set_value(layer_ids.find(node)->second);
+ layer.append_attribute("id").set_value(node_id);
// If determinism is not required, include auto-generated names into xml
// layer name is not critical for hash computing
if (!deterministic) {
@@ -1149,7 +1199,8 @@ void ngfunction_2_ir(pugi::xml_node& netXml,
version,
deterministic,
compress_to_fp16,
- output_element_type);
+ output_element_type,
+ modified_node.data_is_temporary());
OPENVINO_ASSERT(fixed_node.get_node()->visit_attributes(visitor), "Visitor API is not supported in ", node);
}
rt_info::XmlSerializer{data}.serialize(node->get_rt_info());
diff --git a/src/core/tests/pass/serialization/custom_ops.cpp b/src/core/tests/pass/serialization/custom_ops.cpp
index b8c49eebac4..5859b3e2f17 100644
--- a/src/core/tests/pass/serialization/custom_ops.cpp
+++ b/src/core/tests/pass/serialization/custom_ops.cpp
@@ -2,11 +2,13 @@
// SPDX-License-Identifier: Apache-2.0
//
+#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "common_test_utils/common_utils.hpp"
#include "common_test_utils/file_utils.hpp"
#include "common_test_utils/graph_comparator.hpp"
+#include "openvino/op/constant.hpp"
#include "openvino/pass/manager.hpp"
#include "openvino/pass/serialize.hpp"
#include "openvino/runtime/core.hpp"
@@ -114,3 +116,55 @@ TEST_F(CustomOpsSerializationTest, CustomOpNoExtensions) {
ASSERT_TRUE(success) << message;
}
+
+class PostponedOp : public ov::op::Op {
+public:
+ ov::element::Type m_type;
+ ov::Shape m_shape;
+ OPENVINO_OP("PostponedOp");
+
+ PostponedOp(ov::element::Type type, ov::Shape shape) : m_type(type), m_shape(shape) {
+ constructor_validate_and_infer_types();
+
+ ON_CALL(*this, evaluate).WillByDefault([this](ov::TensorVector& outputs, const ov::TensorVector& inputs) {
+ ov::Tensor output(m_type, m_shape);
+ output.copy_to(outputs[0]);
+ return true;
+ });
+ };
+
+ void validate_and_infer_types() override {
+ set_output_size(1);
+ set_output_type(0, m_type, m_shape);
+ }
+
+ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& inputs) const override {
+ return nullptr;
+ }
+
+ MOCK_METHOD(bool,
+ evaluate,
+ (ov::TensorVector & output_values, const ov::TensorVector& input_values),
+ (const, override));
+};
+
+TEST(PostponedOpSerializationTest, CorrectRtInfo) {
+ auto constant = std::make_shared<PostponedOp>(ov::element::f16, ov::Shape{1, 2, 3, 4});
+ constant->get_rt_info()["postponed_constant"] = true;
+ auto model = std::make_shared<ov::Model>(ov::OutputVector{constant});
+
+ EXPECT_CALL(*constant, evaluate).Times(1);
+
+ std::stringstream serialized_model, serialized_weigths;
+ ov::pass::Serialize(serialized_model, serialized_weigths).run_on_model(model);
+}
+
+TEST(PostponedOpSerializationTest, IncorrectRtInfo) {
+ auto constant = std::make_shared<PostponedOp>(ov::element::f16, ov::Shape{1, 2, 3, 4});
+ auto model = std::make_shared<ov::Model>(ov::OutputVector{constant});
+
+ EXPECT_CALL(*constant, evaluate).Times(0);
+
+ std::stringstream serialized_model, serialized_weigths;
+ ov::pass::Serialize(serialized_model, serialized_weigths).run_on_model(model);
+}
diff --git a/tools/benchmark_tool/openvino/__init__.py b/tools/benchmark_tool/openvino/__init__.py
index 0f19b7bfc9b..d5594ee4227 100644
--- a/tools/benchmark_tool/openvino/__init__.py
+++ b/tools/benchmark_tool/openvino/__init__.py
@@ -52,12 +52,12 @@ from openvino._pyopenvino import RemoteContext
from openvino._pyopenvino import RemoteTensor
# Import public classes from _ov_api
+from openvino._op_base import Op
from openvino._ov_api import Model
from openvino._ov_api import Core
from openvino._ov_api import CompiledModel
from openvino._ov_api import InferRequest
from openvino._ov_api import AsyncInferQueue
-from openvino._ov_api import Op
# Import all public modules
from openvino.package_utils import LazyLoader
diff --git a/tools/ovc/openvino/__init__.py b/tools/ovc/openvino/__init__.py
index 0f19b7bfc9b..d5594ee4227 100644
--- a/tools/ovc/openvino/__init__.py
+++ b/tools/ovc/openvino/__init__.py
@@ -52,12 +52,12 @@ from openvino._pyopenvino import RemoteContext
from openvino._pyopenvino import RemoteTensor
# Import public classes from _ov_api
+from openvino._op_base import Op
from openvino._ov_api import Model
from openvino._ov_api import Core
from openvino._ov_api import CompiledModel
from openvino._ov_api import InferRequest
from openvino._ov_api import AsyncInferQueue
-from openvino._ov_api import Op
# Import all public modules
from openvino.package_utils import LazyLoader