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,454 @@
1
+ //! `Array`: an `mlx_array` handle, freed when it goes, and the ways in and
2
+ //! out of one.
3
+ //!
4
+ //! **An `Array` always holds an array.** mlx-c says "no array" with an
5
+ //! empty handle, and hands one back when a constructor fails; neither ever
6
+ //! becomes an `Array`. The slot mlx-c writes a result into is an [`Out`]
7
+ //! until the call has succeeded, constructors return `Result`, and the
8
+ //! empty handle an optional argument wants is its own type
9
+ //! (`fast::NoArray`). So nothing that takes an `Array` has to ask whether
10
+ //! it is one.
11
+ //!
12
+ //! The operations on it are in `ops`. What is here is what every one of
13
+ //! them is built from ([`Array::on_stream`], [`Array::try_from_op`]), and
14
+ //! copying values in and out.
15
+
16
+ use std::ffi::c_int;
17
+
18
+ use super::error::{check, failure, install, Exception, Result};
19
+ use super::handle::Stream;
20
+ use super::sys;
21
+
22
+ /// An `mlx_array`. One reference to an array MLX owns; dropping it gives
23
+ /// the reference back.
24
+ pub struct Array(sys::mlx_array);
25
+
26
+ // MLX arrays may move between threads; what may not happen is two threads
27
+ // submitting work at once, and the runtime's gate is what stops that
28
+ // (`crate::runtime`).
29
+ unsafe impl Send for Array {}
30
+
31
+ impl Drop for Array {
32
+ fn drop(&mut self) {
33
+ unsafe { sys::mlx_array_free(self.0) };
34
+ }
35
+ }
36
+
37
+ impl Clone for Array {
38
+ /// Another reference to the same array, not a copy of its data.
39
+ fn clone(&self) -> Self {
40
+ Array::try_from_op("mlx_array_set", |res| unsafe { sys::mlx_array_set(res, self.0) })
41
+ .expect("mlx_array_set only fails when out of memory")
42
+ }
43
+ }
44
+
45
+ impl AsRef<Array> for Array {
46
+ fn as_ref(&self) -> &Array {
47
+ self
48
+ }
49
+ }
50
+
51
+ /// The dtype and shape, never the values: those are on the device, and
52
+ /// printing them would evaluate the array.
53
+ impl std::fmt::Debug for Array {
54
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55
+ write!(f, "Array({:?} {:?})", self.dtype(), self.shape())
56
+ }
57
+ }
58
+
59
+ /// The slot an mlx-c call writes an array into.
60
+ ///
61
+ /// Empty until the call succeeds, and freed whatever happens: the handle
62
+ /// is owned before the call, so one that fails halfway through writing
63
+ /// leaks nothing. It becomes an [`Array`] only through [`Out::written`],
64
+ /// which is where "the call failed" and "the call returned nothing" both
65
+ /// become errors.
66
+ pub(crate) struct Out(sys::mlx_array);
67
+
68
+ impl Out {
69
+ pub(crate) fn new() -> Self {
70
+ Out(unsafe { sys::mlx_array_new() })
71
+ }
72
+
73
+ pub(crate) fn as_mut(&mut self) -> *mut sys::mlx_array {
74
+ &mut self.0
75
+ }
76
+
77
+ /// The array the call wrote, given the status it returned.
78
+ #[track_caller]
79
+ pub(crate) fn written(self, status: c_int, operation: &str) -> Result<Array> {
80
+ check(status, operation)?;
81
+ if self.0.ctx.is_null() {
82
+ return Err(failure(operation));
83
+ }
84
+ let array = Array(self.0);
85
+ std::mem::forget(self);
86
+ Ok(array)
87
+ }
88
+ }
89
+
90
+ impl Drop for Out {
91
+ fn drop(&mut self) {
92
+ unsafe { sys::mlx_array_free(self.0) };
93
+ }
94
+ }
95
+
96
+ /// MLX's dtypes, under the names mlx-rs gave them, since those names reach
97
+ /// messages and checkpoints' error text through `{:?}`.
98
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99
+ pub enum Dtype {
100
+ Bool,
101
+ Uint8,
102
+ Uint16,
103
+ Uint32,
104
+ Uint64,
105
+ Int8,
106
+ Int16,
107
+ Int32,
108
+ Int64,
109
+ Float16,
110
+ Float32,
111
+ Float64,
112
+ Bfloat16,
113
+ Complex64,
114
+ }
115
+
116
+ impl Dtype {
117
+ /// Both directions of the mapping, in one place. A `#[repr(u32)]` enum
118
+ /// would give one direction for free and still need this for the other.
119
+ const TABLE: [(Dtype, sys::mlx_dtype); 14] = [
120
+ (Dtype::Bool, sys::mlx_dtype__MLX_BOOL),
121
+ (Dtype::Uint8, sys::mlx_dtype__MLX_UINT8),
122
+ (Dtype::Uint16, sys::mlx_dtype__MLX_UINT16),
123
+ (Dtype::Uint32, sys::mlx_dtype__MLX_UINT32),
124
+ (Dtype::Uint64, sys::mlx_dtype__MLX_UINT64),
125
+ (Dtype::Int8, sys::mlx_dtype__MLX_INT8),
126
+ (Dtype::Int16, sys::mlx_dtype__MLX_INT16),
127
+ (Dtype::Int32, sys::mlx_dtype__MLX_INT32),
128
+ (Dtype::Int64, sys::mlx_dtype__MLX_INT64),
129
+ (Dtype::Float16, sys::mlx_dtype__MLX_FLOAT16),
130
+ (Dtype::Float32, sys::mlx_dtype__MLX_FLOAT32),
131
+ (Dtype::Float64, sys::mlx_dtype__MLX_FLOAT64),
132
+ (Dtype::Bfloat16, sys::mlx_dtype__MLX_BFLOAT16),
133
+ (Dtype::Complex64, sys::mlx_dtype__MLX_COMPLEX64),
134
+ ];
135
+
136
+ pub(crate) fn to_raw(self) -> sys::mlx_dtype {
137
+ Self::TABLE.iter().find(|(d, _)| *d == self).map(|(_, raw)| *raw).unwrap()
138
+ }
139
+
140
+ fn from_raw(raw: sys::mlx_dtype) -> Dtype {
141
+ Self::TABLE
142
+ .iter()
143
+ .find(|(_, r)| *r == raw)
144
+ .map(|(d, _)| *d)
145
+ .unwrap_or_else(|| panic!("mlx-c reported dtype {raw}, which this build does not know"))
146
+ }
147
+ }
148
+
149
+ /// A Rust type an array's values can be read into or made from.
150
+ ///
151
+ /// f16 and bf16 are not here and cannot be: mlx-c declares their
152
+ /// accessors only on ARM (`mlx/c/half.h`), and reading half precision into
153
+ /// a host variable is not something the engine does. It converts on the
154
+ /// device first.
155
+ pub trait ArrayElement: Copy {
156
+ const DTYPE: Dtype;
157
+ #[doc(hidden)]
158
+ unsafe fn item(out: *mut Self, array: sys::mlx_array) -> c_int;
159
+ #[doc(hidden)]
160
+ unsafe fn data(array: sys::mlx_array) -> *const Self;
161
+ }
162
+
163
+ macro_rules! element {
164
+ ($t:ty, $dtype:ident, $item:ident, $data:ident) => {
165
+ impl ArrayElement for $t {
166
+ const DTYPE: Dtype = Dtype::$dtype;
167
+ unsafe fn item(out: *mut Self, array: sys::mlx_array) -> c_int {
168
+ unsafe { sys::$item(out, array) }
169
+ }
170
+ unsafe fn data(array: sys::mlx_array) -> *const Self {
171
+ unsafe { sys::$data(array) }
172
+ }
173
+ }
174
+ };
175
+ }
176
+
177
+ element!(f32, Float32, mlx_array_item_float32, mlx_array_data_float32);
178
+ element!(i32, Int32, mlx_array_item_int32, mlx_array_data_int32);
179
+ element!(u32, Uint32, mlx_array_item_uint32, mlx_array_data_uint32);
180
+ element!(bool, Bool, mlx_array_item_bool, mlx_array_data_bool);
181
+
182
+ impl Array {
183
+ /// Runs an mlx-c call that writes a new array, and owns what it wrote.
184
+ /// `operation` names the call for when MLX fails without saying why.
185
+ #[track_caller]
186
+ pub(crate) fn try_from_op(
187
+ operation: &str,
188
+ op: impl FnOnce(*mut sys::mlx_array) -> c_int,
189
+ ) -> Result<Array> {
190
+ install();
191
+ let mut out = Out::new();
192
+ let status = op(out.as_mut());
193
+ out.written(status, operation)
194
+ }
195
+
196
+ /// The same, for the calls that run on a stream, which is every op:
197
+ /// on [`Stream::current`], the one place that decides which.
198
+ #[track_caller]
199
+ pub(crate) fn on_stream(
200
+ operation: &str,
201
+ op: impl FnOnce(*mut sys::mlx_array, sys::mlx_stream) -> c_int,
202
+ ) -> Result<Array> {
203
+ let stream = Stream::current()?;
204
+ Array::try_from_op(operation, |res| op(res, stream.as_raw()))
205
+ }
206
+
207
+ pub(crate) fn as_raw(&self) -> sys::mlx_array {
208
+ self.0
209
+ }
210
+
211
+ /// Owns what a constructor made. Constructors return no status: on
212
+ /// failure mlx-c reports through the handler and hands back an empty
213
+ /// handle, which is turned into the error it was, here, rather than
214
+ /// into an `Array`. On CUDA this happens for real: making an array
215
+ /// allocates device memory there, and with no usable device it fails.
216
+ #[track_caller]
217
+ fn made(constructor: &str, make: impl FnOnce() -> sys::mlx_array) -> Result<Array> {
218
+ install();
219
+ let raw = make();
220
+ if raw.ctx.is_null() {
221
+ Err(failure(constructor))
222
+ } else {
223
+ Ok(Array(raw))
224
+ }
225
+ }
226
+
227
+ pub fn from_f32(value: f32) -> Result<Array> {
228
+ Array::made("mlx_array_new_float32", || unsafe { sys::mlx_array_new_float32(value) })
229
+ }
230
+
231
+ pub fn from_i32(value: i32) -> Result<Array> {
232
+ Array::made("mlx_array_new_int", || unsafe { sys::mlx_array_new_int(value) })
233
+ }
234
+
235
+ /// An array holding a copy of `data`, in row-major order.
236
+ ///
237
+ /// Refused when the data does not fill the shape, before mlx-c is asked,
238
+ /// since it would read past the end of `data`.
239
+ pub fn from_slice<T: ArrayElement>(data: &[T], shape: &[i32]) -> Result<Array> {
240
+ let wanted: i64 = shape.iter().map(|&d| d as i64).product();
241
+ if data.len() as i64 != wanted {
242
+ return Err(Exception::custom(format!(
243
+ "{} values for shape {shape:?}, which holds {wanted}",
244
+ data.len()
245
+ )));
246
+ }
247
+ Array::made("mlx_array_new_data", || unsafe {
248
+ sys::mlx_array_new_data(
249
+ data.as_ptr().cast(),
250
+ shape.as_ptr(),
251
+ shape.len() as c_int,
252
+ T::DTYPE.to_raw(),
253
+ )
254
+ })
255
+ }
256
+
257
+ pub fn ndim(&self) -> usize {
258
+ unsafe { sys::mlx_array_ndim(self.0) }
259
+ }
260
+
261
+ pub fn size(&self) -> usize {
262
+ unsafe { sys::mlx_array_size(self.0) }
263
+ }
264
+
265
+ /// The bytes the array's elements take, known from its shape and
266
+ /// dtype before it is evaluated.
267
+ pub fn nbytes(&self) -> usize {
268
+ unsafe { sys::mlx_array_nbytes(self.0) }
269
+ }
270
+
271
+ pub fn shape(&self) -> &[i32] {
272
+ let ndim = self.ndim();
273
+ if ndim == 0 {
274
+ return &[];
275
+ }
276
+ unsafe { std::slice::from_raw_parts(sys::mlx_array_shape(self.0), ndim) }
277
+ }
278
+
279
+ pub fn dtype(&self) -> Dtype {
280
+ Dtype::from_raw(unsafe { sys::mlx_array_dtype(self.0) })
281
+ }
282
+
283
+ pub fn eval(&self) -> Result<()> {
284
+ check(unsafe { sys::mlx_array_eval(self.0) }, "mlx_array_eval")
285
+ }
286
+
287
+ /// The single value this holds, converted to `T` on the device first
288
+ /// when it is held as something else. Refused for anything but one
289
+ /// value.
290
+ pub fn item<T: ArrayElement>(&self) -> Result<T> {
291
+ if self.size() != 1 {
292
+ return Err(Exception::custom(format!(
293
+ "an item was asked of an array of {} values",
294
+ self.size()
295
+ )));
296
+ }
297
+ self.eval()?;
298
+ if self.dtype() != T::DTYPE {
299
+ return self.as_dtype(T::DTYPE)?.item();
300
+ }
301
+ let mut out = std::mem::MaybeUninit::<T>::uninit();
302
+ check(unsafe { T::item(out.as_mut_ptr(), self.0) }, "reading an item")?;
303
+ Ok(unsafe { out.assume_init() })
304
+ }
305
+
306
+ /// The values, borrowed from the evaluated array.
307
+ ///
308
+ /// Refused for another dtype, and for a layout that is not row-major
309
+ /// contiguous (call `contiguous` first). An empty array reads as an
310
+ /// empty slice.
311
+ pub fn as_slice<T: ArrayElement>(&self) -> Result<&[T]> {
312
+ if self.dtype() != T::DTYPE {
313
+ return Err(Exception::custom(format!(
314
+ "dtype mismatch: expected {:?}, found {:?}",
315
+ T::DTYPE,
316
+ self.dtype()
317
+ )));
318
+ }
319
+ self.eval()?;
320
+ let size = self.size();
321
+ if size == 0 {
322
+ return Ok(&[]);
323
+ }
324
+ let mut row_major = false;
325
+ check(
326
+ unsafe { sys::_mlx_array_is_row_contiguous(&mut row_major, self.0) },
327
+ "_mlx_array_is_row_contiguous",
328
+ )?;
329
+ if !row_major {
330
+ return Err(Exception::custom(
331
+ "array data is not contiguous row-major; call `contiguous()` first",
332
+ ));
333
+ }
334
+ let data = unsafe { T::data(self.0) };
335
+ if data.is_null() {
336
+ return Err(Exception::custom("the data pointer is null"));
337
+ }
338
+ Ok(unsafe { std::slice::from_raw_parts(data, size) })
339
+ }
340
+ }
341
+
342
+ #[cfg(test)]
343
+ mod tests {
344
+ use super::*;
345
+ use crate::runtime;
346
+
347
+ fn run<R>(f: impl FnOnce() -> Result<R>) -> R {
348
+ runtime::runtime()
349
+ .execute(|| Ok(f()?))
350
+ .expect("the runtime should let this through")
351
+ }
352
+
353
+ #[test]
354
+ fn values_go_in_and_come_back_out() {
355
+ let (floats, ints, flags) = run(|| {
356
+ let f = Array::from_slice(&[1.5f32, -2.0, 0.0], &[3])?;
357
+ let i = Array::from_slice(&[7i32, 0, -1, 4], &[2, 2])?;
358
+ let b = Array::from_slice(&[true, false], &[2])?;
359
+ assert_eq!(f.shape(), &[3]);
360
+ assert_eq!(i.shape(), &[2, 2]);
361
+ assert_eq!(i.dtype(), Dtype::Int32);
362
+ Ok((
363
+ f.as_slice::<f32>()?.to_vec(),
364
+ i.as_slice::<i32>()?.to_vec(),
365
+ b.as_slice::<bool>()?.to_vec(),
366
+ ))
367
+ });
368
+ assert_eq!(floats, vec![1.5, -2.0, 0.0]);
369
+ assert_eq!(ints, vec![7, 0, -1, 4]);
370
+ assert_eq!(flags, vec![true, false]);
371
+ }
372
+
373
+ #[test]
374
+ fn a_scalar_has_no_shape_and_one_item() {
375
+ let (shape, ndim, value) = run(|| {
376
+ let x = Array::from_f32(2.5)?;
377
+ Ok((x.shape().to_vec(), x.ndim(), x.item::<f32>()?))
378
+ });
379
+ assert_eq!((shape, ndim, value), (vec![], 0, 2.5));
380
+ }
381
+
382
+ #[test]
383
+ fn an_item_is_converted_on_the_device_when_the_dtype_differs() {
384
+ let value = run(|| Array::from_slice(&[3i32], &[1])?.item::<f32>());
385
+ assert_eq!(value, 3.0);
386
+ }
387
+
388
+ #[test]
389
+ fn an_item_of_many_values_is_refused_rather_than_guessed() {
390
+ let refused = run(|| Ok(Array::from_slice(&[1.0f32, 2.0], &[2])?.item::<f32>().is_err()));
391
+ assert!(refused);
392
+ }
393
+
394
+ #[test]
395
+ fn a_slice_of_another_dtype_is_refused() {
396
+ let said = run(|| Ok(Array::from_slice(&[1i32], &[1])?.as_slice::<f32>().unwrap_err().to_string()));
397
+ assert!(said.contains("Float32") && said.contains("Int32"), "{said}");
398
+ }
399
+
400
+ #[test]
401
+ fn an_empty_array_reads_as_nothing() {
402
+ let got = run(|| Ok(Array::from_slice::<f32>(&[], &[0, 3])?.as_slice::<f32>()?.len()));
403
+ assert_eq!(got, 0);
404
+ }
405
+
406
+ #[test]
407
+ fn data_that_does_not_fill_its_shape_is_refused_before_mlx_reads_it() {
408
+ let said = run(|| Ok(Array::from_slice(&[1.0f32, 2.0], &[3]).unwrap_err().to_string()));
409
+ assert!(said.contains("2 values for shape [3]"), "{said}");
410
+ }
411
+
412
+ #[test]
413
+ fn a_clone_is_another_reference_to_the_same_values() {
414
+ let got = run(|| {
415
+ let a = Array::from_slice(&[4.0f32, 5.0], &[2])?;
416
+ let b = a.clone();
417
+ drop(a);
418
+ Ok(b.as_slice::<f32>()?.to_vec())
419
+ });
420
+ assert_eq!(got, vec![4.0, 5.0]);
421
+ }
422
+
423
+ /// A constructor mlx-c could not serve is an error, in MLX's words, at
424
+ /// the constructor, rather than an array that fails later.
425
+ ///
426
+ /// On a Mac making an array cannot fail, so the failure is staged: MLX's
427
+ /// report, then the empty handle a failing constructor returns.
428
+ #[test]
429
+ fn a_constructor_that_fails_is_an_error_where_it_failed() {
430
+ let said = run(|| {
431
+ crate::mlxc::error::report("cudaMallocManaged(&data, size) failed");
432
+ Ok(Array::made("mlx_array_new_float32", || unsafe { sys::mlx_array_new() })
433
+ .unwrap_err()
434
+ .what()
435
+ .to_string())
436
+ });
437
+ assert!(said.starts_with("cudaMallocManaged"), "{said}");
438
+ }
439
+
440
+ /// A call that succeeds and writes nothing is an error too, not an
441
+ /// array: the other way an empty handle could have got in.
442
+ #[test]
443
+ fn a_call_that_writes_nothing_is_an_error() {
444
+ let said = run(|| Ok(Array::try_from_op("nothing", |_| 0).unwrap_err().what().to_string()));
445
+ assert_eq!(said, "nothing failed");
446
+ }
447
+
448
+ #[test]
449
+ fn every_dtype_survives_the_round_trip_to_mlx_c() {
450
+ for (dtype, _) in Dtype::TABLE {
451
+ assert_eq!(Dtype::from_raw(dtype.to_raw()), dtype);
452
+ }
453
+ }
454
+ }
@@ -0,0 +1,205 @@
1
+ //! What MLX says when it refuses, and how that becomes a Rust error.
2
+ //!
3
+ //! mlx-c reports a failure twice: once through the error handler, with a
4
+ //! message, and once through the status the call returns (or, for a
5
+ //! constructor, the empty handle it returns). The handler runs first, so
6
+ //! its message waits here until the caller sees the failure and asks for
7
+ //! it ([`check`], [`failure`]).
8
+ //!
9
+ //! **Our handler must be in place before mlx-c is first asked anything.**
10
+ //! mlx-c's own prints and calls `exit`, which no caller can rescue. The
11
+ //! rule that makes that hold without a call at every entrance: every mlx-c
12
+ //! call either makes a handle or is handed one, and the handles that can
13
+ //! fail as they are made are born in only a few places, which install
14
+ //! first ([`install`]): `Array::try_from_op` and `Array::made` for arrays,
15
+ //! `Stream::current` and `Stream::cpu` for streams, and `Closure::new` for
16
+ //! closures. `memory` installs too, for the allocator calls that touch no
17
+ //! handle at all. The empty containers (`mlx_array_new`, the vector and
18
+ //! map `_new` calls) are left out: making one allocates and nothing else.
19
+ //! The runtime also installs when it is created, since every route in
20
+ //! production passes through it first.
21
+
22
+ use std::cell::RefCell;
23
+ use std::ffi::{c_char, c_int, c_void, CStr};
24
+ use std::panic::{catch_unwind, AssertUnwindSafe, Location};
25
+ use std::sync::Once;
26
+
27
+ use super::sys;
28
+
29
+ /// A failure MLX reported, or one the engine raised in the same terms.
30
+ ///
31
+ /// Printed as `"<what>" at <location>`, the form mlx-rs's `Exception`
32
+ /// took, so the engine's messages did not change when the binding under
33
+ /// them did.
34
+ #[derive(Debug, Clone, PartialEq)]
35
+ pub struct Exception {
36
+ what: String,
37
+ location: &'static Location<'static>,
38
+ }
39
+
40
+ pub type Result<T> = std::result::Result<T, Exception>;
41
+
42
+ impl Exception {
43
+ #[track_caller]
44
+ pub fn custom(what: impl Into<String>) -> Self {
45
+ Self {
46
+ what: what.into(),
47
+ location: Location::caller(),
48
+ }
49
+ }
50
+
51
+ pub fn what(&self) -> &str {
52
+ &self.what
53
+ }
54
+ }
55
+
56
+ impl std::fmt::Display for Exception {
57
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58
+ write!(f, "{:?} at {}", self.what, self.location)
59
+ }
60
+ }
61
+
62
+ impl std::error::Error for Exception {}
63
+
64
+ impl From<&str> for Exception {
65
+ #[track_caller]
66
+ fn from(what: &str) -> Self {
67
+ Self::custom(what)
68
+ }
69
+ }
70
+
71
+ thread_local! {
72
+ /// What MLX last said on this thread, waiting for the failing status
73
+ /// that goes with it. MLX reports on the thread that failed, so one
74
+ /// slot per thread is one per failure in flight.
75
+ static SAID: RefCell<Option<String>> = const { RefCell::new(None) };
76
+ }
77
+
78
+ /// Called by mlx-c, from C++, before it returns a failing status.
79
+ ///
80
+ /// Nothing may unwind out of here, so the whole body is caught, and the
81
+ /// slot is borrowed with `try_` so a re-entrant report is dropped rather
82
+ /// than a panic.
83
+ extern "C" fn on_error(message: *const c_char, _data: *mut c_void) {
84
+ let _ = catch_unwind(AssertUnwindSafe(|| {
85
+ let text = describe(message);
86
+ let _ = SAID.try_with(|slot| {
87
+ if let Ok(mut said) = slot.try_borrow_mut() {
88
+ *said = Some(text);
89
+ }
90
+ });
91
+ }));
92
+ }
93
+
94
+ fn describe(message: *const c_char) -> String {
95
+ if message.is_null() {
96
+ return String::new();
97
+ }
98
+ unsafe { CStr::from_ptr(message) }.to_string_lossy().into_owned()
99
+ }
100
+
101
+ static INSTALLED: Once = Once::new();
102
+
103
+ /// Puts our handler in place of mlx-c's default, once per process.
104
+ ///
105
+ /// Once rather than per call: mlx-c keeps the handler in a plain global,
106
+ /// so writing it from two threads at once would be a race.
107
+ pub(crate) fn install() {
108
+ INSTALLED.call_once(|| unsafe {
109
+ sys::mlx_set_error_handler(Some(on_error), std::ptr::null_mut(), None);
110
+ });
111
+ }
112
+
113
+ /// A failing status as an error, in MLX's words when it left any.
114
+ #[track_caller]
115
+ pub(crate) fn failure(operation: &str) -> Exception {
116
+ let location = Location::caller();
117
+ let what = SAID.with(|slot| slot.borrow_mut().take()).unwrap_or_else(|| format!("{operation} failed"));
118
+ Exception { what, location }
119
+ }
120
+
121
+ /// `Ok` for mlx-c's success, MLX's own message otherwise.
122
+ #[track_caller]
123
+ pub(crate) fn check(status: c_int, operation: &str) -> Result<()> {
124
+ if status == 0 {
125
+ Ok(())
126
+ } else {
127
+ Err(failure(operation))
128
+ }
129
+ }
130
+
131
+ /// Drops whatever MLX last said on this thread, for a caller that already
132
+ /// knows a better reason for the failure (a closure's own error).
133
+ pub(crate) fn forget_said() {
134
+ SAID.with(|slot| slot.borrow_mut().take());
135
+ }
136
+
137
+ /// MLX's report, as mlx-c would deliver it, for tests that stage a failure
138
+ /// MLX cannot be made to produce on this machine.
139
+ #[cfg(test)]
140
+ pub(crate) fn report(message: &str) {
141
+ let message = std::ffi::CString::new(message).unwrap();
142
+ on_error(message.as_ptr(), std::ptr::null_mut());
143
+ }
144
+
145
+ #[cfg(test)]
146
+ mod tests {
147
+ use super::*;
148
+ use crate::mlxc::Array;
149
+ use crate::runtime;
150
+
151
+ /// The marker that tells a copy of this test binary it is the child.
152
+ const CHILD: &str = "TOROBI_MLXC_CHILD";
153
+
154
+ /// An MLX failure is an error, not the end of the process.
155
+ ///
156
+ /// Tested in a copy of this binary that runs one test and nothing else:
157
+ /// if the handler were not in place, mlx-c's default would print and
158
+ /// exit, and that exit should fail this test rather than end the whole
159
+ /// run with nothing reported.
160
+ #[test]
161
+ fn an_mlx_failure_is_an_error_not_an_exit() {
162
+ let output = std::process::Command::new(std::env::current_exe().unwrap())
163
+ .args([
164
+ "--exact",
165
+ "mlxc::error::tests::child_an_mlx_failure_comes_back",
166
+ "--ignored",
167
+ "--test-threads=1",
168
+ ])
169
+ .env(CHILD, "1")
170
+ .output()
171
+ .expect("the test binary should run again");
172
+ let said = String::from_utf8_lossy(&output.stdout);
173
+ assert!(
174
+ output.status.success(),
175
+ "the child did not finish: {:?}\n{said}\n{}",
176
+ output.status,
177
+ String::from_utf8_lossy(&output.stderr)
178
+ );
179
+ assert!(said.contains("1 passed"), "the child ran nothing: {said}");
180
+ }
181
+
182
+ /// The child's half. Ignored so it runs only when asked for by name.
183
+ #[test]
184
+ #[ignore = "run by an_mlx_failure_is_an_error_not_an_exit"]
185
+ fn child_an_mlx_failure_comes_back() {
186
+ if std::env::var_os(CHILD).is_none() {
187
+ return;
188
+ }
189
+ let said = runtime::runtime()
190
+ .execute(|| {
191
+ let two = Array::from_slice(&[1.0f32, 2.0], &[2])?;
192
+ let three = Array::from_slice(&[1.0f32, 2.0, 3.0], &[3])?;
193
+ Ok(two.add(&three).err().map(|error| error.what().to_string()))
194
+ })
195
+ .expect("the runtime should let this through");
196
+ let said = said.expect("shapes 2 and 3 do not broadcast");
197
+ assert!(said.contains("broadcast"), "{said}");
198
+ }
199
+
200
+ #[test]
201
+ fn an_exception_prints_the_way_mlx_rs_printed_one() {
202
+ let said = Exception::custom("no binding for input \"x\"").to_string();
203
+ assert!(said.starts_with(r#""no binding for input \"x\"" at "#), "{said}");
204
+ }
205
+ }
@@ -0,0 +1,46 @@
1
+ //! MLX's fused kernels.
2
+
3
+ use super::error::Result;
4
+ use super::handle::NoArray;
5
+ use super::{sys, Array};
6
+
7
+ /// What masks the scores before the softmax: an additive array, or the
8
+ /// causal triangle MLX builds itself.
9
+ #[derive(Debug)]
10
+ pub enum ScaledDotProductAttentionMask<'a> {
11
+ Array(&'a Array),
12
+ Causal,
13
+ }
14
+
15
+ impl<'a> From<&'a Array> for ScaledDotProductAttentionMask<'a> {
16
+ fn from(mask: &'a Array) -> Self {
17
+ ScaledDotProductAttentionMask::Array(mask)
18
+ }
19
+ }
20
+
21
+ /// softmax(q kᵀ · scale + mask) v, through MLX's own kernel.
22
+ ///
23
+ /// mlx-c says "no mask" and "no sinks" with an empty array and names the
24
+ /// mask's kind in a string: `""` for an array (or none) and `"causal"` for
25
+ /// the triangle ([`NoArray`]). `force_fused` is `false`, as mlx-rs passes it,
26
+ /// so MLX falls back to the unfused form where its kernel does not apply.
27
+ pub fn scaled_dot_product_attention<'a>(
28
+ queries: impl AsRef<Array>,
29
+ keys: impl AsRef<Array>,
30
+ values: impl AsRef<Array>,
31
+ scale: f32,
32
+ mask: impl Into<Option<ScaledDotProductAttentionMask<'a>>>,
33
+ sinks: impl Into<Option<&'a Array>>,
34
+ ) -> Result<Array> {
35
+ let none = NoArray::new();
36
+ let (mode, mask) = match mask.into() {
37
+ None => (c"", none.as_raw()),
38
+ Some(ScaledDotProductAttentionMask::Array(mask)) => (c"", mask.as_raw()),
39
+ Some(ScaledDotProductAttentionMask::Causal) => (c"causal", none.as_raw()),
40
+ };
41
+ let sinks = sinks.into().map_or(none.as_raw(), Array::as_raw);
42
+ let (q, k, v) = (queries.as_ref().as_raw(), keys.as_ref().as_raw(), values.as_ref().as_raw());
43
+ Array::on_stream("mlx_fast_scaled_dot_product_attention", |res, s| unsafe {
44
+ sys::mlx_fast_scaled_dot_product_attention(res, q, k, v, scale, mode.as_ptr(), mask, sinks, false, s)
45
+ })
46
+ }