Skip to content

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

[Py OV] Extend Node with binary operations in openvino namespace (#29243)

Alicja Miloszewska95aa4b7352f9
diff --git a/src/bindings/python/src/openvino/runtime/__init__.py b/src/bindings/python/src/openvino/runtime/__init__.py
index 33421a07a05..6668a99f90e 100644
--- a/src/bindings/python/src/openvino/runtime/__init__.py
+++ b/src/bindings/python/src/openvino/runtime/__init__.py
@@ -88,16 +88,6 @@ from openvino.runtime.ie_api import compile_model
from openvino.utils import deprecated
# Extend Node class to support binary operators
-Node.__add__ = opset13.add
-Node.__sub__ = opset13.subtract
-Node.__mul__ = opset13.multiply
-Node.__div__ = opset13.divide
-Node.__truediv__ = opset13.divide
-Node.__radd__ = lambda left, right: opset13.add(right, left)
-Node.__rsub__ = lambda left, right: opset13.subtract(right, left)
-Node.__rmul__ = lambda left, right: opset13.multiply(right, left)
-Node.__rdiv__ = lambda left, right: opset13.divide(right, left)
-Node.__rtruediv__ = lambda left, right: opset13.divide(right, left)
Node.__eq__ = deprecated(version="2025.3", message="Use ops.equal instead")(opset13.equal)
Node.__ne__ = deprecated(version="2025.3", message="Use ops.not_equal instead")(opset13.not_equal)
Node.__lt__ = deprecated(version="2025.3", message="Use ops.less instead")(opset13.less)
diff --git a/src/bindings/python/src/pyopenvino/core/common.cpp b/src/bindings/python/src/pyopenvino/core/common.cpp
index 1c3594151dd..e06d5a8e947 100644
--- a/src/bindings/python/src/pyopenvino/core/common.cpp
+++ b/src/bindings/python/src/pyopenvino/core/common.cpp
@@ -8,7 +8,6 @@
#include "Python.h"
#include "openvino/core/except.hpp"
-#include "openvino/runtime/shared_buffer.hpp"
#include "openvino/util/common_util.hpp"
#include "pyopenvino/core/remote_tensor.hpp"
@@ -407,6 +406,27 @@ std::vector<size_t> _get_strides(const ov::op::v0::Constant& self) {
return self.get_strides();
}
}
+
+std::shared_ptr<ov::SharedBuffer<py::array>> get_shared_memory(py::array& array) {
+ // Check if passed array has C-style contiguous memory layout.
+ // If memory is going to be shared it needs to be contiguous before passing to the constructor.
+ // If ndim is equal to 0, creates scalar Constant.
+ // If size is equal to 0, creates empty Constant.
+ if (array_helpers::is_contiguous(array)) {
+ auto buffer = new ov::SharedBuffer<py::array>(
+ static_cast<char*>((array.ndim() == 0 || array.size() == 0) ? array.mutable_data() : array.mutable_data(0)),
+ array.ndim() == 0 ? array.itemsize() : array.nbytes(),
+ array);
+ std::shared_ptr<ov::SharedBuffer<py::array>> memory(buffer, [](ov::SharedBuffer<py::array>* buffer) {
+ py::gil_scoped_acquire acquire;
+ delete buffer;
+ });
+ return memory;
+ }
+ // If passed array is not C-style, throw an error.
+ OPENVINO_THROW("SHARED MEMORY MODE FOR THIS CONSTANT IS NOT APPLICABLE! Passed numpy array must be C contiguous.");
+}
+
}; // namespace constant_helpers
template <>
@@ -435,23 +455,9 @@ ov::op::v0::Constant create_copied(ov::Tensor& tensor) {
template <>
ov::op::v0::Constant create_shared(py::array& array) {
- // Check if passed array has C-style contiguous memory layout.
- // If memory is going to be shared it needs to be contiguous before passing to the constructor.
- // If ndim is equal to 0, creates scalar Constant.
- // If size is equal to 0, creates empty Constant.
- if (array_helpers::is_contiguous(array)) {
- auto buffer = new ov::SharedBuffer<py::array>(
- static_cast<char*>((array.ndim() == 0 || array.size() == 0) ? array.mutable_data() : array.mutable_data(0)),
- array.ndim() == 0 ? array.itemsize() : array.nbytes(),
- array);
- std::shared_ptr<ov::SharedBuffer<py::array>> memory(buffer, [](ov::SharedBuffer<py::array>* buffer) {
- py::gil_scoped_acquire acquire;
- delete buffer;
- });
- return ov::op::v0::Constant(type_helpers::get_ov_type(array), array_helpers::get_shape(array), memory);
- }
- // If passed array is not C-style, throw an error.
- OPENVINO_THROW("SHARED MEMORY MODE FOR THIS CONSTANT IS NOT APPLICABLE! Passed numpy array must be C contiguous.");
+ return ov::op::v0::Constant(type_helpers::get_ov_type(array),
+ array_helpers::get_shape(array),
+ constant_helpers::get_shared_memory(array));
}
template <>
@@ -664,4 +670,19 @@ ov::pass::Serialize::Version convert_to_version(const std::string& version) {
"'! The supported versions are: 'UNSPECIFIED'(default), 'IR_V10', 'IR_V11'.");
}
+std::shared_ptr<ov::Node> node_from_input_value(NodeInput& input) {
+ if (std::shared_ptr<ov::Node>* node = std::get_if<std::shared_ptr<ov::Node>>(&input)) {
+ return *node;
+ } else if (const int64_t* i_val = std::get_if<int64_t>(&input)) {
+ return std::make_shared<ov::op::v0::Constant>(ov::element::Type_t::i64, ov::Shape{}, i_val);
+ } else if (const double* f_val = std::get_if<double>(&input)) {
+ return std::make_shared<ov::op::v0::Constant>(ov::element::Type_t::f64, ov::Shape{}, f_val);
+ } else {
+ auto& np_array = std::get<py::array>(input);
+ return std::make_shared<ov::op::v0::Constant>(type_helpers::get_ov_type(np_array),
+ array_helpers::get_shape(np_array),
+ constant_helpers::get_shared_memory(np_array));
+ }
+}
+
}; // namespace Common
diff --git a/src/bindings/python/src/pyopenvino/core/common.hpp b/src/bindings/python/src/pyopenvino/core/common.hpp
index 25fe7c6cd01..335b0eed974 100644
--- a/src/bindings/python/src/pyopenvino/core/common.hpp
+++ b/src/bindings/python/src/pyopenvino/core/common.hpp
@@ -12,11 +12,13 @@
#include <string>
#include <iterator>
#include <climits>
+#include <variant>
#include "Python.h"
#include "openvino/core/type/element_type.hpp"
#include "openvino/runtime/compiled_model.hpp"
#include "openvino/runtime/infer_request.hpp"
+#include "openvino/runtime/shared_buffer.hpp"
#include "openvino/runtime/tensor.hpp"
#include "openvino/pass/serialize.hpp"
#include "pyopenvino/graph/any.hpp"
@@ -122,6 +124,8 @@ std::vector<size_t> _get_byte_strides(const ov::Shape& s) {
std::vector<size_t> _get_strides(const ov::op::v0::Constant& self);
+std::shared_ptr<ov::SharedBuffer<py::array>> get_shared_memory(py::array& array);
+
}; // namespace constant_helpers
// Helpers for shapes
@@ -184,6 +188,10 @@ std::string get_simple_repr(const T& obj) {
return "<" + class_name + ">";
}
+typedef std::variant<std::shared_ptr<ov::Node>, int64_t, double, py::array> NodeInput;
+
+std::shared_ptr<ov::Node> node_from_input_value(NodeInput& input);
+
// Use only with classes that are not creatable by users on Python's side, because
// Objects created in Python that are wrapped with such wrapper will cause memory leaks.
template <typename T>
diff --git a/src/bindings/python/src/pyopenvino/graph/node.cpp b/src/bindings/python/src/pyopenvino/graph/node.cpp
index 0f10f00fa7d..56af307c4a3 100644
--- a/src/bindings/python/src/pyopenvino/graph/node.cpp
+++ b/src/bindings/python/src/pyopenvino/graph/node.cpp
@@ -17,6 +17,7 @@
#include "openvino/op/divide.hpp"
#include "openvino/op/multiply.hpp"
#include "openvino/op/subtract.hpp"
+#include "pyopenvino/core/common.hpp"
#include "pyopenvino/graph/any.hpp"
#include "pyopenvino/graph/node.hpp"
#include "pyopenvino/graph/rt_map.hpp"
@@ -44,35 +45,118 @@ void regclass_graph_Node(py::module m) {
node.doc() = "openvino.Node wraps ov::Node";
node.def(
"__add__",
- [](const std::shared_ptr<ov::Node>& a, const std::shared_ptr<ov::Node> b) {
- return std::make_shared<ov::op::v1::Add>(a, b);
+ [](const std::shared_ptr<ov::Node>& left, Common::NodeInput& right) {
+ return std::shared_ptr<ov::Node>(
+ std::make_shared<ov::op::v1::Add>(left, Common::node_from_input_value(right)));
+ },
+ py::arg("right"),
+ R""(
+ Return node which applies f(A,B) = A+B to the input nodes element-wise.
+
+ :param right: The right operand.
+ :type right: Union[openvino.Node, int, float, numpy.ndarray]
+ :return: The node performing element-wise addition.
+ :rtype: openvino.Node
+ )"",
+ py::is_operator());
+ node.def(
+ "__radd__",
+ [](const std::shared_ptr<ov::Node>& right, Common::NodeInput& left) {
+ return std::shared_ptr<ov::Node>(
+ std::make_shared<ov::op::v1::Add>(Common::node_from_input_value(left), right));
},
py::is_operator());
node.def(
"__sub__",
- [](const std::shared_ptr<ov::Node>& a, const std::shared_ptr<ov::Node> b) {
- return std::make_shared<ov::op::v1::Subtract>(a, b);
+ [](const std::shared_ptr<ov::Node>& left, Common::NodeInput& right) {
+ return std::shared_ptr<ov::Node>(
+ std::make_shared<ov::op::v1::Subtract>(left, Common::node_from_input_value(right)));
+ },
+ py::arg("right"),
+ R""(
+ Return node which applies f(A,B) = A-B to the input nodes element-wise.
+
+ :param right: The right operand.
+ :type right: Union[openvino.Node, int, float, numpy.ndarray]
+ :return: The node performing element-wise subtraction.
+ :rtype: openvino.Node
+ )"",
+ py::is_operator());
+ node.def(
+ "__rsub__",
+ [](const std::shared_ptr<ov::Node>& right, Common::NodeInput& left) {
+ return std::shared_ptr<ov::Node>(
+ std::make_shared<ov::op::v1::Subtract>(Common::node_from_input_value(left), right));
},
py::is_operator());
node.def(
"__mul__",
- [](const std::shared_ptr<ov::Node>& a, const std::shared_ptr<ov::Node> b) {
- return std::make_shared<ov::op::v1::Multiply>(a, b);
+ [](const std::shared_ptr<ov::Node>& left, Common::NodeInput& right) {
+ return std::shared_ptr<ov::Node>(
+ std::make_shared<ov::op::v1::Multiply>(left, Common::node_from_input_value(right)));
},
+ py::arg("right"),
+ R""(
+ Return node which applies f(A,B) = A*B to the input nodes element-wise.
+
+ :param right: The right operand.
+ :type right: Union[openvino.Node, int, float, numpy.ndarray]
+ :return: The node performing element-wise multiplication.
+ :rtype: openvino.Node
+ )"",
py::is_operator());
node.def(
- "__div__",
- [](const std::shared_ptr<ov::Node>& a, const std::shared_ptr<ov::Node> b) {
- return std::make_shared<ov::op::v1::Divide>(a, b);
+ "__rmul__",
+ [](const std::shared_ptr<ov::Node>& right, Common::NodeInput& left) {
+ return std::shared_ptr<ov::Node>(
+ std::make_shared<ov::op::v1::Multiply>(Common::node_from_input_value(left), right));
},
py::is_operator());
node.def(
"__truediv__",
- [](const std::shared_ptr<ov::Node>& a, const std::shared_ptr<ov::Node> b) {
- return std::make_shared<ov::op::v1::Divide>(a, b);
+ [](const std::shared_ptr<ov::Node>& left, Common::NodeInput& right) {
+ return std::shared_ptr<ov::Node>(
+ std::make_shared<ov::op::v1::Divide>(left, Common::node_from_input_value(right)));
+ },
+ py::arg("right"),
+ R""(
+ Return node which applies f(A,B) = A/B to the input nodes element-wise.
+
+ :param right: The right operand.
+ :type right: Union[openvino.Node, int, float, numpy.ndarray]
+ :return: The node performing element-wise division.
+ :rtype: openvino.Node
+ )"",
+ py::is_operator());
+ node.def(
+ "__rtruediv__",
+ [](const std::shared_ptr<ov::Node>& right, Common::NodeInput& left) {
+ return std::shared_ptr<ov::Node>(
+ std::make_shared<ov::op::v1::Divide>(Common::node_from_input_value(left), right));
},
py::is_operator());
+ node.def(
+ "__array_ufunc__",
+ [](py::object self, py::object ufunc, const char* method, py::args inputs, py::kwargs kwargs) {
+ py::object result = py::none();
+ if (std::strcmp(method, "__call__") == 0) {
+ if (ufunc.is(py::module::import("numpy").attr("add"))) {
+ result = self.attr("__radd__")(inputs[0]);
+ } else if (ufunc.is(py::module::import("numpy").attr("subtract"))) {
+ result = self.attr("__rsub__")(inputs[0]);
+ } else if (ufunc.is(py::module::import("numpy").attr("multiply"))) {
+ result = self.attr("__rmul__")(inputs[0]);
+ } else if (ufunc.is(py::module::import("numpy").attr("divide"))) {
+ result = self.attr("__rtruediv__")(inputs[0]);
+ }
+ if (result.is_none()) {
+ throw py::type_error("Unsupported __array_ufunc__ operation between openvino.Node and np.array.");
+ }
+ }
+ return result;
+ });
+
node.def("__repr__", [](const ov::Node& self) {
std::string type_name = self.get_type_name();
std::stringstream shapes_ss;
diff --git a/src/bindings/python/tests/test_graph/test_ops_binary.py b/src/bindings/python/tests/test_graph/test_ops_binary.py
index 1a5a23e77da..3051acc0402 100644
--- a/src/bindings/python/tests/test_graph/test_ops_binary.py
+++ b/src/bindings/python/tests/test_graph/test_ops_binary.py
@@ -108,58 +108,58 @@ def test_binary_logical_op_with_scalar(graph_api_helper):
@pytest.mark.parametrize(
- ("operator", "expected_type", "warning_type"),
+ ("operator", "expected_ov_str", "expected_type"),
[
- (operator.add, Type.f32, warnings.catch_warnings(record=True)),
- (operator.sub, Type.f32, warnings.catch_warnings(record=True)),
- (operator.mul, Type.f32, warnings.catch_warnings(record=True)),
- (operator.truediv, Type.f32, warnings.catch_warnings(record=True)),
- (operator.eq, Type.boolean, pytest.warns(DeprecationWarning)),
- (operator.ne, Type.boolean, pytest.warns(DeprecationWarning)),
- (operator.gt, Type.boolean, pytest.warns(DeprecationWarning)),
- (operator.ge, Type.boolean, pytest.warns(DeprecationWarning)),
- (operator.lt, Type.boolean, pytest.warns(DeprecationWarning)),
- (operator.le, Type.boolean, pytest.warns(DeprecationWarning)),
+ (operator.add, "Add", Type.f32),
+ (operator.sub, "Subtract", Type.f32),
+ (operator.mul, "Multiply", Type.f32),
+ (operator.truediv, "Divide", Type.f32),
],
)
-def test_binary_operators(operator, expected_type, warning_type):
- value_b = np.array([[4, 5], [1, 7]], dtype=np.float32)
-
+ "value_b",
+ [
+ np.array([[4, 5], [1, 7]], dtype=np.float32),
+ np.array([[5, 6], [7, 8]], dtype=np.float32),
+ ov.parameter([2, 2], name="B", dtype=np.float32),
+ ],
+)
+def test_binary_operators(operator, expected_ov_str, expected_type, value_b):
shape = [2, 2]
parameter_a = ov.parameter(shape, name="A", dtype=np.float32)
- with warning_type:
- model = operator(parameter_a, value_b)
+ model = operator(parameter_a, value_b)
+ assert model.get_type_name() == expected_ov_str
assert model.get_output_size() == 1
assert list(model.get_output_shape(0)) == shape
assert model.get_output_element_type(0) == expected_type
@pytest.mark.parametrize(
- ("operator", "expected_type", "warning_type"),
+ ("operator", "expected_ov_str"),
[
- (operator.add, Type.f32, warnings.catch_warnings(record=True)),
- (operator.sub, Type.f32, warnings.catch_warnings(record=True)),
- (operator.mul, Type.f32, warnings.catch_warnings(record=True)),
- (operator.truediv, Type.f32, warnings.catch_warnings(record=True)),
- (operator.eq, Type.boolean, pytest.warns(DeprecationWarning)),
- (operator.ne, Type.boolean, pytest.warns(DeprecationWarning)),
- (operator.gt, Type.boolean, pytest.warns(DeprecationWarning)),
- (operator.ge, Type.boolean, pytest.warns(DeprecationWarning)),
- (operator.lt, Type.boolean, pytest.warns(DeprecationWarning)),
- (operator.le, Type.boolean, pytest.warns(DeprecationWarning)),
+ (operator.add, "Add"),
+ (operator.sub, "Subtract"),
+ (operator.mul, "Multiply"),
+ (operator.truediv, "Divide"),
],
)
-def test_binary_operators_with_scalar(operator, expected_type, warning_type):
- value_b = np.array([[5, 6], [7, 8]], dtype=np.float32)
-
+ ("expected_type", "value_a", "value_b"),
+ [
+ (Type.f64, ov.parameter([2, 2], name="A", dtype=np.float64), 3.12),
+ (Type.i64, ov.parameter([2, 2], name="A", dtype=np.int64), 2),
+ (Type.f64, 3.12, ov.parameter([2, 2], name="A", dtype=np.float64)),
+ (Type.i64, 2, ov.parameter([2, 2], name="A", dtype=np.int64)),
+ (Type.f32, np.array([[4, 5], [1, 7]], dtype=np.float32), ov.parameter([2, 2], name="B", dtype=np.float32)),
+ ],
+)
+def test_binary_operators_rside(operator, expected_ov_str, expected_type, value_a, value_b):
shape = [2, 2]
- parameter_a = ov.parameter(shape, name="A", dtype=np.float32)
-
- with warning_type:
- model = operator(parameter_a, value_b)
+ model = operator(value_a, value_b)
+ assert model.get_type_name() == expected_ov_str
assert model.get_output_size() == 1
assert list(model.get_output_shape(0)) == shape
assert model.get_output_element_type(0) == expected_type
diff --git a/src/bindings/python/tests/test_runtime/test_deprecated_runtime.py b/src/bindings/python/tests/test_runtime/test_deprecated_runtime.py
index 2ae4ee1b0d1..845659b17f3 100644
--- a/src/bindings/python/tests/test_runtime/test_deprecated_runtime.py
+++ b/src/bindings/python/tests/test_runtime/test_deprecated_runtime.py
@@ -7,6 +7,7 @@ import numpy as np
from pathlib import Path
from contextlib import nullcontext as does_not_raise
import warnings
+import operator
with pytest.warns(DeprecationWarning, match="The `openvino.runtime` module is deprecated and will be removed in the 2026.0 release."):
import openvino.runtime as ov
@@ -365,3 +366,62 @@ def test_runtime_passes_manager():
assert count_ops_of_type(model, node_ceil) == 0
assert count_ops_of_type(model, node_constant) == 1
+
+
+# from test_graph/test_ops_binary.py
+ ("operator", "expected_type", "warning_type"),
+ [
+ (operator.add, Type.f32, warnings.catch_warnings(record=True)),
+ (operator.sub, Type.f32, warnings.catch_warnings(record=True)),
+ (operator.mul, Type.f32, warnings.catch_warnings(record=True)),
+ (operator.truediv, Type.f32, warnings.catch_warnings(record=True)),
+ (operator.eq, Type.boolean, pytest.warns(DeprecationWarning)),
+ (operator.ne, Type.boolean, pytest.warns(DeprecationWarning)),
+ (operator.gt, Type.boolean, pytest.warns(DeprecationWarning)),
+ (operator.ge, Type.boolean, pytest.warns(DeprecationWarning)),
+ (operator.lt, Type.boolean, pytest.warns(DeprecationWarning)),
+ (operator.le, Type.boolean, pytest.warns(DeprecationWarning)),
+ ],
+)
+def test_binary_operators(operator, expected_type, warning_type):
+ value_b = np.array([[4, 5], [1, 7]], dtype=np.float32)
+
+ shape = [2, 2]
+ parameter_a = ops.parameter(shape, name="A", dtype=np.float32)
+
+ with warning_type:
+ model = operator(parameter_a, value_b)
+
+ assert model.get_output_size() == 1
+ assert list(model.get_output_shape(0)) == shape
+ assert model.get_output_element_type(0) == expected_type
+
+
+ ("operator", "expected_type", "warning_type"),
+ [
+ (operator.add, Type.f32, warnings.catch_warnings(record=True)),
+ (operator.sub, Type.f32, warnings.catch_warnings(record=True)),
+ (operator.mul, Type.f32, warnings.catch_warnings(record=True)),
+ (operator.truediv, Type.f32, warnings.catch_warnings(record=True)),
+ (operator.eq, Type.boolean, pytest.warns(DeprecationWarning)),
+ (operator.ne, Type.boolean, pytest.warns(DeprecationWarning)),
+ (operator.gt, Type.boolean, pytest.warns(DeprecationWarning)),
+ (operator.ge, Type.boolean, pytest.warns(DeprecationWarning)),
+ (operator.lt, Type.boolean, pytest.warns(DeprecationWarning)),
+ (operator.le, Type.boolean, pytest.warns(DeprecationWarning)),
+ ],
+)
+def test_binary_operators_with_scalar(operator, expected_type, warning_type):
+ value_b = np.array([[5, 6], [7, 8]], dtype=np.float32)
+
+ shape = [2, 2]
+ parameter_a = ops.parameter(shape, name="A", dtype=np.float32)
+
+ with warning_type:
+ model = operator(parameter_a, value_b)
+
+ assert model.get_output_size() == 1
+ assert list(model.get_output_shape(0)) == shape
+ assert model.get_output_element_type(0) == expected_type