| 152 | )DOC"); |
| 153 | |
| 154 | static PyObject* tensor_method_numpy(TensorObject* self, |
| 155 | PyObject* args, |
| 156 | PyObject* kwargs) { |
| 157 | EAGER_TRY |
| 158 | if (kwargs) { |
| 159 | PyObject* arg = PyDict_GetItemString(kwargs, "force"); |
| 160 | if (arg && arg == Py_False) { |
| 161 | LOG(WARNING) << "Warning: Currently paddle.Tensor.numpy() only supports " |
| 162 | "force conversion i.e. t.detach().cpu().numpy()."; |
| 163 | } |
| 164 | } |
| 165 | auto& api = pybind11::detail::npy_api::get(); |
| 166 | if (!self->tensor.impl()) { |
| 167 | Py_intptr_t py_dims[phi::DDim::kMaxRank]; // NOLINT |
| 168 | Py_intptr_t py_strides[phi::DDim::kMaxRank]; // NOLINT |
| 169 | py_dims[0] = 0; |
| 170 | py_strides[0] = 0; |
| 171 | |
| 172 | PyObject* array = api.PyArray_NewFromDescr_( |
| 173 | api.PyArray_Type_, |
| 174 | api.PyArray_DescrFromType_(pybind11::detail::npy_api::NPY_FLOAT_), |
| 175 | 1, |
| 176 | py_dims, |
| 177 | py_strides, |
| 178 | nullptr, |
| 179 | pybind11::detail::npy_api::NPY_ARRAY_ALIGNED_ | |
| 180 | pybind11::detail::npy_api::NPY_ARRAY_WRITEABLE_, |
| 181 | nullptr); |
| 182 | return array; |
| 183 | } |
| 184 | auto tensor_dims = self->tensor.shape(); |
| 185 | auto numpy_dtype = TensorDtype2NumpyDtype(self->tensor.type()); |
| 186 | auto sizeof_dtype = phi::SizeOf(self->tensor.type()); |
| 187 | Py_intptr_t py_dims[phi::DDim::kMaxRank]; // NOLINT |
| 188 | Py_intptr_t py_strides[phi::DDim::kMaxRank]; // NOLINT |
| 189 | size_t py_rank = tensor_dims.size(); |
| 190 | size_t numel = 1; |
| 191 | if (self->tensor.is_dense_tensor()) { |
| 192 | auto tensor_stride = self->tensor.strides(); |
| 193 | |
| 194 | for (int i = static_cast<int>(tensor_dims.size()) - 1; i >= 0; --i) { |
| 195 | py_dims[i] = static_cast<Py_intptr_t>(tensor_dims[i]); |
| 196 | py_strides[i] = static_cast<Py_intptr_t>(sizeof_dtype * tensor_stride[i]); |
| 197 | numel *= py_dims[i]; |
| 198 | } |
| 199 | } else { |
| 200 | for (int i = static_cast<int>(tensor_dims.size()) - 1; i >= 0; --i) { |
| 201 | py_dims[i] = static_cast<Py_intptr_t>(tensor_dims[i]); |
| 202 | py_strides[i] = static_cast<Py_intptr_t>(sizeof_dtype * numel); |
| 203 | numel *= py_dims[i]; |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | if (!self->tensor.impl()->initialized()) { |
| 208 | if (tensor_dims.empty()) { |
| 209 | py_dims[0] = 0; |
| 210 | py_strides[0] = 0; |
| 211 | PyObject* array = api.PyArray_NewFromDescr_( |
nothing calls this directly
no test coverage detected