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] Keep f16 type when creating Constant from non-contiguous array (#38954)
Oke Iyanuoluwa Enoch6bc76cf3c178
diff --git a/src/bindings/python/src/pyopenvino/core/common.cpp b/src/bindings/python/src/pyopenvino/core/common.cppindex 8143e0f3c1f..7ec1d9fc221 100644--- a/src/bindings/python/src/pyopenvino/core/common.cpp+++ b/src/bindings/python/src/pyopenvino/core/common.cpp@@ -443,18 +443,20 @@ std::shared_ptr<ov::SharedBuffer<py::array>> get_shared_memory(py::array& array)template <>ov::op::v0::Constant create_copied(py::array& array) {+ // Take the type before conversion, as_contiguous may return a view with a different dtype (e.g. f16 as int16).+ const auto type = type_helpers::get_ov_type(array);// Do not copy data from the array, only return empty tensor based on type.if (array.size() == 0) {- return ov::op::v0::Constant(type_helpers::get_ov_type(array), array_helpers::get_shape(array));+ return ov::op::v0::Constant(type, array_helpers::get_shape(array));}// Convert to contiguous array if not already in C-style.if (!array_helpers::is_contiguous(array)) {- array = array_helpers::as_contiguous(array, type_helpers::get_ov_type(array));+ array = array_helpers::as_contiguous(array, type);}// Create actual Constant and a constructor is copying data.// If ndim is equal to 0, creates scalar Constant.// If size is equal to 0, creates empty Constant.- return ov::op::v0::Constant(type_helpers::get_ov_type(array),+ return ov::op::v0::Constant(type,array_helpers::get_shape(array),array.ndim() == 0 ? array.data() : array.data(0));}diff --git a/src/bindings/python/tests/test_graph/test_constant.py b/src/bindings/python/tests/test_graph/test_constant.pyindex 5766a6c074b..09b5320772f 100644--- a/src/bindings/python/tests/test_graph/test_constant.py+++ b/src/bindings/python/tests/test_graph/test_constant.py@@ -814,3 +814,33 @@ def test_const_from_tensor_with_shared_memory_by_default():arr += 1assert np.array_equal(ov_const.data, arr)assert np.shares_memory(arr, ov_const.data)+++ ("src_dtype", "ov_type"),+ [+ (np.float16, Type.f16),+ (np.float32, Type.f32),+ (np.int8, Type.i8),+ (np.uint16, Type.u16),+ (np.bool_, Type.boolean),+ ],+)+ "make_view",+ [+ lambda arr: arr[:, ::2],+ lambda arr: arr.T,+ lambda arr: arr[::-1],+ ],+)+def test_constant_from_non_contiguous_array_keeps_type(src_dtype, ov_type, make_view):+ arr = make_view(np.arange(24).reshape(4, 6).astype(src_dtype))+ assert not arr.flags["C_CONTIGUOUS"]++ ov_const = ops.constant(arr)++ assert ov_const.get_element_type() == ov_type+ assert list(ov_const.shape) == list(arr.shape)+ assert ov_const.data.dtype == arr.dtype+ assert np.array_equal(ov_const.data, arr)