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,331 @@
1
+ //! What crosses the boundary, and how.
2
+ //!
3
+ //! One shape of value travels between Ruby and the engine, in either
4
+ //! direction, and always as a copy: a dtype, a shape, and the numbers.
5
+ //! Nothing that lives on the device escapes this crate.
6
+
7
+ use std::collections::BTreeMap;
8
+
9
+ use anyhow::{Context, Result};
10
+ use crate::mlxc::transforms::eval;
11
+ use crate::mlxc::Array;
12
+ /// MLX's dtypes, which a [`Tensor`] is labelled with. Re-exported because
13
+ /// the binding that defines it is the engine's own and not public.
14
+ pub use crate::mlxc::Dtype;
15
+
16
+ /// A tensor as it crosses the boundary: a dtype, a shape, and the values.
17
+ /// Always a copy, never a handle.
18
+ ///
19
+ /// The dtype travels because a graph can declare an i32 input - which is
20
+ /// what an embedding reads - and a boundary that assumed f32 could not
21
+ /// carry one (docs/plan.md section 5A.2). It travels *as* the payload's
22
+ /// kind ([`Tensor::dtype`]) rather than beside it, so a label and the
23
+ /// numbers cannot disagree.
24
+ ///
25
+ /// `Clone` copies the numbers; nothing here is a handle.
26
+ #[derive(Clone)]
27
+ pub struct Tensor {
28
+ pub shape: Vec<i32>,
29
+ pub values: Values,
30
+ }
31
+
32
+ /// The payload, in the only two forms the boundary carries.
33
+ #[derive(Clone)]
34
+ pub enum Values {
35
+ F32(Vec<f32>),
36
+ I32(Vec<i32>),
37
+ }
38
+
39
+ impl Values {
40
+ pub fn len(&self) -> usize {
41
+ match self {
42
+ Values::F32(v) => v.len(),
43
+ Values::I32(v) => v.len(),
44
+ }
45
+ }
46
+
47
+ pub fn is_empty(&self) -> bool {
48
+ self.len() == 0
49
+ }
50
+ }
51
+
52
+ /// A shape and a size, never the numbers: a batch tensor can hold a
53
+ /// million of them, and a panic message that printed them all would be
54
+ /// unreadable.
55
+ impl std::fmt::Debug for Tensor {
56
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57
+ write!(
58
+ f,
59
+ "Tensor({:?} {:?}, {} values)",
60
+ self.dtype(),
61
+ self.shape,
62
+ self.values.len()
63
+ )
64
+ }
65
+ }
66
+
67
+ impl Tensor {
68
+ /// What the payload is: f32 or i32, the two the boundary carries.
69
+ pub fn dtype(&self) -> Dtype {
70
+ match self.values {
71
+ Values::F32(_) => Dtype::Float32,
72
+ Values::I32(_) => Dtype::Int32,
73
+ }
74
+ }
75
+
76
+ pub fn to_array(&self) -> Result<Array> {
77
+ Ok(match &self.values {
78
+ Values::F32(data) => Array::from_slice(data, &self.shape)?,
79
+ Values::I32(data) => Array::from_slice(data, &self.shape)?,
80
+ })
81
+ }
82
+
83
+ /// From the bytes the boundary carries: native-endian, four to a value.
84
+ ///
85
+ /// Measurement chose this over JSON (docs/plan.md section 5A.2.1):
86
+ /// serializing a batch as JSON cost two thirds of a step at 512 rows,
87
+ /// while the call boundary itself was noise. The shape travels
88
+ /// separately, being a handful of integers and readable.
89
+ ///
90
+ /// `name` is only for saying which input was wrong.
91
+ pub fn from_bytes(dtype: &str, shape: Vec<i32>, bytes: &[u8], name: &str) -> Result<Self> {
92
+ anyhow::ensure!(
93
+ bytes.len() % 4 == 0,
94
+ "input {name:?}: {} bytes is not a whole number of 4-byte values",
95
+ bytes.len()
96
+ );
97
+ let words = bytes.chunks_exact(4).map(|b| [b[0], b[1], b[2], b[3]]);
98
+ let values = match dtype {
99
+ "f32" => Values::F32(words.map(f32::from_ne_bytes).collect()),
100
+ "i32" => Values::I32(words.map(i32::from_ne_bytes).collect()),
101
+ other => anyhow::bail!("input {name:?}: dtype {other:?} does not cross the boundary"),
102
+ };
103
+ Ok(Self { shape, values })
104
+ }
105
+
106
+ /// The same tensor as the boundary carries it: the dtype spelled the
107
+ /// way a graph names it, and the values as bytes.
108
+ ///
109
+ /// The inverse of [`Tensor::from_bytes`], and the reason a caller does
110
+ /// not get numbers: reading ruri-v3's embedding table as a Ruby Array
111
+ /// added 600 MB of resident memory where its bytes are 200 MB, and
112
+ /// most of what a caller does with a parameter is save it or compare
113
+ /// it rather than look at fifty million numbers.
114
+ ///
115
+ /// A view rather than a copy, since the caller's next act is to copy
116
+ /// it somewhere (into a Ruby String, say) and 200 MB is worth not
117
+ /// doing twice.
118
+ pub fn as_bytes(&self) -> Result<(&'static str, &[u8])> {
119
+ let spelling = dtype_spelling(self.dtype())
120
+ .with_context(|| format!("{:?} is not a dtype the boundary carries", self.dtype()))?;
121
+ // Safety: any f32 or i32 is a valid sequence of bytes, and u8
122
+ // needs no alignment beyond what the source already has. This is
123
+ // what bytemuck's cast_slice does, without the dependency.
124
+ let bytes = match &self.values {
125
+ Values::F32(values) => unsafe { as_byte_slice(values) },
126
+ Values::I32(values) => unsafe { as_byte_slice(values) },
127
+ };
128
+ Ok((spelling, bytes))
129
+ }
130
+ }
131
+
132
+ /// One step's inputs, by graph input name.
133
+ pub type Batch = BTreeMap<String, Tensor>;
134
+
135
+
136
+ /// The dtypes the IR speaks, and what MLX calls them.
137
+ ///
138
+ /// Deliberately few: what the target models need, not what MLX offers.
139
+ /// The list is the Ruby side's (lib/torobi/ir/dtype.rb), and the two must
140
+ /// agree, so it is written once here and read in both directions rather
141
+ /// than spelled out again wherever a name is needed.
142
+ ///
143
+ /// `u32` is the packed form of a quantized weight (docs/qlora.md) and
144
+ /// nothing else: a graph never computes in it, and the boundary never
145
+ /// carries it (`to_tensor` refuses it; `TrainState::fetch` reads the
146
+ /// numbers it stands for instead).
147
+ const VOCABULARY: [(&str, Dtype); 5] = [
148
+ ("f32", Dtype::Float32),
149
+ ("bf16", Dtype::Bfloat16),
150
+ ("i32", Dtype::Int32),
151
+ ("bool", Dtype::Bool),
152
+ ("u32", Dtype::Uint32),
153
+ ];
154
+
155
+ /// The dtype a graph means by this name.
156
+ pub fn dtype_named(name: &str) -> Option<Dtype> {
157
+ VOCABULARY
158
+ .iter()
159
+ .find(|(spelled, _)| *spelled == name)
160
+ .map(|(_, dtype)| *dtype)
161
+ }
162
+
163
+ /// What to call this dtype, in the graph's vocabulary.
164
+ ///
165
+ /// `None` for anything the IR cannot name. A checkpoint that recorded such
166
+ /// a dtype would be one no graph could ask for, so the answer is to refuse
167
+ /// rather than invent a spelling.
168
+ pub fn dtype_spelling(dtype: Dtype) -> Option<&'static str> {
169
+ VOCABULARY
170
+ .iter()
171
+ .find(|(_, known)| *known == dtype)
172
+ .map(|(spelled, _)| *spelled)
173
+ }
174
+
175
+ /// A device array as a copy on the host. Contiguous first: a gradient can
176
+ /// come back strided (through a transpose, say), and reading it out needs
177
+ /// contiguous memory.
178
+ pub fn to_tensor(array: &Array) -> Result<Tensor> {
179
+ let array = array.contiguous()?;
180
+ eval(std::iter::once(&array))?;
181
+ // The boundary carries two payloads, and the label says which one
182
+ // this is rather than what the array was. A bf16 parameter read from
183
+ // here is f32 numbers: they are the numbers it holds, Ruby has no
184
+ // bf16 to put them in, and a label that disagreed with the bytes
185
+ // would be a trap for whoever unpacked them.
186
+ // A u32 array is read as f32 too: the RNG key is one, and its two
187
+ // words fit. A packed quantized weight is also u32, and its words as
188
+ // f32 are not what anyone wants; `TrainState::fetch` reads those as
189
+ // the numbers they stand for before they get here.
190
+ let values = match array.dtype() {
191
+ Dtype::Int32 => Values::I32(array.as_slice::<i32>()?.to_vec()),
192
+ _ => Values::F32(array.as_dtype(Dtype::Float32)?.as_slice::<f32>()?.to_vec()),
193
+ };
194
+ Ok(Tensor {
195
+ shape: array.shape().to_vec(),
196
+ values,
197
+ })
198
+ }
199
+
200
+ /// Reads a slice of 4-byte values as the bytes they are.
201
+ ///
202
+ /// # Safety
203
+ ///
204
+ /// `T` must have no padding and no invalid bit patterns (f32 and i32,
205
+ /// here), so that every byte of it is initialized and readable.
206
+ unsafe fn as_byte_slice<T>(values: &[T]) -> &[u8] {
207
+ unsafe { std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values)) }
208
+ }
209
+
210
+ #[cfg(test)]
211
+ mod tests {
212
+ use super::*;
213
+
214
+ fn bytes_of<T: Copy, const N: usize>(values: [T; N], to_ne: fn(T) -> [u8; 4]) -> Vec<u8> {
215
+ values.iter().flat_map(|v| to_ne(*v)).collect()
216
+ }
217
+
218
+ #[test]
219
+ fn reads_f32_in_native_order() {
220
+ let bytes = bytes_of([1.5f32, -2.0], f32::to_ne_bytes);
221
+ let t = Tensor::from_bytes("f32", vec![2], &bytes, "x").unwrap();
222
+ assert_eq!(t.dtype(), Dtype::Float32);
223
+ assert_eq!(t.shape, vec![2]);
224
+ match t.values {
225
+ Values::F32(v) => assert_eq!(v, vec![1.5, -2.0]),
226
+ _ => panic!("f32 came back as something else"),
227
+ }
228
+ }
229
+
230
+ #[test]
231
+ fn reads_i32_because_an_embedding_reads_ids() {
232
+ let bytes = bytes_of([7i32, 0], i32::to_ne_bytes);
233
+ let t = Tensor::from_bytes("i32", vec![2], &bytes, "ids").unwrap();
234
+ assert_eq!(t.dtype(), Dtype::Int32);
235
+ match t.values {
236
+ Values::I32(v) => assert_eq!(v, vec![7, 0]),
237
+ _ => panic!("i32 came back as something else"),
238
+ }
239
+ }
240
+
241
+ #[test]
242
+ fn refuses_bytes_that_do_not_divide_and_says_which_input() {
243
+ let e = Tensor::from_bytes("f32", vec![1], &[0, 1, 2], "x").unwrap_err();
244
+ let message = e.to_string();
245
+ assert!(message.contains("\"x\""), "{message}");
246
+ assert!(message.contains("3 bytes"), "{message}");
247
+ }
248
+
249
+ #[test]
250
+ fn refuses_a_dtype_the_boundary_does_not_carry() {
251
+ let e = Tensor::from_bytes("f64", vec![1], &[0; 8], "x").unwrap_err();
252
+ assert!(e.to_string().contains("f64"), "{e}");
253
+ }
254
+
255
+ #[test]
256
+ fn the_bytes_that_went_in_are_the_bytes_that_come_out() {
257
+ for (dtype, bytes) in [
258
+ ("f32", bytes_of([1.5f32, -2.0, 0.0], f32::to_ne_bytes)),
259
+ ("i32", bytes_of([7i32, 0, -1], i32::to_ne_bytes)),
260
+ ] {
261
+ let t = Tensor::from_bytes(dtype, vec![3], &bytes, "x").unwrap();
262
+ assert_eq!(t.as_bytes().unwrap(), (dtype, bytes.as_slice()));
263
+ }
264
+ }
265
+
266
+ #[test]
267
+ fn a_strided_array_comes_back_in_reading_order() {
268
+ // A gradient can arrive through a transpose. Reading it out needs
269
+ // contiguous memory, so to_tensor must not hand back the strides.
270
+ let a = Array::from_slice(&[1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]).unwrap();
271
+ let t = to_tensor(&a.transpose_axes(&[1, 0]).unwrap()).unwrap();
272
+ assert_eq!(t.shape, vec![3, 2]);
273
+ match t.values {
274
+ Values::F32(v) => assert_eq!(v, vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]),
275
+ _ => panic!("f32 came back as something else"),
276
+ }
277
+ }
278
+
279
+ /// The boundary carries two payloads, and says which one it is
280
+ /// carrying rather than what the array was: a label that disagreed
281
+ /// with the bytes would be a trap for whoever unpacked them.
282
+ #[test]
283
+ fn the_boundary_carries_i32_or_f32_and_says_which() {
284
+ let ids = to_tensor(&Array::from_slice(&[3i32, 4], &[2]).unwrap()).unwrap();
285
+ assert_eq!(ids.dtype(), Dtype::Int32);
286
+ assert!(matches!(ids.values, Values::I32(_)));
287
+
288
+ for other in [
289
+ Array::from_slice(&[true, false], &[2]).unwrap(),
290
+ Array::from_slice(&[1.0f32, 0.0], &[2]).unwrap()
291
+ .as_dtype(Dtype::Bfloat16)
292
+ .unwrap(),
293
+ ] {
294
+ let crossed = to_tensor(&other).unwrap();
295
+ assert_eq!(crossed.dtype(), Dtype::Float32);
296
+ match crossed.values {
297
+ Values::F32(v) => assert_eq!(v, vec![1.0, 0.0]),
298
+ _ => panic!("it should convert, not be reinterpreted"),
299
+ }
300
+ }
301
+ }
302
+
303
+ #[test]
304
+ fn to_array_round_trips_both_payloads() {
305
+ for t in [
306
+ Tensor {
307
+ shape: vec![2, 1],
308
+ values: Values::F32(vec![1.0, 2.0]),
309
+ },
310
+ Tensor {
311
+ shape: vec![2, 1],
312
+ values: Values::I32(vec![1, 2]),
313
+ },
314
+ ] {
315
+ let back = to_tensor(&t.to_array().unwrap()).unwrap();
316
+ assert_eq!(back.dtype(), t.dtype());
317
+ assert_eq!(back.shape, t.shape);
318
+ }
319
+ }
320
+
321
+ #[test]
322
+ fn only_the_declared_dtypes_have_names() {
323
+ assert_eq!(dtype_named("f32"), Some(Dtype::Float32));
324
+ assert_eq!(dtype_named("bf16"), Some(Dtype::Bfloat16));
325
+ assert_eq!(dtype_named("i32"), Some(Dtype::Int32));
326
+ assert_eq!(dtype_named("bool"), Some(Dtype::Bool));
327
+ assert_eq!(dtype_named("u32"), Some(Dtype::Uint32));
328
+ assert_eq!(dtype_spelling(Dtype::Uint32), Some("u32"));
329
+ assert_eq!(dtype_named("f64"), None);
330
+ }
331
+ }
@@ -0,0 +1,21 @@
1
+ [package]
2
+ name = "torobi"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ publish = false
6
+
7
+ [lib]
8
+ name = "torobi"
9
+ crate-type = ["cdylib"]
10
+
11
+ [dependencies]
12
+ torobi-engine = { path = "../../engine" }
13
+ # The narrow waist: magnus for the Ruby objects, rb-sys for the one thing
14
+ # magnus does not cover (releasing the GVL around a long computation).
15
+ # The `rb-sys` feature brings `magnus::rb_sys::protect`, which is how a raw
16
+ # Ruby C call that raises by longjmp is turned into a value this crate can
17
+ # return from (see the interrupt check in `in_mlx`).
18
+ magnus = { version = "0.8", features = ["rb-sys"] }
19
+ rb-sys = "0.9"
20
+ anyhow = "1"
21
+ serde_json = "1"
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "mkmf"
4
+ require "rb_sys/mkmf"
5
+ require_relative "../../lib/torobi/mlx_prebuilt"
6
+
7
+ # Before cargo runs: fetch the pre-built MLX and check it, so the engine's
8
+ # build.rs has a prefix to bind and link (lib/torobi/mlx_prebuilt.rb).
9
+ prefix =
10
+ begin
11
+ MlxPrebuilt.ensure!
12
+ rescue MlxPrebuilt::Refused => e
13
+ abort "torobi: #{e.message}"
14
+ end
15
+
16
+ create_rust_makefile("torobi/torobi")
17
+
18
+ # MLX finds its Metal kernels through dladdr: mlx.metallib must sit beside
19
+ # the library that holds the MLX symbols, which is this extension. It is
20
+ # installed from the prefix, where the archive put it. Without it MLX ends
21
+ # the process rather than raising, which is why Torobi::Preflight refuses
22
+ # first (docs/plan.md section 4.1).
23
+ File.open("Makefile", "a") do |makefile|
24
+ # Exported rather than set in this process: make spawns cargo, and this
25
+ # process is gone by then.
26
+ # What engine/build.rs reads: the headers it generates bindings from and
27
+ # the archives it links.
28
+ makefile.puts("\nexport TOROBI_MLX_PREFIX := #{prefix}")
29
+
30
+ # The rest is Metal's: CUDA compiles its kernels at run time and ships
31
+ # no metallib to install beside the bundle.
32
+ next unless MlxPrebuilt.metal?
33
+
34
+ makefile.puts(<<~MAKE)
35
+
36
+ install-so: install-metallib
37
+ install-metallib: $(RUSTLIB)
38
+ \t$(ECHO) installing mlx.metallib to $(RUBYARCHDIR)
39
+ \t$(Q) $(MAKEDIRS) $(RUBYARCHDIR)
40
+ \t$(Q) $(COPY) "#{MlxPrebuilt.metallib(prefix)}" $(RUBYARCHDIR)
41
+ MAKE
42
+ end
@@ -0,0 +1,182 @@
1
+ //! Releasing the GVL around the engine's long calls.
2
+ //!
3
+ //! Everything unsafe in this crate is here. `lib.rs` calls no Ruby C API
4
+ //! directly (notes/ENGINE_RUNTIME_BOUNDARY_PLAN.md section 7.1).
5
+ //!
6
+ //! This is the one piece of unsafe machinery in the binding, and it stays
7
+ //! small on purpose: the closure it runs must not touch the Ruby API, and
8
+ //! nothing else in this crate needs the GVL released.
9
+ //!
10
+ //! Two things make it more than a wrapper (notes/SESSION_CONCURRENCY_SPEC.md
11
+ //! section 5).
12
+ //!
13
+ //! A panic is caught and returned rather than resumed. magnus turns a panic
14
+ //! that escapes into a Ruby `fatal`, which no `rescue` catches and which
15
+ //! ends the process.
16
+ //!
17
+ //! And `rb_nogvl` with `RB_NOGVL_INTR_FAIL` is used rather than
18
+ //! `rb_thread_call_without_gvl`. The latter checks for pending interrupts
19
+ //! on the way out of the blocking region and raises there, which is a
20
+ //! longjmp through this frame: anything the caller still had to do (drop a
21
+ //! guard, record a step) would never happen. With the flag, the region
22
+ //! returns normally and Ruby delivers the interrupt at its next checkpoint,
23
+ //! by which time the caller has finished and the Ruby side has recorded the
24
+ //! step the engine actually took.
25
+
26
+ use std::any::Any;
27
+ use std::ffi::c_void;
28
+ use std::panic::{catch_unwind, AssertUnwindSafe};
29
+
30
+ /// What came back from a GVL-released call.
31
+ pub enum Outcome<R> {
32
+ Done(R),
33
+ /// The closure panicked. Its message, as far as it can be recovered.
34
+ Panicked(String),
35
+ /// An interrupt was already pending, so the closure never ran. Nothing
36
+ /// happened: no step was taken, and no state moved.
37
+ Interrupted,
38
+ }
39
+
40
+ /// What a refused entry into the blocking region is allowed to do.
41
+ pub enum OnRefusal {
42
+ /// Hand control back to Ruby, which raises whatever it was holding,
43
+ /// then try again. What ordinary work does: the caller asked for an
44
+ /// interrupt and should get it.
45
+ AskRuby,
46
+ /// Never raise. Run the work with the GVL held instead.
47
+ ///
48
+ /// `close` needs this. It runs from `ensure`, where raising would
49
+ /// replace the exception being handled.
50
+ PressOn,
51
+ }
52
+
53
+ /// How many times a call retries after the blocking region refuses to
54
+ /// start. `RB_NOGVL_INTR_FAIL` refuses whenever Ruby's interrupt flag is
55
+ /// set, and that flag is also the scheduler's timer, so most refusals mean
56
+ /// nothing at all. `rb_thread_check_ints` clears a timer and raises a real
57
+ /// interrupt; a handful of rounds is more than enough, and the bound is
58
+ /// there so this can never spin.
59
+ const ENTRY_ATTEMPTS: u32 = 8;
60
+
61
+ /// Runs `work` with the GVL released, retrying an entry Ruby refused.
62
+ ///
63
+ /// `work` waits in an `Option` rather than being captured by value: the
64
+ /// blocking region can refuse to start, dropping the closure with whatever
65
+ /// it holds, and there would be nothing left to retry with.
66
+ ///
67
+ /// This function knows nothing about MLX. Serializing MLX and refusing a
68
+ /// forked child belong to the engine, which owns them; what belongs here
69
+ /// is the Ruby runtime's half (section 7.1 of the plan above).
70
+ pub fn released<W, R>(work: W, refusal: OnRefusal) -> Result<Outcome<R>, magnus::Error>
71
+ where
72
+ W: FnOnce() -> R,
73
+ {
74
+ let attempts = match refusal {
75
+ OnRefusal::AskRuby => ENTRY_ATTEMPTS,
76
+ OnRefusal::PressOn => 1,
77
+ };
78
+ let mut pending = Some(work);
79
+ for _ in 0..attempts {
80
+ let outcome = without_gvl(|| {
81
+ let work = pending.take().expect("the region is entered at most once");
82
+ work()
83
+ });
84
+ match outcome {
85
+ Outcome::Done(value) => return Ok(Outcome::Done(value)),
86
+ Outcome::Panicked(what) => return Ok(Outcome::Panicked(what)),
87
+ Outcome::Interrupted => {
88
+ if matches!(refusal, OnRefusal::AskRuby) {
89
+ check_ints()?;
90
+ // Nothing was raised, so the flag was the scheduler's
91
+ // timer, which that call has now cleared. Try again.
92
+ }
93
+ }
94
+ }
95
+ }
96
+
97
+ // Ruby's flag stayed set through every round. Run the work with the
98
+ // GVL held rather than refuse it: it stalls the other Ruby threads for
99
+ // one call, but nothing is lost and this terminates.
100
+ let work = pending.take().expect("no attempt entered the region");
101
+ match catch_unwind(AssertUnwindSafe(work)) {
102
+ Ok(value) => Ok(Outcome::Done(value)),
103
+ Err(panic) => Ok(Outcome::Panicked(describe(panic))),
104
+ }
105
+ }
106
+
107
+ /// Lets Ruby deliver whatever interrupt it is holding.
108
+ ///
109
+ /// Through `protect`, because `rb_thread_check_ints` raises by longjmp,
110
+ /// and a longjmp through this frame would skip every Rust destructor
111
+ /// between here and Ruby: the work, and the batch it borrows. `protect`
112
+ /// turns that into a value, so the return is an ordinary one and
113
+ /// everything is dropped on the way out.
114
+ fn check_ints() -> Result<(), magnus::Error> {
115
+ magnus::rb_sys::protect(|| {
116
+ unsafe { rb_sys::rb_thread_check_ints() };
117
+ rb_sys::special_consts::Qnil as rb_sys::VALUE
118
+ })?;
119
+ Ok(())
120
+ }
121
+
122
+ struct Payload<F, R> {
123
+ call: Option<F>,
124
+ outcome: Option<Result<R, Box<dyn Any + Send>>>,
125
+ }
126
+
127
+ unsafe extern "C" fn trampoline<F, R>(data: *mut c_void) -> *mut c_void
128
+ where
129
+ F: FnOnce() -> R,
130
+ {
131
+ let payload = &mut *(data as *mut Payload<F, R>);
132
+ let call = payload.call.take().expect("the closure runs exactly once");
133
+ payload.outcome = Some(catch_unwind(AssertUnwindSafe(call)));
134
+ std::ptr::null_mut()
135
+ }
136
+
137
+ /// Runs `call` with the GVL released, so other Ruby threads proceed.
138
+ ///
139
+ /// `call` must leave nothing for its caller to finish: whatever has to
140
+ /// happen for the session to stay consistent has to happen inside it.
141
+ /// Only reading a plain value out of the result is safe afterwards.
142
+ ///
143
+ /// # Safety contract (upheld by the callers in this crate, not by the type
144
+ /// system): `call` must not touch the Ruby VM in any way.
145
+ fn without_gvl<F, R>(call: F) -> Outcome<R>
146
+ where
147
+ F: FnOnce() -> R,
148
+ {
149
+ let mut payload = Payload {
150
+ call: Some(call),
151
+ outcome: None,
152
+ };
153
+ unsafe {
154
+ rb_sys::rb_nogvl(
155
+ Some(trampoline::<F, R>),
156
+ &mut payload as *mut Payload<F, R> as *mut c_void,
157
+ // No unblocking function: a step is not interruptible from
158
+ // outside. Ruby drives the loop one step at a time, so an
159
+ // interrupt lands between steps, which is the same semantics a
160
+ // UBF would buy here (the spec, section 7).
161
+ None,
162
+ std::ptr::null_mut(),
163
+ rb_sys::RB_NOGVL_INTR_FAIL as std::ffi::c_int,
164
+ );
165
+ }
166
+ match payload.outcome {
167
+ Some(Ok(value)) => Outcome::Done(value),
168
+ Some(Err(panic)) => Outcome::Panicked(describe(panic)),
169
+ // RB_NOGVL_INTR_FAIL: an interrupt was already pending, so the
170
+ // region was never entered.
171
+ None => Outcome::Interrupted,
172
+ }
173
+ }
174
+
175
+ /// What a panic said, as far as it can be recovered.
176
+ pub(crate) fn describe(panic: Box<dyn Any + Send>) -> String {
177
+ panic
178
+ .downcast_ref::<&str>()
179
+ .map(|s| (*s).to_string())
180
+ .or_else(|| panic.downcast_ref::<String>().cloned())
181
+ .unwrap_or_else(|| "a panic with no message".to_string())
182
+ }