| 25 | namespace pybind { |
| 26 | |
| 27 | std::shared_ptr<mlx::data::Array> to_array(py::buffer a) { |
| 28 | auto is_contiguous = [](const py::buffer_info& info) { |
| 29 | bool contiguous = |
| 30 | info.ndim > 0 && info.strides[info.ndim - 1] == info.itemsize; |
| 31 | for (int i = 0; i < info.ndim - 1; i++) { |
| 32 | contiguous &= info.shape[i + 1] * info.strides[i + 1] == info.strides[i]; |
| 33 | } |
| 34 | return contiguous; |
| 35 | }; |
| 36 | |
| 37 | py::buffer_info info = a.request(); |
| 38 | if (info.ndim > 0 && !is_contiguous(info)) { |
| 39 | throw std::runtime_error( |
| 40 | "[to_array] Contiguous buffer expected -- maybe cast to np.array"); |
| 41 | } |
| 42 | |
| 43 | mlx::data::ArrayType dtype; |
| 44 | switch (info.format[0]) { |
| 45 | case 'b': |
| 46 | case 'S': |
| 47 | case 'U': |
| 48 | dtype = mlx::data::ArrayType::Int8; |
| 49 | break; |
| 50 | case 'B': |
| 51 | dtype = mlx::data::ArrayType::UInt8; |
| 52 | break; |
| 53 | case 'i': |
| 54 | dtype = mlx::data::ArrayType::Int32; |
| 55 | break; |
| 56 | case 'l': |
| 57 | dtype = mlx::data::ArrayType::Int64; |
| 58 | break; |
| 59 | case 'd': |
| 60 | dtype = mlx::data::ArrayType::Double; |
| 61 | break; |
| 62 | case 'f': |
| 63 | dtype = mlx::data::ArrayType::Float; |
| 64 | break; |
| 65 | default: { |
| 66 | std::ostringstream msg; |
| 67 | msg << "[to_array] Unsupported buffer type '" << info.format << "'"; |
| 68 | throw std::invalid_argument(msg.str()); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | std::vector<int64_t> shape; |
| 73 | shape.reserve(info.ndim); |
| 74 | for (auto i : info.shape) { |
| 75 | shape.push_back(static_cast<int64_t>(i)); |
| 76 | } |
| 77 | auto nbytes = |
| 78 | (info.ndim > 0) ? info.strides[0] * info.shape[0] : info.itemsize; |
| 79 | auto arr = std::make_shared<mlx::data::Array>(dtype, shape); |
| 80 | std::memcpy(arr->data(), info.ptr, nbytes); |
| 81 | |
| 82 | return arr; |
| 83 | } |
| 84 |
no test coverage detected