| 8 | namespace mx = mlx::core; |
| 9 | |
| 10 | void array_basics() { |
| 11 | // Make a scalar array: |
| 12 | mx::array x(1.0); |
| 13 | |
| 14 | // Get the value out of it: |
| 15 | auto s = x.item<float>(); |
| 16 | assert(s == 1.0); |
| 17 | |
| 18 | // Scalars have a size of 1: |
| 19 | size_t size = x.size(); |
| 20 | assert(size == 1); |
| 21 | |
| 22 | // Scalars have 0 dimensions: |
| 23 | int ndim = x.ndim(); |
| 24 | assert(ndim == 0); |
| 25 | |
| 26 | // The shape should be an empty vector: |
| 27 | auto shape = x.shape(); |
| 28 | assert(shape.empty()); |
| 29 | |
| 30 | // The datatype should be float32: |
| 31 | auto dtype = x.dtype(); |
| 32 | assert(dtype == mx::float32); |
| 33 | |
| 34 | // Specify the dtype when constructing the array: |
| 35 | x = mx::array(1, mx::int32); |
| 36 | assert(x.dtype() == mx::int32); |
| 37 | x.item<int>(); // OK |
| 38 | // x.item<float>(); // Undefined! |
| 39 | |
| 40 | // Make a multidimensional array: |
| 41 | x = mx::array({1.0f, 2.0f, 3.0f, 4.0f}, {2, 2}); |
| 42 | // mlx is row-major by default so the first row of this array |
| 43 | // is [1.0, 2.0] and the second row is [3.0, 4.0] |
| 44 | |
| 45 | // Make an array of shape {2, 2} filled with ones: |
| 46 | auto y = mx::ones({2, 2}); |
| 47 | |
| 48 | // Pointwise add x and y: |
| 49 | auto z = mx::add(x, y); |
| 50 | |
| 51 | // Same thing: |
| 52 | z = x + y; |
| 53 | |
| 54 | // mlx is lazy by default. At this point `z` only |
| 55 | // has a shape and a type but no actual data: |
| 56 | assert(z.dtype() == mx::float32); |
| 57 | assert(z.shape(0) == 2); |
| 58 | assert(z.shape(1) == 2); |
| 59 | |
| 60 | // To actually run the computation you must evaluate `z`. |
| 61 | // Under the hood, mlx records operations in a graph. |
| 62 | // The variable `z` is a node in the graph which points to its operation |
| 63 | // and inputs. When `eval` is called on an array (or arrays), the array and |
| 64 | // all of its dependencies are recursively evaluated to produce the result. |
| 65 | // Once an array is evaluated, it has data and is detached from its inputs. |
| 66 | mx::eval(z); |
| 67 | |