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,1037 @@
1
+ //! The narrow waist between Ruby and the engine.
2
+ //!
3
+ //! Ruby holds one object, a session. It can start one, run steps on it,
4
+ //! read numbers off it, turn its knobs, and copy a parameter or a gradient
5
+ //! out by name. No tensor handles cross this line, no Ruby block ever runs
6
+ //! inside a computation, and the only unsafe code is `gvl`.
7
+ //!
8
+ //! # Every entry point goes through one of three doors
9
+ //!
10
+ //! A panic in Rust does not abort here: magnus catches it leaving a
11
+ //! `method!` and raises a Ruby `fatal`. But a `fatal` is not rescuable, so
12
+ //! a caller cannot tell one from a crash or decide anything about it.
13
+ //! Catching first is what makes it an error.
14
+ //!
15
+ //! | door | for | what it adds |
16
+ //! | --- | --- | --- |
17
+ //! | [`Session::with_engine`] | anything that uses a session's engine | the session's state machine (busy, closed, poisoned), the GVL, the engine's runtime |
18
+ //! | [`global`] | the process-wide MLX calls (`Torobi::Memory`) | the GVL and the engine's runtime |
19
+ //! | [`plainly`] | what touches no MLX (`build_info`, `checkpoint_manifest`) | the catch, and nothing else |
20
+ //!
21
+ //! Two methods are outside them on purpose: `closed?` and `poisoned?` take
22
+ //! this crate's own lock and match on a value. They reach no engine, run
23
+ //! no MLX, and have nothing in them that can panic, so a door would add a
24
+ //! closure and no safety.
25
+
26
+ mod gvl;
27
+
28
+ use std::panic::{catch_unwind, AssertUnwindSafe};
29
+ use std::sync::atomic::{AtomicBool, Ordering};
30
+ use std::sync::Mutex;
31
+
32
+ use magnus::exception::ExceptionClass;
33
+ use magnus::value::ReprValue;
34
+ use magnus::{function, method, prelude::*, Error, RArray, RHash, RString, Ruby, Value};
35
+ use torobi_engine::tensor::{Batch, Tensor};
36
+ use torobi_engine::{RuntimeError, Session as EngineSession, Weights};
37
+
38
+ use gvl::{OnRefusal, Outcome};
39
+
40
+ /// The engine's session, owned by one Ruby object.
41
+ ///
42
+ /// What is left here is the Ruby runtime's half: converting values,
43
+ /// releasing the GVL, and saying that one Ruby session serves one thread.
44
+ /// Serializing MLX, refusing a forked child and freeing device memory are
45
+ /// the engine's, which owns them
46
+ /// (notes/ENGINE_RUNTIME_BOUNDARY_PLAN.md section 3).
47
+ ///
48
+ /// A `Mutex` rather than a `RefCell`, and `try_lock` rather than `lock`.
49
+ /// The reason is the GVL: a step runs with it released, so a second Ruby
50
+ /// thread can reach this object while the first is inside MLX. A RefCell
51
+ /// panicked there, and a panic that escapes becomes a Ruby `fatal` that no
52
+ /// `rescue` catches. Blocking would be worse still: the second thread
53
+ /// would hold the GVL while waiting, and the first needs the GVL back to
54
+ /// return. So a session in use answers "busy" and stays alive.
55
+ ///
56
+ /// The engine is taken *out* of the slot for the duration of a step, and
57
+ /// put back before the GVL is reacquired. Holding the guard across that
58
+ /// boundary is what an interrupt used to destroy: CRuby raises on the way
59
+ /// out of a blocking region, the Rust frame is skipped, and the guard is
60
+ /// never dropped, leaving the session permanently busy. Nothing may be
61
+ /// left to do after the boundary (notes/SESSION_CONCURRENCY_SPEC.md 0, 3.1).
62
+ #[magnus::wrap(class = "Torobi::Native::Session", free_immediately, size)]
63
+ struct Session {
64
+ /// Whether a call that runs MLX is in progress for this session, which
65
+ /// includes waiting for the engine's gate.
66
+ ///
67
+ /// Not the same as `Slot::Running`, which says the engine is out of
68
+ /// the slot. A second thread must be told the session is busy rather
69
+ /// than queued behind the engine's gate and served afterwards: one
70
+ /// session is one conversation (the spec, section 1), and two threads
71
+ /// taking turns at one would interleave a run without saying so.
72
+ in_flight: AtomicBool,
73
+ slot: Mutex<Slot>,
74
+ /// The numbers a watcher reads, kept apart from the engine so that
75
+ /// reading them never waits on a step. Its lock is held for a copy and
76
+ /// never across the GVL boundary.
77
+ snapshot: Mutex<Snapshot>,
78
+ /// What the run is made of, which is settled when it opens.
79
+ names: Names,
80
+ }
81
+
82
+ /// The names a run answers to: its parameters, the batch fields it reads,
83
+ /// and the nodes a tap may ask for.
84
+ ///
85
+ /// Taken once, because the plan settles all three at open and nothing
86
+ /// moves them (docs/plan.md section 5A.1). Held here rather than asked of
87
+ /// the engine so that reading them is not a claim: a watcher wanting to
88
+ /// know what a run is made of would otherwise be told the session is
89
+ /// busy, which is true of the engine and not of the answer.
90
+ ///
91
+ /// What is trained is not here. Freezing moves it, so it is state, and
92
+ /// state is the engine's to report.
93
+ struct Names {
94
+ parameters: Vec<String>,
95
+ inputs: Vec<String>,
96
+ nodes: Vec<String>,
97
+ outputs: Vec<String>,
98
+ }
99
+
100
+ impl Names {
101
+ /// Taken from an open session; the caller has one in hand.
102
+ ///
103
+ /// These cannot refuse: a session that has just opened is not closed,
104
+ /// and none of the three reaches MLX. A default would be worse than a
105
+ /// panic here, because an empty parameter list is a sentence about the
106
+ /// run rather than a missing answer.
107
+ fn of(engine: &EngineSession) -> Self {
108
+ Self {
109
+ parameters: engine
110
+ .parameter_paths()
111
+ .expect("an open session answers parameter_paths"),
112
+ inputs: engine
113
+ .input_names()
114
+ .expect("an open session answers input_names"),
115
+ nodes: engine
116
+ .node_names()
117
+ .expect("an open session answers node_names"),
118
+ outputs: engine
119
+ .output_names()
120
+ .expect("an open session answers output_names"),
121
+ }
122
+ }
123
+ }
124
+
125
+ /// What the last completed step left behind.
126
+ ///
127
+ /// A session serves one thread, but watching it is not serving it: a
128
+ /// progress bar or a metrics thread wants the numbers, not the engine.
129
+ /// Answering "busy" to those was the shape the spec objected to, and it is
130
+ /// what this exists to avoid (notes/SESSION_CONCURRENCY_SPEC.md 3, 4).
131
+ ///
132
+ /// Never a partial step. It is published after the engine has committed,
133
+ /// so a reader sees a state the run actually passed through.
134
+ #[derive(Clone, Copy)]
135
+ struct Snapshot {
136
+ step: usize,
137
+ loss: f32,
138
+ lr: f32,
139
+ seed: u64,
140
+ /// The last step's gradient norm, before clipping: NaN until a step
141
+ /// is taken, and on a step that was skipped.
142
+ grad_norm: f32,
143
+ /// The cap in force, or `None`.
144
+ clip: Option<f32>,
145
+ }
146
+
147
+ impl Snapshot {
148
+ /// Taken from an open session; the caller has one in hand.
149
+ ///
150
+ /// None of these can refuse (they read state and reach no MLX), and
151
+ /// a default would be a lie a watcher could not tell from an answer:
152
+ /// step 0 is where a run starts.
153
+ fn of(engine: &EngineSession) -> Self {
154
+ Self {
155
+ step: engine.step().expect("an open session answers step"),
156
+ loss: engine.loss().expect("an open session answers loss"),
157
+ lr: engine.lr().expect("an open session answers lr"),
158
+ seed: engine.seed().expect("an open session answers seed"),
159
+ grad_norm: engine.grad_norm().expect("an open session answers grad_norm"),
160
+ clip: engine.clip().expect("an open session answers clip"),
161
+ }
162
+ }
163
+ }
164
+
165
+ /// Holds a session's claim for as long as one MLX call needs it.
166
+ struct Claim<'a>(&'a AtomicBool);
167
+
168
+ impl Drop for Claim<'_> {
169
+ fn drop(&mut self) {
170
+ self.0.store(false, Ordering::Release);
171
+ }
172
+ }
173
+
174
+ /// What a session is, from the outside.
175
+ enum Slot {
176
+ /// Usable, and nobody is inside it.
177
+ Ready(Box<EngineSession>),
178
+ /// A step is running. The engine belongs to that call's Rust frame,
179
+ /// not to this slot.
180
+ Running,
181
+ /// A panic escaped the engine. The state it left behind is not known
182
+ /// to be consistent, so nothing more is attempted with it.
183
+ Poisoned(String),
184
+ /// Closed by its owner. Its device memory is gone.
185
+ Closed,
186
+ }
187
+
188
+ /// Why a slot could not hand its engine over.
189
+ ///
190
+ /// Data rather than a `magnus::Error`, because it is decided with the GVL
191
+ /// released, where no Ruby object may be touched.
192
+ enum Refusal {
193
+ Busy,
194
+ Poisoned(String),
195
+ Closed,
196
+ }
197
+
198
+ impl Refusal {
199
+ fn of(slot: &Slot) -> Self {
200
+ match slot {
201
+ Slot::Ready(_) => unreachable!("a ready slot refuses nothing"),
202
+ Slot::Running => Refusal::Busy,
203
+ Slot::Poisoned(what) => Refusal::Poisoned(what.clone()),
204
+ Slot::Closed => Refusal::Closed,
205
+ }
206
+ }
207
+
208
+ fn into_error(self, ruby: &Ruby) -> Error {
209
+ match self {
210
+ Refusal::Busy => busy(ruby),
211
+ Refusal::Poisoned(what) => Error::new(
212
+ error_class(ruby, "SessionPoisoned"),
213
+ format!(
214
+ "this session is poisoned: the engine panicked ({what}), so its \
215
+ state cannot be trusted. Open a new one, from a checkpoint if \
216
+ you have it."
217
+ ),
218
+ ),
219
+ Refusal::Closed => Error::new(
220
+ error_class(ruby, "SessionClosed"),
221
+ "this session is closed",
222
+ ),
223
+ }
224
+ }
225
+ }
226
+
227
+ /// What one call produced, decided where the GVL may be released.
228
+ enum Ran<T> {
229
+ Finished(Result<T, RuntimeError>),
230
+ Refused(Refusal),
231
+ Panicked(String),
232
+ }
233
+
234
+ impl<T> Ran<T> {
235
+ /// Turned into Ruby's terms, which happens only once the GVL is back.
236
+ fn into_result(self, ruby: &Ruby) -> Result<T, Error> {
237
+ match self {
238
+ Ran::Finished(result) => result.map_err(|e| from_engine(ruby, e)),
239
+ Ran::Refused(refusal) => Err(refusal.into_error(ruby)),
240
+ Ran::Panicked(what) => Err(poisoned(ruby, &what)),
241
+ }
242
+ }
243
+ }
244
+
245
+ /// An engine refusal, in Ruby's terms.
246
+ ///
247
+ /// The engine says which layer refused; this decides which class carries
248
+ /// it. Nothing reads a message to find out (the plan, section 9).
249
+ fn from_engine(ruby: &Ruby, error: RuntimeError) -> Error {
250
+ let class = match error {
251
+ RuntimeError::ForeignProcess | RuntimeError::Unavailable(_) => "EngineUnavailable",
252
+ RuntimeError::Poisoned => "RuntimePoisoned",
253
+ RuntimeError::Engine(inner) => return to_error(ruby, inner),
254
+ };
255
+ Error::new(error_class(ruby, class), error.to_string())
256
+ }
257
+
258
+ const BUSY: &str = "this session is busy: it serves one thread at a time (a step is \
259
+ running). Use one session per thread, or a pool.";
260
+
261
+ fn to_error(ruby: &Ruby, error: anyhow::Error) -> Error {
262
+ Error::new(step_error_class(ruby), format!("{error:#}"))
263
+ }
264
+
265
+ /// One of Torobi's error classes by name. They are defined on the Ruby side
266
+ /// (errors.rb), so that the pure-Ruby half has the same hierarchy without
267
+ /// this extension; looked up here rather than duplicated.
268
+ fn error_class(ruby: &Ruby, name: &str) -> ExceptionClass {
269
+ ruby.class_object()
270
+ .const_get::<_, magnus::RModule>("Torobi")
271
+ .and_then(|m| m.const_get::<_, ExceptionClass>(name))
272
+ .unwrap_or_else(|_| ruby.exception_runtime_error())
273
+ }
274
+
275
+ /// The class a failed step raises.
276
+ fn step_error_class(ruby: &Ruby) -> ExceptionClass {
277
+ error_class(ruby, "StepError")
278
+ }
279
+
280
+ fn poisoned(ruby: &Ruby, what: &str) -> Error {
281
+ Error::new(
282
+ error_class(ruby, "SessionPoisoned"),
283
+ format!("the engine panicked ({what}); this session is now poisoned"),
284
+ )
285
+ }
286
+
287
+ fn busy(ruby: &Ruby) -> Error {
288
+ Error::new(error_class(ruby, "Busy"), BUSY)
289
+ }
290
+
291
+ impl Session {
292
+ /// Opens with the parameters given as values.
293
+ ///
294
+ /// `optimizer_json` names the update rule, e.g.
295
+ /// {"kind":"adamw","lr":0.001}. Data, so a journal can record it.
296
+ fn open(
297
+ ruby: &Ruby,
298
+ graph_json: String,
299
+ weights_json: String,
300
+ optimizer_json: String,
301
+ seed: u64,
302
+ ) -> Result<Self, Error> {
303
+ Self::opened(
304
+ ruby,
305
+ &graph_json,
306
+ Weights::Inline(&weights_json),
307
+ &optimizer_json,
308
+ seed,
309
+ )
310
+ }
311
+
312
+ /// Opens with the parameters read from a safetensors file.
313
+ ///
314
+ /// A second entry point rather than one that inspects its argument:
315
+ /// where parameters come from is a choice the caller makes, and a
316
+ /// choice made by what type a value happens to be is a choice nobody
317
+ /// wrote down.
318
+ fn open_from_file(
319
+ ruby: &Ruby,
320
+ graph_json: String,
321
+ path: String,
322
+ optimizer_json: String,
323
+ seed: u64,
324
+ ) -> Result<Self, Error> {
325
+ Self::opened(
326
+ ruby,
327
+ &graph_json,
328
+ Weights::File(std::path::Path::new(&path)),
329
+ &optimizer_json,
330
+ seed,
331
+ )
332
+ }
333
+
334
+ /// Opens with one published checkpoint per model, named by model.
335
+ ///
336
+ /// `files_json` is {"student": "path", ...}. A model published on its
337
+ /// own does not know what this run will call it, so its tensors carry
338
+ /// no model prefix; naming a file per model is what lets it be
339
+ /// imported without renaming anything.
340
+ /// `fresh_json` is the patterns naming parameters that are expected to
341
+ /// be in no file and are built from their declarations instead.
342
+ fn open_pretrained(
343
+ ruby: &Ruby,
344
+ graph_json: String,
345
+ files_json: String,
346
+ fresh_json: String,
347
+ optimizer_json: String,
348
+ seed: u64,
349
+ ) -> Result<Self, Error> {
350
+ let files: std::collections::BTreeMap<String, std::path::PathBuf> =
351
+ serde_json::from_str(&files_json).map_err(|e| {
352
+ Error::new(ruby.exception_arg_error(), format!("bad file list: {e}"))
353
+ })?;
354
+ let fresh: Vec<String> = serde_json::from_str(&fresh_json).map_err(|e| {
355
+ Error::new(ruby.exception_arg_error(), format!("bad fresh list: {e}"))
356
+ })?;
357
+ Self::opened(
358
+ ruby,
359
+ &graph_json,
360
+ Weights::Pretrained {
361
+ files: &files,
362
+ fresh: &fresh,
363
+ },
364
+ &optimizer_json,
365
+ seed,
366
+ )
367
+ }
368
+
369
+ fn opened(
370
+ ruby: &Ruby,
371
+ graph_json: &str,
372
+ weights: Weights<'_>,
373
+ optimizer_json: &str,
374
+ seed: u64,
375
+ ) -> Result<Self, Error> {
376
+ let optimizer = serde_json::from_str(optimizer_json).map_err(|e| {
377
+ Error::new(ruby.exception_arg_error(), format!("bad optimizer: {e}"))
378
+ })?;
379
+ // Opening builds every parameter, an RNG key and the optimizer's
380
+ // slots. That it is MLX work, and therefore waits its turn, is the
381
+ // engine's to know.
382
+ let opened = match gvl::released(
383
+ || EngineSession::open_with(graph_json, weights, optimizer, seed),
384
+ OnRefusal::AskRuby,
385
+ )? {
386
+ Outcome::Done(opened) => opened,
387
+ Outcome::Panicked(what) => return Err(poisoned(ruby, &what)),
388
+ Outcome::Interrupted => unreachable!("released() falls back rather than refusing"),
389
+ };
390
+ opened
391
+ .map(|session| Self {
392
+ in_flight: AtomicBool::new(false),
393
+ snapshot: Mutex::new(Snapshot::of(&session)),
394
+ names: Names::of(&session),
395
+ slot: Mutex::new(Slot::Ready(Box::new(session))),
396
+ })
397
+ .map_err(|e| from_engine(ruby, e))
398
+ }
399
+
400
+ /// Runs `work` on the engine, or says why it cannot.
401
+ ///
402
+ /// This is where the Ruby side's rules are enforced: a session already
403
+ /// serving a thread answers "busy" rather than panicking, and a panic
404
+ /// inside the engine poisons this session rather than escaping. What
405
+ /// it does *not* decide is whether `work` touches MLX. That belongs to
406
+ /// the engine, which serializes it and refuses a forked child before
407
+ /// any of it runs (notes/ENGINE_RUNTIME_BOUNDARY_PLAN.md section 3).
408
+ ///
409
+ /// The shape still matters (notes/SESSION_CONCURRENCY_SPEC.md 3.1, 5).
410
+ /// The engine is taken from the slot, used, and put back entirely
411
+ /// inside the GVL-released region. Before that region nothing is held;
412
+ /// after it there is nothing to do but read a value. An interrupt
413
+ /// raised at either edge therefore costs nothing, which is what a
414
+ /// `MutexGuard` held across the boundary used to cost.
415
+ fn with_engine<T>(
416
+ &self,
417
+ ruby: &Ruby,
418
+ work: impl FnOnce(&mut EngineSession) -> Result<T, RuntimeError>,
419
+ ) -> Result<T, Error> {
420
+ // Claimed before the engine is asked, so a second thread on this
421
+ // session is told rather than queued behind the engine's gate.
422
+ let _claim = self.claim().ok_or_else(|| busy(ruby))?;
423
+
424
+ match gvl::released(|| self.run(work), OnRefusal::AskRuby)? {
425
+ Outcome::Done(ran) => ran.into_result(ruby),
426
+ Outcome::Panicked(what) => Err(poisoned(ruby, &what)),
427
+ Outcome::Interrupted => unreachable!("released() falls back rather than refusing"),
428
+ }
429
+ }
430
+
431
+ /// Claims this session for one MLX call, or answers that someone else
432
+ /// has it. Released when the returned guard is dropped, which happens
433
+ /// on every path out: nothing here raises by longjmp.
434
+ fn claim(&self) -> Option<Claim<'_>> {
435
+ self.in_flight
436
+ .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
437
+ .ok()
438
+ .map(|_| Claim(&self.in_flight))
439
+ }
440
+
441
+ /// Take the engine, use it, put it back. Touches no Ruby, so this is
442
+ /// the whole of what runs with the GVL released.
443
+ fn run<T>(
444
+ &self,
445
+ work: impl FnOnce(&mut EngineSession) -> Result<T, RuntimeError>,
446
+ ) -> Ran<T> {
447
+ let mut engine = match self.take() {
448
+ Ok(engine) => engine,
449
+ Err(refusal) => return Ran::Refused(refusal),
450
+ };
451
+ match catch_unwind(AssertUnwindSafe(|| work(&mut engine))) {
452
+ Ok(result) => {
453
+ // Published before the engine goes back, so a reader never
454
+ // sees a Ready session whose numbers are a step stale.
455
+ self.publish(&engine);
456
+ self.put_back(Ok(engine));
457
+ Ran::Finished(result)
458
+ }
459
+ Err(panic) => {
460
+ let what = gvl::describe(panic);
461
+ self.put_back(Err(what.clone()));
462
+ Ran::Panicked(what)
463
+ }
464
+ }
465
+ }
466
+
467
+ /// Takes the engine out of the slot, leaving `Running` behind.
468
+ fn take(&self) -> Result<Box<EngineSession>, Refusal> {
469
+ self.take_leaving(Slot::Running)
470
+ }
471
+
472
+ /// Takes the engine out for good, leaving `Closed` behind.
473
+ ///
474
+ /// A session already closed answers `None` rather than refusing, so a
475
+ /// second `close` is a no-op; anything else (running, poisoned) is a
476
+ /// refusal like any other. Here rather than in `close` so that every
477
+ /// transition of `Slot` is in this one pair of methods: a variant
478
+ /// added later is a match this compiler checks, not a fourth place to
479
+ /// remember.
480
+ fn take_to_close(&self) -> Result<Option<Box<EngineSession>>, Refusal> {
481
+ match self.take_leaving(Slot::Closed) {
482
+ Ok(engine) => Ok(Some(engine)),
483
+ Err(Refusal::Closed) => Ok(None),
484
+ Err(refusal) => Err(refusal),
485
+ }
486
+ }
487
+
488
+ /// The engine, if the slot is ready to give it up, leaving `next`
489
+ /// behind. A slot that is not ready keeps what it holds and says why.
490
+ fn take_leaving(&self, next: Slot) -> Result<Box<EngineSession>, Refusal> {
491
+ let Ok(mut guard) = self.slot.try_lock() else {
492
+ return Err(Refusal::Busy);
493
+ };
494
+ match std::mem::replace(&mut *guard, next) {
495
+ Slot::Ready(engine) => Ok(engine),
496
+ other => {
497
+ let refusal = Refusal::of(&other);
498
+ *guard = other;
499
+ Err(refusal)
500
+ }
501
+ }
502
+ }
503
+
504
+ /// Copies the engine's numbers out for watchers to read.
505
+ fn publish(&self, engine: &EngineSession) {
506
+ let mut guard = self.snapshot.lock().unwrap_or_else(|e| e.into_inner());
507
+ *guard = Snapshot::of(engine);
508
+ }
509
+
510
+ /// The last published numbers. Never refuses: a closed or poisoned
511
+ /// session still says where it got to.
512
+ fn watch(&self) -> Snapshot {
513
+ *self.snapshot.lock().unwrap_or_else(|e| e.into_inner())
514
+ }
515
+
516
+ /// Puts the engine back, or records why there is none to put back.
517
+ ///
518
+ /// Blocking rather than `try_lock`, and safe to block: the only other
519
+ /// holders are Ruby threads whose critical section is pure Rust and
520
+ /// never waits for the GVL.
521
+ fn put_back(&self, engine: Result<Box<EngineSession>, String>) {
522
+ let mut guard = self.slot.lock().unwrap_or_else(|e| e.into_inner());
523
+ *guard = match engine {
524
+ Ok(engine) => Slot::Ready(engine),
525
+ Err(panic) => Slot::Poisoned(panic),
526
+ };
527
+ }
528
+
529
+ /// A reading. It goes the same way as everything else: whether it
530
+ /// costs MLX is the engine's to know, not this crate's.
531
+ fn read<T>(
532
+ &self,
533
+ ruby: &Ruby,
534
+ work: impl FnOnce(&EngineSession) -> Result<T, RuntimeError>,
535
+ ) -> Result<T, Error> {
536
+ self.with_engine(ruby, |engine| work(engine))
537
+ }
538
+
539
+ /// One step on one batch, with the GVL released.
540
+ ///
541
+ /// The batch arrives as {name => [dtype, shape, packed_bytes]}: dtype
542
+ /// and shape readable, payload as native-endian 4-byte values.
543
+ /// Measurement chose this over JSON (docs/plan.md section 5A.2.1).
544
+ fn run_step(ruby: &Ruby, rb_self: &Self, batch: RHash) -> Result<f32, Error> {
545
+ let batch = read_batch(ruby, batch)?;
546
+ rb_self.with_engine(ruby, |engine| engine.run_step(&batch))
547
+ }
548
+
549
+ /// One batch's gradients added to what is waiting, with no step: the
550
+ /// parameters do not move until `apply`. What a batch too large to
551
+ /// hold is trained as several of.
552
+ fn accumulate(ruby: &Ruby, rb_self: &Self, batch: RHash) -> Result<f32, Error> {
553
+ let batch = read_batch(ruby, batch)?;
554
+ rb_self.with_engine(ruby, |engine| engine.accumulate(&batch))
555
+ }
556
+
557
+ /// The step the accumulated gradients ask for.
558
+ fn apply(ruby: &Ruby, rb_self: &Self) -> Result<f32, Error> {
559
+ rb_self.with_engine(ruby, |engine| engine.apply())
560
+ }
561
+
562
+ /// How many parts are waiting for a step.
563
+ fn accumulated(ruby: &Ruby, rb_self: &Self) -> Result<usize, Error> {
564
+ rb_self.read(ruby, |engine| engine.accumulated())
565
+ }
566
+
567
+ /// Throws away what is waiting, and says how many parts went.
568
+ fn discard(ruby: &Ruby, rb_self: &Self) -> Result<usize, Error> {
569
+ rb_self.with_engine(ruby, |engine| engine.discard())
570
+ }
571
+
572
+ /// The loss for one batch without taking a step: no gradients, no
573
+ /// randomness, nothing moved. What a validation set is read with.
574
+ fn evaluate(ruby: &Ruby, rb_self: &Self, batch: RHash) -> Result<f32, Error> {
575
+ let batch = read_batch(ruby, batch)?;
576
+ rb_self.with_engine(ruby, |engine| engine.evaluate(&batch))
577
+ }
578
+
579
+ /// Named model outputs for one batch: [name, dtype, shape, bytes]
580
+ /// each. The forward an evaluation runs, stopping before the
581
+ /// objective, with nothing about the run moved.
582
+ fn forward(ruby: &Ruby, rb_self: &Self, batch: RHash, of: Vec<String>) -> Result<RArray, Error> {
583
+ let batch = read_batch(ruby, batch)?;
584
+ let produced = rb_self.with_engine(ruby, |engine| engine.forward(&batch, &of))?;
585
+ tensors_to_ruby(ruby, produced)
586
+ }
587
+
588
+ /// Every model output a forward may ask for. Answered from what was
589
+ /// taken at open, like the other names.
590
+ fn output_names(ruby: &Ruby, rb_self: &Self) -> RArray {
591
+ ruby.ary_from_vec(rb_self.names.outputs.clone())
592
+ }
593
+
594
+ /// Writes the run's state and returns where it landed. `run` is the
595
+ /// caller's own record (epoch, batch position, sampler state) as JSON;
596
+ /// the engine writes it verbatim and never reads it.
597
+ fn save(
598
+ ruby: &Ruby,
599
+ rb_self: &Self,
600
+ dir: String,
601
+ run: String,
602
+ light: bool,
603
+ ) -> Result<String, Error> {
604
+ rb_self.with_engine(ruby, |engine| engine.save_as(&dir, &run, light))
605
+ }
606
+
607
+ /// Writes one model's parameters as an HF-compatible safetensors
608
+ /// file (`dtype`: "f32", "bf16" or "f16"). Returns [[old_path, new_path], ...] so the caller can write
609
+ /// metadata that names what was saved. `merge` is an adapter's scale
610
+ /// (`alpha / rank`) to fold it into the weights, or nil.
611
+ fn export_model(
612
+ ruby: &Ruby,
613
+ rb_self: &Self,
614
+ model: String,
615
+ dir: String,
616
+ merge: Option<f64>,
617
+ dtype: String,
618
+ ) -> Result<RArray, Error> {
619
+ let merge = merge.map(|scale| scale as f32);
620
+ let pairs = rb_self.with_engine(ruby, |engine| engine.export_model_as(&model, &dir, merge, &dtype))?;
621
+ Self::pairs(ruby, pairs)
622
+ }
623
+
624
+ /// Writes one model's adapter alone, as PEFT names it, to
625
+ /// `adapter_model.safetensors`. Returns the same pairs.
626
+ fn export_adapter(ruby: &Ruby, rb_self: &Self, model: String, dir: String) -> Result<RArray, Error> {
627
+ let pairs = rb_self.with_engine(ruby, |engine| engine.export_adapter(&model, &dir))?;
628
+ Self::pairs(ruby, pairs)
629
+ }
630
+
631
+ fn pairs(ruby: &Ruby, pairs: Vec<(String, String)>) -> Result<RArray, Error> {
632
+ let out = ruby.ary_new_capa(pairs.len());
633
+ for (old, new) in pairs {
634
+ out.push((old, new))?;
635
+ }
636
+ Ok(out)
637
+ }
638
+
639
+ /// Restores state written by `save`, refusing what does not belong.
640
+ /// Returns the caller's record as JSON.
641
+ fn restore(ruby: &Ruby, rb_self: &Self, dir: String) -> Result<String, Error> {
642
+ rb_self.with_engine(ruby, |engine| engine.restore(&dir))
643
+ }
644
+
645
+ /// Releases the engine and its device memory. Idempotent, and the
646
+ /// session refuses everything afterwards rather than pretending.
647
+ ///
648
+ /// The freeing itself is the engine's: it takes its own gate, and in a
649
+ /// forked child it leaks rather than talking to a device that did not
650
+ /// come along. What is decided here is only that `close` runs from
651
+ /// `ensure`, where raising would replace the exception being handled,
652
+ /// so a refusal comes back as `false` rather than as an error.
653
+ fn close(ruby: &Ruby, rb_self: &Self) -> Result<bool, Error> {
654
+ // A running session is not closed out from under its own step: the
655
+ // caller closes it at a step boundary (the spec, section 8), and
656
+ // the slot answers "busy" for one that is.
657
+ let Some(mut engine) = rb_self
658
+ .take_to_close()
659
+ .map_err(|refusal| refusal.into_error(ruby))?
660
+ else {
661
+ return Ok(false);
662
+ };
663
+ match gvl::released(move || engine.close(), OnRefusal::PressOn)? {
664
+ // A forked child is told nothing: it is leaving, and its
665
+ // `ensure` should not be made to raise.
666
+ Outcome::Done(closed) => Ok(closed.unwrap_or(false)),
667
+ Outcome::Panicked(what) => Err(poisoned(ruby, &what)),
668
+ Outcome::Interrupted => unreachable!("released() falls back rather than refusing"),
669
+ }
670
+ }
671
+
672
+ fn closed(&self) -> bool {
673
+ match self.slot.try_lock() {
674
+ Ok(guard) => matches!(*guard, Slot::Closed),
675
+ // In use, therefore not closed.
676
+ Err(_) => false,
677
+ }
678
+ }
679
+
680
+ fn poisoned(&self) -> bool {
681
+ match self.slot.try_lock() {
682
+ Ok(guard) => matches!(*guard, Slot::Poisoned(_)),
683
+ Err(_) => false,
684
+ }
685
+ }
686
+
687
+ fn step(&self) -> usize {
688
+ self.watch().step
689
+ }
690
+
691
+ fn loss(&self) -> f32 {
692
+ self.watch().loss
693
+ }
694
+
695
+ fn lr(&self) -> f32 {
696
+ self.watch().lr
697
+ }
698
+
699
+ fn set_lr(ruby: &Ruby, rb_self: &Self, lr: f32) -> Result<f32, Error> {
700
+ rb_self.with_engine(ruby, |engine| {
701
+ engine.set_lr(lr)?;
702
+ Ok(lr)
703
+ })
704
+ }
705
+
706
+ /// The last step's gradient norm, before clipping.
707
+ fn grad_norm(&self) -> f32 {
708
+ self.watch().grad_norm
709
+ }
710
+
711
+ /// The cap in force, or nil.
712
+ fn clip(&self) -> Option<f32> {
713
+ self.watch().clip
714
+ }
715
+
716
+ fn set_clip(
717
+ ruby: &Ruby,
718
+ rb_self: &Self,
719
+ clip: Option<f32>,
720
+ ) -> Result<Option<f32>, Error> {
721
+ rb_self.with_engine(ruby, |engine| {
722
+ engine.set_clip(clip)?;
723
+ Ok(clip)
724
+ })
725
+ }
726
+
727
+ /// The L2 norm of every parameter. A reduction over the whole model, so
728
+ /// it is asked for rather than published with the step's numbers.
729
+ fn param_norm(ruby: &Ruby, rb_self: &Self) -> Result<f32, Error> {
730
+ rb_self.read(ruby, |engine| engine.param_norm())
731
+ }
732
+
733
+ fn seed(&self) -> u64 {
734
+ self.watch().seed
735
+ }
736
+
737
+ fn set_seed(ruby: &Ruby, rb_self: &Self, seed: u64) -> Result<u64, Error> {
738
+ rb_self.with_engine(ruby, |engine| {
739
+ engine.set_seed(seed)?;
740
+ Ok(seed)
741
+ })
742
+ }
743
+
744
+ /// Freezes or unfreezes what matches `pattern`; returns what moved.
745
+ fn set_frozen(
746
+ ruby: &Ruby,
747
+ rb_self: &Self,
748
+ pattern: String,
749
+ frozen: bool,
750
+ ) -> Result<RArray, Error> {
751
+ let moved = rb_self.with_engine(ruby, |engine| {
752
+ engine.set_frozen(&pattern, frozen)
753
+ })?;
754
+ Ok(ruby.ary_from_vec(moved))
755
+ }
756
+
757
+ fn trainable(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
758
+ let paths = rb_self.read(ruby, |engine| engine.trainable())?;
759
+ Ok(ruby.ary_from_vec(paths))
760
+ }
761
+
762
+ /// Writes one parameter from a copy: [dtype, shape, packed].
763
+ fn put(ruby: &Ruby, rb_self: &Self, path: String, tensor: RArray) -> Result<(), Error> {
764
+ let tensor = read_tensor(ruby, &path, tensor)?;
765
+ rb_self.with_engine(ruby, |engine| engine.put(&path, &tensor))
766
+ }
767
+
768
+ /// Watches a named value. Read-only, and in force from the next step.
769
+ fn tap(ruby: &Ruby, rb_self: &Self, name: String, stat: String) -> Result<(), Error> {
770
+ rb_self.with_engine(ruby, |engine| engine.tap(&name, &stat))
771
+ }
772
+
773
+ fn untap(ruby: &Ruby, rb_self: &Self, name: String) -> Result<bool, Error> {
774
+ rb_self.with_engine(ruby, |engine| engine.untap(&name))
775
+ }
776
+
777
+ fn taps(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
778
+ let names = rb_self.read(ruby, |engine| engine.taps())?;
779
+ Ok(ruby.ary_from_vec(names))
780
+ }
781
+
782
+ /// Every name a tap may ask for. Answered from what was taken at
783
+ /// open, so a watcher can ask while a step is in flight.
784
+ fn node_names(ruby: &Ruby, rb_self: &Self) -> RArray {
785
+ ruby.ary_from_vec(rb_self.names.nodes.clone())
786
+ }
787
+
788
+ /// What the last step's taps saw: [name, dtype, shape, bytes] each.
789
+ fn tapped(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
790
+ let seen = rb_self.with_engine(ruby, |engine| engine.tapped())?;
791
+ tensors_to_ruby(ruby, seen)
792
+ }
793
+
794
+ fn parameter_paths(ruby: &Ruby, rb_self: &Self) -> RArray {
795
+ ruby.ary_from_vec(rb_self.names.parameters.clone())
796
+ }
797
+
798
+ fn input_names(ruby: &Ruby, rb_self: &Self) -> RArray {
799
+ ruby.ary_from_vec(rb_self.names.inputs.clone())
800
+ }
801
+
802
+ fn fetch(ruby: &Ruby, rb_self: &Self, path: String) -> Result<(String, RArray, RString), Error> {
803
+ let tensor = rb_self.with_engine(ruby, |engine| engine.fetch(&path))?;
804
+ tensor_to_ruby(ruby, tensor)
805
+ }
806
+
807
+ /// Gradients with respect to named batch fields: [name, dtype, shape,
808
+ /// bytes] each. The parameters do not move.
809
+ fn field_gradients(
810
+ ruby: &Ruby,
811
+ rb_self: &Self,
812
+ batch: RHash,
813
+ of: Vec<String>,
814
+ ) -> Result<RArray, Error> {
815
+ let batch = read_batch(ruby, batch)?;
816
+ let grads = rb_self.with_engine(ruby, |engine| engine.field_gradients(&batch, &of))?;
817
+ tensors_to_ruby(ruby, grads)
818
+ }
819
+
820
+ fn gradients(ruby: &Ruby, rb_self: &Self, batch: RHash) -> Result<RArray, Error> {
821
+ let batch = read_batch(ruby, batch)?;
822
+ let grads = rb_self.with_engine(ruby, |engine| engine.gradients(&batch))?;
823
+ tensors_to_ruby(ruby, grads)
824
+ }
825
+ }
826
+
827
+ /// Reads {name => [dtype, shape, packed]} into the engine's batch. The
828
+ /// bytes are copied out of the Ruby string here, while the GVL is still
829
+ /// held; nothing borrowed from Ruby survives into the computation.
830
+ ///
831
+ /// The dtype travels because a graph may declare an i32 input, which is
832
+ /// what an embedding reads (docs/plan.md section 5A.2).
833
+ fn read_batch(ruby: &Ruby, batch: RHash) -> Result<Batch, Error> {
834
+ let mut read = Batch::new();
835
+ batch.foreach(|name: String, triple: RArray| {
836
+ let tensor = read_tensor(ruby, &name, triple)?;
837
+ read.insert(name, tensor);
838
+ Ok(magnus::r_hash::ForEach::Continue)
839
+ })?;
840
+ Ok(read)
841
+ }
842
+
843
+ /// One [dtype, shape, packed] as the engine's tensor, `name` being what to
844
+ /// call it if it is wrong.
845
+ ///
846
+ /// Separate from [`read_batch`] because a batch is not the only thing made
847
+ /// of these: `put` writes one parameter, and reading it should not mean
848
+ /// building a Ruby Hash to hand to a reader of batches.
849
+ fn read_tensor(ruby: &Ruby, name: &str, triple: RArray) -> Result<Tensor, Error> {
850
+ let bad = |what: String| Error::new(ruby.exception_arg_error(), what);
851
+ let dtype: String = triple
852
+ .entry::<String>(0)
853
+ .map_err(|e| bad(format!("input {name:?}: bad dtype ({e})")))?;
854
+ let shape: Vec<i32> = triple
855
+ .entry::<Vec<i32>>(1)
856
+ .map_err(|e| bad(format!("input {name:?}: bad shape ({e})")))?;
857
+ let data: RString = triple
858
+ .entry::<RString>(2)
859
+ .map_err(|e| bad(format!("input {name:?}: data must be a packed String ({e})")))?;
860
+ // Safety: the bytes are read while the GVL is held and copied before it
861
+ // is released. Borrowing them across that would be unsound rather than
862
+ // merely fast: another thread can trigger a compacting GC, and Ruby is
863
+ // free to move the string's buffer.
864
+ let bytes = unsafe { data.as_slice() };
865
+ Tensor::from_bytes(&dtype, shape, bytes, name).map_err(|e| bad(format!("{e:#}")))
866
+ }
867
+
868
+ /// A tensor on its way out: dtype, shape, and the bytes.
869
+ ///
870
+ /// The same three the boundary carries inward, and bytes rather than
871
+ /// numbers for the same reason. The Ruby side wraps them in a
872
+ /// `Torobi::TensorData`, and turning them into numbers is `to_a`, where a
873
+ /// caller can see the cost.
874
+ fn tensor_to_ruby(ruby: &Ruby, tensor: Tensor) -> Result<(String, RArray, RString), Error> {
875
+ let shape = ruby.ary_from_vec(tensor.shape.clone());
876
+ let (dtype, bytes) = tensor.as_bytes().map_err(|e| to_error(ruby, e))?;
877
+ Ok((dtype.to_string(), shape, ruby.str_from_slice(bytes)))
878
+ }
879
+
880
+ /// Named tensors on their way out: [name, dtype, shape, bytes] each.
881
+ ///
882
+ /// Three things leave this way (what the taps saw, gradients by parameter,
883
+ /// gradients by field), and they leave the same way on purpose: a caller
884
+ /// reads all three into `Torobi::TensorData` with one piece of code.
885
+ fn tensors_to_ruby(ruby: &Ruby, tensors: Vec<(String, Tensor)>) -> Result<RArray, Error> {
886
+ let out = ruby.ary_new_capa(tensors.len());
887
+ for (name, tensor) in tensors {
888
+ let (dtype, shape, bytes) = tensor_to_ruby(ruby, tensor)?;
889
+ out.push((name, dtype, shape, bytes))?;
890
+ }
891
+ Ok(out)
892
+ }
893
+
894
+ /// Runs one of the engine's process-global calls with the GVL released.
895
+ /// The engine serializes them against every running session, because they
896
+ /// reach the allocator those sessions share.
897
+ fn global<R>(ruby: &Ruby, work: impl FnOnce() -> Result<R, RuntimeError>) -> Result<R, Error> {
898
+ match gvl::released(work, OnRefusal::AskRuby)? {
899
+ Outcome::Done(result) => result.map_err(|e| from_engine(ruby, e)),
900
+ Outcome::Panicked(what) => Err(poisoned(ruby, &what)),
901
+ Outcome::Interrupted => unreachable!("released() falls back rather than refusing"),
902
+ }
903
+ }
904
+
905
+ fn memory(ruby: &Ruby) -> Result<Value, Error> {
906
+ // The reading is MLX's and goes through the gate; turning it into a
907
+ // Ruby Hash is not, and happens after.
908
+ let report = global(ruby, torobi_engine::memory::Memory::report)?;
909
+ plainly(ruby, || json_to_ruby(ruby, report))
910
+ }
911
+
912
+ /// Frees what the allocator holds but is not using. Returns [before, after].
913
+ fn clear_cache(ruby: &Ruby) -> Result<(usize, usize), Error> {
914
+ global(ruby, torobi_engine::memory::Memory::clear_cache)
915
+ }
916
+
917
+ /// Caps what this process may allocate on the device, in bytes; 0 lifts the
918
+ /// cap. Returns the cap now in force.
919
+ fn set_memory_limit(ruby: &Ruby, bytes: usize) -> Result<usize, Error> {
920
+ global(ruby, || torobi_engine::memory::Memory::set_limit(bytes))
921
+ }
922
+
923
+ fn reset_peak_memory(ruby: &Ruby) -> Result<(), Error> {
924
+ global(ruby, torobi_engine::memory::Memory::reset_peak)
925
+ }
926
+
927
+ fn json_to_ruby(ruby: &Ruby, value: serde_json::Value) -> Result<Value, Error> {
928
+ ruby.class_object()
929
+ .const_get::<_, magnus::RModule>("JSON")
930
+ .and_then(|json| json.funcall("parse", (value.to_string(),)))
931
+ }
932
+
933
+ /// Runs work that touches no MLX, turning a panic into an error a caller
934
+ /// can rescue.
935
+ ///
936
+ /// magnus already catches a panic on its way out of a `method!`, so the
937
+ /// process does not abort. What it makes of it is a Ruby `fatal`, which no
938
+ /// `rescue` holds and which ends the run anyway. Catching first is what
939
+ /// turns that into a `Torobi::SessionPoisoned` a caller can see, decide
940
+ /// about, and log. burn-rb's `boundary` is the same move for the same
941
+ /// reason.
942
+ ///
943
+ /// See the module comment for which door each entry point uses.
944
+ fn plainly<T>(ruby: &Ruby, work: impl FnOnce() -> Result<T, Error>) -> Result<T, Error> {
945
+ match catch_unwind(AssertUnwindSafe(work)) {
946
+ Ok(result) => result,
947
+ Err(panic) => Err(poisoned(ruby, &gvl::describe(panic))),
948
+ }
949
+ }
950
+
951
+ /// What the engine was built from, as a Ruby Hash. A journal records it,
952
+ /// so a run can say which build produced it.
953
+ fn build_info(ruby: &Ruby) -> Result<Value, Error> {
954
+ plainly(ruby, || json_to_ruby(ruby, torobi_engine::build_info()))
955
+ }
956
+
957
+ /// Tells MLX where `mlx.metallib` is, before it looks. Called before any
958
+ /// session opens; a no-op off Apple, where there is no metallib.
959
+ fn set_metallib_path(ruby: &Ruby, path: String) -> Result<(), Error> {
960
+ plainly(ruby, || {
961
+ torobi_engine::set_metallib_path(std::path::Path::new(&path))
962
+ .map_err(|error| from_engine(ruby, error))
963
+ })
964
+ }
965
+
966
+ /// What a checkpoint says about itself, without opening it into a session.
967
+ /// For a caller deciding which one to resume from, and for anyone asking
968
+ /// what a directory on disk actually holds.
969
+ fn checkpoint_manifest(ruby: &Ruby, dir: String) -> Result<Value, Error> {
970
+ plainly(ruby, || {
971
+ let json =
972
+ torobi_engine::checkpoint::read_manifest_json(&dir).map_err(|e| to_error(ruby, e))?;
973
+ ruby.class_object()
974
+ .const_get::<_, magnus::RModule>("JSON")
975
+ .and_then(|module| module.funcall("parse", (json,)))
976
+ })
977
+ }
978
+
979
+ #[magnus::init]
980
+ fn init(ruby: &Ruby) -> Result<(), Error> {
981
+ // Recorded here, before anything can fork: everything native checks it.
982
+ // The engine records the process it belongs to, so a fork after this
983
+ // is refused even before anything has touched MLX.
984
+ torobi_engine::initialize();
985
+ let torobi = ruby.define_module("Torobi")?;
986
+ let native = torobi.define_module("Native")?;
987
+ native.define_singleton_method("build_info", function!(build_info, 0))?;
988
+ native.define_singleton_method("set_metallib_path", function!(set_metallib_path, 1))?;
989
+ native.define_singleton_method("checkpoint_manifest", function!(checkpoint_manifest, 1))?;
990
+ native.define_singleton_method("memory", function!(memory, 0))?;
991
+ native.define_singleton_method("clear_cache", function!(clear_cache, 0))?;
992
+ native.define_singleton_method("memory_limit=", function!(set_memory_limit, 1))?;
993
+ native.define_singleton_method("reset_peak_memory", function!(reset_peak_memory, 0))?;
994
+ let class = native.define_class("Session", ruby.class_object())?;
995
+ class.define_singleton_method("open", function!(Session::open, 4))?;
996
+ class.define_singleton_method("open_from_file", function!(Session::open_from_file, 4))?;
997
+ class.define_singleton_method("open_pretrained", function!(Session::open_pretrained, 5))?;
998
+ class.define_method("run_step", method!(Session::run_step, 1))?;
999
+ class.define_method("accumulate", method!(Session::accumulate, 1))?;
1000
+ class.define_method("apply", method!(Session::apply, 0))?;
1001
+ class.define_method("accumulated", method!(Session::accumulated, 0))?;
1002
+ class.define_method("discard", method!(Session::discard, 0))?;
1003
+ class.define_method("evaluate", method!(Session::evaluate, 1))?;
1004
+ class.define_method("save", method!(Session::save, 3))?;
1005
+ class.define_method("export_model", method!(Session::export_model, 4))?;
1006
+ class.define_method("export_adapter", method!(Session::export_adapter, 2))?;
1007
+ class.define_method("restore", method!(Session::restore, 1))?;
1008
+ class.define_method("close", method!(Session::close, 0))?;
1009
+ class.define_method("closed?", method!(Session::closed, 0))?;
1010
+ class.define_method("poisoned?", method!(Session::poisoned, 0))?;
1011
+ class.define_method("step", method!(Session::step, 0))?;
1012
+ class.define_method("loss", method!(Session::loss, 0))?;
1013
+ class.define_method("lr", method!(Session::lr, 0))?;
1014
+ class.define_method("lr=", method!(Session::set_lr, 1))?;
1015
+ class.define_method("grad_norm", method!(Session::grad_norm, 0))?;
1016
+ class.define_method("clip", method!(Session::clip, 0))?;
1017
+ class.define_method("clip=", method!(Session::set_clip, 1))?;
1018
+ class.define_method("param_norm", method!(Session::param_norm, 0))?;
1019
+ class.define_method("seed", method!(Session::seed, 0))?;
1020
+ class.define_method("seed=", method!(Session::set_seed, 1))?;
1021
+ class.define_method("set_frozen", method!(Session::set_frozen, 2))?;
1022
+ class.define_method("trainable", method!(Session::trainable, 0))?;
1023
+ class.define_method("put", method!(Session::put, 2))?;
1024
+ class.define_method("tap_node", method!(Session::tap, 2))?;
1025
+ class.define_method("untap", method!(Session::untap, 1))?;
1026
+ class.define_method("taps", method!(Session::taps, 0))?;
1027
+ class.define_method("forward", method!(Session::forward, 2))?;
1028
+ class.define_method("output_names", method!(Session::output_names, 0))?;
1029
+ class.define_method("node_names", method!(Session::node_names, 0))?;
1030
+ class.define_method("tapped", method!(Session::tapped, 0))?;
1031
+ class.define_method("parameter_paths", method!(Session::parameter_paths, 0))?;
1032
+ class.define_method("input_names", method!(Session::input_names, 0))?;
1033
+ class.define_method("fetch", method!(Session::fetch, 1))?;
1034
+ class.define_method("gradients", method!(Session::gradients, 1))?;
1035
+ class.define_method("field_gradients", method!(Session::field_gradients, 2))?;
1036
+ Ok(())
1037
+ }