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,155 @@
1
+ //! The mlx-c handles that are not arrays, each freed when it goes.
2
+ //!
3
+ //! Every handle is owned from the moment mlx-c returns it, so that an
4
+ //! early `?` anywhere after that frees it on the way out. The raw handle is
5
+ //! reached only through `as_raw` (to pass in) and `as_out` (for mlx-c to
6
+ //! write into). The one place ownership changes hands is [`Vector::read`],
7
+ //! for a vector mlx-c still owns.
8
+
9
+ use super::error::{check, failure, install, Result};
10
+ use super::{sys, Array};
11
+
12
+ /// An `mlx_stream`.
13
+ pub(crate) struct Stream(sys::mlx_stream);
14
+
15
+ impl Stream {
16
+ /// The stream every op runs on: the default stream of the default
17
+ /// device, the GPU unless something moved the default. The one place
18
+ /// that decides it.
19
+ ///
20
+ /// Made afresh per op, as mlx-rs made it. Measured on an M-series Mac
21
+ /// in release (2026-09-23): making and freeing one costs 0.35 µs, half
22
+ /// of what building a trivial op costs, but ruri-v3-130m's graph is 691
23
+ /// nodes and a step takes 140 ms, so it is about 0.2% of a step. Not
24
+ /// worth a stream kept per thread, which would be freed at thread exit:
25
+ /// exactly when MLX's CUDA backend is least safe to talk to.
26
+ pub(crate) fn current() -> Result<Self> {
27
+ install();
28
+ let mut device = Device(unsafe { sys::mlx_device_new() });
29
+ check(unsafe { sys::mlx_get_default_device(&mut device.0) }, "mlx_get_default_device")?;
30
+ let mut stream = Stream(unsafe { sys::mlx_stream_new() });
31
+ check(
32
+ unsafe { sys::mlx_get_default_stream(&mut stream.0, device.0) },
33
+ "mlx_get_default_stream",
34
+ )?;
35
+ Ok(stream)
36
+ }
37
+
38
+ /// The CPU's default stream, which is where MLX reads files.
39
+ pub(crate) fn cpu() -> Result<Self> {
40
+ install();
41
+ let stream = Stream(unsafe { sys::mlx_default_cpu_stream_new() });
42
+ if stream.0.ctx.is_null() {
43
+ return Err(failure("mlx_default_cpu_stream_new"));
44
+ }
45
+ Ok(stream)
46
+ }
47
+
48
+ pub(crate) fn as_raw(&self) -> sys::mlx_stream {
49
+ self.0
50
+ }
51
+ }
52
+
53
+ impl Drop for Stream {
54
+ fn drop(&mut self) {
55
+ unsafe { sys::mlx_stream_free(self.0) };
56
+ }
57
+ }
58
+
59
+ /// An `mlx_device`, held only while a stream is looked up on it.
60
+ struct Device(sys::mlx_device);
61
+
62
+ impl Drop for Device {
63
+ fn drop(&mut self) {
64
+ unsafe { sys::mlx_device_free(self.0) };
65
+ }
66
+ }
67
+
68
+ /// An `mlx_vector_array` this side owns.
69
+ pub(crate) struct Vector(sys::mlx_vector_array);
70
+
71
+ impl Vector {
72
+ pub(crate) fn new() -> Self {
73
+ Self(unsafe { sys::mlx_vector_array_new() })
74
+ }
75
+
76
+ /// A vector holding a new reference to each array.
77
+ pub(crate) fn of<'a>(arrays: impl IntoIterator<Item = &'a Array>) -> Result<Self> {
78
+ let vector = Self::new();
79
+ for array in arrays {
80
+ check(
81
+ unsafe { sys::mlx_vector_array_append_value(vector.0, array.as_raw()) },
82
+ "mlx_vector_array_append_value",
83
+ )?;
84
+ }
85
+ Ok(vector)
86
+ }
87
+
88
+ pub(crate) fn as_raw(&self) -> sys::mlx_vector_array {
89
+ self.0
90
+ }
91
+
92
+ /// Where mlx-c writes a vector it returns.
93
+ pub(crate) fn as_out(&mut self) -> *mut sys::mlx_vector_array {
94
+ &mut self.0
95
+ }
96
+
97
+ /// The arrays inside, each one owned by the caller.
98
+ pub(crate) fn arrays(&self) -> Result<Vec<Array>> {
99
+ unsafe { Self::read(self.0) }
100
+ }
101
+
102
+ /// The arrays inside a vector that belongs to someone else.
103
+ ///
104
+ /// `mlx_vector_array_get` hands out a new reference rather than a
105
+ /// borrow, so what comes back is the caller's to free, and the vector
106
+ /// is left alone.
107
+ ///
108
+ /// # Safety
109
+ ///
110
+ /// `raw` must be a live vector for the duration of the call.
111
+ pub(crate) unsafe fn read(raw: sys::mlx_vector_array) -> Result<Vec<Array>> {
112
+ let count = unsafe { sys::mlx_vector_array_size(raw) };
113
+ (0..count)
114
+ .map(|index| {
115
+ Array::try_from_op("mlx_vector_array_get", |res| unsafe {
116
+ sys::mlx_vector_array_get(res, raw, index)
117
+ })
118
+ })
119
+ .collect()
120
+ }
121
+ }
122
+
123
+ impl Drop for Vector {
124
+ fn drop(&mut self) {
125
+ unsafe { sys::mlx_vector_array_free(self.0) };
126
+ }
127
+ }
128
+
129
+ /// mlx-c's "no array", for an optional argument: an empty handle. Its own
130
+ /// type because an [`Array`] always holds one, and owned so it is freed;
131
+ /// mlx-rs made these and let them go.
132
+ pub(crate) struct NoArray(sys::mlx_array);
133
+
134
+ impl NoArray {
135
+ pub(crate) fn new() -> Self {
136
+ NoArray(unsafe { sys::mlx_array_new() })
137
+ }
138
+
139
+ pub(crate) fn as_raw(&self) -> sys::mlx_array {
140
+ self.0
141
+ }
142
+
143
+ /// `array` when there is one, and the empty handle when there is not:
144
+ /// how every `/* may be null */` argument is passed.
145
+ pub(crate) fn or<'a>(&'a self, array: Option<&'a Array>) -> sys::mlx_array {
146
+ array.map_or(self.0, Array::as_raw)
147
+ }
148
+ }
149
+
150
+ impl Drop for NoArray {
151
+ fn drop(&mut self) {
152
+ unsafe { sys::mlx_array_free(self.0) };
153
+ }
154
+ }
155
+
@@ -0,0 +1,268 @@
1
+ //! Safetensors files, in and out.
2
+ //!
3
+ //! Both directions go through mlx-c's string-keyed maps, which are handles
4
+ //! like any other and are freed here whatever happens: a key with a NUL in
5
+ //! it, an insert MLX refuses, or a file that will not write.
6
+
7
+ use std::collections::HashMap;
8
+ use std::ffi::{c_char, CStr, CString};
9
+ use std::path::Path;
10
+
11
+ use super::error::{check, Exception, Result};
12
+ use super::handle::Stream;
13
+ use super::array::Out;
14
+ use super::{sys, Array};
15
+
16
+ /// An `mlx_map_string_to_array`.
17
+ struct Arrays(sys::mlx_map_string_to_array);
18
+
19
+ impl Arrays {
20
+ fn new() -> Self {
21
+ Self(unsafe { sys::mlx_map_string_to_array_new() })
22
+ }
23
+
24
+ fn insert(&self, name: &str, array: &Array) -> Result<()> {
25
+ let name = c_string(name)?;
26
+ check(
27
+ unsafe { sys::mlx_map_string_to_array_insert(self.0, name.as_ptr(), array.as_raw()) },
28
+ "mlx_map_string_to_array_insert",
29
+ )
30
+ }
31
+
32
+ fn as_raw(&self) -> sys::mlx_map_string_to_array {
33
+ self.0
34
+ }
35
+
36
+ fn as_out(&mut self) -> *mut sys::mlx_map_string_to_array {
37
+ &mut self.0
38
+ }
39
+
40
+ /// Every entry, each array owned by the caller. The map must outlive
41
+ /// the iteration, which the borrow says.
42
+ fn entries(&self) -> Entries<'_> {
43
+ Entries {
44
+ raw: unsafe { sys::mlx_map_string_to_array_iterator_new(self.0) },
45
+ _map: self,
46
+ }
47
+ }
48
+ }
49
+
50
+ impl Drop for Arrays {
51
+ fn drop(&mut self) {
52
+ unsafe { sys::mlx_map_string_to_array_free(self.0) };
53
+ }
54
+ }
55
+
56
+ /// An `mlx_map_string_to_string`.
57
+ struct Strings(sys::mlx_map_string_to_string);
58
+
59
+ impl Strings {
60
+ fn new() -> Self {
61
+ Self(unsafe { sys::mlx_map_string_to_string_new() })
62
+ }
63
+
64
+ fn as_raw(&self) -> sys::mlx_map_string_to_string {
65
+ self.0
66
+ }
67
+
68
+ fn as_out(&mut self) -> *mut sys::mlx_map_string_to_string {
69
+ &mut self.0
70
+ }
71
+
72
+ fn insert(&self, key: &str, value: &str) -> Result<()> {
73
+ let (key, value) = (c_string(key)?, c_string(value)?);
74
+ check(
75
+ unsafe { sys::mlx_map_string_to_string_insert(self.0, key.as_ptr(), value.as_ptr()) },
76
+ "mlx_map_string_to_string_insert",
77
+ )
78
+ }
79
+ }
80
+
81
+ impl Drop for Strings {
82
+ fn drop(&mut self) {
83
+ unsafe { sys::mlx_map_string_to_string_free(self.0) };
84
+ }
85
+ }
86
+
87
+ /// An `mlx_map_string_to_array_iterator`, as a Rust iterator.
88
+ struct Entries<'a> {
89
+ raw: sys::mlx_map_string_to_array_iterator,
90
+ _map: &'a Arrays,
91
+ }
92
+
93
+ impl Iterator for Entries<'_> {
94
+ type Item = Result<(String, Array)>;
95
+
96
+ /// mlx-c answers 0 with an entry, 2 at the end, and anything else on
97
+ /// failure.
98
+ fn next(&mut self) -> Option<Self::Item> {
99
+ const END: i32 = 2;
100
+ let mut key: *const c_char = std::ptr::null();
101
+ let mut value = Out::new();
102
+ let status = unsafe { sys::mlx_map_string_to_array_iterator_next(&mut key, value.as_mut(), self.raw) };
103
+ if status == END {
104
+ return None;
105
+ }
106
+ Some(value.written(status, "mlx_map_string_to_array_iterator_next").map(|array| {
107
+ // The key belongs to the map, which outlives this borrow.
108
+ (unsafe { CStr::from_ptr(key) }.to_string_lossy().into_owned(), array)
109
+ }))
110
+ }
111
+ }
112
+
113
+ impl Drop for Entries<'_> {
114
+ fn drop(&mut self) {
115
+ unsafe { sys::mlx_map_string_to_array_iterator_free(self.raw) };
116
+ }
117
+ }
118
+
119
+ /// The path as mlx-c takes it, refused the way mlx-rs refused it.
120
+ fn c_path(path: &Path) -> Result<CString> {
121
+ if path.extension().and_then(|e| e.to_str()) != Some("safetensors") {
122
+ return Err(Exception::custom("Unsupported file format"));
123
+ }
124
+ let text = path.to_str().ok_or_else(|| Exception::custom("Path contains invalid UTF-8"))?;
125
+ CString::new(text).map_err(|_| Exception::custom("Path contains null bytes"))
126
+ }
127
+
128
+ fn c_string(text: &str) -> Result<CString> {
129
+ CString::new(text).map_err(|_| Exception::custom(format!("{text:?} contains a NUL byte")))
130
+ }
131
+
132
+ impl Array {
133
+ /// Every tensor in a safetensors file, by name. Lazy: nothing is read
134
+ /// until an array is evaluated. Loaded on the CPU stream, as mlx-rs
135
+ /// does, which is where MLX reads files. The header's metadata is read
136
+ /// by mlx-c and dropped here.
137
+ pub fn load_safetensors(path: impl AsRef<Path>) -> Result<HashMap<String, Array>> {
138
+ let path = path.as_ref();
139
+ if !path.is_file() {
140
+ return Err(Exception::custom("Path must point to a local file"));
141
+ }
142
+ let file = c_path(path)?;
143
+ let stream = Stream::cpu()?;
144
+ let mut arrays = Arrays::new();
145
+ let mut metadata = Strings::new();
146
+ check(
147
+ unsafe {
148
+ sys::mlx_load_safetensors(arrays.as_out(), metadata.as_out(), file.as_ptr(), stream.as_raw())
149
+ },
150
+ "mlx_load_safetensors",
151
+ )?;
152
+ arrays.entries().collect()
153
+ }
154
+
155
+ /// Writes `arrays` to a safetensors file with `metadata` in its header.
156
+ pub fn save_safetensors<'a, I, S, V>(
157
+ arrays: I,
158
+ metadata: impl Into<Option<&'a HashMap<String, String>>>,
159
+ path: impl AsRef<Path>,
160
+ ) -> Result<()>
161
+ where
162
+ I: IntoIterator<Item = (S, V)>,
163
+ S: AsRef<str>,
164
+ V: AsRef<Array>,
165
+ {
166
+ let file = c_path(path.as_ref())?;
167
+ let map = Arrays::new();
168
+ for (name, array) in arrays {
169
+ map.insert(name.as_ref(), array.as_ref())?;
170
+ }
171
+ let header = Strings::new();
172
+ for (key, value) in metadata.into().into_iter().flatten() {
173
+ header.insert(key, value)?;
174
+ }
175
+ check(
176
+ unsafe { sys::mlx_save_safetensors(file.as_ptr(), map.as_raw(), header.as_raw()) },
177
+ "mlx_save_safetensors",
178
+ )
179
+ }
180
+ }
181
+
182
+ #[cfg(test)]
183
+ mod tests {
184
+ use super::*;
185
+ use crate::mlxc::Dtype;
186
+ use crate::runtime;
187
+
188
+ fn run<R>(f: impl FnOnce() -> Result<R>) -> R {
189
+ runtime::runtime()
190
+ .execute(|| Ok(f()?))
191
+ .expect("the runtime should let this through")
192
+ }
193
+
194
+ #[test]
195
+ fn what_is_saved_loads_back_by_name() {
196
+ let dir = tempfile::tempdir().unwrap();
197
+ let file = dir.path().join("t.safetensors");
198
+ let (names, w, ids, half) = run(|| {
199
+ let metadata = HashMap::from([("format".to_string(), "pt".to_string())]);
200
+ let w = Array::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2])?;
201
+ let ids = Array::from_slice(&[7i32, 8], &[2])?;
202
+ let half = Array::from_slice(&[0.5f32, 2.0], &[2])?.as_dtype(Dtype::Bfloat16)?;
203
+ Array::save_safetensors([("m.w", &w), ("ids", &ids), ("half", &half)], &metadata, &file)?;
204
+
205
+ let loaded = Array::load_safetensors(&file)?;
206
+ let mut names: Vec<_> = loaded.keys().cloned().collect();
207
+ names.sort();
208
+ let w = &loaded["m.w"];
209
+ Ok((
210
+ names,
211
+ (w.shape().to_vec(), w.as_slice::<f32>()?.to_vec()),
212
+ loaded["ids"].as_slice::<i32>()?.to_vec(),
213
+ (loaded["half"].dtype(), loaded["half"].as_dtype(Dtype::Float32)?.as_slice::<f32>()?.to_vec()),
214
+ ))
215
+ });
216
+ assert_eq!(names, vec!["half", "ids", "m.w"]);
217
+ assert_eq!(w, (vec![2, 2], vec![1.0, 2.0, 3.0, 4.0]));
218
+ assert_eq!(ids, vec![7, 8]);
219
+ assert_eq!(half, (Dtype::Bfloat16, vec![0.5, 2.0]));
220
+ }
221
+
222
+ /// The header a published checkpoint carries, which transformers looks
223
+ /// for before it will load a file (`TrainState::export`).
224
+ #[test]
225
+ fn the_metadata_is_written_into_the_header() {
226
+ let dir = tempfile::tempdir().unwrap();
227
+ let file = dir.path().join("t.safetensors");
228
+ run(|| {
229
+ let metadata = HashMap::from([("format".to_string(), "pt".to_string())]);
230
+ Array::save_safetensors([("x", Array::from_f32(1.0)?)], &metadata, &file)
231
+ });
232
+ let bytes = std::fs::read(&file).unwrap();
233
+ let length = u64::from_le_bytes(bytes[..8].try_into().unwrap()) as usize;
234
+ let header = std::str::from_utf8(&bytes[8..8 + length]).unwrap();
235
+ assert!(header.contains(r#""__metadata__":{"format":"pt"}"#), "{header}");
236
+ }
237
+
238
+ #[test]
239
+ fn a_missing_file_or_another_format_is_refused_before_mlx_sees_it() {
240
+ let dir = tempfile::tempdir().unwrap();
241
+ let (missing, other) = run(|| {
242
+ let missing = Array::load_safetensors(dir.path().join("none.safetensors")).unwrap_err();
243
+ let other = Array::save_safetensors([("x", Array::from_f32(1.0)?)], None, dir.path().join("x.npy"))
244
+ .unwrap_err();
245
+ Ok((missing.what().to_string(), other.what().to_string()))
246
+ });
247
+ assert_eq!(missing, "Path must point to a local file");
248
+ assert_eq!(other, "Unsupported file format");
249
+ }
250
+
251
+ #[test]
252
+ fn a_name_with_a_nul_in_it_is_an_error_and_writes_nothing() {
253
+ let dir = tempfile::tempdir().unwrap();
254
+ let file = dir.path().join("t.safetensors");
255
+ let refused = run(|| Ok(Array::save_safetensors([("a\0b", Array::from_f32(1.0)?)], None, &file).is_err()));
256
+ assert!(refused);
257
+ assert!(!file.exists());
258
+ }
259
+
260
+ #[test]
261
+ fn a_file_mlx_cannot_read_is_an_error_in_mlx_s_words() {
262
+ let dir = tempfile::tempdir().unwrap();
263
+ let file = dir.path().join("broken.safetensors");
264
+ std::fs::write(&file, b"not a safetensors file").unwrap();
265
+ let said = run(|| Ok(Array::load_safetensors(&file).unwrap_err().what().to_string()));
266
+ assert!(!said.is_empty() && !said.contains("mlx_load_safetensors failed"), "{said}");
267
+ }
268
+ }
@@ -0,0 +1,56 @@
1
+ //! MLX's allocator, which is process-wide.
2
+ //!
3
+ //! mlx-rs had nothing for these, so the engine called mlx-sys directly
4
+ //! (`crate::memory`). They are here now so that a failure reports what MLX
5
+ //! said, through the same handler as everything else.
6
+
7
+ use super::error::{check, install, Result};
8
+ use super::sys;
9
+
10
+ fn read(call: unsafe extern "C" fn(*mut usize) -> std::ffi::c_int, name: &str) -> Result<usize> {
11
+ ready();
12
+ let mut bytes = 0usize;
13
+ check(unsafe { call(&mut bytes) }, name)?;
14
+ Ok(bytes)
15
+ }
16
+
17
+ pub fn active() -> Result<usize> {
18
+ read(sys::mlx_get_active_memory, "mlx_get_active_memory")
19
+ }
20
+
21
+ pub fn cache() -> Result<usize> {
22
+ read(sys::mlx_get_cache_memory, "mlx_get_cache_memory")
23
+ }
24
+
25
+ pub fn peak() -> Result<usize> {
26
+ read(sys::mlx_get_peak_memory, "mlx_get_peak_memory")
27
+ }
28
+
29
+ pub fn limit() -> Result<usize> {
30
+ read(sys::mlx_get_memory_limit, "mlx_get_memory_limit")
31
+ }
32
+
33
+ /// Every call here starts with this: these are the one kind of mlx-c
34
+ /// call that neither makes a handle nor is handed one (`error::install`).
35
+ fn ready() {
36
+ install();
37
+ }
38
+
39
+ pub fn clear_cache() -> Result<()> {
40
+ ready();
41
+ check(unsafe { sys::mlx_clear_cache() }, "mlx_clear_cache")
42
+ }
43
+
44
+ pub fn reset_peak() -> Result<()> {
45
+ ready();
46
+ check(unsafe { sys::mlx_reset_peak_memory() }, "mlx_reset_peak_memory")
47
+ }
48
+
49
+ /// Caps allocation at `bytes` (0 lifts the cap) and returns the cap now in
50
+ /// force: mlx-c writes the new limit into its out-parameter, not the old.
51
+ pub fn set_limit(bytes: usize) -> Result<usize> {
52
+ ready();
53
+ let mut now = 0usize;
54
+ check(unsafe { sys::mlx_set_memory_limit(&mut now, bytes) }, "mlx_set_memory_limit")?;
55
+ Ok(now)
56
+ }
@@ -0,0 +1,24 @@
1
+ //! Where MLX finds its Metal kernels.
2
+ //!
3
+ //! MLX looks for `mlx.metallib` beside its own code, through `dladdr`,
4
+ //! unless it is told otherwise first. `mlx_metal_set_metallib_path` is that
5
+ //! telling: set before the device initializes, the named file is tried
6
+ //! first and the default search is the fallback (mlx-swift issue #415).
7
+ //!
8
+ //! It exists so a platform gem can fetch the kernels into a directory it
9
+ //! can write and point MLX there, rather than writing beside the installed
10
+ //! bundle, which the gem's own directory need not allow.
11
+
12
+ use super::error::{check, install, Exception, Result};
13
+ use super::sys;
14
+
15
+ /// Points MLX at `mlx.metallib` before it looks.
16
+ pub fn set_metallib_path(path: &str) -> Result<()> {
17
+ install();
18
+ let path = std::ffi::CString::new(path)
19
+ .map_err(|_| Exception::custom("a metallib path may not hold a NUL"))?;
20
+ check(
21
+ unsafe { sys::mlx_metal_set_metallib_path(path.as_ptr()) },
22
+ "mlx_metal_set_metallib_path",
23
+ )
24
+ }
@@ -0,0 +1,55 @@
1
+ //! mlx-c, bound here rather than through mlx-rs (notes/plan-mlxc-migration.md).
2
+ //!
3
+ //! Why: `mlx-rs` cannot be built for anything but Apple's platforms, and one
4
+ //! of the reasons is not its own. `mlx/c/half.h` defines `float16_t` and
5
+ //! `bfloat16_t` only on ARM, so `mlx_array_data_float16` and its three
6
+ //! siblings are absent from the C API on x86_64, and `mlx-rs` uses them
7
+ //! unconditionally. Teaching it not to would change its public API per
8
+ //! platform, which is not a change to ask of somebody else's crate.
9
+ //!
10
+ //! What those four do is read a half-precision value into a *host*
11
+ //! variable, which x86_64 has no type for. Computing in fp16 or bf16 is
12
+ //! untouched: the dtypes are in the enum, `mlx_astype` converts, and every
13
+ //! op takes them. The engine reads f32 and i32 across its boundary and
14
+ //! converts the rest, so it never wanted them.
15
+ //!
16
+ //! **mlx-rs's names where they cost nothing; stronger types where they
17
+ //! can hold a rule.** The binding began as mlx-rs's shape exactly, which made
18
+ //! moving the engine onto it a change of `use` lines, and mlx-rs is still
19
+ //! the reference for which mlx-c variant each call means (docs/vendoring.md
20
+ //! keeps that table). With mlx-rs gone, its signatures are no longer a
21
+ //! constraint where a type can hold a rule the code would otherwise have to
22
+ //! remember: constructors return `Result`, so an [`Array`] always holds an
23
+ //! array; a draw takes its key as `&Array`; and reading a value returns
24
+ //! `Result` rather than panicking.
25
+
26
+ /// mlx-c, as bindgen read its headers. Generated by build.rs from the
27
+ /// prefix that is linked, so what is declared here is what is in the
28
+ /// archive.
29
+ #[allow(
30
+ non_upper_case_globals,
31
+ non_camel_case_types,
32
+ non_snake_case,
33
+ dead_code,
34
+ clippy::all
35
+ )]
36
+ pub(crate) mod sys {
37
+ include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
38
+ }
39
+
40
+ mod array;
41
+ pub mod error;
42
+ pub mod fast;
43
+ pub(crate) mod handle;
44
+ mod io;
45
+ pub mod memory;
46
+ #[cfg(target_os = "macos")]
47
+ pub mod metal;
48
+ pub mod nn;
49
+ pub mod ops;
50
+ pub mod quantized;
51
+ pub mod random;
52
+ pub mod transforms;
53
+
54
+ pub use array::{Array, ArrayElement, Dtype};
55
+ pub use ops::stop_gradient;
@@ -0,0 +1,38 @@
1
+ //! The one activation the engine takes from a library rather than writing
2
+ //! out in its own interpreter.
3
+
4
+ use std::f32::consts::PI;
5
+
6
+ use super::error::Result;
7
+ use super::ops::tanh;
8
+ use super::{Array, Dtype};
9
+
10
+ /// GELU's tanh approximation:
11
+ /// 0.5 · x · (1 + tanh(√(2/π) · (x + 0.044715 · x³))).
12
+ ///
13
+ /// The same operations, in the same order, as mlx-rs's
14
+ /// `nn::gelu_approximate`, with one difference: the constants are in
15
+ /// `x`'s dtype rather than f32. mlx-rs's f32 constants promote a bf16 `x`
16
+ /// to f32, which turned everything after the first activation of a bf16
17
+ /// Gemma into f32 (2026-11-09); for an f32 `x` the two are the same
18
+ /// function to the bit. What mlx-rs adds is `compile`, which fuses these
19
+ /// into one kernel; that
20
+ /// changes how fast this runs, not what it computes. Not compiled here:
21
+ /// compiling through mlx-c means handing MLX a closure with a stable id
22
+ /// (`mlx_detail_compile`) and owning the cache that id keys, and one
23
+ /// activation in one model family is not worth being the first thing the
24
+ /// engine compiles. `rake oracle:gemma3_forward` is what holds its numbers.
25
+ pub fn gelu_approximate(x: impl AsRef<Array>) -> Result<Array> {
26
+ let x = x.as_ref();
27
+ let like = |value: f32| -> Result<Array> {
28
+ let array = Array::from_f32(value)?;
29
+ match x.dtype() {
30
+ Dtype::Bfloat16 | Dtype::Float16 => array.as_dtype(x.dtype()),
31
+ _ => Ok(array),
32
+ }
33
+ };
34
+ let cubed = x.power(Array::from_i32(3)?)?;
35
+ let inner = x.add(like(0.044715)?.multiply(&cubed)?)?;
36
+ let scaled = like(2.0 / PI)?.sqrt()?.multiply(&inner)?;
37
+ like(0.5)?.multiply(x)?.multiply(like(1.0)?.add(tanh(&scaled)?)?)
38
+ }