From 4a8b97eeaa84f787ee93f0531ef9699dc20b5a46 Mon Sep 17 00:00:00 2001 From: Zhou Wei <1183042833@qq.com> Date: Tue, 14 Mar 2023 22:00:28 +0800 Subject: [PATCH] [Zero Dim] hack process Tensor.numpy() from 0D to 1D to avoid much incompatible (#51586) --- paddle/fluid/pybind/eager_method.cc | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/paddle/fluid/pybind/eager_method.cc b/paddle/fluid/pybind/eager_method.cc index 2bf113ecc71..30a8d77ca1d 100644 --- a/paddle/fluid/pybind/eager_method.cc +++ b/paddle/fluid/pybind/eager_method.cc @@ -120,11 +120,24 @@ static PyObject* tensor_method_numpy(TensorObject* self, auto sizeof_dtype = phi::SizeOf(self->tensor.type()); Py_intptr_t py_dims[paddle::framework::DDim::kMaxRank]; Py_intptr_t py_strides[paddle::framework::DDim::kMaxRank]; + size_t py_rank = tensor_dims.size(); size_t numel = 1; - for (int i = tensor_dims.size() - 1; i >= 0; --i) { - py_dims[i] = static_cast(tensor_dims[i]); - py_strides[i] = sizeof_dtype * numel; - numel *= py_dims[i]; + if (py_rank == 0) { + // 0D Tensor hack process to 1D numpy, will remove in future + VLOG(0) << "Warning:: 0D Tensor cannot be used as Tensor.numpy()[0], Now " + "0D will be changed to 1D numpy to avoid this problem, but it's " + "not correct and will be removed in future. Please change " + "'Tensor.numpy()[0]' to 'float(Tensor)' or " + "'Tensor.numpy().item()' as soon as possible."; + py_rank = 1; + py_dims[0] = 1; + py_strides[0] = sizeof_dtype * numel; + } else { + for (int i = tensor_dims.size() - 1; i >= 0; --i) { + py_dims[i] = static_cast(tensor_dims[i]); + py_strides[i] = sizeof_dtype * numel; + numel *= py_dims[i]; + } } PyObject* array = api.PyArray_NewFromDescr_( -- GitLab