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
data/engine/src/op.rs ADDED
@@ -0,0 +1,745 @@
1
+ //! The operation vocabulary, resolved once.
2
+ //!
3
+ //! A GraphConfig arrives as JSON: an op is a string, its attributes are a
4
+ //! `serde_json::Map`, and its inputs are strings like "node:7". None of
5
+ //! that changes while a run goes, so none of it should be read while one
6
+ //! does. [`Program::resolve`] turns a graph into values the interpreter can
7
+ //! match on, and does it when the plan opens.
8
+ //!
9
+ //! What that buys is not only speed. **A graph that cannot run fails when
10
+ //! it is opened, not on its first step**: a missing attribute, an
11
+ //! attribute of the wrong type, a reference to a node that does not exist
12
+ //! or has not been computed yet, an op given the wrong number of inputs.
13
+ //! Those used to surface from inside `value_and_grad`, as MLX exceptions,
14
+ //! at step one.
15
+
16
+
17
+ use anyhow::{Context, Result};
18
+ use serde_json::{Map, Value};
19
+
20
+ use crate::graph::{parse_ref, Graph, InputSpec, NodeSpec, Ref};
21
+ use crate::mlxc::quantized::{Mode, Quantization};
22
+ use crate::tensor::{dtype_named, Dtype};
23
+
24
+ /// The quantizations MLX has kernels for, as `lib/torobi/shape.rb` lists
25
+ /// them: the IR refuses anything else with the linear's name, and this
26
+ /// is what the engine would say if something got past it.
27
+ const GROUP_SIZES: [i32; 3] = [32, 64, 128];
28
+ const BITS: [i32; 6] = [2, 3, 4, 5, 6, 8];
29
+
30
+ /// One node's operation, with its attributes already read.
31
+ ///
32
+ /// The list is `config/ops.yml`, which is the single source of truth for
33
+ /// the vocabulary; this is the same list in the form the interpreter
34
+ /// dispatches on.
35
+ #[derive(Debug)]
36
+ pub enum Op {
37
+ /// The model's parameter at this position in its own slice.
38
+ Parameter(usize),
39
+
40
+ Add,
41
+ Sub,
42
+ Mul,
43
+ Div,
44
+ AddScalar(f32),
45
+ SubScalar(f32),
46
+ MulScalar(f32),
47
+ DivScalar(f32),
48
+ /// The number divided by the value: `value / x`.
49
+ RdivScalar(f32),
50
+
51
+ Neg,
52
+ Abs,
53
+ Sqrt,
54
+ Square,
55
+ Exp,
56
+ Log,
57
+ Gelu,
58
+ GeluTanh,
59
+ Relu,
60
+ Sigmoid,
61
+ Tanh,
62
+
63
+ /// The only op that consumes randomness (docs/plan.md section 11.1).
64
+ Dropout(f32),
65
+ StopGradient,
66
+
67
+ Softmax { axis: i32 },
68
+ /// The rotary embedding, by its base or by the frequencies a scaled
69
+ /// one was given: `freqs` names one per pair of dimensions, and
70
+ /// replaces what `theta` would have produced.
71
+ Rope { theta: f32, freqs: Option<Vec<f32>> },
72
+
73
+ Transpose(Vec<i32>),
74
+ Reshape(Vec<i32>),
75
+ Slice { axis: i32, start: i32, length: i32 },
76
+ Mean { axes: Option<Vec<i32>>, keepdims: bool },
77
+ Sum { axes: Option<Vec<i32>>, keepdims: bool },
78
+ Max { axes: Option<Vec<i32>>, keepdims: bool },
79
+
80
+ Cast(Dtype),
81
+ Matmul,
82
+ /// `x @ dequantize(weight)ᵀ` with the weight packed (docs/qlora.md):
83
+ /// inputs x, the u32 weight, the scales and, for affine, the biases.
84
+ QuantizedMatmul(Quantization),
85
+ Take,
86
+
87
+ /// Semantic ops, kept whole: the backend decides how to realize them,
88
+ /// and the IR says what they mean.
89
+ LayerNorm { eps: f32 },
90
+ RmsNorm { eps: f32 },
91
+ Sdpa { scale: Option<f32>, causal: bool },
92
+ CrossEntropy,
93
+ }
94
+
95
+ impl Op {
96
+ /// How many value inputs this op takes, as `config/ops.yml` declares.
97
+ /// A range where the manifest gives one.
98
+ fn arity(&self) -> (usize, usize) {
99
+ match self {
100
+ // Every variant by name, and no `_`: a new op has to say how
101
+ // many inputs it takes, rather than being taken for a unary one.
102
+ Op::Parameter(_) => (0, 0),
103
+ Op::Add
104
+ | Op::Sub
105
+ | Op::Mul
106
+ | Op::Div
107
+ | Op::Matmul
108
+ | Op::Take
109
+ | Op::CrossEntropy
110
+ | Op::RmsNorm { .. } => (2, 2),
111
+ Op::LayerNorm { .. } => (2, 3),
112
+ Op::Sdpa { .. } | Op::QuantizedMatmul(_) => (3, 4),
113
+ Op::AddScalar(_)
114
+ | Op::SubScalar(_)
115
+ | Op::MulScalar(_)
116
+ | Op::DivScalar(_)
117
+ | Op::RdivScalar(_)
118
+ | Op::Neg
119
+ | Op::Abs
120
+ | Op::Sqrt
121
+ | Op::Square
122
+ | Op::Exp
123
+ | Op::Log
124
+ | Op::Gelu
125
+ | Op::GeluTanh
126
+ | Op::Relu
127
+ | Op::Sigmoid
128
+ | Op::Tanh
129
+ | Op::Dropout(_)
130
+ | Op::StopGradient
131
+ | Op::Softmax { .. }
132
+ | Op::Rope { .. }
133
+ | Op::Transpose(_)
134
+ | Op::Reshape(_)
135
+ | Op::Slice { .. }
136
+ | Op::Mean { .. }
137
+ | Op::Sum { .. }
138
+ | Op::Max { .. }
139
+ | Op::Cast(_) => (1, 1),
140
+ }
141
+ }
142
+
143
+ /// The op a node spec describes. `parameters` is how many the model
144
+ /// declares, so a `parameter` node naming one past the end is refused
145
+ /// here rather than indexing past them in the middle of a step.
146
+ fn resolve(spec: &NodeSpec, parameters: usize) -> Result<Self> {
147
+ let attributes = &spec.attributes;
148
+ Ok(match spec.op.as_str() {
149
+ "parameter" => {
150
+ let index = *spec
151
+ .parameters
152
+ .first()
153
+ .context("a parameter node names no parameter")?;
154
+ anyhow::ensure!(index < parameters, "parameter {index} of {parameters}");
155
+ Op::Parameter(index)
156
+ }
157
+ "add" => Op::Add,
158
+ "sub" => Op::Sub,
159
+ "mul" => Op::Mul,
160
+ "div" => Op::Div,
161
+ "add_scalar" => Op::AddScalar(number(attributes, "value")?),
162
+ "sub_scalar" => Op::SubScalar(number(attributes, "value")?),
163
+ "mul_scalar" => Op::MulScalar(number(attributes, "value")?),
164
+ "div_scalar" => Op::DivScalar(number(attributes, "value")?),
165
+ "rdiv_scalar" => Op::RdivScalar(number(attributes, "value")?),
166
+ "neg" => Op::Neg,
167
+ "abs" => Op::Abs,
168
+ "sqrt" => Op::Sqrt,
169
+ "square" => Op::Square,
170
+ "exp" => Op::Exp,
171
+ "log" => Op::Log,
172
+ "gelu" => Op::Gelu,
173
+ "gelu_tanh" => Op::GeluTanh,
174
+ "relu" => Op::Relu,
175
+ "sigmoid" => Op::Sigmoid,
176
+ "tanh" => Op::Tanh,
177
+ "dropout" => {
178
+ let p = number(attributes, "p")?;
179
+ anyhow::ensure!(
180
+ (0.0..1.0).contains(&p),
181
+ "dropout: p must be in 0..1, got {p}"
182
+ );
183
+ Op::Dropout(p)
184
+ }
185
+ "stop_gradient" => Op::StopGradient,
186
+ "softmax" => Op::Softmax {
187
+ axis: integer(attributes, "axis")?,
188
+ },
189
+ "rope" => Op::Rope {
190
+ theta: number(attributes, "theta")?,
191
+ freqs: optional_numbers(attributes, "freqs")?,
192
+ },
193
+ "transpose" => Op::Transpose(integers(attributes, "axes")?),
194
+ "reshape" => {
195
+ let shape = integers(attributes, "shape")?;
196
+ anyhow::ensure!(
197
+ shape.iter().filter(|d| **d == -1).count() <= 1,
198
+ "reshape: only one dimension may be -1, got {shape:?}"
199
+ );
200
+ anyhow::ensure!(
201
+ shape.iter().all(|d| *d >= -1),
202
+ "reshape: a shape is positive integers, at most one -1, and leading \
203
+ 0s for the dimensions kept as they are, got {shape:?}"
204
+ );
205
+ // A 0 is "the dimension the input already has there", so
206
+ // only the leading ones can be kept: what follows is
207
+ // being re-divided and has no dimension to keep.
208
+ let keeps = shape.iter().take_while(|d| **d == 0).count();
209
+ anyhow::ensure!(
210
+ !shape[keeps..].contains(&0),
211
+ "reshape: a 0 keeps the dimension the input has there, so only the \
212
+ leading ones can be kept, got {shape:?}"
213
+ );
214
+ Op::Reshape(shape)
215
+ }
216
+ "slice" => Op::Slice {
217
+ axis: integer(attributes, "axis")?,
218
+ start: integer(attributes, "start")?,
219
+ length: integer(attributes, "length")?,
220
+ },
221
+ "mean" => Op::Mean {
222
+ axes: optional_integers(attributes, "axes")?,
223
+ keepdims: boolean(attributes, "keepdims")?,
224
+ },
225
+ "sum" => Op::Sum {
226
+ axes: optional_integers(attributes, "axes")?,
227
+ keepdims: boolean(attributes, "keepdims")?,
228
+ },
229
+ "max" => Op::Max {
230
+ axes: optional_integers(attributes, "axes")?,
231
+ keepdims: boolean(attributes, "keepdims")?,
232
+ },
233
+ "cast" => {
234
+ let name = string(attributes, "dtype")?;
235
+ Op::Cast(dtype_named(&name).with_context(|| format!("cast: unknown dtype {name:?}"))?)
236
+ }
237
+ "matmul" => Op::Matmul,
238
+ "quantized_matmul" => {
239
+ let group_size = integer(attributes, "group_size")?;
240
+ let bits = integer(attributes, "bits")?;
241
+ anyhow::ensure!(
242
+ GROUP_SIZES.contains(&group_size),
243
+ "quantized_matmul: group_size must be one of {GROUP_SIZES:?}, got {group_size}"
244
+ );
245
+ anyhow::ensure!(BITS.contains(&bits), "quantized_matmul: bits must be one of {BITS:?}, got {bits}");
246
+ let mode = Mode::parse(&string(attributes, "mode")?).map_err(|e| anyhow::anyhow!("{}", e.what()))?;
247
+ Op::QuantizedMatmul(Quantization { group_size, bits, mode })
248
+ }
249
+ "take" => Op::Take,
250
+ "layer_norm" => Op::LayerNorm {
251
+ eps: number(attributes, "eps")?,
252
+ },
253
+ "rms_norm" => Op::RmsNorm {
254
+ eps: number(attributes, "eps")?,
255
+ },
256
+ "sdpa" => Op::Sdpa {
257
+ scale: optional_number(attributes, "scale")?,
258
+ causal: boolean(attributes, "causal")?,
259
+ },
260
+ "cross_entropy" => Op::CrossEntropy,
261
+ other => anyhow::bail!(
262
+ "op {other:?} is not in this engine's vocabulary. The manifest is \
263
+ Ruby's (config/ops.yml) and this list is compiled, so if the \
264
+ manifest declares it, what is stale is the extension: build it \
265
+ again (rake compile). Otherwise it is a typo."
266
+ ),
267
+ })
268
+ }
269
+ }
270
+
271
+ /// One resolved node.
272
+ pub struct Node {
273
+ pub op: Op,
274
+ /// Where each input comes from, already parsed and checked.
275
+ pub inputs: Vec<Ref>,
276
+ /// A stable name a tap can ask for, or none.
277
+ pub name: Option<String>,
278
+ /// The dtype the graph declares this node produces, which the
279
+ /// interpreter holds what it computed to (`interp::evaluate_tapped`).
280
+ pub dtype: Option<Dtype>,
281
+ }
282
+
283
+ /// A graph in the form the interpreter runs.
284
+ pub struct Program {
285
+ /// Kept as declared: binding a batch reads the source, shape and dtype.
286
+ pub inputs: Vec<InputSpec>,
287
+ pub nodes: Vec<Node>,
288
+ /// Named outputs, in the order the config declared them.
289
+ pub outputs: Vec<(String, Ref)>,
290
+ }
291
+
292
+ impl Program {
293
+ /// Reads a graph into runnable form, checking everything that can be
294
+ /// checked without data.
295
+ ///
296
+ /// `parameters` is how many the model declares, so a `parameter` node
297
+ /// that names one past the end says so here rather than panicking in
298
+ /// the middle of a step.
299
+ pub fn resolve(graph: Graph, parameters: usize, model: &str) -> Result<Self> {
300
+ let mut nodes = Vec::with_capacity(graph.nodes.len());
301
+ for (position, spec) in graph.nodes.iter().enumerate() {
302
+ let where_ = format!("{model}: node {} ({})", spec.id, spec.op);
303
+ let op = Op::resolve(spec, parameters).context(where_.clone())?;
304
+
305
+ let inputs = spec
306
+ .inputs
307
+ .iter()
308
+ .map(|text| {
309
+ let reference = parse_ref(text).with_context(|| where_.clone())?;
310
+ check(&reference, position, graph.inputs.len(), &where_)?;
311
+ Ok(reference)
312
+ })
313
+ .collect::<Result<Vec<_>>>()?;
314
+
315
+ let (least, most) = op.arity();
316
+ anyhow::ensure!(
317
+ (least..=most).contains(&inputs.len()),
318
+ "{where_}: {} inputs, but this op takes {}",
319
+ inputs.len(),
320
+ if least == most {
321
+ least.to_string()
322
+ } else {
323
+ format!("{least} to {most}")
324
+ }
325
+ );
326
+
327
+ let dtype = spec
328
+ .dtype
329
+ .as_deref()
330
+ .map(|name| dtype_named(name).with_context(|| format!("{where_}: unknown dtype {name:?}")))
331
+ .transpose()?;
332
+ nodes.push(Node {
333
+ op,
334
+ inputs,
335
+ name: spec.name.clone(),
336
+ dtype,
337
+ });
338
+ }
339
+
340
+ let outputs = graph
341
+ .outputs
342
+ .iter()
343
+ .map(|(name, text)| {
344
+ let where_ = format!("{model}: output {name:?}");
345
+ let reference = parse_ref(text).with_context(|| where_.clone())?;
346
+ check(&reference, nodes.len(), graph.inputs.len(), &where_)?;
347
+ Ok((name.clone(), reference))
348
+ })
349
+ .collect::<Result<Vec<_>>>()?;
350
+ anyhow::ensure!(!outputs.is_empty(), "{model}: no outputs");
351
+
352
+ Ok(Self {
353
+ inputs: graph.inputs,
354
+ nodes,
355
+ outputs,
356
+ })
357
+ }
358
+
359
+ /// Every name a tap could ask for.
360
+ pub fn node_names(&self) -> impl Iterator<Item = &String> {
361
+ self.nodes.iter().filter_map(|n| n.name.as_ref())
362
+ }
363
+ }
364
+
365
+ /// What the objective's own nodes and inputs are named by, since it is a
366
+ /// graph without being a model.
367
+ pub const OBJECTIVE: &str = "objective";
368
+
369
+ /// How a tap names a node: the graph it belongs to, then the node.
370
+ ///
371
+ /// The same shape as a parameter path ("student.head.weight"), and for
372
+ /// the same reason: two models of one architecture share every name
373
+ /// inside them.
374
+ pub fn qualified(graph: &str, node: &str) -> String {
375
+ format!("{graph}.{node}")
376
+ }
377
+
378
+ /// That a reference names something that exists, and that a node reference
379
+ /// names one already computed.
380
+ ///
381
+ /// The second is what keeps the interpreter's `values[id]` in bounds. A
382
+ /// config whose nodes are not in topological order used to be a panic at
383
+ /// step one; it is a refusal at open now.
384
+ fn check(reference: &Ref, position: usize, inputs: usize, where_: &str) -> Result<()> {
385
+ match *reference {
386
+ Ref::Input(id) => anyhow::ensure!(
387
+ id < inputs,
388
+ "{where_}: reads input {id}, and there are {inputs}"
389
+ ),
390
+ Ref::Node(id) => anyhow::ensure!(
391
+ id < position,
392
+ "{where_}: reads node {id}, which is not computed before it. \
393
+ Nodes run in the order they are declared."
394
+ ),
395
+ }
396
+ Ok(())
397
+ }
398
+
399
+ fn number(attributes: &Map<String, Value>, key: &str) -> Result<f32> {
400
+ attributes
401
+ .get(key)
402
+ .and_then(Value::as_f64)
403
+ .map(|v| v as f32)
404
+ .with_context(|| format!("attribute {key:?} must be a number"))
405
+ }
406
+
407
+ fn string(attributes: &Map<String, Value>, key: &str) -> Result<String> {
408
+ attributes
409
+ .get(key)
410
+ .and_then(Value::as_str)
411
+ .map(str::to_string)
412
+ .with_context(|| format!("attribute {key:?} must be a string"))
413
+ }
414
+
415
+ fn optional_number(attributes: &Map<String, Value>, key: &str) -> Result<Option<f32>> {
416
+ match attributes.get(key) {
417
+ None | Some(Value::Null) => Ok(None),
418
+ Some(_) => number(attributes, key).map(Some),
419
+ }
420
+ }
421
+
422
+ fn integer(attributes: &Map<String, Value>, key: &str) -> Result<i32> {
423
+ attributes
424
+ .get(key)
425
+ .and_then(Value::as_i64)
426
+ .map(|v| v as i32)
427
+ .with_context(|| format!("attribute {key:?} must be an integer"))
428
+ }
429
+
430
+ fn integers(attributes: &Map<String, Value>, key: &str) -> Result<Vec<i32>> {
431
+ let list = attributes
432
+ .get(key)
433
+ .and_then(Value::as_array)
434
+ .with_context(|| format!("attribute {key:?} must be a list of integers"))?;
435
+ list.iter()
436
+ .map(|v| {
437
+ v.as_i64()
438
+ .map(|i| i as i32)
439
+ .with_context(|| format!("attribute {key:?} must be a list of integers"))
440
+ })
441
+ .collect()
442
+ }
443
+
444
+ fn numbers(attributes: &Map<String, Value>, key: &str) -> Result<Vec<f32>> {
445
+ let list = attributes
446
+ .get(key)
447
+ .and_then(Value::as_array)
448
+ .with_context(|| format!("attribute {key:?} must be a list of numbers"))?;
449
+ list.iter()
450
+ .map(|v| {
451
+ v.as_f64()
452
+ .map(|f| f as f32)
453
+ .with_context(|| format!("attribute {key:?} must be a list of numbers"))
454
+ })
455
+ .collect()
456
+ }
457
+
458
+ fn optional_numbers(attributes: &Map<String, Value>, key: &str) -> Result<Option<Vec<f32>>> {
459
+ match attributes.get(key) {
460
+ None | Some(Value::Null) => Ok(None),
461
+ Some(_) => numbers(attributes, key).map(Some),
462
+ }
463
+ }
464
+
465
+ fn optional_integers(attributes: &Map<String, Value>, key: &str) -> Result<Option<Vec<i32>>> {
466
+ match attributes.get(key) {
467
+ None | Some(Value::Null) => Ok(None),
468
+ Some(_) => integers(attributes, key).map(Some),
469
+ }
470
+ }
471
+
472
+ /// `false` when the attribute is absent or null, as a graph that does not
473
+ /// say `keepdims` means; anything else must be a boolean, since a typo read
474
+ /// as `false` would be a different computation that runs.
475
+ fn boolean(attributes: &Map<String, Value>, key: &str) -> Result<bool> {
476
+ match attributes.get(key) {
477
+ None | Some(Value::Null) => Ok(false),
478
+ Some(value) => value
479
+ .as_bool()
480
+ .with_context(|| format!("attribute {key:?} must be true or false, got {value}")),
481
+ }
482
+ }
483
+
484
+ /// A resolved graph's outputs, by name, as the caller reads them.
485
+
486
+ #[cfg(test)]
487
+ mod tests {
488
+ use super::*;
489
+ use crate::graph::{Graph, NodeSpec};
490
+ use serde_json::json;
491
+
492
+ fn node(id: usize, op: &str, inputs: &[&str], attributes: Value) -> NodeSpec {
493
+ serde_json::from_value(json!({
494
+ "id": id,
495
+ "op": op,
496
+ "inputs": inputs,
497
+ "parameters": [],
498
+ "attributes": attributes,
499
+ }))
500
+ .unwrap()
501
+ }
502
+
503
+ fn graph(nodes: Vec<NodeSpec>, outputs: &[(&str, &str)]) -> Graph {
504
+ let inputs = json!([{
505
+ "id": 0, "name": "x", "source": {"batch": "x"},
506
+ "shape": [null, 2], "dtype": "f32",
507
+ }]);
508
+ Graph {
509
+ inputs: serde_json::from_value(inputs).unwrap(),
510
+ parameters: Vec::new(),
511
+ nodes,
512
+ outputs: outputs
513
+ .iter()
514
+ .map(|(k, v)| (k.to_string(), v.to_string()))
515
+ .collect(),
516
+ }
517
+ }
518
+
519
+ fn refusal(nodes: Vec<NodeSpec>, outputs: &[(&str, &str)], parameters: usize) -> String {
520
+ match Program::resolve(graph(nodes, outputs), parameters, "m") {
521
+ Ok(_) => panic!("this should not have resolved"),
522
+ Err(e) => format!("{e:#}"),
523
+ }
524
+ }
525
+
526
+ #[test]
527
+ fn a_graph_resolves_into_values_the_interpreter_matches_on() {
528
+ let program = Program::resolve(
529
+ graph(
530
+ vec![
531
+ node(0, "square", &["input:0"], json!({})),
532
+ node(1, "mul_scalar", &["node:0"], json!({"value": 3.0})),
533
+ ],
534
+ &[("loss", "node:1")],
535
+ ),
536
+ 0,
537
+ "m",
538
+ )
539
+ .unwrap();
540
+
541
+ assert!(matches!(program.nodes[0].op, Op::Square));
542
+ assert!(matches!(program.nodes[1].op, Op::MulScalar(v) if v == 3.0));
543
+ assert_eq!(program.outputs.len(), 1);
544
+ }
545
+
546
+ // Each of these used to surface from inside value_and_grad, as an MLX
547
+ // exception, on the first step. They are refusals at open now.
548
+
549
+ #[test]
550
+ fn an_op_outside_the_vocabulary_is_named() {
551
+ let e = refusal(
552
+ vec![node(0, "convolve", &["input:0"], json!({}))],
553
+ &[("loss", "node:0")],
554
+ 0,
555
+ );
556
+ assert!(e.contains("convolve"), "{e}");
557
+ assert!(e.contains("vocabulary"), "{e}");
558
+ }
559
+
560
+ #[test]
561
+ fn a_missing_attribute_is_named_with_its_node() {
562
+ let e = refusal(
563
+ vec![node(0, "mul_scalar", &["input:0"], json!({}))],
564
+ &[("loss", "node:0")],
565
+ 0,
566
+ );
567
+ assert!(e.contains("node 0 (mul_scalar)"), "{e}");
568
+ assert!(e.contains("\"value\" must be a number"), "{e}");
569
+ }
570
+
571
+ #[test]
572
+ fn an_attribute_of_the_wrong_type_is_refused() {
573
+ let e = refusal(
574
+ vec![node(0, "softmax", &["input:0"], json!({"axis": "last"}))],
575
+ &[("loss", "node:0")],
576
+ 0,
577
+ );
578
+ assert!(e.contains("must be an integer"), "{e}");
579
+ }
580
+
581
+ #[test]
582
+ fn a_rate_outside_zero_to_one_is_refused_before_a_step_draws_one() {
583
+ let e = refusal(
584
+ vec![node(0, "dropout", &["input:0"], json!({"p": 1.5}))],
585
+ &[("loss", "node:0")],
586
+ 0,
587
+ );
588
+ assert!(e.contains("p must be in 0..1"), "{e}");
589
+ }
590
+
591
+ #[test]
592
+ fn an_op_given_the_wrong_number_of_inputs_is_refused() {
593
+ let e = refusal(
594
+ vec![node(0, "matmul", &["input:0"], json!({}))],
595
+ &[("loss", "node:0")],
596
+ 0,
597
+ );
598
+ assert!(e.contains("1 inputs"), "{e}");
599
+ assert!(e.contains("takes 2"), "{e}");
600
+ }
601
+
602
+ #[test]
603
+ fn a_reshape_naming_two_free_dimensions_is_refused() {
604
+ let e = refusal(
605
+ vec![node(0, "reshape", &["input:0"], json!({"shape": [-1, -1]}))],
606
+ &[("loss", "node:0")],
607
+ 0,
608
+ );
609
+ assert!(e.contains("only one dimension may be -1"), "{e}");
610
+ }
611
+
612
+ // A 0 keeps the dimension the array already has, and only the
613
+ // leading ones can be kept: what follows is being re-divided and has
614
+ // nothing of its own to stand for.
615
+ #[test]
616
+ fn a_kept_dimension_after_a_divided_one_is_refused() {
617
+ let e = refusal(
618
+ vec![node(0, "reshape", &["input:0"], json!({"shape": [0, 2, 0]}))],
619
+ &[("loss", "node:0")],
620
+ 0,
621
+ );
622
+ assert!(e.contains("only the leading ones can be kept"), "{e}");
623
+ }
624
+
625
+ #[test]
626
+ fn a_node_that_reads_one_not_yet_computed_is_refused() {
627
+ // The interpreter indexes `values[id]`, which is only in bounds
628
+ // because of this check.
629
+ let e = refusal(
630
+ vec![
631
+ node(0, "square", &["node:1"], json!({})),
632
+ node(1, "square", &["input:0"], json!({})),
633
+ ],
634
+ &[("loss", "node:1")],
635
+ 0,
636
+ );
637
+ assert!(e.contains("not computed before it"), "{e}");
638
+ }
639
+
640
+ #[test]
641
+ fn a_reference_to_an_input_that_does_not_exist_is_refused() {
642
+ let e = refusal(
643
+ vec![node(0, "square", &["input:9"], json!({}))],
644
+ &[("loss", "node:0")],
645
+ 0,
646
+ );
647
+ assert!(e.contains("reads input 9"), "{e}");
648
+ }
649
+
650
+ #[test]
651
+ fn a_parameter_node_past_the_end_is_refused() {
652
+ let mut spec = node(0, "parameter", &[], json!({}));
653
+ spec.parameters = vec![3];
654
+ let e = refusal(vec![spec], &[("loss", "node:0")], 2);
655
+ assert!(e.contains("parameter 3 of 2"), "{e}");
656
+ }
657
+
658
+ /// A cast names its dtype in the graph, so an unknown one is a graph
659
+ /// that cannot run, and it is refused when the plan opens.
660
+ #[test]
661
+ fn a_cast_to_an_unknown_dtype_is_refused_when_the_plan_opens() {
662
+ let said = refusal(
663
+ vec![node(0, "cast", &["input:0"], json!({"dtype": "f64"}))],
664
+ &[("y", "node:0")],
665
+ 0,
666
+ );
667
+ assert!(said.contains("cast: unknown dtype \"f64\""), "{said}");
668
+ }
669
+
670
+ /// Absent means false, as a graph that does not say `keepdims` means;
671
+ /// a value that is not a boolean is a typo, not a false.
672
+ #[test]
673
+ fn a_flag_that_is_not_a_boolean_is_refused_rather_than_read_as_false() {
674
+ let said = refusal(
675
+ vec![node(0, "sum", &["input:0"], json!({"axes": [1], "keepdims": "yes"}))],
676
+ &[("y", "node:0")],
677
+ 0,
678
+ );
679
+ assert!(said.contains("\"keepdims\" must be true or false"), "{said}");
680
+
681
+ let absent = Program::resolve(
682
+ graph(vec![node(0, "sum", &["input:0"], json!({"axes": [1]}))], &[("y", "node:0")]),
683
+ 0,
684
+ "m",
685
+ )
686
+ .unwrap();
687
+ assert!(matches!(absent.nodes[0].op, Op::Sum { keepdims: false, .. }));
688
+ }
689
+
690
+ /// The attributes say how the weight was quantized, and the engine
691
+ /// reads them into the one value the kernel is called with.
692
+ #[test]
693
+ fn a_quantized_matmul_carries_its_quantization() {
694
+ let program = Program::resolve(
695
+ graph(
696
+ vec![node(
697
+ 0,
698
+ "quantized_matmul",
699
+ &["input:0", "input:0", "input:0", "input:0"],
700
+ json!({"group_size": 64, "bits": 4, "mode": "affine"}),
701
+ )],
702
+ &[("y", "node:0")],
703
+ ),
704
+ 0,
705
+ "m",
706
+ )
707
+ .unwrap();
708
+ assert!(matches!(
709
+ program.nodes[0].op,
710
+ Op::QuantizedMatmul(Quantization { group_size: 64, bits: 4, mode: Mode::Affine })
711
+ ));
712
+
713
+ let two_inputs = refusal(
714
+ vec![node(0, "quantized_matmul", &["input:0", "input:0"], json!({"group_size": 64, "bits": 4, "mode": "affine"}))],
715
+ &[("y", "node:0")],
716
+ 0,
717
+ );
718
+ assert!(two_inputs.contains("takes 3 to 4"), "{two_inputs}");
719
+ }
720
+
721
+ /// A quantization MLX has no kernel for is refused when the plan
722
+ /// opens, in the words the IR uses.
723
+ #[test]
724
+ fn a_quantization_without_a_kernel_is_refused() {
725
+ for (attributes, fragment) in [
726
+ (json!({"group_size": 48, "bits": 4, "mode": "affine"}), "group_size must be one of"),
727
+ (json!({"group_size": 64, "bits": 7, "mode": "affine"}), "bits must be one of"),
728
+ (json!({"group_size": 64, "bits": 4, "mode": "mxfp4"}), "\"mxfp4\" is not one this engine reads"),
729
+ (json!({"group_size": 64, "bits": 4}), "\"mode\" must be a string"),
730
+ ] {
731
+ let said = refusal(
732
+ vec![node(0, "quantized_matmul", &["input:0", "input:0", "input:0"], attributes)],
733
+ &[("y", "node:0")],
734
+ 0,
735
+ );
736
+ assert!(said.contains(fragment), "{said}");
737
+ }
738
+ }
739
+
740
+ #[test]
741
+ fn a_graph_with_no_outputs_is_refused() {
742
+ let e = refusal(vec![node(0, "square", &["input:0"], json!({}))], &[], 0);
743
+ assert!(e.contains("no outputs"), "{e}");
744
+ }
745
+ }