Skip to content

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

[PyOV] OpExtension (#27664)

Anastasia Kuporosovaa0e8de0f6582
diff --git a/src/bindings/python/src/openvino/__init__.py b/src/bindings/python/src/openvino/__init__.py
index 151524545a9..70b5f372352 100644
--- a/src/bindings/python/src/openvino/__init__.py
+++ b/src/bindings/python/src/openvino/__init__.py
@@ -32,6 +32,7 @@ from openvino._pyopenvino import Version
from openvino._pyopenvino import Symbol
from openvino._pyopenvino import Dimension
from openvino._pyopenvino import Input
+from openvino._pyopenvino import OpExtension
from openvino._pyopenvino import Output
from openvino._pyopenvino import Node
from openvino._pyopenvino import Strides
@@ -49,7 +50,6 @@ from openvino._pyopenvino import save_model
from openvino._pyopenvino import layout_helpers
from openvino._pyopenvino import RemoteContext
from openvino._pyopenvino import RemoteTensor
-from openvino._pyopenvino import Op
# Import public classes from _ov_api
from openvino._ov_api import Model
@@ -57,6 +57,7 @@ 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 import runtime as runtime
diff --git a/src/bindings/python/src/openvino/_ov_api.py b/src/bindings/python/src/openvino/_ov_api.py
index ee3172be2b3..f1b69fb86fc 100644
--- a/src/bindings/python/src/openvino/_ov_api.py
+++ b/src/bindings/python/src/openvino/_ov_api.py
@@ -3,7 +3,7 @@
# SPDX-License-Identifier: Apache-2.0
from types import TracebackType
-from typing import Any, Iterable, Union, Optional, Dict, Type
+from typing import Any, Iterable, Union, Optional, Dict, Tuple, Type, List
from pathlib import Path
@@ -11,8 +11,8 @@ 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 Tensor
-from openvino._pyopenvino import Node
+from openvino._pyopenvino import Op as OpBase
+from openvino._pyopenvino import Node, Output, Tensor
from openvino.utils.data_helpers import (
OVDict,
@@ -22,6 +22,19 @@ from openvino.utils.data_helpers import (
)
+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/frontend/__init__.py b/src/bindings/python/src/openvino/frontend/__init__.py
index 95d410c51f4..ac2eff6819f 100644
--- a/src/bindings/python/src/openvino/frontend/__init__.py
+++ b/src/bindings/python/src/openvino/frontend/__init__.py
@@ -22,7 +22,7 @@ from openvino._pyopenvino import Place
# extensions
from openvino._pyopenvino import DecoderTransformationExtension
from openvino._pyopenvino import ConversionExtension
-from openvino._pyopenvino import OpExtension
+from openvino._pyopenvino.frontend import OpExtension
from openvino._pyopenvino import ProgressReporterExtension
from openvino._pyopenvino import TelemetryExtension
diff --git a/src/bindings/python/src/pyopenvino/core/core.cpp b/src/bindings/python/src/pyopenvino/core/core.cpp
index 57c796d8456..526ebb02952 100644
--- a/src/bindings/python/src/pyopenvino/core/core.cpp
+++ b/src/bindings/python/src/pyopenvino/core/core.cpp
@@ -14,6 +14,7 @@
#include "common.hpp"
#include "pyopenvino/core/remote_context.hpp"
+#include "pyopenvino/graph/op_extension.hpp"
#include "pyopenvino/utils/utils.hpp"
namespace py = pybind11;
@@ -703,6 +704,19 @@ void regclass_Core(py::module m) {
:type extensions: list[openvino.runtime.Extension]
)");
+ cls.def(
+ "add_extension",
+ [](ov::Core& self, py::object dtype) {
+ self.add_extension(PyOpExtension(dtype));
+ },
+ py::arg("custom_op"),
+ R"(
+ Registers custom Op to a Core object.
+
+ :param custom_op: type of custom Op
+ :type custom_op: openvino.Op
+ )");
+
cls.def("get_available_devices",
&ov::Core::get_available_devices,
py::call_guard<py::gil_scoped_release>(),
diff --git a/src/bindings/python/src/pyopenvino/core/extension.cpp b/src/bindings/python/src/pyopenvino/core/extension.cpp
index 5de781c6de1..ac8869fca1f 100644
--- a/src/bindings/python/src/pyopenvino/core/extension.cpp
+++ b/src/bindings/python/src/pyopenvino/core/extension.cpp
@@ -9,7 +9,7 @@
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
-#include "openvino/frontend/manager.hpp"
+#include "openvino/core/extension.hpp"
#include "pyopenvino/core/common.hpp"
namespace py = pybind11;
diff --git a/src/bindings/python/src/pyopenvino/frontend/extension.cpp b/src/bindings/python/src/pyopenvino/frontend/extension.cpp
index 8875690c140..69c0453ae93 100644
--- a/src/bindings/python/src/pyopenvino/frontend/extension.cpp
+++ b/src/bindings/python/src/pyopenvino/frontend/extension.cpp
@@ -142,9 +142,9 @@ void regclass_frontend_ProgressReporterExtension(py::module m) {
}
void regclass_frontend_OpExtension(py::module m) {
- py::class_<OpExtension<void>, std::shared_ptr<OpExtension<void>>, ConversionExtension> ext(m,
- "OpExtension",
- py::dynamic_attr());
+ py::module frontend = m.def_submodule("frontend");
+ py::class_<ov::frontend::OpExtension<void>, std::shared_ptr<ov::frontend::OpExtension<void>>, ConversionExtension>
+ ext(frontend, "OpExtension", py::dynamic_attr());
ext.def(py::init([](const std::string& fw_type_name,
const std::map<std::string, std::string>& attr_names_map,
diff --git a/src/bindings/python/src/pyopenvino/graph/discrete_type_info.cpp b/src/bindings/python/src/pyopenvino/graph/discrete_type_info.cpp
index c6a825a614f..6cd4586fa4a 100644
--- a/src/bindings/python/src/pyopenvino/graph/discrete_type_info.cpp
+++ b/src/bindings/python/src/pyopenvino/graph/discrete_type_info.cpp
@@ -8,28 +8,11 @@
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
-#include "openvino/core/type.hpp"
#include "pyopenvino/core/common.hpp"
#include "pyopenvino/utils/utils.hpp"
namespace py = pybind11;
-// DiscreteTypeInfo doesn't own provided memory. Wrapper allows to avoid leaks.
-class DiscreteTypeInfoWrapper : public ov::DiscreteTypeInfo {
-private:
- const std::string name_str;
- const std::string version_id_str;
-
-public:
- DiscreteTypeInfoWrapper(std::string _name_str, std::string _version_id_str)
- : DiscreteTypeInfo(nullptr, nullptr, nullptr),
- name_str(std::move(_name_str)),
- version_id_str(std::move(_version_id_str)) {
- name = name_str.c_str();
- version_id = version_id_str.c_str();
- }
-};
-
void regclass_graph_DiscreteTypeInfo(py::module m) {
py::class_<ov::DiscreteTypeInfo, std::shared_ptr<ov::DiscreteTypeInfo>> discrete_type_info(m, "DiscreteTypeInfo");
discrete_type_info.doc() = "openvino.runtime.DiscreteTypeInfo wraps ov::DiscreteTypeInfo";
diff --git a/src/bindings/python/src/pyopenvino/graph/discrete_type_info.hpp b/src/bindings/python/src/pyopenvino/graph/discrete_type_info.hpp
index 5a1f8b2c68d..4f3b69949ee 100644
--- a/src/bindings/python/src/pyopenvino/graph/discrete_type_info.hpp
+++ b/src/bindings/python/src/pyopenvino/graph/discrete_type_info.hpp
@@ -6,6 +6,26 @@
#include <pybind11/pybind11.h>
+#include "openvino/core/type.hpp"
+#include <string>
namespace py = pybind11;
+
+// DiscreteTypeInfo doesn't own provided memory. Wrapper allows to avoid leaks.
+class DiscreteTypeInfoWrapper : public ov::DiscreteTypeInfo {
+private:
+ const std::string name_str;
+ const std::string version_id_str;
+
+public:
+ DiscreteTypeInfoWrapper(std::string _name_str, std::string _version_id_str)
+ : DiscreteTypeInfo(nullptr, nullptr, nullptr),
+ name_str(std::move(_name_str)),
+ version_id_str(std::move(_version_id_str)) {
+ name = name_str.c_str();
+ version_id = version_id_str.c_str();
+ }
+};
+
+
void regclass_graph_DiscreteTypeInfo(py::module m);
diff --git a/src/bindings/python/src/pyopenvino/graph/node.cpp b/src/bindings/python/src/pyopenvino/graph/node.cpp
index cfa861bbbd4..146acf0ff65 100644
--- a/src/bindings/python/src/pyopenvino/graph/node.cpp
+++ b/src/bindings/python/src/pyopenvino/graph/node.cpp
@@ -439,6 +439,7 @@ void regclass_graph_Node(py::module m) {
node.def_property_readonly("type_info", &ov::Node::get_type_info);
node.def_property("friendly_name", &ov::Node::get_friendly_name, &ov::Node::set_friendly_name);
+ node.def("visit_attributes", &ov::Node::visit_attributes);
node.def("get_attributes", [](const std::shared_ptr<ov::Node>& self) {
util::DictAttributeSerializer dict_serializer(self);
return dict_serializer.get_attributes();
diff --git a/src/bindings/python/src/pyopenvino/graph/op.cpp b/src/bindings/python/src/pyopenvino/graph/op.cpp
index eadd4a657b6..f648b42018d 100644
--- a/src/bindings/python/src/pyopenvino/graph/op.cpp
+++ b/src/bindings/python/src/pyopenvino/graph/op.cpp
@@ -16,47 +16,61 @@
namespace py = pybind11;
-/// Trampoline class to support inheritance from TorchDecoder in Python
-class PyOp : public ov::op::Op {
-public:
- using ov::op::Op::Op;
-
- // Keeps a reference to the Python object to manage its lifetime
- PyOp(const py::object& py_obj) : py_handle(py_obj) {}
+void PyOp::validate_and_infer_types() {
+ PYBIND11_OVERRIDE(void, ov::op::Op, validate_and_infer_types);
+}
- void validate_and_infer_types() override {
- PYBIND11_OVERRIDE(void, ov::op::Op, validate_and_infer_types);
+bool PyOp::visit_attributes(ov::AttributeVisitor& value) {
+ py::gil_scoped_acquire gil; // Acquire the GIL while in this scope.
+ // Try to look up the overridden method on the Python side.
+ py::function overrided_py_method = pybind11::get_override(this, "visit_attributes");
+ if (overrided_py_method) { // method is found
+ return static_cast<py::bool_>(overrided_py_method(&value)); // Call the Python function.
}
+ return true;
+}
- bool visit_attributes(ov::AttributeVisitor& value) override {
- pybind11::gil_scoped_acquire gil; // Acquire the GIL while in this scope.
- // Try to look up the overridden method on the Python side.
- pybind11::function overrided_py_method = pybind11::get_override(this, "visit_attributes");
- if (overrided_py_method) { // method is found
- return static_cast<py::bool_>(overrided_py_method(&value)); // Call the Python function.
- }
- return false;
+std::shared_ptr<ov::Node> PyOp::clone_with_new_inputs(const ov::OutputVector& new_args) const {
+ py::gil_scoped_acquire gil; // Acquire the GIL while in this scope.
+ // Try to look up the overridden method on the Python side.
+ py::function overrided_py_method = pybind11::get_override(this, "clone_with_new_inputs");
+ if (overrided_py_method) { // method is found
+ auto result = overrided_py_method(new_args); // Call the Python function.
+ return result.cast<std::shared_ptr<ov::Node>>();
}
+ // Default implementation for clone_with_new_inputs
+ auto py_handle_type = py_handle.get_type();
+ auto new_py_object = py_handle_type(new_args);
+ return new_py_object.cast<std::shared_ptr<ov::Node>>();
+}
- std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override {
- PYBIND11_OVERRIDE_PURE(std::shared_ptr<Node>, ov::op::Op, clone_with_new_inputs, new_args);
- }
+const ov::op::Op::type_info_t& PyOp::get_type_info() const {
+ return *m_type_info;
+}
- const type_info_t& get_type_info() const override {
- PYBIND11_OVERRIDE(const ov::Node::type_info_t&, ov::op::Op, get_type_info);
- }
+bool PyOp::evaluate(ov::TensorVector& output_values, const ov::TensorVector& input_values) const {
+ PYBIND11_OVERRIDE(bool, ov::op::Op, evaluate, output_values, input_values);
+}
- bool evaluate(ov::TensorVector& output_values, const ov::TensorVector& input_values) const override {
- PYBIND11_OVERRIDE(bool, ov::op::Op, evaluate, output_values, input_values);
- }
+bool PyOp::has_evaluate() const {
+ PYBIND11_OVERRIDE(bool, ov::op::Op, has_evaluate);
+}
- bool has_evaluate() const override {
- PYBIND11_OVERRIDE(bool, ov::op::Op, has_evaluate);
+void PyOp::update_type_info() {
+ py::gil_scoped_acquire gil; // Acquire the GIL while in this scope.
+
+ // Try to look up the overridden method on the Python side.
+ py::function overriden_py_method = pybind11::get_override(this, "get_type_info");
+ if (overriden_py_method) {
+ const auto type_info_from_py = overriden_py_method();
+ if (!py::isinstance<ov::DiscreteTypeInfo>(type_info_from_py)) {
+ OPENVINO_THROW("operation type_info must be an instance of DiscreteTypeInfo, but ",
+ py::str(py::type::of(type_info_from_py)),
+ " is passed.");
+ }
+ m_type_info = type_info_from_py.cast<std::shared_ptr<ov::DiscreteTypeInfo>>();
}
-
-private:
- py::object py_handle; // Holds the Python object to manage its lifetime
-};
+}
void regclass_graph_Op(py::module m) {
py::class_<ov::op::Op, std::shared_ptr<ov::op::Op>, PyOp, ov::Node> op(m, "Op");
@@ -64,4 +78,8 @@ void regclass_graph_Op(py::module m) {
op.def(py::init([](const py::object& py_obj) {
return PyOp(py_obj);
}));
+
+ op.def("_update_type_info", [](PyOp& self) {
+ self.update_type_info();
+ });
}
diff --git a/src/bindings/python/src/pyopenvino/graph/op.hpp b/src/bindings/python/src/pyopenvino/graph/op.hpp
index 4b9a30a69f4..9ea602b764c 100644
--- a/src/bindings/python/src/pyopenvino/graph/op.hpp
+++ b/src/bindings/python/src/pyopenvino/graph/op.hpp
@@ -6,6 +6,43 @@
#include <pybind11/pybind11.h>
+#include "openvino/op/op.hpp"
+#include "openvino/core/node.hpp"
+#include "pyopenvino/graph/discrete_type_info.hpp"
+
namespace py = pybind11;
+/// Trampoline class to support inheritance from TorchDecoder in Python
+class PyOp : public ov::op::Op {
+public:
+ using ov::op::Op::Op;
+
+ PyOp() = default;
+
+ // Keeps a reference to the Python object to manage its lifetime
+ PyOp(const py::object& py_obj) : py_handle(py_obj) {
+ // Set default value for DiscreteTypeInfo
+ const auto py_class_name = py_handle.get_type().attr("__name__").cast<std::string>();
+ m_type_info = std::make_shared<DiscreteTypeInfoWrapper>(py_class_name, "extension");
+ }
+
+ void update_type_info();
+
+ void validate_and_infer_types() override;
+
+ bool visit_attributes(ov::AttributeVisitor& value) override;
+
+ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;
+
+ const type_info_t& get_type_info() const override;
+
+ bool evaluate(ov::TensorVector& output_values, const ov::TensorVector& input_values) const override;
+
+ bool has_evaluate() const override;
+
+private:
+ py::object py_handle; // Holds the Python object to manage its lifetime
+ std::shared_ptr<ov::DiscreteTypeInfo> m_type_info;
+};
+
void regclass_graph_Op(py::module m);
diff --git a/src/bindings/python/src/pyopenvino/graph/op_extension.cpp b/src/bindings/python/src/pyopenvino/graph/op_extension.cpp
new file mode 100644
index 00000000000..9922493efdf
--- /dev/null
+++ b/src/bindings/python/src/pyopenvino/graph/op_extension.cpp
@@ -0,0 +1,51 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/core/op_extension.hpp"
+
+#include <pybind11/pybind11.h>
+
+#include <pyopenvino/graph/op_extension.hpp>
+
+#include "pyopenvino/core/common.hpp"
+#include "pyopenvino/core/extension.hpp"
+#include "pyopenvino/graph/discrete_type_info.hpp"
+#include "pyopenvino/graph/node_output.hpp"
+#include "pyopenvino/graph/op.hpp"
+
+namespace py = pybind11;
+
+const ov::DiscreteTypeInfo& PyOpExtension::get_type_info() const {
+ return *m_type_info;
+}
+
+ov::OutputVector PyOpExtension::create(const ov::OutputVector& inputs, ov::AttributeVisitor& visitor) const {
+ py::gil_scoped_acquire acquire;
+
+ const auto node = py_handle_dtype();
+
+ node.attr("set_arguments")(py::cast(inputs));
+ if (node.attr("visit_attributes")(&visitor)) {
+ node.attr("constructor_validate_and_infer_types")();
+ }
+
+ return py::cast<ov::OutputVector>(node.attr("outputs")());
+}
+
+std::vector<ov::Extension::Ptr> PyOpExtension::get_attached_extensions() const {
+ return {};
+}
+
+void regclass_graph_OpExtension(py::module m) {
+ py::class_<PyOpExtension, std::shared_ptr<PyOpExtension>, ov::Extension> op_extension(m, "OpExtension");
+ op_extension.doc() = "openvino.OpExtension provides the base interface for OpenVINO extensions.";
+
+ op_extension.def("__repr__", [](const PyOpExtension& self) {
+ return Common::get_simple_repr(self);
+ });
+
+ op_extension.def(py::init([](py::object dtype) {
+ return PyOpExtension(dtype);
+ }));
+}
diff --git a/src/bindings/python/src/pyopenvino/graph/op_extension.hpp b/src/bindings/python/src/pyopenvino/graph/op_extension.hpp
new file mode 100644
index 00000000000..1f5f0e42d0c
--- /dev/null
+++ b/src/bindings/python/src/pyopenvino/graph/op_extension.hpp
@@ -0,0 +1,50 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <pybind11/pybind11.h>
+
+#include <pybind11/stl.h>
+#include <pybind11/stl_bind.h>
+
+#include "openvino/core/op_extension.hpp"
+#include "pyopenvino/graph/op.hpp"
+
+namespace py = pybind11;
+
+class PyOpExtension : public ov::BaseOpExtension {
+public:
+ PyOpExtension(const py::object& dtype) : py_handle_dtype{dtype} {
+ py::object py_issubclass = py::module::import("builtins").attr("issubclass");
+ if (!py_issubclass(dtype, py::type::of<PyOp>()).cast<bool>()) {
+ std::stringstream str;
+ str << "Unsupported data type : '" << dtype << "' is passed as an argument.";
+ OPENVINO_THROW(str.str());
+ }
+
+ py::object type_info;
+ try {
+ type_info = py_handle_dtype().attr("get_type_info")();
+ } catch (const std::exception &exc) {
+ OPENVINO_THROW("Creation of OpExtension failed: ", exc.what());
+ }
+
+ m_type_info = type_info.cast<std::shared_ptr<ov::DiscreteTypeInfo>>();
+ OPENVINO_ASSERT(m_type_info->name != nullptr && m_type_info->version_id != nullptr,
+ "Extension type should have information about operation set and operation type.");
+ }
+
+ const ov::DiscreteTypeInfo& get_type_info() const override;
+
+ ov::OutputVector create(const ov::OutputVector& inputs, ov::AttributeVisitor& visitor) const override;
+
+ std::vector<ov::Extension::Ptr> get_attached_extensions() const override;
+
+private:
+ py::object py_handle_dtype; // Holds the Python object to manage its lifetime
+ std::shared_ptr<ov::DiscreteTypeInfo> m_type_info;
+};
+
+void regclass_graph_OpExtension(py::module m);
diff --git a/src/bindings/python/src/pyopenvino/pyopenvino.cpp b/src/bindings/python/src/pyopenvino/pyopenvino.cpp
index 5ff4490368a..00d43223c1a 100644
--- a/src/bindings/python/src/pyopenvino/pyopenvino.cpp
+++ b/src/bindings/python/src/pyopenvino/pyopenvino.cpp
@@ -20,6 +20,7 @@
#include "pyopenvino/graph/node_input.hpp"
#include "pyopenvino/graph/node_output.hpp"
#include <pyopenvino/graph/op.hpp>
+#include <pyopenvino/graph/op_extension.hpp>
#if defined(ENABLE_OV_ONNX_FRONTEND)
# include "pyopenvino/graph/onnx_import/onnx_import.hpp"
#endif
@@ -228,7 +229,7 @@ PYBIND11_MODULE(_pyopenvino, m) {
You might want to use this function if you are developing a dynamically-loaded library which should clean up all
resources after itself when the library is unloaded.
)");
-
+ regclass_Extension(m);
regclass_graph_PyRTMap(m);
regmodule_graph_types(m);
regclass_graph_Symbol(m); // Symbol must be registered before Dimension
@@ -238,6 +239,7 @@ PYBIND11_MODULE(_pyopenvino, m) {
regclass_graph_PartialShape(m);
regclass_graph_Node(m);
regclass_graph_Op(m);
+ regclass_graph_OpExtension(m);
regclass_graph_Input(m);
regclass_graph_NodeFactory(m);
regclass_graph_Strides(m);
@@ -284,7 +286,6 @@ PYBIND11_MODULE(_pyopenvino, m) {
regclass_Version(m);
regclass_AsyncInferQueue(m);
regclass_ProfilingInfo(m);
- regclass_Extension(m);
regclass_RemoteContext(m);
regclass_RemoteTensor(m);
diff --git a/src/bindings/python/tests/test_graph/test_custom_op.py b/src/bindings/python/tests/test_graph/test_custom_op.py
index 841a4351948..a662c374956 100644
--- a/src/bindings/python/tests/test_graph/test_custom_op.py
+++ b/src/bindings/python/tests/test_graph/test_custom_op.py
@@ -7,12 +7,12 @@ import pytest
import numpy as np
from contextlib import nullcontext as does_not_raise
-from openvino import Op
-from openvino import CompiledModel, Model, Dimension, Shape, Tensor, compile_model, serialize
+from openvino import Op, OpExtension
+from openvino import CompiledModel, Core, Model, Dimension, Shape, Tensor, compile_model, serialize
from openvino import DiscreteTypeInfo
import openvino.opset14 as ops
-from tests.utils.helpers import create_filenames_for_ir
+from tests.utils.helpers import create_filenames_for_ir, compare_models
class CustomOp(Op):
@@ -55,10 +55,11 @@ def create_snake_model():
class CustomAdd(Op):
class_type_info = DiscreteTypeInfo("CustomAdd", "extension")
- def __init__(self, inputs):
+ def __init__(self, inputs=None):
super().__init__(self)
- self.set_arguments(inputs)
- self.constructor_validate_and_infer_types()
+ if inputs is not None:
+ self.set_arguments(inputs)
+ self.constructor_validate_and_infer_types()
def validate_and_infer_types(self):
self.set_output_type(0, self.get_input_element_type(0), self.get_input_partial_shape(0))
@@ -85,11 +86,12 @@ def create_add_model():
class CustomOpWithAttribute(Op):
class_type_info = DiscreteTypeInfo("CustomOpWithAttribute", "extension")
- def __init__(self, inputs, attrs):
+ def __init__(self, inputs=None, attrs=None):
super().__init__(self)
self._attrs = attrs
- self.set_arguments(inputs)
- self.constructor_validate_and_infer_types()
+ if inputs is not None:
+ self.set_arguments(inputs)
+ self.constructor_validate_and_infer_types()
def validate_and_infer_types(self):
self.set_output_type(0, self.get_input_element_type(0), self.get_input_partial_shape(0))
@@ -197,3 +199,90 @@ def test_custom_op():
input_tensor = Tensor(input_data)
results = request.infer({"data": input_tensor})
assert np.allclose(results[list(results)[0]], expected_output, 1e-4, 1e-4)
+
+
+class CustomSimpleOp(Op):
+ def __init__(self, *inputs):
+ super().__init__(self, inputs)
+
+ def validate_and_infer_types(self):
+ self.set_output_type(0, self.get_input_element_type(0), self.get_input_partial_shape(0))
+
+
+class CustomSimpleOpWithAttribute(Op):
+ class_type_info = DiscreteTypeInfo("CustomSimpleOpWithAttribute", "extension")
+
+ def __init__(self, inputs=None, **attrs):
+ super().__init__(self, inputs)
+ self._attrs = attrs
+
+ def validate_and_infer_types(self):
+ self.set_output_type(0, self.get_input_element_type(0), self.get_input_partial_shape(0))
+
+ @staticmethod
+ def get_type_info():
+ return CustomSimpleOpWithAttribute.class_type_info
+
+ def visit_attributes(self, visitor):
+ if self._attrs:
+ visitor.on_attributes(self._attrs)
+ return True
+
+
+def test_op_extension(prepared_paths):
+ input_shape = [2, 1]
+
+ core = Core()
+ core.add_extension(CustomSimpleOp)
+ core.add_extension(OpExtension(CustomSimpleOpWithAttribute))
+ core.add_extension(OpExtension(CustomAdd))
+
+ param1 = ops.parameter(Shape(input_shape), dtype=np.float32, name="data1")
+ param2 = ops.parameter(Shape(input_shape), dtype=np.float32, name="data2")
+ custom_simple = CustomSimpleOp(param1, param2)
+ assert custom_simple.get_type_name() == "CustomSimpleOp"
+ custom_simple.set_friendly_name("test_add")
+ custom_with_attribute = CustomSimpleOpWithAttribute([custom_simple], value_str="test_attribute")
+ custom_add = CustomAdd(inputs=[custom_with_attribute])
+ res = ops.result(custom_add, name="result")
+ simple_model = Model(res, [param1, param2], "SimpleModel")
+
+ cloned_model = simple_model.clone()
+ assert compare_models(simple_model, cloned_model)
+
+ xml_path, bin_path = prepared_paths
+ serialize(simple_model, xml_path, bin_path)
+ model_with_custom_op = core.read_model(xml_path)
+ assert compare_models(simple_model, model_with_custom_op)
+
+
+def test_fail_create_op_extension():
+ class OpWithBadClassTypeInfo(Op):
+ class_type_info = "OpWithBadClassTypeInfo"
+
+ def __init__(self, inputs=None):
+ super().__init__(self)
+ if inputs is not None:
+ self.set_arguments(inputs)
+ self.constructor_validate_and_infer_types()
+
+ @staticmethod
+ def get_type_info():
+ return OpWithBadClassTypeInfo.class_type_info
+
+ core = Core()
+ with pytest.raises(RuntimeError) as e:
+ core.add_extension(CustomOp)
+ assert "__init__() missing 1 required positional argument: 'inputs'" in str(e.value)
+
+ with pytest.raises(RuntimeError) as e:
+ core.add_extension(OpExtension(bool))
+ assert "Unsupported data type : '<class 'bool'>' is passed as an argument." in str(e.value)
+
+ with pytest.raises(RuntimeError) as e:
+ core.add_extension(bool)
+ assert "Unsupported data type : '<class 'bool'>' is passed as an argument." in str(e.value)
+
+ with pytest.raises(RuntimeError) as e:
+ core.add_extension(OpWithBadClassTypeInfo)
+ assert "operation type_info must be an instance of DiscreteTypeInfo, but <class 'str'> is passed." in str(e.value)
diff --git a/tools/benchmark_tool/openvino/__init__.py b/tools/benchmark_tool/openvino/__init__.py
index 151524545a9..70b5f372352 100644
--- a/tools/benchmark_tool/openvino/__init__.py
+++ b/tools/benchmark_tool/openvino/__init__.py
@@ -32,6 +32,7 @@ from openvino._pyopenvino import Version
from openvino._pyopenvino import Symbol
from openvino._pyopenvino import Dimension
from openvino._pyopenvino import Input
+from openvino._pyopenvino import OpExtension
from openvino._pyopenvino import Output
from openvino._pyopenvino import Node
from openvino._pyopenvino import Strides
@@ -49,7 +50,6 @@ from openvino._pyopenvino import save_model
from openvino._pyopenvino import layout_helpers
from openvino._pyopenvino import RemoteContext
from openvino._pyopenvino import RemoteTensor
-from openvino._pyopenvino import Op
# Import public classes from _ov_api
from openvino._ov_api import Model
@@ -57,6 +57,7 @@ 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 import runtime as runtime
diff --git a/tools/ovc/openvino/__init__.py b/tools/ovc/openvino/__init__.py
index 151524545a9..70b5f372352 100644
--- a/tools/ovc/openvino/__init__.py
+++ b/tools/ovc/openvino/__init__.py
@@ -32,6 +32,7 @@ from openvino._pyopenvino import Version
from openvino._pyopenvino import Symbol
from openvino._pyopenvino import Dimension
from openvino._pyopenvino import Input
+from openvino._pyopenvino import OpExtension
from openvino._pyopenvino import Output
from openvino._pyopenvino import Node
from openvino._pyopenvino import Strides
@@ -49,7 +50,6 @@ from openvino._pyopenvino import save_model
from openvino._pyopenvino import layout_helpers
from openvino._pyopenvino import RemoteContext
from openvino._pyopenvino import RemoteTensor
-from openvino._pyopenvino import Op
# Import public classes from _ov_api
from openvino._ov_api import Model
@@ -57,6 +57,7 @@ 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 import runtime as runtime