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,377 @@
1
+ //! The one MLX this process has.
2
+ //!
3
+ //! MLX's constraints are the engine's, not its callers'. There is one
4
+ //! device, one default stream, one command queue and one allocator per
5
+ //! process; two threads submitting to them at once ends the process, and a
6
+ //! forked child inherits none of them. Those facts belong here, where MLX
7
+ //! is actually owned, rather than in whatever happens to be calling
8
+ //! (notes/ENGINE_RUNTIME_BOUNDARY_PLAN.md).
9
+ //!
10
+ //! They used to live in the Ruby extension, which meant every binding had
11
+ //! to decide per call whether it was about to touch MLX. `seed=` looked
12
+ //! like a setter and built an RNG key; `fetch` looked like a read and
13
+ //! evaluated an array and copied it off the device. Both were wrong, and
14
+ //! the engine's own tests and command-line tool went through no gate at
15
+ //! all.
16
+ //!
17
+ //! The rule this replaces that with: **every public route to MLX passes
18
+ //! through [`execute`], and callers do not classify.**
19
+
20
+ use std::sync::{Mutex, MutexGuard, OnceLock};
21
+
22
+ /// What the runtime refuses, and why. Typed rather than a message: the
23
+ /// engine does not know Ruby's error classes, and the layer that does
24
+ /// should not read strings to find out which failure this was.
25
+ #[derive(Debug)]
26
+ pub enum RuntimeError {
27
+ /// A fork. The device did not come along, and neither did whatever
28
+ /// held the gate at the time.
29
+ ForeignProcess,
30
+ /// MLX could not run here even once: something it needs is not in
31
+ /// place, and asking it anyway would end the process rather than
32
+ /// return. The string says what is missing and where it was expected.
33
+ Unavailable(String),
34
+ /// A panic escaped an operation while it held the gate. MLX is
35
+ /// process-global, so what that left behind is not knowable, and no
36
+ /// further work is attempted in this process.
37
+ Poisoned,
38
+ /// The operation itself failed, and the runtime is fine.
39
+ Engine(anyhow::Error),
40
+ }
41
+
42
+ impl std::fmt::Display for RuntimeError {
43
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44
+ match self {
45
+ RuntimeError::ForeignProcess => write!(
46
+ f,
47
+ "this process is not the one that loaded the engine (a fork). \
48
+ A Metal device does not survive fork: open a session in the \
49
+ child, or run the work in a process of its own."
50
+ ),
51
+ RuntimeError::Unavailable(what) => write!(f, "{what}"),
52
+ RuntimeError::Poisoned => write!(
53
+ f,
54
+ "the engine panicked while it held MLX, so nothing more is \
55
+ attempted in this process. Start a new one, from a \
56
+ checkpoint if you have it."
57
+ ),
58
+ RuntimeError::Engine(error) => write!(f, "{error:#}"),
59
+ }
60
+ }
61
+ }
62
+
63
+ impl std::error::Error for RuntimeError {}
64
+
65
+ impl From<anyhow::Error> for RuntimeError {
66
+ fn from(error: anyhow::Error) -> Self {
67
+ RuntimeError::Engine(error)
68
+ }
69
+ }
70
+
71
+ /// One per process, and no way to make a second: two runtimes would be two
72
+ /// mutexes, which is no exclusion at all.
73
+ static RUNTIME: OnceLock<Runtime> = OnceLock::new();
74
+
75
+ pub(crate) fn runtime() -> &'static Runtime {
76
+ RUNTIME.get_or_init(Runtime::new)
77
+ }
78
+
79
+ /// Records the process the engine belongs to.
80
+ ///
81
+ /// Called once when a binding loads, so that a fork after loading is
82
+ /// refused even if nothing has touched MLX yet. Without it the runtime
83
+ /// would take its pid from whoever first ran an operation, which would
84
+ /// quietly bless a child that forked early. Builds nothing.
85
+ pub fn initialize() {
86
+ let _ = runtime();
87
+ }
88
+
89
+ pub(crate) struct Runtime {
90
+ origin_pid: u32,
91
+ gate: Mutex<()>,
92
+ }
93
+
94
+ impl Runtime {
95
+ /// Also where MLX's error handler goes in: every route to MLX in
96
+ /// production goes through here first, and mlx-c's own handler exits
97
+ /// the process. The binding installs it where handles are born as well
98
+ /// (`crate::mlxc::error`), which is what covers the engine's tests of
99
+ /// the layers under the runtime, since they build arrays by hand.
100
+ fn new() -> Self {
101
+ crate::mlxc::error::install();
102
+ Self {
103
+ origin_pid: std::process::id(),
104
+ gate: Mutex::new(()),
105
+ }
106
+ }
107
+
108
+ /// Runs one MLX operation, alone.
109
+ ///
110
+ /// Waiting, not refusing: two sessions in a process take turns, which
111
+ /// is what one queue means. Refusing a second call on the *same*
112
+ /// session is the caller's business, and has to happen before this,
113
+ /// or the two would silently interleave.
114
+ ///
115
+ /// A panic is not caught here. It unwinds through the guard, which
116
+ /// poisons the gate and closes this process to further MLX work; the
117
+ /// binding above catches it and says which session it belonged to.
118
+ /// Catching it here would leave the gate unpoisoned and the rule in
119
+ /// `RuntimeError::Poisoned` unenforced.
120
+ pub(crate) fn execute<R>(
121
+ &self,
122
+ operation: impl FnOnce() -> anyhow::Result<R>,
123
+ ) -> Result<R, RuntimeError> {
124
+ let _guard = self.enter()?;
125
+ operation().map_err(RuntimeError::Engine)
126
+ }
127
+
128
+ /// The pid first, and before the gate. A mutex another thread held
129
+ /// when the fork happened is locked forever in the child, so a child
130
+ /// that waited would wait for good. Then whether MLX can run here at
131
+ /// all, because the failure that answers otherwise is an abort, not an
132
+ /// error.
133
+ fn enter(&self) -> Result<MutexGuard<'_, ()>, RuntimeError> {
134
+ self.here()?;
135
+ available()?;
136
+ self.gate.lock().map_err(|_| RuntimeError::Poisoned)
137
+ }
138
+
139
+ fn here(&self) -> Result<(), RuntimeError> {
140
+ if self.origin_pid == std::process::id() {
141
+ Ok(())
142
+ } else {
143
+ Err(RuntimeError::ForeignProcess)
144
+ }
145
+ }
146
+
147
+ /// Frees what an operation cannot: the resources of something being
148
+ /// dropped.
149
+ ///
150
+ /// Two things separate this from [`Runtime::execute`]. A poisoned gate
151
+ /// still lets a release through, because refusing would leak device
152
+ /// memory to no purpose. And in a forked child the value is leaked on
153
+ /// purpose: the device those handles name did not come along, and
154
+ /// freeing them would talk to a device that is not there.
155
+ pub(crate) fn release<T>(&self, value: T) -> Result<(), RuntimeError> {
156
+ if self.here().is_err() {
157
+ std::mem::forget(value);
158
+ return Err(RuntimeError::ForeignProcess);
159
+ }
160
+ let _guard = match self.gate.lock() {
161
+ Ok(guard) => guard,
162
+ Err(poisoned) => poisoned.into_inner(),
163
+ };
164
+ drop(value);
165
+ Ok(())
166
+ }
167
+
168
+ /// Whether this process may still reach MLX at all. For a caller
169
+ /// deciding whether to keep going or start over.
170
+ pub(crate) fn usable(&self) -> bool {
171
+ self.here().is_ok() && !self.gate.is_poisoned()
172
+ }
173
+ }
174
+
175
+ /// Whether MLX can still be reached from this process.
176
+ pub fn usable() -> bool {
177
+ runtime().usable()
178
+ }
179
+
180
+ /// Refuses, once and for all, if MLX could not start here.
181
+ ///
182
+ /// The failure this prevents is not an error. MLX finds its Metal kernels
183
+ /// by asking `dladdr` where its own code lives and looking for
184
+ /// `mlx.metallib` next to it; if the file is not there, device
185
+ /// initialization throws a C++ exception that nothing in Rust can catch,
186
+ /// and the process exits with nothing for any caller to rescue
187
+ /// (docs/vendoring.md). So the same question is asked here first, the same
188
+ /// way, before MLX ever is.
189
+ ///
190
+ /// Asked once per process: the file does not move while we run, and the
191
+ /// answer is the same for every session.
192
+ fn available() -> Result<(), RuntimeError> {
193
+ static ANSWER: OnceLock<Option<String>> = OnceLock::new();
194
+ match ANSWER.get_or_init(|| missing_metallib(recorded_metallib_path())) {
195
+ None => Ok(()),
196
+ Some(what) => Err(RuntimeError::Unavailable(what.clone())),
197
+ }
198
+ }
199
+
200
+ /// Where a caller has told MLX the kernels are, if it has.
201
+ ///
202
+ /// Set through [`set_metallib_path`] before MLX is first asked anything:
203
+ /// [`available`] answers once per process, so a path named after that is
204
+ /// not consulted.
205
+ static METALLIB_PATH: OnceLock<std::path::PathBuf> = OnceLock::new();
206
+
207
+ fn recorded_metallib_path() -> Option<&'static std::path::Path> {
208
+ METALLIB_PATH.get().map(std::path::PathBuf::as_path)
209
+ }
210
+
211
+ /// Tells MLX where `mlx.metallib` is, before it looks.
212
+ ///
213
+ /// The point is a caller that cannot write beside the engine: a platform
214
+ /// gem fetches the kernels into a cache and names them here, rather than
215
+ /// writing into the installed bundle's directory. Apple only - the file is
216
+ /// Metal's - and a no-op elsewhere.
217
+ #[cfg(target_os = "macos")]
218
+ pub fn set_metallib_path(path: &std::path::Path) -> Result<(), RuntimeError> {
219
+ // The error handler first: mlx-c's default would exit the process.
220
+ let _ = runtime();
221
+ crate::mlxc::metal::set_metallib_path(&path.to_string_lossy())
222
+ .map_err(|error| RuntimeError::Engine(error.into()))?;
223
+ let _ = METALLIB_PATH.set(path.to_path_buf());
224
+ Ok(())
225
+ }
226
+
227
+ #[cfg(not(target_os = "macos"))]
228
+ pub fn set_metallib_path(_path: &std::path::Path) -> Result<(), RuntimeError> {
229
+ Ok(())
230
+ }
231
+
232
+ /// The path this code is loaded from, through `dladdr` on an anchor in its
233
+ /// own data segment. MLX is statically linked into the same object, so its
234
+ /// own `current_binary_dir()` names the same place, and what it loads at
235
+ /// run time is found relative to it.
236
+ #[cfg(any(target_os = "macos", target_os = "linux"))]
237
+ fn object_path() -> Option<std::path::PathBuf> {
238
+ static ANCHOR: u8 = 0;
239
+ let mut info: libc::Dl_info = unsafe { std::mem::zeroed() };
240
+ let found =
241
+ unsafe { libc::dladdr(std::ptr::addr_of!(ANCHOR) as *const libc::c_void, &mut info) };
242
+ if found == 0 || info.dli_fname.is_null() {
243
+ // Cannot tell where we are; refusing on ignorance would block a
244
+ // working setup, so let MLX try.
245
+ return None;
246
+ }
247
+ let object = unsafe { std::ffi::CStr::from_ptr(info.dli_fname) };
248
+ Some(std::path::PathBuf::from(object.to_string_lossy().into_owned()))
249
+ }
250
+
251
+ /// The name of an object, for a refusal that says where it looked.
252
+ #[cfg(any(target_os = "macos", target_os = "linux"))]
253
+ fn object_name(object: &std::path::Path) -> String {
254
+ object.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()
255
+ }
256
+
257
+ /// What is missing, if MLX would fail to find its kernels here.
258
+ ///
259
+ /// Apple aborts the process over a missing metallib; Linux only fails the
260
+ /// first JIT-compiled kernel. Both say so here, where a caller can still
261
+ /// act, rather than a step later or not at all.
262
+ #[cfg(target_os = "macos")]
263
+ fn missing_metallib(named: Option<&std::path::Path>) -> Option<String> {
264
+ // A caller that named a file knows more than this check does, so the
265
+ // name is the answer: if the file is not there, that is the refusal.
266
+ if let Some(path) = named {
267
+ return (!path.exists()).then(|| {
268
+ format!(
269
+ "the named mlx.metallib is not there: {}. Without kernels MLX \
270
+ aborts the process rather than raising, so this refuses \
271
+ first.",
272
+ path.display()
273
+ )
274
+ });
275
+ }
276
+ let object = object_path()?;
277
+ let expected = object.parent()?.join("mlx.metallib");
278
+ if expected.exists() {
279
+ return None;
280
+ }
281
+ Some(format!(
282
+ "MLX's Metal kernels are not where it will look for them: expected \
283
+ {} beside {}. Without that file MLX aborts the process rather than \
284
+ raising, so this refuses first. A platform gem fetches it on first \
285
+ use; in a checkout, run `rake metallib`.",
286
+ expected.display(),
287
+ object_name(&object)
288
+ ))
289
+ }
290
+
291
+ /// Linux's counterpart: MLX compiles its CUDA kernels at run time through
292
+ /// NVRTC and reads NVIDIA's headers (`cccl`, `cute`, `cutlass`) from one
293
+ /// directory above the extension - its parent's `include/`. The platform
294
+ /// gem ships them there; a checkout gets them from the MLX prefix.
295
+ #[cfg(target_os = "linux")]
296
+ fn missing_metallib(_named: Option<&std::path::Path>) -> Option<String> {
297
+ let object = object_path()?;
298
+ let expected = object.parent()?.parent()?.join("include").join("cccl");
299
+ if expected.is_dir() {
300
+ return None;
301
+ }
302
+ Some(format!(
303
+ "MLX's CUDA kernels are compiled at run time and cannot find NVIDIA's \
304
+ headers: expected {} beside {}. A platform gem carries them; in a \
305
+ checkout they come from the MLX prefix.",
306
+ expected.display(),
307
+ object_name(&object)
308
+ ))
309
+ }
310
+
311
+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]
312
+ fn missing_metallib(_named: Option<&std::path::Path>) -> Option<String> {
313
+ None
314
+ }
315
+
316
+ #[cfg(test)]
317
+ mod tests {
318
+ use super::*;
319
+
320
+ #[test]
321
+ fn this_process_owns_the_runtime() {
322
+ assert!(usable(), "the tests run where the engine was loaded");
323
+ assert!(runtime().here().is_ok());
324
+ }
325
+
326
+ #[test]
327
+ fn the_metallib_is_looked_for_beside_this_object() {
328
+ // The check has to agree with MLX, which asks dladdr where its own
329
+ // code is. Ours is in the same object, so if it finds nothing to
330
+ // complain about, MLX will find the file.
331
+ assert!(
332
+ missing_metallib(None).is_none(),
333
+ "the test binary should have mlx.metallib beside it \
334
+ (engine/build.rs links it into deps/): {:?}",
335
+ missing_metallib(None)
336
+ );
337
+ }
338
+
339
+ #[cfg(target_os = "macos")]
340
+ #[test]
341
+ fn a_named_metallib_that_exists_is_taken_as_the_answer() {
342
+ // What a platform gem does: fetch the kernels somewhere writable
343
+ // and name them, instead of writing beside the bundle.
344
+ let dir = std::env::temp_dir().join(format!("torobi-metallib-{}", std::process::id()));
345
+ std::fs::create_dir_all(&dir).unwrap();
346
+ let file = dir.join("mlx.metallib");
347
+ std::fs::write(&file, b"kernels").unwrap();
348
+
349
+ assert!(missing_metallib(Some(&file)).is_none(), "a file that is there is used");
350
+
351
+ std::fs::remove_file(&file).unwrap();
352
+ assert!(
353
+ missing_metallib(Some(&file)).is_some(),
354
+ "a name for a file that is not there is refused, not waved through"
355
+ );
356
+ std::fs::remove_dir_all(&dir).ok();
357
+ }
358
+
359
+ #[test]
360
+ fn a_refusal_says_what_is_missing_and_where() {
361
+ // The message is the whole value of refusing rather than aborting,
362
+ // so its shape is worth pinning.
363
+ let refusal = RuntimeError::Unavailable("no kernels at /x/mlx.metallib".into());
364
+ let said = refusal.to_string();
365
+ assert!(said.contains("/x/mlx.metallib"), "{said}");
366
+ }
367
+
368
+ #[test]
369
+ fn the_layers_are_told_apart_rather_than_flattened() {
370
+ // The binding maps these to different Ruby classes, so they must
371
+ // not collapse into one another on the way up.
372
+ let engine = RuntimeError::Engine(anyhow::anyhow!("a step failed"));
373
+ assert!(matches!(engine, RuntimeError::Engine(_)));
374
+ assert!(!matches!(RuntimeError::ForeignProcess, RuntimeError::Engine(_)));
375
+ assert!(!matches!(RuntimeError::Poisoned, RuntimeError::ForeignProcess));
376
+ }
377
+ }