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
[PYTHON] add __deepcopy__, __copy__ for Tensor (#28860)
Aleksei Kashapov58ee4f27d00e
diff --git a/src/bindings/python/src/pyopenvino/core/tensor.cpp b/src/bindings/python/src/pyopenvino/core/tensor.cppindex 0ed8e753469..21ed87896a4 100644--- a/src/bindings/python/src/pyopenvino/core/tensor.cpp+++ b/src/bindings/python/src/pyopenvino/core/tensor.cpp@@ -496,4 +496,15 @@ void regclass_Tensor(py::module m) {return "<" + Common::get_class_name(self) + ": " + ss.str() + ">";});++ cls.def("__copy__", [](const ov::Tensor& self) {+ ov::Tensor dst = self;+ return dst;+ });++ cls.def("__deepcopy__", [](const ov::Tensor& self, py::dict& memo) {+ ov::Tensor dst(self.get_element_type(), self.get_shape());+ std::memcpy(dst.data(), self.data(), self.get_byte_size());+ return dst;+ });}diff --git a/src/bindings/python/tests/test_runtime/test_tensor.py b/src/bindings/python/tests/test_runtime/test_tensor.pyindex 54bee4f2f45..c3ee75ce39e 100644--- a/src/bindings/python/tests/test_runtime/test_tensor.py+++ b/src/bindings/python/tests/test_runtime/test_tensor.py@@ -2,6 +2,7 @@# Copyright (C) 2018-2025 Intel Corporation# SPDX-License-Identifier: Apache-2.0+from copy import deepcopy, copyimport osimport subprocessimport sys@@ -617,3 +618,25 @@ def test_tensor_keeps_memory():tensor = get_tensor()assert np.allclose(tensor.data[0][0][0:3], [0, 0, 1])+++ ("copy_func", "should_share_data"), [(copy, True), (deepcopy, False)]+)+def test_copy_and_deepcopy(copy_func, should_share_data):+ shape = (3, 4)+ value, outlier = 7, 100+ tensor_data = np.full(shape, value)+ tensor = ov.Tensor(tensor_data)+ tensor_copy = copy_func(tensor)++ assert np.array_equal(tensor_copy.data, tensor.data)+ assert tensor_copy is not tensor+ # Update value of the original tensor+ tensor.data[0, 0] = outlier+ assert tensor.data[0, 0] == outlier++ if should_share_data:+ assert tensor_copy.data[0, 0] == outlier+ else:+ assert tensor_copy.data[0, 0] == value