Skip to content

Commit

Permalink
[PYTHON] add __deepcopy__, __copy__ for Tensor (#28860)
Browse files Browse the repository at this point in the history
### Details:
Add support of `deepcopy()` and `copy()` for ov.Tensor Python API
`copy()` returns a shallow copy, `deepcopy()` a new object with its own
data buffer

### Ticket:
161969
  • Loading branch information
kshpv authored Feb 10, 2025
1 parent 4d54efa commit 58ee4f2
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/bindings/python/src/pyopenvino/core/tensor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});
}
23 changes: 23 additions & 0 deletions src/bindings/python/tests/test_runtime/test_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# Copyright (C) 2018-2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

from copy import deepcopy, copy
import os
import subprocess
import sys
Expand Down Expand Up @@ -617,3 +618,25 @@ def get_tensor():

tensor = get_tensor()
assert np.allclose(tensor.data[0][0][0:3], [0, 0, 1])


@pytest.mark.parametrize(
("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

0 comments on commit 58ee4f2

Please sign in to comment.