MCPcopy Create free account
hub / github.com/ml-explore/mlx-data / to_py_array

Function to_py_array

python/src/wrap.cpp:183–222  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

181};
182
183py::array to_py_array(const std::shared_ptr<const mlx::data::Array>& a) {
184 const py::capsule free_when_done(new PyArrayPayload({a}), [](void* payload) {
185 delete reinterpret_cast<PyArrayPayload*>(payload);
186 });
187 std::vector<int64_t> shape;
188 std::vector<int64_t> stride;
189 py::dtype pytype;
190 switch (a->type()) {
191 case mlx::data::ArrayType::Int8:
192 pytype = py::dtype("b");
193 break;
194 case mlx::data::ArrayType::UInt8:
195 pytype = py::dtype("B");
196 break;
197 case mlx::data::ArrayType::Int32:
198 pytype = py::dtype("i4");
199 break;
200 case mlx::data::ArrayType::Int64:
201 pytype = py::dtype("i8");
202 break;
203 case mlx::data::ArrayType::Float:
204 pytype = py::dtype("f");
205 break;
206 case mlx::data::ArrayType::Double:
207 pytype = py::dtype("d");
208 break;
209 default:
210 throw std::runtime_error("internal error: unknown type");
211 }
212 auto ndim = a->shape().size();
213 if (ndim > 0) {
214 stride = std::vector<int64_t>(ndim);
215 shape = a->shape();
216 stride[ndim - 1] = a->itemsize();
217 for (int i = ndim - 1; i > 0; i--) {
218 stride[i - 1] = stride[i] * a->shape(i);
219 }
220 }
221 return py::array(pytype, shape, stride, a->data(), free_when_done);
222}
223
224py::dict to_py_sample(const Sample& s) {
225 py::dict res;

Callers 5

mlx_data_export_datasetFunction · 0.85
init_mlx_data_coreFunction · 0.85
init_mlx_data_streamFunction · 0.85
to_py_sampleFunction · 0.85
init_mlx_data_bufferFunction · 0.85

Calls 5

typeMethod · 0.80
itemsizeMethod · 0.80
sizeMethod · 0.45
shapeMethod · 0.45
dataMethod · 0.45

Tested by

no test coverage detected