torobi 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +71 -0
  3. data/Cargo.lock +539 -0
  4. data/Cargo.toml +6 -0
  5. data/LICENSE +21 -0
  6. data/README.md +259 -0
  7. data/config/ops.yml +230 -0
  8. data/docs/plan.md +3982 -0
  9. data/docs/vendoring.md +656 -0
  10. data/engine/Cargo.toml +35 -0
  11. data/engine/build.rs +253 -0
  12. data/engine/src/checkpoint.rs +513 -0
  13. data/engine/src/executor.rs +257 -0
  14. data/engine/src/export.rs +431 -0
  15. data/engine/src/fixtures.rs +518 -0
  16. data/engine/src/graph.rs +115 -0
  17. data/engine/src/init.rs +65 -0
  18. data/engine/src/interp.rs +985 -0
  19. data/engine/src/lib.rs +62 -0
  20. data/engine/src/main.rs +97 -0
  21. data/engine/src/memory.rs +109 -0
  22. data/engine/src/mlxc/array.rs +454 -0
  23. data/engine/src/mlxc/error.rs +205 -0
  24. data/engine/src/mlxc/fast.rs +46 -0
  25. data/engine/src/mlxc/handle.rs +155 -0
  26. data/engine/src/mlxc/io.rs +268 -0
  27. data/engine/src/mlxc/memory.rs +56 -0
  28. data/engine/src/mlxc/metal.rs +24 -0
  29. data/engine/src/mlxc/mod.rs +55 -0
  30. data/engine/src/mlxc/nn.rs +38 -0
  31. data/engine/src/mlxc/ops.rs +477 -0
  32. data/engine/src/mlxc/quantized.rs +405 -0
  33. data/engine/src/mlxc/random.rs +161 -0
  34. data/engine/src/mlxc/transforms.rs +439 -0
  35. data/engine/src/op.rs +745 -0
  36. data/engine/src/optimizer.rs +650 -0
  37. data/engine/src/plan.rs +1638 -0
  38. data/engine/src/runtime.rs +377 -0
  39. data/engine/src/session.rs +1523 -0
  40. data/engine/src/state.rs +1007 -0
  41. data/engine/src/tensor.rs +331 -0
  42. data/ext/torobi/Cargo.toml +21 -0
  43. data/ext/torobi/extconf.rb +42 -0
  44. data/ext/torobi/src/gvl.rs +182 -0
  45. data/ext/torobi/src/lib.rs +1037 -0
  46. data/lib/torobi/adapter_file.rb +184 -0
  47. data/lib/torobi/batch.rb +55 -0
  48. data/lib/torobi/checkpoint.rb +60 -0
  49. data/lib/torobi/dsl/builder.rb +414 -0
  50. data/lib/torobi/dsl/handle.rb +156 -0
  51. data/lib/torobi/dsl/layers.rb +82 -0
  52. data/lib/torobi/dsl.rb +35 -0
  53. data/lib/torobi/errors.rb +88 -0
  54. data/lib/torobi/export.rb +534 -0
  55. data/lib/torobi/freeze.rb +24 -0
  56. data/lib/torobi/freshness.rb +57 -0
  57. data/lib/torobi/grad_cache.rb +143 -0
  58. data/lib/torobi/graph_config.rb +301 -0
  59. data/lib/torobi/hooks.rb +439 -0
  60. data/lib/torobi/ir/dimensions.rb +26 -0
  61. data/lib/torobi/ir/dtype.rb +28 -0
  62. data/lib/torobi/ir/graph/check.rb +116 -0
  63. data/lib/torobi/ir/graph.rb +52 -0
  64. data/lib/torobi/ir/input_spec.rb +39 -0
  65. data/lib/torobi/ir/json.rb +45 -0
  66. data/lib/torobi/ir/node_spec.rb +52 -0
  67. data/lib/torobi/ir/parameter_spec.rb +67 -0
  68. data/lib/torobi/ir/ref.rb +52 -0
  69. data/lib/torobi/ir/source.rb +65 -0
  70. data/lib/torobi/ir.rb +23 -0
  71. data/lib/torobi/journal.rb +310 -0
  72. data/lib/torobi/lora.rb +190 -0
  73. data/lib/torobi/memory.rb +50 -0
  74. data/lib/torobi/metallib.rb +50 -0
  75. data/lib/torobi/mlx_prebuilt.json +24 -0
  76. data/lib/torobi/mlx_prebuilt.rb +378 -0
  77. data/lib/torobi/models/build.rb +37 -0
  78. data/lib/torobi/models/description.rb +59 -0
  79. data/lib/torobi/models/gemma3.rb +273 -0
  80. data/lib/torobi/models/llama.rb +381 -0
  81. data/lib/torobi/models/modern_bert.rb +513 -0
  82. data/lib/torobi/models/padding.rb +27 -0
  83. data/lib/torobi/models/windows.rb +53 -0
  84. data/lib/torobi/ops.rb +81 -0
  85. data/lib/torobi/preflight.rb +136 -0
  86. data/lib/torobi/provenance.rb +75 -0
  87. data/lib/torobi/quantization.rb +151 -0
  88. data/lib/torobi/replay.rb +229 -0
  89. data/lib/torobi/runner.rb +419 -0
  90. data/lib/torobi/session.rb +855 -0
  91. data/lib/torobi/shape.rb +438 -0
  92. data/lib/torobi/tensor_data.rb +178 -0
  93. data/lib/torobi/version.rb +5 -0
  94. data/lib/torobi/weights.rb +108 -0
  95. data/lib/torobi.rb +67 -0
  96. data/licenses/MLX.txt +21 -0
  97. data/licenses/README.md +16 -0
  98. data/licenses/gguflib.txt +21 -0
  99. data/licenses/mlx-c.txt +21 -0
  100. data/licenses/mlx-rs.txt +27 -0
  101. metadata +229 -0
@@ -0,0 +1,477 @@
1
+ //! The operations, one mlx-c call each.
2
+ //!
3
+ //! Which call is the whole difficulty: `sum` and `sum_axes` are different
4
+ //! functions in mlx-c (`mlx_sum` reduces everything, `mlx_sum_axes` only
5
+ //! what it is told), and picking the wrong one compiles and gives a wrong
6
+ //! number. Each one here is the call mlx-rs 0.32.0 made for the same
7
+ //! method, and docs/vendoring.md ("mlx-c, call by call") lists them.
8
+ //!
9
+ //! Every op goes through [`Array::on_stream`], which runs it on the current
10
+ //! stream and names the mlx-c call in the error if MLX gives no reason.
11
+
12
+ use super::error::Result;
13
+ use super::handle::Vector;
14
+ use super::{sys, Array, ArrayElement, Dtype};
15
+
16
+ /// `a.$name()`: one array in, one out.
17
+ macro_rules! unary {
18
+ ($($name:ident => $call:ident),* $(,)?) => {
19
+ impl Array {
20
+ $(
21
+ pub fn $name(&self) -> Result<Array> {
22
+ Array::on_stream(stringify!($call), |res, s| unsafe { sys::$call(res, self.as_raw(), s) })
23
+ }
24
+ )*
25
+ }
26
+ };
27
+ }
28
+
29
+ /// `a.$name(b)`, broadcasting as MLX does.
30
+ macro_rules! binary {
31
+ ($($name:ident => $call:ident),* $(,)?) => {
32
+ impl Array {
33
+ $(
34
+ pub fn $name(&self, other: impl AsRef<Array>) -> Result<Array> {
35
+ let b = other.as_ref().as_raw();
36
+ Array::on_stream(stringify!($call), |res, s| unsafe { sys::$call(res, self.as_raw(), b, s) })
37
+ }
38
+ )*
39
+ }
40
+ };
41
+ }
42
+
43
+ /// `a.$name(keep_dims)`: a reduction over every axis. `None` keeps no
44
+ /// dimensions, as mlx-rs's default did.
45
+ macro_rules! reduce_all {
46
+ ($($name:ident => $call:ident),* $(,)?) => {
47
+ impl Array {
48
+ $(
49
+ pub fn $name(&self, keep_dims: impl Into<Option<bool>>) -> Result<Array> {
50
+ let keep = keep_dims.into().unwrap_or(false);
51
+ Array::on_stream(stringify!($call), |res, s| unsafe { sys::$call(res, self.as_raw(), keep, s) })
52
+ }
53
+ )*
54
+ }
55
+ };
56
+ }
57
+
58
+ /// `a.$name(axes, keep_dims)`: a reduction over the axes named, negative
59
+ /// ones counting from the end. An empty list reduces nothing, which is
60
+ /// MLX's reading and mlx-rs's.
61
+ macro_rules! reduce_axes {
62
+ ($($name:ident => $call:ident),* $(,)?) => {
63
+ impl Array {
64
+ $(
65
+ pub fn $name(&self, axes: &[i32], keep_dims: impl Into<Option<bool>>) -> Result<Array> {
66
+ let keep = keep_dims.into().unwrap_or(false);
67
+ Array::on_stream(stringify!($call), |res, s| unsafe {
68
+ sys::$call(res, self.as_raw(), axes.as_ptr(), axes.len(), keep, s)
69
+ })
70
+ }
71
+ )*
72
+ }
73
+ };
74
+ }
75
+
76
+ /// `a.$name(ints)`: a shape, or a list of axes, and nothing else.
77
+ macro_rules! with_ints {
78
+ ($($name:ident => $call:ident),* $(,)?) => {
79
+ impl Array {
80
+ $(
81
+ pub fn $name(&self, ints: &[i32]) -> Result<Array> {
82
+ Array::on_stream(stringify!($call), |res, s| unsafe {
83
+ sys::$call(res, self.as_raw(), ints.as_ptr(), ints.len(), s)
84
+ })
85
+ }
86
+ )*
87
+ }
88
+ };
89
+ }
90
+
91
+ unary! {
92
+ abs => mlx_abs,
93
+ negative => mlx_negative,
94
+ sqrt => mlx_sqrt,
95
+ rsqrt => mlx_rsqrt,
96
+ square => mlx_square,
97
+ exp => mlx_exp,
98
+ log => mlx_log,
99
+ cos => mlx_cos,
100
+ sin => mlx_sin,
101
+ }
102
+
103
+ binary! {
104
+ add => mlx_add,
105
+ subtract => mlx_subtract,
106
+ multiply => mlx_multiply,
107
+ divide => mlx_divide,
108
+ matmul => mlx_matmul,
109
+ power => mlx_power,
110
+ }
111
+
112
+ reduce_all! {
113
+ sum => mlx_sum,
114
+ mean => mlx_mean,
115
+ max => mlx_max,
116
+ min => mlx_min,
117
+ }
118
+
119
+ reduce_axes! {
120
+ sum_axes => mlx_sum_axes,
121
+ mean_axes => mlx_mean_axes,
122
+ max_axes => mlx_max_axes,
123
+ }
124
+
125
+ with_ints! {
126
+ reshape => mlx_reshape,
127
+ transpose_axes => mlx_transpose_axes,
128
+ expand_dims_axes => mlx_expand_dims_axes,
129
+ squeeze_axes => mlx_squeeze_axes,
130
+ }
131
+
132
+ impl Array {
133
+ /// The array in another dtype.
134
+ pub fn as_dtype(&self, dtype: Dtype) -> Result<Array> {
135
+ Array::on_stream("mlx_astype", |res, s| unsafe {
136
+ sys::mlx_astype(res, self.as_raw(), dtype.to_raw(), s)
137
+ })
138
+ }
139
+
140
+ /// The rows (or whatever `axis` is) that `indices` names, in its order.
141
+ pub fn take_axis(&self, indices: impl AsRef<Array>, axis: i32) -> Result<Array> {
142
+ let at = indices.as_ref().as_raw();
143
+ Array::on_stream("mlx_take_axis", |res, s| unsafe {
144
+ sys::mlx_take_axis(res, self.as_raw(), at, axis, s)
145
+ })
146
+ }
147
+
148
+ /// The same values laid out row-major, sharing the buffer when it
149
+ /// already is. Column-major is not accepted as contiguous, which is
150
+ /// mlx-rs's default and what `as_slice` needs.
151
+ pub fn contiguous(&self) -> Result<Array> {
152
+ Array::on_stream("mlx_contiguous", |res, s| unsafe {
153
+ sys::mlx_contiguous(res, self.as_raw(), false, s)
154
+ })
155
+ }
156
+
157
+ pub fn zeros<T: ArrayElement>(shape: &[i32]) -> Result<Array> {
158
+ Array::zeros_dtype(shape, T::DTYPE)
159
+ }
160
+
161
+ pub fn ones<T: ArrayElement>(shape: &[i32]) -> Result<Array> {
162
+ Array::on_stream("mlx_ones", |res, s| unsafe {
163
+ sys::mlx_ones(res, shape.as_ptr(), shape.len(), T::DTYPE.to_raw(), s)
164
+ })
165
+ }
166
+
167
+ fn zeros_dtype(shape: &[i32], dtype: Dtype) -> Result<Array> {
168
+ Array::on_stream("mlx_zeros", |res, s| unsafe {
169
+ sys::mlx_zeros(res, shape.as_ptr(), shape.len(), dtype.to_raw(), s)
170
+ })
171
+ }
172
+ }
173
+
174
+ /// `$name(a)`: the ops mlx-rs offers as free functions rather than methods.
175
+ macro_rules! unary_function {
176
+ ($($name:ident => $call:ident),* $(,)?) => {
177
+ $(
178
+ pub fn $name(a: impl AsRef<Array>) -> Result<Array> {
179
+ let a = a.as_ref().as_raw();
180
+ Array::on_stream(stringify!($call), |res, s| unsafe { sys::$call(res, a, s) })
181
+ }
182
+ )*
183
+ };
184
+ }
185
+
186
+ unary_function! {
187
+ tanh => mlx_tanh,
188
+ sigmoid => mlx_sigmoid,
189
+ erf => mlx_erf,
190
+ stop_gradient => mlx_stop_gradient,
191
+ }
192
+
193
+ /// Zeros of `a`'s shape and dtype. Through `mlx_zeros` rather than
194
+ /// `mlx_zeros_like`, as mlx-rs does: the array is read for its shape, and
195
+ /// nothing about it enters the graph.
196
+ pub fn zeros_like(a: impl AsRef<Array>) -> Result<Array> {
197
+ let a = a.as_ref();
198
+ Array::zeros_dtype(a.shape(), a.dtype())
199
+ }
200
+
201
+ pub fn maximum(a: impl AsRef<Array>, b: impl AsRef<Array>) -> Result<Array> {
202
+ let (a, b) = (a.as_ref().as_raw(), b.as_ref().as_raw());
203
+ Array::on_stream("mlx_maximum", |res, s| unsafe { sys::mlx_maximum(res, a, b, s) })
204
+ }
205
+
206
+ /// Softmax along one axis. `precise: None` is `false`: MLX then computes
207
+ /// in the input's precision, which for f32 is f32.
208
+ pub fn softmax_axis(a: impl AsRef<Array>, axis: i32, precise: impl Into<Option<bool>>) -> Result<Array> {
209
+ let a = a.as_ref().as_raw();
210
+ let precise = precise.into().unwrap_or(false);
211
+ Array::on_stream("mlx_softmax_axis", |res, s| unsafe { sys::mlx_softmax_axis(res, a, axis, precise, s) })
212
+ }
213
+
214
+ pub fn logsumexp_axes(
215
+ a: impl AsRef<Array>,
216
+ axes: &[i32],
217
+ keep_dims: impl Into<Option<bool>>,
218
+ ) -> Result<Array> {
219
+ let a = a.as_ref().as_raw();
220
+ let keep = keep_dims.into().unwrap_or(false);
221
+ Array::on_stream("mlx_logsumexp_axes", |res, s| unsafe {
222
+ sys::mlx_logsumexp_axes(res, a, axes.as_ptr(), axes.len(), keep, s)
223
+ })
224
+ }
225
+
226
+ /// The arrays end to end along an existing axis.
227
+ pub fn concatenate(arrays: &[impl AsRef<Array>], axis: i32) -> Result<Array> {
228
+ let vector = Vector::of(arrays.iter().map(AsRef::as_ref))?;
229
+ Array::on_stream("mlx_concatenate_axis", |res, s| unsafe {
230
+ sys::mlx_concatenate_axis(res, vector.as_raw(), axis, s)
231
+ })
232
+ }
233
+
234
+ /// The arrays side by side along a new axis.
235
+ pub fn stack(arrays: &[impl AsRef<Array>], axis: i32) -> Result<Array> {
236
+ let vector = Vector::of(arrays.iter().map(AsRef::as_ref))?;
237
+ Array::on_stream("mlx_stack_axis", |res, s| unsafe { sys::mlx_stack_axis(res, vector.as_raw(), axis, s) })
238
+ }
239
+
240
+ pub mod indexing {
241
+ use super::*;
242
+
243
+ /// At each position, the element of `a` along `axis` that `indices`
244
+ /// names there. `None` for the axis reads `a` flattened, as mlx-rs
245
+ /// does.
246
+ pub fn take_along_axis(
247
+ a: impl AsRef<Array>,
248
+ indices: impl AsRef<Array>,
249
+ axis: impl Into<Option<i32>>,
250
+ ) -> Result<Array> {
251
+ let (flat, axis) = match axis.into() {
252
+ None => (Some(a.as_ref().reshape(&[-1])?), 0),
253
+ Some(axis) => (None, axis),
254
+ };
255
+ let a = flat.as_ref().unwrap_or(a.as_ref()).as_raw();
256
+ let at = indices.as_ref().as_raw();
257
+ Array::on_stream("mlx_take_along_axis", |res, s| unsafe { sys::mlx_take_along_axis(res, a, at, axis, s) })
258
+ }
259
+ }
260
+
261
+ #[cfg(test)]
262
+ mod tests {
263
+ use super::*;
264
+ use crate::runtime;
265
+
266
+ fn run<R>(f: impl FnOnce() -> Result<R>) -> R {
267
+ runtime::runtime()
268
+ .execute(|| Ok(f()?))
269
+ .expect("the runtime should let this through")
270
+ }
271
+
272
+ fn values(a: &Array) -> Vec<f32> {
273
+ a.contiguous().unwrap().as_slice::<f32>().unwrap().to_vec()
274
+ }
275
+
276
+ fn close(got: &[f32], want: &[f32]) {
277
+ assert_eq!(got.len(), want.len(), "{got:?} against {want:?}");
278
+ for (g, w) in got.iter().zip(want) {
279
+ assert!((g - w).abs() < 1e-6, "{got:?} against {want:?}");
280
+ }
281
+ }
282
+
283
+ /// [[1, 2, 3], [4, 5, 6]]: small enough to check by hand, and not
284
+ /// square, so an axis mistaken for the other shows.
285
+ fn grid() -> Array {
286
+ Array::from_slice(&[1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]).unwrap()
287
+ }
288
+
289
+ #[test]
290
+ fn the_unary_ops_are_the_functions_they_name() {
291
+ let x = [0.25f32, 1.0, 4.0];
292
+ let got = run(|| {
293
+ let a = Array::from_slice(&x, &[3])?;
294
+ Ok([
295
+ values(&a.negative()?),
296
+ values(&a.negative()?.abs()?),
297
+ values(&a.sqrt()?),
298
+ values(&a.rsqrt()?),
299
+ values(&a.square()?),
300
+ values(&a.exp()?),
301
+ values(&a.log()?),
302
+ values(&a.cos()?),
303
+ values(&a.sin()?),
304
+ ])
305
+ });
306
+ let want: [Vec<f32>; 9] = [
307
+ x.map(|v| -v).to_vec(),
308
+ x.to_vec(),
309
+ x.map(f32::sqrt).to_vec(),
310
+ x.map(|v| 1.0 / v.sqrt()).to_vec(),
311
+ x.map(|v| v * v).to_vec(),
312
+ x.map(f32::exp).to_vec(),
313
+ x.map(f32::ln).to_vec(),
314
+ x.map(f32::cos).to_vec(),
315
+ x.map(f32::sin).to_vec(),
316
+ ];
317
+ for (got, want) in got.iter().zip(&want) {
318
+ close(got, want);
319
+ }
320
+ }
321
+
322
+ #[test]
323
+ fn the_binary_ops_broadcast_a_scalar_and_keep_their_order() {
324
+ let got = run(|| {
325
+ let a = Array::from_slice(&[6.0f32, 8.0], &[2])?;
326
+ let two = Array::from_f32(2.0)?;
327
+ Ok([
328
+ values(&a.add(&two)?),
329
+ values(&a.subtract(&two)?),
330
+ values(&two.subtract(&a)?),
331
+ values(&a.multiply(&two)?),
332
+ values(&a.divide(&two)?),
333
+ values(&two.divide(&a)?),
334
+ ])
335
+ });
336
+ close(&got[0], &[8.0, 10.0]);
337
+ close(&got[1], &[4.0, 6.0]);
338
+ close(&got[2], &[-4.0, -6.0]);
339
+ close(&got[3], &[12.0, 16.0]);
340
+ close(&got[4], &[3.0, 4.0]);
341
+ close(&got[5], &[1.0 / 3.0, 0.25]);
342
+ }
343
+
344
+ #[test]
345
+ fn matmul_is_rows_by_columns() {
346
+ let (got, shape) = run(|| {
347
+ let identityish = Array::from_slice(&[1.0f32, 0.0, 0.0, 1.0, 1.0, 1.0], &[3, 2])?;
348
+ let product = grid().matmul(&identityish)?;
349
+ Ok((values(&product), product.shape().to_vec()))
350
+ });
351
+ assert_eq!(shape, vec![2, 2]);
352
+ close(&got, &[4.0, 5.0, 10.0, 11.0]);
353
+ }
354
+
355
+ /// The whole-array reductions and the per-axis ones are different
356
+ /// mlx-c functions, and the mistake this guards is calling one for the
357
+ /// other: both compile, and the numbers differ.
358
+ #[test]
359
+ fn a_reduction_over_everything_is_not_one_over_an_axis() {
360
+ let got = run(|| {
361
+ let g = grid();
362
+ Ok([
363
+ (values(&g.sum(false)?), g.sum(false)?.shape().to_vec()),
364
+ (values(&g.sum(true)?), g.sum(true)?.shape().to_vec()),
365
+ (values(&g.sum_axes(&[1], false)?), g.sum_axes(&[1], false)?.shape().to_vec()),
366
+ (values(&g.sum_axes(&[-1], true)?), g.sum_axes(&[-1], true)?.shape().to_vec()),
367
+ (values(&g.sum_axes(&[0], None)?), g.sum_axes(&[0], None)?.shape().to_vec()),
368
+ ])
369
+ });
370
+ assert_eq!(got[0], (vec![21.0], vec![]));
371
+ assert_eq!(got[1], (vec![21.0], vec![1, 1]));
372
+ assert_eq!(got[2], (vec![6.0, 15.0], vec![2]));
373
+ assert_eq!(got[3], (vec![6.0, 15.0], vec![2, 1]));
374
+ assert_eq!(got[4], (vec![5.0, 7.0, 9.0], vec![3]));
375
+ }
376
+
377
+ #[test]
378
+ fn mean_max_and_min_reduce_the_way_sum_does() {
379
+ let got = run(|| {
380
+ let g = grid();
381
+ Ok([
382
+ values(&g.mean(false)?),
383
+ values(&g.mean_axes(&[-1], false)?),
384
+ values(&g.max(false)?),
385
+ values(&g.max_axes(&[0], false)?),
386
+ values(&g.min(None)?),
387
+ ])
388
+ });
389
+ close(&got[0], &[3.5]);
390
+ close(&got[1], &[2.0, 5.0]);
391
+ close(&got[2], &[6.0]);
392
+ close(&got[3], &[4.0, 5.0, 6.0]);
393
+ close(&got[4], &[1.0]);
394
+ }
395
+
396
+ /// No axes, no reduction: mlx-c reads the empty list literally, and so
397
+ /// does mlx-rs. A graph that means "everything" says `None`.
398
+ #[test]
399
+ fn an_empty_list_of_axes_reduces_nothing() {
400
+ let (got, shape) = run(|| {
401
+ let summed = grid().sum_axes(&[], false)?;
402
+ Ok((values(&summed), summed.shape().to_vec()))
403
+ });
404
+ assert_eq!(shape, vec![2, 3]);
405
+ close(&got, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
406
+ }
407
+
408
+ #[test]
409
+ fn the_shape_ops_move_axes_and_not_values() {
410
+ let got = run(|| {
411
+ let g = grid();
412
+ let t = g.transpose_axes(&[1, 0])?;
413
+ let r = g.reshape(&[3, -1])?;
414
+ let e = g.expand_dims_axes(&[1])?;
415
+ let s = e.squeeze_axes(&[1])?;
416
+ let last = g.expand_dims_axes(&[-1])?;
417
+ Ok([
418
+ (t.shape().to_vec(), values(&t)),
419
+ (r.shape().to_vec(), values(&r)),
420
+ (e.shape().to_vec(), values(&e)),
421
+ (s.shape().to_vec(), values(&s)),
422
+ (last.shape().to_vec(), values(&last)),
423
+ ])
424
+ });
425
+ let flat = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
426
+ assert_eq!(got[0], (vec![3, 2], vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]));
427
+ assert_eq!(got[1], (vec![3, 2], flat.clone()));
428
+ assert_eq!(got[2], (vec![2, 1, 3], flat.clone()));
429
+ assert_eq!(got[3], (vec![2, 3], flat.clone()));
430
+ assert_eq!(got[4], (vec![2, 3, 1], flat));
431
+ }
432
+
433
+ #[test]
434
+ fn take_axis_selects_along_the_axis_it_is_given() {
435
+ let got = run(|| {
436
+ let g = grid();
437
+ let rows = g.take_axis(Array::from_slice(&[1i32, 0, 1], &[3])?, 0)?;
438
+ let cols = g.take_axis(Array::from_slice(&[2i32], &[1])?, -1)?;
439
+ Ok([(rows.shape().to_vec(), values(&rows)), (cols.shape().to_vec(), values(&cols))])
440
+ });
441
+ assert_eq!(got[0], (vec![3, 3], vec![4.0, 5.0, 6.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]));
442
+ assert_eq!(got[1], (vec![2, 1], vec![3.0, 6.0]));
443
+ }
444
+
445
+ #[test]
446
+ fn zeros_and_ones_have_the_dtype_asked_for() {
447
+ let got = run(|| {
448
+ let z = Array::zeros::<f32>(&[2, 2])?;
449
+ let o = Array::ones::<i32>(&[3])?;
450
+ Ok((z.dtype(), values(&z), o.dtype(), o.as_slice::<i32>()?.to_vec()))
451
+ });
452
+ assert_eq!(got, (Dtype::Float32, vec![0.0; 4], Dtype::Int32, vec![1, 1, 1]));
453
+ }
454
+
455
+ #[test]
456
+ fn a_strided_array_reads_in_order_once_contiguous() {
457
+ let got = run(|| Ok(grid().transpose_axes(&[1, 0])?.contiguous()?.as_slice::<f32>()?.to_vec()));
458
+ assert_eq!(got, vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
459
+ }
460
+
461
+ #[test]
462
+ fn a_dtype_changes_on_the_device() {
463
+ let got = run(|| {
464
+ let b = grid().as_dtype(Dtype::Bfloat16)?;
465
+ let back = b.as_dtype(Dtype::Float32)?;
466
+ Ok((b.dtype(), values(&back)))
467
+ });
468
+ assert_eq!(got, (Dtype::Bfloat16, vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]));
469
+ }
470
+
471
+ /// MLX's refusal comes back in MLX's words, not the shim's.
472
+ #[test]
473
+ fn a_shape_mlx_refuses_is_an_error_that_says_why() {
474
+ let said = run(|| Ok(grid().reshape(&[4, 2]).unwrap_err().what().to_string()));
475
+ assert!(said.contains("reshape"), "{said}");
476
+ }
477
+ }