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
[PyOV] Retain plain NodeFactory extension owners (#39606)
Rhonin Wang000d86dbe1c6
diff --git a/src/bindings/python/src/pyopenvino/graph/node_factory.cpp b/src/bindings/python/src/pyopenvino/graph/node_factory.cppindex 5bcbe87c2ad..6cb85afdd68 100644--- a/src/bindings/python/src/pyopenvino/graph/node_factory.cpp+++ b/src/bindings/python/src/pyopenvino/graph/node_factory.cpp@@ -40,9 +40,12 @@ public:const ov::OutputVector& arguments,const py::dict& attributes = py::dict()) {// Check for available extensions first, because they may override ops from main opset- auto ext_it = m_opset_so_extensions.find(op_type_name);- if (ext_it != m_opset_so_extensions.end()) {- auto op_extension = std::dynamic_pointer_cast<ov::BaseOpExtension>(ext_it->second->extension());+ auto ext_it = m_opset_extensions.find(op_type_name);+ if (ext_it != m_opset_extensions.end()) {+ const auto& extension = ext_it->second;+ auto so_extension = std::dynamic_pointer_cast<ov::detail::SOExtension>(extension);+ ov::Extension::Ptr extension_extracted = so_extension ? so_extension->extension() : extension;+ auto op_extension = std::dynamic_pointer_cast<ov::BaseOpExtension>(extension_extracted);OPENVINO_ASSERT(op_extension); // guaranteed by add_extension methodutil::DictAttributeDeserializer visitor(attributes, m_variables);auto outputs = op_extension->create(arguments, visitor);@@ -74,9 +77,9 @@ public:std::shared_ptr<ov::Node> create(const std::string op_type_name) {// Check for available extensions first, because they may override ops from main opset- auto ext_it = m_opset_so_extensions.find(op_type_name);+ auto ext_it = m_opset_extensions.find(op_type_name);// No way to instantiate operation without inputs, so if extension operation is found report an error.- OPENVINO_ASSERT(ext_it == m_opset_so_extensions.end(),+ OPENVINO_ASSERT(ext_it == m_opset_extensions.end(),"Couldn't create operation of type ",op_type_name," from an extension library as no inputs were provided. Currently NodeFactory doesn't support ",@@ -99,14 +102,14 @@ public:ov::Extension::Ptr extension_extracted = so_extension ? so_extension->extension() : extension;if (auto op_extension = std::dynamic_pointer_cast<ov::BaseOpExtension>(extension_extracted)) {auto op_type = op_extension->get_type_info().name;- // keep so extension instead of extension_extracted to hold loaded library- m_opset_so_extensions[op_type] = so_extension;+ // Keep the original owner, including its library when it is an SOExtension.+ m_opset_extensions[op_type] = extension;}}void add_extension(const std::vector<std::shared_ptr<ov::Extension>>& extensions) {// Load extension library, seach for operation extensions (derived from ov::BaseOpExtension) and keep- // them in m_opset_so_extensions for future use in create methods.+ // them in m_opset_extensions for future use in create methods.// NodeFactory provides a simplified API for node creation without involving version of operation.// It means all operations share the same name space and real operation versions (opsets) from extension// library are ignored.@@ -115,15 +118,15 @@ public:ov::Extension::Ptr extension_extracted = so_extension ? so_extension->extension() : extension;if (auto op_extension = std::dynamic_pointer_cast<ov::BaseOpExtension>(extension_extracted)) {auto op_type = op_extension->get_type_info().name;- // keep so extension instead of extension_extracted to hold loaded library- m_opset_so_extensions[op_type] = so_extension;+ // Keep the original owner, including its library when it is an SOExtension.+ m_opset_extensions[op_type] = extension;}}}void add_extension(const std::filesystem::path& lib_path) {// Load extension library, seach for operation extensions (derived from ov::BaseOpExtension) and keep- // them in m_opset_so_extensions for future use in create methods.+ // them in m_opset_extensions for future use in create methods.// NodeFactory provides a simplified API for node creation without involving version of operation.// It means all operations share the same name space and real operation versions (opsets) from extension// library are ignored.@@ -133,8 +136,8 @@ public:ov::Extension::Ptr extension_extracted = so_extension ? so_extension->extension() : extension;if (auto op_extension = std::dynamic_pointer_cast<ov::BaseOpExtension>(extension_extracted)) {auto op_type = op_extension->get_type_info().name;- // keep so extension instead of extension_extracted to hold loaded library- m_opset_so_extensions[op_type] = so_extension;+ // Keep the original owner, including its library when it is an SOExtension.+ m_opset_extensions[op_type] = extension;}}}@@ -154,7 +157,7 @@ private:}const ov::OpSet& m_opset = ov::get_opset13();- std::map<std::string, std::shared_ptr<ov::detail::SOExtension>> m_opset_so_extensions;+ std::map<std::string, std::shared_ptr<ov::Extension>> m_opset_extensions;std::unordered_map<std::string, std::shared_ptr<ov::op::util::Variable>> m_variables;};} // namespacediff --git a/src/bindings/python/tests/test_graph/test_node_factory.py b/src/bindings/python/tests/test_graph/test_node_factory.pyindex 721478cf328..ff1943ae20f 100644--- a/src/bindings/python/tests/test_graph/test_node_factory.py+++ b/src/bindings/python/tests/test_graph/test_node_factory.py@@ -2,11 +2,12 @@# Copyright (C) 2018-2026 Intel Corporation# SPDX-License-Identifier: Apache-2.0+import gcimport numpy as npimport pytestfrom sys import platformfrom openvino import compile_model, Model-from openvino import Extension+from openvino import DiscreteTypeInfo, Extension, Op, OpExtension, Tensor, Typeimport openvino.opset8 as ovfrom openvino.exceptions import UserInputErrorfrom openvino.utils.node_factory import NodeFactory@@ -139,3 +140,55 @@ def test_add_extension():data = ov.parameter([1, 2], dtype=np.float32)param = factory.create("Parameter", data.outputs())assert param is not None++[email protected]("registration", ["direct", "list"])+def test_plain_extension_retains_owner(registration):+ class PlainIdentity(Op):+ class_type_info = DiscreteTypeInfo("PlainFactoryIdentity", "extension")++ def __init__(self, inputs=None):+ super().__init__(self)+ if inputs is not None:+ self.set_arguments(inputs)+ self.constructor_validate_and_infer_types()++ def get_type_info(self):+ return self.class_type_info++ def visit_attributes(self, visitor):+ return True++ def validate_and_infer_types(self):+ self.set_output_type(0, self.get_input_element_type(0), self.get_input_partial_shape(0))++ def clone_with_new_inputs(self, inputs):+ return PlainIdentity(inputs)++ def has_evaluate(self):+ return True++ def evaluate(self, outputs, inputs):+ inputs[0].copy_to(outputs[0])+ return True++ class EmptyExtension(Extension):+ def __init__(self):+ super().__init__()++ factory = NodeFactory()+ extension = OpExtension(PlainIdentity)+ factory.add_extension(extension if registration == "direct" else [EmptyExtension(), extension])+ del extension+ gc.collect()++ input_parameter = ov.parameter([2, 3], dtype=np.float32)+ node = factory.create("PlainFactoryIdentity", [input_parameter], {})+ assert list(node.output(0).shape) == [2, 3]+ assert node.output(0).element_type == Type.f32+ model = Model([node], [input_parameter])+ values = np.array([[1.25, -2.5, 0], [3.5, -1, 7.75]], dtype=np.float32)+ output = Tensor(Type.f32, [2, 3])+ assert model.evaluate([output], [Tensor(values)])+ np.testing.assert_array_equal(output.data, values)+ del model, node