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] make Tensor responsible for keeping numpy memory (#26209)
Anastasia Kuporosovae3b06e9f351e
diff --git a/src/bindings/python/src/pyopenvino/core/tensor.cpp b/src/bindings/python/src/pyopenvino/core/tensor.cppindex 20c9b9aeec6..19d6816006b 100644--- a/src/bindings/python/src/pyopenvino/core/tensor.cpp+++ b/src/bindings/python/src/pyopenvino/core/tensor.cpp@@ -10,6 +10,7 @@#include "openvino/runtime/tensor.hpp"#include "pyopenvino/core/common.hpp"#include "pyopenvino/core/remote_tensor.hpp"+#include "pyopenvino/utils/utils.hpp"namespace py = pybind11;@@ -22,17 +23,17 @@ void regclass_Tensor(py::module m) {}),py::arg("array"),py::arg("shared_memory") = false,+ py::ov_extension::conditional_keep_alive<1, 2, 3>(),R"(Tensor's special constructor.:param array: Array to create the tensor from.:type array: numpy.array- :param shared_memory: If `True`, this Tensor memory is being shared with a host,- that means the responsibility of keeping host memory is- on the side of a user. Any action performed on the host- memory is reflected on this Tensor's memory!+ :param shared_memory: If `True`, this Tensor memory is being shared with a host.+ Any action performed on the host memory is reflected on this Tensor's memory!If `False`, data is being copied to this Tensor.Requires data to be C_CONTIGUOUS if `True`.+ If the passed array contains strings, the flag must be set to `False'.:type shared_memory: bool)");@@ -42,6 +43,7 @@ void regclass_Tensor(py::module m) {py::arg("array"),py::arg("shape"),py::arg("type") = ov::element::undefined,+ py::keep_alive<1, 2>(),R"(Another Tensor's special constructor.@@ -51,10 +53,8 @@ void regclass_Tensor(py::module m) {:param array: C_CONTIGUOUS numpy array which will be wrapped inopenvino.runtime.Tensor with given parameters (shape- and element_type). Array's memory is being shared with- a host, that means the responsibility of keeping host memory is- on the side of a user. Any action performed on the host- memory will be reflected on this Tensor's memory!+ and element_type). Array's memory is being shared with a host.+ Any action performed on the host memory will be reflected on this Tensor's memory!:type array: numpy.array:param shape: Shape of the new tensor.:type shape: openvino.runtime.Shape@@ -77,6 +77,7 @@ void regclass_Tensor(py::module m) {py::arg("array"),py::arg("shape"),py::arg("type") = ov::element::undefined,+ py::keep_alive<1, 2>(),R"(Another Tensor's special constructor.@@ -86,10 +87,8 @@ void regclass_Tensor(py::module m) {:param array: C_CONTIGUOUS numpy array which will be wrapped inopenvino.runtime.Tensor with given parameters (shape- and element_type). Array's memory is being shared with- a host, that means the responsibility of keeping host memory is- on the side of a user. Any action performed on the host- memory will be reflected on this Tensor's memory!+ and element_type). Array's memory is being shared with a host.+ Any action performed on the host memory will be reflected on this Tensor's memory!:type array: numpy.array:param shape: Shape of the new tensor.:type shape: list or tuple@@ -167,6 +166,7 @@ void regclass_Tensor(py::module m) {}),py::arg("port"),py::arg("array"),+ py::keep_alive<1, 3>(),R"(Constructs Tensor using port from node.Type and shape will be taken from the port.@@ -174,10 +174,8 @@ void regclass_Tensor(py::module m) {:param port: Output port from a node.:type param: openvino.runtime.Output:param array: C_CONTIGUOUS numpy array which will be wrapped in- openvino.runtime.Tensor. Array's memory is being shared with- a host, that means the responsibility of keeping host memory is- on the side of a user. Any action performed on the host- memory will be reflected on this Tensor's memory!+ openvino.runtime.Tensor. Array's memory is being shared wi a host.+ Any action performed on the host memory will be reflected on this Tensor's memory!:type array: numpy.array)");@@ -196,6 +194,7 @@ void regclass_Tensor(py::module m) {}),py::arg("port"),py::arg("array"),+ py::keep_alive<1, 3>(),R"(Constructs Tensor using port from node.Type and shape will be taken from the port.@@ -203,10 +202,8 @@ void regclass_Tensor(py::module m) {:param port: Output port from a node.:type param: openvino.runtime.ConstOutput:param array: C_CONTIGUOUS numpy array which will be wrapped in- openvino.runtime.Tensor. Array's memory is being shared with- a host, that means the responsibility of keeping host memory is- on the side of a user. Any action performed on the host- memory will be reflected on this Tensor's memory!+ openvino.runtime.Tensor. Array's memory is being shared with a host.+ Any action performed on the host memory will be reflected on this Tensor's memory!:type array: numpy.array)");diff --git a/src/bindings/python/src/pyopenvino/utils/utils.cpp b/src/bindings/python/src/pyopenvino/utils/utils.cppindex 845691749b6..3b7501824c8 100644--- a/src/bindings/python/src/pyopenvino/utils/utils.cpp+++ b/src/bindings/python/src/pyopenvino/utils/utils.cpp@@ -442,3 +442,36 @@ std::shared_ptr<py::function> wrap_pyfunction(py::function f_callback) {}}; // namespace utils}; // namespace Common++namespace pybind11 {+namespace ov_extension {+void conditional_keep_alive_impl(size_t Nurse,+ size_t Patient,+ size_t Condition,+ detail::function_call& call,+ handle ret) {+ auto get_arg = [&](size_t n) {+ if (n == 0) {+ return ret;+ }+ if (n == 1 && call.init_self) {+ return call.init_self;+ }+ if (n <= call.args.size()) {+ return call.args[n - 1];+ }+ return handle();+ };++ const auto cd = get_arg(Condition);+ if (!cd || !py::isinstance<py::bool_>(cd)) {+ pybind11_fail("Could not activate conditional_keep_alive!");+ }++ if (cd.cast<bool>()) {+ detail::keep_alive_impl(get_arg(Nurse), get_arg(Patient));+ }+}++}; // namespace ov_extension+}; // namespace pybind11diff --git a/src/bindings/python/src/pyopenvino/utils/utils.hpp b/src/bindings/python/src/pyopenvino/utils/utils.hppindex 2a376cc27b4..b59ffe530f6 100644--- a/src/bindings/python/src/pyopenvino/utils/utils.hpp+++ b/src/bindings/python/src/pyopenvino/utils/utils.hpp@@ -66,3 +66,24 @@ namespace utils {}; // namespace utils}; // namespace Common++namespace pybind11 {+namespace ov_extension {+ void conditional_keep_alive_impl(size_t Nurse, size_t Patient, size_t Condition, detail::function_call &call, handle ret);++ // Keep patient alive while nurse lives+ template <size_t Nurse, size_t Patient, size_t Condition>+ struct conditional_keep_alive {};++}; // namespace ov_extension++ // Process a conditional_keep_alive call policy -- invokes conditional_keep_alive_impl during the the pre-call handler+ template <size_t Nurse, size_t Patient, size_t Condition>+ struct detail::process_attribute<ov_extension::conditional_keep_alive<Nurse, Patient, Condition>>+ : public detail::process_attribute_default<ov_extension::conditional_keep_alive<Nurse, Patient, Condition>> {+ static void precall(function_call &call) {+ ov_extension::conditional_keep_alive_impl(Nurse, Patient, Condition, call, handle());+ }+ };++}; // namespace pybind11diff --git a/src/bindings/python/tests/test_graph/test_gather.py b/src/bindings/python/tests/test_graph/test_gather.pyindex b578b6ac4a8..8db7ed5abd8 100644--- a/src/bindings/python/tests/test_graph/test_gather.py+++ b/src/bindings/python/tests/test_graph/test_gather.py@@ -47,5 +47,5 @@ def test_gather_string(data_str, input_shape, indices, axis, expected_shape, batassert list(node.get_output_shape(0)) == expected_shapeassert node.get_output_element_type(0) == Type.string- node.evaluate([out_tensor], [Tensor(input_data), Tensor(input_indices), Tensor(input_axis)])+ node.evaluate([out_tensor], [Tensor(input_data, shared_memory=False), Tensor(input_indices), Tensor(input_axis)])assert np.array(data_str[indices[0]]) == out_tensor.str_datadiff --git a/src/bindings/python/tests/test_runtime/test_tensor.py b/src/bindings/python/tests/test_runtime/test_tensor.pyindex da38c93fa91..019eab6dbc5 100644--- a/src/bindings/python/tests/test_runtime/test_tensor.py+++ b/src/bindings/python/tests/test_runtime/test_tensor.py@@ -161,38 +161,59 @@ def test_init_with_numpy_copy_memory(ov_type, numpy_dtype):def test_init_with_node_output_port():- param1 = ops.parameter(ov.Shape([1, 3, 2, 2]), dtype=np.float64)- param2 = ops.parameter(ov.Shape([1, 3, 32, 32]), dtype=np.float64)- param3 = ops.parameter(ov.PartialShape.dynamic(), dtype=np.float64)- ones_arr = np.ones(shape=(1, 3, 32, 32), dtype=np.float64)- tensor1 = ov.Tensor(param1.output(0))- tensor2 = ov.Tensor(param2.output(0), ones_arr)- tensor3 = ov.Tensor(param3.output(0))- tensor4 = ov.Tensor(param3.output(0), ones_arr)- assert tensor1.shape == param1.shape- assert tensor1.element_type == param1.get_element_type()- assert tensor2.shape == param2.shape- assert tensor2.element_type == param2.get_element_type()- assert tensor3.shape == ov.Shape([0])- assert tensor3.element_type == param3.get_element_type()- assert tensor4.shape == ov.Shape([0])- assert tensor4.element_type == param3.get_element_type()+ def get_tensor():+ param1 = ops.parameter(ov.Shape([1, 3, 2, 2]), dtype=np.float64)+ param2 = ops.parameter(ov.Shape([1, 3, 32, 32]), dtype=np.float64)+ param3 = ops.parameter(ov.PartialShape.dynamic(), dtype=np.float64)+ ones_arr = np.ones(shape=(1, 3, 32, 32), dtype=np.float64)+ assert sys.getrefcount(ones_arr) == 2+ tensor1 = ov.Tensor(param1.output(0))+ tensor2 = ov.Tensor(param2.output(0), ones_arr)+ assert sys.getrefcount(ones_arr) == 3+ tensor3 = ov.Tensor(param3.output(0))+ tensor4 = ov.Tensor(param3.output(0), ones_arr)+ assert tensor1.shape == param1.shape+ assert tensor1.element_type == param1.get_element_type()+ assert tensor2.shape == param2.shape+ assert tensor2.element_type == param2.get_element_type()+ assert tensor3.shape == ov.Shape([0])+ assert tensor3.element_type == param3.get_element_type()+ assert tensor4.shape == ov.Shape([0])+ assert tensor4.element_type == param3.get_element_type()+ ones_arr[0][0][0][0:2] = 0++ del ones_arr+ return tensor2++ shared_tensor = get_tensor()+ assert np.allclose(shared_tensor.data[0][0][0][0:3], [0, 0, 1])def test_init_with_node_constoutput_port(device):- compiled_model = generate_relu_compiled_model(device)- output = compiled_model.output(0)- ones_arr = np.ones(shape=(1, 3, 32, 32), dtype=np.float32)+ def get_tensor():+ compiled_model = generate_relu_compiled_model(device)+ output = compiled_model.output(0)+ ones_arr = np.ones(shape=(1, 3, 32, 32), dtype=np.float32)+ assert sys.getrefcount(ones_arr) == 2++ tensor1 = ov.Tensor(output)+ tensor2 = ov.Tensor(output, ones_arr)+ assert sys.getrefcount(ones_arr) == 3++ output_node = output.get_node()+ assert tensor1.shape == output_node.shape+ assert tensor1.element_type == output_node.get_element_type()+ assert tensor2.shape == output_node.shape+ assert tensor2.element_type == output_node.get_element_type()+ assert np.array_equal(tensor2.data, ones_arr)- tensor1 = ov.Tensor(output)- tensor2 = ov.Tensor(output, ones_arr)+ ones_arr[0][0][0][0:2] = 0- output_node = output.get_node()- assert tensor1.shape == output_node.shape- assert tensor1.element_type == output_node.get_element_type()- assert tensor2.shape == output_node.shape- assert tensor2.element_type == output_node.get_element_type()- assert np.array_equal(tensor2.data, ones_arr)+ del ones_arr+ return tensor2++ tensor = get_tensor()+ assert np.allclose(tensor.data[0][0][0][0:3], [0, 0, 1])def test_init_with_output_port_different_shapes():@@ -580,3 +601,19 @@ def test_init_from_list(init_value):assert tuple(tensor.shape) == _init_value.shapeassert tensor.element_type.to_dtype() == _init_value.dtypeassert tensor.byte_size == _init_value.nbytes+++def test_tensor_keeps_memory():+ def get_tensor():+ arr = np.ones((8, 16, 300), dtype=np.float32)+ assert sys.getrefcount(arr) == 2++ shared_tensor = ov.Tensor(arr, shared_memory=True)+ arr[0][0][0:2] = 0+ assert sys.getrefcount(arr) == 3++ del arr+ return shared_tensor++ tensor = get_tensor()+ assert np.allclose(tensor.data[0][0][0:3], [0, 0, 1])diff --git a/src/bindings/python/tests/test_runtime/test_tensor_string.py b/src/bindings/python/tests/test_runtime/test_tensor_string.pyindex 763ff6f4c9d..ff9b40504c7 100644--- a/src/bindings/python/tests/test_runtime/test_tensor_string.py+++ b/src/bindings/python/tests/test_runtime/test_tensor_string.py@@ -258,7 +258,7 @@ def test_empty_tensor_populate(init_type, init_shape, string_data, data_getter):def test_invalid_bytes_replaced():string_data = np.array(b"\xe2\x80")- tensor = ov.Tensor(string_data)+ tensor = ov.Tensor(string_data, shared_memory=False)# Encoded:check_bytes_based(tensor, string_data, to_flat=True)