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,985 @@
1
+ //! The interpreter: one pass over a resolved program's nodes, dispatching
2
+ //! to MLX through the engine's own binding (`crate::mlxc`).
3
+ //!
4
+ //! Everything that could be decided without data was decided when the plan
5
+ //! opened (`crate::op`): the op is a variant, its attributes are fields,
6
+ //! and its inputs are indices that are known to be in range. What is left
7
+ //! here is arithmetic.
8
+
9
+ use std::collections::BTreeMap;
10
+
11
+ use crate::mlxc::error::Exception;
12
+ use crate::mlxc::fast::ScaledDotProductAttentionMask as Mask;
13
+ use crate::mlxc::ops::indexing::take_along_axis;
14
+ use crate::mlxc::{Array, Dtype};
15
+
16
+ use crate::graph::Ref;
17
+ use crate::op::{qualified, Node, Op, Program};
18
+
19
+ type Result<T> = std::result::Result<T, Exception>;
20
+
21
+ /// What a tap asked for, by node name.
22
+ pub type Taps = BTreeMap<String, Stat>;
23
+
24
+ /// What the taps saw, by node name.
25
+ pub type Tapped = BTreeMap<String, Array>;
26
+
27
+ /// What is being watched, and where what it saw goes.
28
+ ///
29
+ /// The two always travelled together and as two parameters: one to say
30
+ /// which nodes are wanted, one to put them in. Two chances to pass a
31
+ /// mismatched pair, and the deciding (is anything watching? is this node
32
+ /// one of them? reduce it how?) sat inline in the interpreter's innermost
33
+ /// loop, which is not what that loop is about.
34
+ pub struct Watch<'a> {
35
+ taps: &'a Taps,
36
+ collected: &'a mut Tapped,
37
+ }
38
+
39
+ impl<'a> Watch<'a> {
40
+ pub fn new(taps: &'a Taps, collected: &'a mut Tapped) -> Self {
41
+ Self { taps, collected }
42
+ }
43
+
44
+ /// Nothing is watched, whatever is passed in to collect into.
45
+ ///
46
+ /// What a traced pass wants: the values a `value_and_grad` produces
47
+ /// belong to the trace, and reading them out is not what a tap means
48
+ /// (`crate::executor::differentiate`).
49
+ pub fn none(collected: &'a mut Tapped) -> Self {
50
+ static NOTHING: std::sync::OnceLock<Taps> = std::sync::OnceLock::new();
51
+ Self {
52
+ taps: NOTHING.get_or_init(Taps::new),
53
+ collected,
54
+ }
55
+ }
56
+
57
+ /// Keeps what a node produced, if that node is one of the watched.
58
+ ///
59
+ /// Nothing is watched most of the time, and this is called once per
60
+ /// node per pass, so the usual answer is the first line.
61
+ fn saw(&mut self, qualifier: &str, name: &str, value: &Array) -> Result<()> {
62
+ if self.taps.is_empty() {
63
+ return Ok(());
64
+ }
65
+ let watched = qualified(qualifier, name);
66
+ let Some(stat) = self.taps.get(&watched) else {
67
+ return Ok(());
68
+ };
69
+ self.collected.insert(watched, stat.apply(value)?);
70
+ Ok(())
71
+ }
72
+ }
73
+
74
+ /// What a tap asks for: a node's name, and how much of it to bring back.
75
+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]
76
+ pub enum Stat {
77
+ /// The whole tensor. Honest and expensive; for debugging.
78
+ Full,
79
+ Mean,
80
+ /// The L2 norm, which is what a gradient or an activation is usually
81
+ /// watched by.
82
+ Norm,
83
+ /// Smallest and largest, as a two-element tensor.
84
+ Extent,
85
+ }
86
+
87
+ impl Stat {
88
+ pub fn parse(name: &str) -> Option<Self> {
89
+ match name {
90
+ "full" => Some(Stat::Full),
91
+ "mean" => Some(Stat::Mean),
92
+ "norm" => Some(Stat::Norm),
93
+ "extent" => Some(Stat::Extent),
94
+ _ => None,
95
+ }
96
+ }
97
+
98
+ /// Reduces on the device, so a tap that is left on costs a scalar per
99
+ /// step rather than a tensor (docs/plan.md section 8.3).
100
+ fn apply(self, value: &Array) -> Result<Array> {
101
+ match self {
102
+ Stat::Full => Ok(value.clone()),
103
+ Stat::Mean => value.mean(false),
104
+ Stat::Norm => value.square()?.sum(false)?.sqrt(),
105
+ Stat::Extent => {
106
+ let min = value.min(false)?;
107
+ let max = value.max(false)?;
108
+ crate::mlxc::ops::stack(&[min, max], 0)
109
+ }
110
+ }
111
+ }
112
+ }
113
+
114
+ /// Evaluates one program and returns its outputs by name.
115
+ ///
116
+ /// `rng` is both the randomness and the mode. A key means this is a
117
+ /// training pass and the random ops draw; no key means it is not, and they
118
+ /// stand aside (dropout becomes the identity). Inference has no other
119
+ /// meaning here, and a flag beside the key could disagree with it.
120
+ ///
121
+ /// Collects the values `taps` asks for as it goes. A tap is read-only: it
122
+ /// adds an output, it does not change one. What it costs is that the value
123
+ /// must be kept rather than fused away, which is why a standing tap should
124
+ /// reduce (docs/plan.md section 8.3).
125
+ ///
126
+ /// `qualifier` is which graph this is (a model's name, or "objective"),
127
+ /// and a tap names a node through it: "student.hidden" rather than
128
+ /// "hidden". Two models of the same architecture have the same node names,
129
+ /// which is the ordinary shape of a distillation, so an unqualified tap
130
+ /// would report one of them and drop the other without saying so.
131
+ pub fn evaluate_tapped(
132
+ program: &Program,
133
+ params: &[Array],
134
+ inputs: &BTreeMap<String, Array>,
135
+ rng: Option<&Array>,
136
+ qualifier: &str,
137
+ watch: &mut Watch<'_>,
138
+ ) -> Result<BTreeMap<String, Array>> {
139
+ // One key per random op, split from the graph's, so two dropouts in one
140
+ // step draw different masks and the same step always draws the same
141
+ // ones.
142
+ let mut key = rng.cloned();
143
+ let mut values: Vec<Array> = Vec::with_capacity(program.nodes.len());
144
+
145
+ for node in &program.nodes {
146
+ let ins: Vec<Array> = node
147
+ .inputs
148
+ .iter()
149
+ .map(|r| read(r, program, inputs, &values))
150
+ .collect::<Result<_>>()?;
151
+ let out = apply(node, &ins, params, &mut key)?;
152
+ // What was computed has the dtype the graph says, or the graph and
153
+ // the engine are describing two different runs. MLX promotes a
154
+ // bf16 array combined with an f32 one to f32 without a word, and
155
+ // that is how a bf16 model came to compute in f32 from its first
156
+ // norm on, while the graph went on saying bf16 (2026-11-09).
157
+ if let Some(declared) = node.dtype {
158
+ if out.dtype() != declared {
159
+ return Err(Exception::custom(format!(
160
+ "{qualifier}: node {} ({:?}) computed {:?} where the graph declares {:?}. \
161
+ This is the engine's mistake, not the graph's: an op mixed a dtype into its \
162
+ arithmetic that the graph did not ask for.",
163
+ values.len(),
164
+ node.op,
165
+ out.dtype(),
166
+ declared
167
+ )));
168
+ }
169
+ }
170
+ if let Some(name) = &node.name {
171
+ watch.saw(qualifier, name, &out)?;
172
+ }
173
+ values.push(out);
174
+ }
175
+
176
+ program
177
+ .outputs
178
+ .iter()
179
+ .map(|(name, r)| Ok((name.clone(), read(r, program, inputs, &values)?)))
180
+ .collect()
181
+ }
182
+
183
+ /// One resolved reference. Both arms were bounds-checked when the program
184
+ /// was resolved, so this cannot be out of range.
185
+ fn read(
186
+ reference: &Ref,
187
+ program: &Program,
188
+ inputs: &BTreeMap<String, Array>,
189
+ values: &[Array],
190
+ ) -> Result<Array> {
191
+ match *reference {
192
+ Ref::Input(id) => {
193
+ let name = &program.inputs[id].name;
194
+ inputs
195
+ .get(name)
196
+ .cloned()
197
+ .ok_or_else(|| Exception::custom(format!("no binding for input {name:?}")))
198
+ }
199
+ Ref::Node(id) => Ok(values[id].clone()),
200
+ }
201
+ }
202
+
203
+ /// One node's arithmetic. `key` is the graph's remaining randomness, split
204
+ /// by each op that draws.
205
+ fn apply(node: &Node, ins: &[Array], params: &[Array], key: &mut Option<Array>) -> Result<Array> {
206
+ // A number from the graph, in the dtype of what it is combined with.
207
+ let scalar = |value: f32| constant(value, &ins[0]);
208
+ Ok(match &node.op {
209
+ Op::Parameter(index) => params[*index].clone(),
210
+
211
+ Op::Add => ins[0].add(&ins[1])?,
212
+ Op::Sub => ins[0].subtract(&ins[1])?,
213
+ Op::Mul => ins[0].multiply(&ins[1])?,
214
+ Op::Div => ins[0].divide(&ins[1])?,
215
+ Op::AddScalar(v) => ins[0].add(scalar(*v)?)?,
216
+ Op::SubScalar(v) => ins[0].subtract(scalar(*v)?)?,
217
+ Op::MulScalar(v) => ins[0].multiply(scalar(*v)?)?,
218
+ Op::DivScalar(v) => ins[0].divide(scalar(*v)?)?,
219
+ Op::RdivScalar(v) => scalar(*v)?.divide(&ins[0])?,
220
+
221
+ Op::Neg => ins[0].negative()?,
222
+ Op::Abs => ins[0].abs()?,
223
+ Op::Sqrt => ins[0].sqrt()?,
224
+ Op::Square => ins[0].square()?,
225
+ Op::Exp => ins[0].exp()?,
226
+ Op::Log => ins[0].log()?,
227
+ Op::Relu => crate::mlxc::ops::maximum(&ins[0], scalar(0.0)?)?,
228
+ Op::Sigmoid => crate::mlxc::ops::sigmoid(&ins[0])?,
229
+ Op::Tanh => crate::mlxc::ops::tanh(&ins[0])?,
230
+ // The exact form, not the tanh approximation: erf is what the
231
+ // reference implementations of these models use, and a parity
232
+ // check against them is the point (docs/plan.md 9.2).
233
+ Op::Gelu => {
234
+ let half = ins[0].multiply(scalar(0.5)?)?;
235
+ let inner = ins[0].divide(scalar(std::f32::consts::SQRT_2)?)?;
236
+ half.multiply(crate::mlxc::ops::erf(&inner)?.add(scalar(1.0)?)?)?
237
+ }
238
+ // And the tanh approximation, which is a different function:
239
+ // 0.5x(1 + tanh(sqrt(2/pi)(x + 0.044715x^3))). Gemma is trained
240
+ // with it, so a graph that reached for the exact one above would
241
+ // be a model that runs and is not the published one.
242
+ Op::GeluTanh => crate::mlxc::nn::gelu_approximate(&ins[0])?,
243
+
244
+ Op::Dropout(p) => {
245
+ // No key means this is not a training pass. Inverted dropout
246
+ // already scales what survives, so standing aside is the whole
247
+ // of what inference has to do.
248
+ match key.as_ref() {
249
+ None => ins[0].clone(),
250
+ Some(current) => {
251
+ let (next, draw) = crate::mlxc::random::split(current, 2)?;
252
+ *key = Some(next);
253
+ let chance = Array::from_f32(1.0 - p)?;
254
+ let mask = crate::mlxc::random::bernoulli(&chance, ins[0].shape(), &draw)?;
255
+ ins[0]
256
+ .multiply(mask.as_dtype(ins[0].dtype())?)?
257
+ .divide(scalar(1.0 - p)?)?
258
+ }
259
+ }
260
+ }
261
+ Op::StopGradient => crate::mlxc::stop_gradient(&ins[0])?,
262
+
263
+ Op::Softmax { axis } => crate::mlxc::ops::softmax_axis(&ins[0], *axis, None)?,
264
+ Op::Rope { theta, freqs } => rope(&ins[0], *theta, freqs.as_deref())?,
265
+
266
+ Op::Transpose(axes) => ins[0].transpose_axes(axes)?,
267
+ Op::Reshape(shape) => ins[0].reshape(&kept(shape, ins[0].shape())?)?,
268
+ Op::Slice {
269
+ axis,
270
+ start,
271
+ length,
272
+ } => slice(&ins[0], *axis, *start, *length)?,
273
+ Op::Mean { axes, keepdims } => match axes {
274
+ None => ins[0].mean(*keepdims)?,
275
+ Some(axes) => ins[0].mean_axes(axes, *keepdims)?,
276
+ },
277
+ Op::Sum { axes, keepdims } => match axes {
278
+ None => ins[0].sum(*keepdims)?,
279
+ Some(axes) => ins[0].sum_axes(axes, *keepdims)?,
280
+ },
281
+ Op::Max { axes, keepdims } => match axes {
282
+ None => ins[0].max(*keepdims)?,
283
+ Some(axes) => ins[0].max_axes(axes, *keepdims)?,
284
+ },
285
+
286
+ // The one op that changes a dtype. Named rather than inferred:
287
+ // the graph says where a model's precision changes.
288
+ Op::Cast(to) => ins[0].as_dtype(*to)?,
289
+ Op::Matmul => ins[0].matmul(&ins[1])?,
290
+ // The weight is a linear's [d_out, d_in], so it is always read
291
+ // transposed; the IR has no attribute for it (config/ops.yml).
292
+ Op::QuantizedMatmul(quantization) => {
293
+ crate::mlxc::quantized::quantized_matmul(&ins[0], &ins[1], &ins[2], ins.get(3), true, *quantization)?
294
+ }
295
+ // An embedding: rows of the table, selected by i32 ids. The
296
+ // gradient reaches only the rows that were read.
297
+ Op::Take => ins[0].take_axis(&ins[1], 0)?,
298
+
299
+ Op::LayerNorm { eps } => layer_norm(ins, *eps)?,
300
+ Op::RmsNorm { eps } => rms_norm(&ins[0], &ins[1], *eps)?,
301
+ Op::Sdpa { scale, causal } => sdpa(ins, *scale, *causal)?,
302
+ Op::CrossEntropy => cross_entropy(&ins[0], &ins[1])?,
303
+ })
304
+ }
305
+
306
+ /// `length` elements of `axis`, starting at `start`.
307
+ ///
308
+ /// Through `take_axis` rather than a strided slice: mlx-rs kept the latter
309
+ /// to itself when this was written, and selecting a contiguous run of
310
+ /// indices is the same function.
311
+ fn slice(x: &Array, axis: i32, start: i32, length: i32) -> Result<Array> {
312
+ let indices: Vec<i32> = (start..start + length).collect();
313
+ x.take_axis(&Array::from_slice(&indices, &[length])?, axis)
314
+ }
315
+
316
+ /// `value` as an array of `like`'s dtype, when that is a floating dtype
317
+ /// narrower than f32; as f32 otherwise.
318
+ ///
319
+ /// MLX's arrays carry their dtype strongly: a bf16 array times an f32
320
+ /// one is f32, where a Python scalar would have stayed out of the way.
321
+ /// So a constant made as f32 and combined with a bf16 value promotes the
322
+ /// value, and everything downstream of it, to f32.
323
+ fn constant(value: f32, like: &Array) -> Result<Array> {
324
+ let array = Array::from_f32(value)?;
325
+ match like.dtype() {
326
+ Dtype::Bfloat16 | Dtype::Float16 => array.as_dtype(like.dtype()),
327
+ _ => Ok(array),
328
+ }
329
+ }
330
+
331
+ /// `x` in f32, for arithmetic whose precision should not be `x`'s own
332
+ /// (a norm's statistics, a rotation's angles).
333
+ fn widened(x: &Array) -> Result<Array> {
334
+ if x.dtype() == Dtype::Float32 {
335
+ Ok(x.clone())
336
+ } else {
337
+ x.as_dtype(Dtype::Float32)
338
+ }
339
+ }
340
+
341
+ /// Normalize over the last axis, then scale and shift.
342
+ ///
343
+ /// Two or three inputs: the value, the gain, and optionally the bias. Kept
344
+ /// whole as a semantic op, so this is what it means rather than how a
345
+ /// backend must do it.
346
+ ///
347
+ /// In f32 whatever `x` is held in, and returned in `x`'s dtype, as MLX's
348
+ /// own fused norms do: the mean and variance of a bf16 row are too coarse
349
+ /// in bf16, and a result left in f32 would turn the rest of a bf16 model
350
+ /// into an f32 one.
351
+ fn layer_norm(ins: &[Array], eps: f32) -> Result<Array> {
352
+ let (x, weight) = (widened(&ins[0])?, widened(&ins[1])?);
353
+ let mean = x.mean_axes(&[-1], true)?;
354
+ let centred = x.subtract(&mean)?;
355
+ let variance = centred.square()?.mean_axes(&[-1], true)?;
356
+ let normed = centred.divide(variance.add(Array::from_f32(eps)?)?.sqrt()?)?;
357
+ let scaled = normed.multiply(&weight)?;
358
+ let shifted = match ins.get(2) {
359
+ Some(bias) => scaled.add(widened(bias)?)?,
360
+ None => scaled,
361
+ };
362
+ narrowed(shifted, ins[0].dtype())
363
+ }
364
+
365
+ /// Scale by the root mean square of the last axis, then by the gain. No
366
+ /// centring and no bias, which is what makes it not layer_norm. In f32,
367
+ /// returned in `x`'s dtype, for the reason `layer_norm` is.
368
+ fn rms_norm(x: &Array, weight: &Array, eps: f32) -> Result<Array> {
369
+ let wide = widened(x)?;
370
+ let scale = wide
371
+ .square()?
372
+ .mean_axes(&[-1], true)?
373
+ .add(Array::from_f32(eps)?)?
374
+ .rsqrt()?;
375
+ narrowed(wide.multiply(scale)?.multiply(widened(weight)?)?, x.dtype())
376
+ }
377
+
378
+ /// `x` back in `dtype`, after arithmetic done wider.
379
+ fn narrowed(x: Array, dtype: Dtype) -> Result<Array> {
380
+ if x.dtype() == dtype {
381
+ Ok(x)
382
+ } else {
383
+ x.as_dtype(dtype)
384
+ }
385
+ }
386
+
387
+ /// A reshape target with its 0s filled in from the array in hand.
388
+ ///
389
+ /// A 0 says "the dimension this already has", which is how a graph that
390
+ /// does not know its batch *or* its sequence still splits the last axis
391
+ /// into heads. The Ruby side settles this when the graph is built; the
392
+ /// engine resolves it again here because it is handed a shape, not a
393
+ /// promise about one.
394
+ fn kept(target: &[i32], from: &[i32]) -> Result<Vec<i32>> {
395
+ target
396
+ .iter()
397
+ .enumerate()
398
+ .map(|(axis, &dim)| {
399
+ if dim != 0 {
400
+ return Ok(dim);
401
+ }
402
+ from.get(axis).copied().ok_or_else(|| {
403
+ Exception::custom(format!(
404
+ "a reshape to {target:?} keeps axis {axis} of a shape with {} of them",
405
+ from.len()
406
+ ))
407
+ })
408
+ })
409
+ .collect()
410
+ }
411
+
412
+ /// Rotary position embedding over the last axis, at the given base.
413
+ ///
414
+ /// Positions are the second-to-last axis, which is the sequence, and the
415
+ /// last axis is split in half: the first half rotates against the second.
416
+ fn rope(x: &Array, theta: f32, freqs: Option<&[f32]>) -> Result<Array> {
417
+ let shape = x.shape().to_vec();
418
+ let rank = shape.len();
419
+ let (positions, width) = (shape[rank - 2], shape[rank - 1]);
420
+ let half = width / 2;
421
+
422
+ // angle[p, i] = p / theta^(2i/width), or p * freqs[i] where the model
423
+ // scaled them (Op::Rope). Built on the host: it is positions x half
424
+ // floats, which is nothing beside the matmuls this sits between, and
425
+ // it keeps the device graph to the rotation itself.
426
+ let angles: Vec<f32> = match freqs {
427
+ Some(given) => {
428
+ if given.len() != half as usize {
429
+ return Err(Exception::custom(format!(
430
+ "rope: {} frequencies for {width} dimensions, which wants {half}",
431
+ given.len()
432
+ )));
433
+ }
434
+ (0..positions)
435
+ .flat_map(|p| given.iter().map(move |f| p as f32 * f))
436
+ .collect()
437
+ }
438
+ None => (0..positions)
439
+ .flat_map(|p| {
440
+ (0..half).map(move |i| {
441
+ p as f32 / theta.powf(2.0 * i as f32 / width as f32)
442
+ })
443
+ })
444
+ .collect(),
445
+ };
446
+ let angle = Array::from_slice(&angles, &[positions, half])?;
447
+ let (cos, sin) = (angle.cos()?, angle.sin()?);
448
+
449
+ // Rotated in f32 and returned in `x`'s dtype, as MLX's fused rope
450
+ // does: the angles are f32, and multiplying a bf16 `x` by them would
451
+ // otherwise leave the queries and keys in f32.
452
+ let wide = widened(x)?;
453
+ let first = slice(&wide, -1, 0, half)?;
454
+ let second = slice(&wide, -1, half, half)?;
455
+ let rotated_first = first.multiply(&cos)?.subtract(second.multiply(&sin)?)?;
456
+ let rotated_second = second.multiply(&cos)?.add(first.multiply(&sin)?)?;
457
+ narrowed(crate::mlxc::ops::concatenate(&[rotated_first, rotated_second], -1)?, x.dtype())
458
+ }
459
+
460
+ /// Scaled dot-product attention: softmax(q k^T / sqrt(d) + mask) v.
461
+ ///
462
+ /// Three or four inputs, the fourth being an additive mask. Kept whole so
463
+ /// a backend may run a fused kernel instead; what the IR says is the
464
+ /// meaning, and the numbers are held to a tolerance rather than to an
465
+ /// order of operations (docs/plan.md 9.2).
466
+ /// Attention, through the backend's own kernel.
467
+ ///
468
+ /// The fused one rather than the decomposition it replaced (docs/plan.md
469
+ /// 6.1: a semantic op uses the backend's kernel when there is one). What
470
+ /// that buys is not only speed: it takes k and v untiled, which is what
471
+ /// makes grouped-query attention expressible at all, and it has a causal
472
+ /// mode, so a decoder does not hand over a triangle of the same number
473
+ /// every step. It differentiates, which is the thing to check before
474
+ /// trusting a fused kernel in a trainer, and there is a test that it does.
475
+ fn sdpa(ins: &[Array], scale: Option<f32>, causal: bool) -> Result<Array> {
476
+ let width = *ins[0].shape().last().expect("a query has a last axis");
477
+ let scale = scale.unwrap_or_else(|| 1.0 / (width as f32).sqrt());
478
+
479
+ // The kernel takes [batch, heads, positions, head_dim]. A graph that
480
+ // writes attention without a head axis means one head, and saying so
481
+ // is an axis of 1 rather than a different op.
482
+ let flat = ins[0].ndim() == 3;
483
+ let lift = |a: &Array| if flat { a.expand_dims_axes(&[1]) } else { Ok(a.clone()) };
484
+ let (q, k, v) = (lift(&ins[0])?, lift(&ins[1])?, lift(&ins[2])?);
485
+ let held;
486
+ let mask = if causal {
487
+ Some(Mask::Causal)
488
+ } else {
489
+ match ins.get(3) {
490
+ // A mask is broadcast against the scores, so one written for
491
+ // three axes needs the head axis these just grew. And it is in
492
+ // the scores' dtype, as mlx-lm casts it: an f32 mask added to
493
+ // bf16 scores would hand back f32 attention.
494
+ Some(mask) => {
495
+ let lifted = if flat && mask.ndim() == 3 { mask.expand_dims_axes(&[1])? } else { mask.clone() };
496
+ held = narrowed(lifted, q.dtype())?;
497
+ Some(Mask::Array(&held))
498
+ }
499
+ None => None,
500
+ }
501
+ };
502
+ // The last argument is attention sinks, which nothing here uses.
503
+ let out = crate::mlxc::fast::scaled_dot_product_attention(&q, &k, &v, scale, mask, None)?;
504
+ Ok(if flat { out.squeeze_axes(&[1])? } else { out })
505
+ }
506
+
507
+ /// The loss at each position: `logsumexp(logits) - logits[target]`.
508
+ ///
509
+ /// The largest logit comes out before anything is exponentiated, which is
510
+ /// what `logsumexp` is; a vocabulary's logits overflow f32 without it.
511
+ /// The same two lines as mlx-rs's `CrossEntropy` with no reduction,
512
+ /// written here because the reduction is the objective's to choose.
513
+ fn cross_entropy(logits: &Array, targets: &Array) -> Result<Array> {
514
+ let wanted = take_along_axis(logits, &targets.expand_dims_axes(&[-1])?, -1)?
515
+ .squeeze_axes(&[-1])?;
516
+ Ok(crate::mlxc::ops::logsumexp_axes(logits, &[-1], None)?.subtract(wanted)?)
517
+ }
518
+
519
+ #[cfg(test)]
520
+ mod tests {
521
+ use crate::fixtures;
522
+ use crate::plan::Weights;
523
+ use crate::session::Session;
524
+ use crate::tensor::{Batch, Values};
525
+
526
+ /// Runs `op` over one batch and returns what its tap saw. The tap is
527
+ /// how a value inside the graph is read without a second graph to read
528
+ /// it with.
529
+ fn output(op: &str, shape: &[i32], attributes: serde_json::Value, inputs: &[&[f32]]) -> Vec<f32> {
530
+ let extra = inputs.len() - 1;
531
+ let (config, weights) = fixtures::one_op(op, serde_json::json!(shape), attributes, extra);
532
+ let mut session = Session::open(&config, Weights::Inline(&weights)).unwrap();
533
+ session.tap("m.seen", "full").unwrap();
534
+
535
+ let batch: Batch = inputs
536
+ .iter()
537
+ .enumerate()
538
+ .map(|(i, data)| {
539
+ let name = if i == 0 { "x".to_string() } else { format!("v{}", i - 1) };
540
+ fixtures::field(&name, shape, data)
541
+ })
542
+ .collect();
543
+ session.evaluate(&batch).unwrap();
544
+
545
+ let seen = session.tapped().unwrap();
546
+ match &seen[0].1.values {
547
+ Values::F32(v) => v.clone(),
548
+ _ => panic!("a tapped value is f32"),
549
+ }
550
+ }
551
+
552
+ fn close(got: &[f32], want: &[f32]) {
553
+ assert_eq!(got.len(), want.len(), "{got:?} against {want:?}");
554
+ for (g, w) in got.iter().zip(want) {
555
+ assert!((g - w).abs() < 1e-5, "{got:?} against {want:?}");
556
+ }
557
+ }
558
+
559
+ /// A graph built knowing neither its batch nor its sequence still
560
+ /// splits the last axis: the 0s take whatever the array turns out to
561
+ /// have (docs/plan.md 15.63).
562
+ #[test]
563
+ fn a_reshape_keeps_the_dimensions_the_graph_never_knew() {
564
+ let (config, weights) = fixtures::one_op(
565
+ "reshape",
566
+ serde_json::json!([null, null, 4]),
567
+ serde_json::json!({"shape": [0, 0, 2, 2]}),
568
+ 0,
569
+ );
570
+ let mut session = Session::open(&config, Weights::Inline(&weights)).unwrap();
571
+ session.tap("m.seen", "full").unwrap();
572
+
573
+ for rows in [3, 7] {
574
+ let batch: Batch = [fixtures::field("x", &[rows, 5, 4], &vec![1.0f32; (rows * 20) as usize])]
575
+ .into_iter()
576
+ .collect();
577
+ session.evaluate(&batch).unwrap();
578
+ let seen = session.tapped().unwrap();
579
+ assert_eq!(seen[0].1.shape, vec![rows, 5, 2, 2]);
580
+ }
581
+ }
582
+
583
+ /// `value / x`, and at an infinite x that is 0, not NaN: the reason
584
+ /// it is an op rather than a number spread to x's shape by x * 0.
585
+ #[test]
586
+ fn a_number_divided_by_the_value_is_zero_where_the_value_is_infinite() {
587
+ let got = output(
588
+ "rdiv_scalar",
589
+ &[3],
590
+ serde_json::json!({"value": 2.0}),
591
+ &[&[4.0, -0.5, f32::INFINITY]],
592
+ );
593
+ close(&got, &[0.5, -4.0, 0.0]);
594
+ }
595
+
596
+ #[test]
597
+ fn the_elementwise_ops_are_what_they_say() {
598
+ let x = [-1.0f32, 0.0, 0.5, 2.0];
599
+ let shape = [4];
600
+ close(&output("neg", &shape, serde_json::json!({}), &[&x]), &[1.0, 0.0, -0.5, -2.0]);
601
+ close(&output("abs", &shape, serde_json::json!({}), &[&x]), &[1.0, 0.0, 0.5, 2.0]);
602
+ close(
603
+ &output("relu", &shape, serde_json::json!({}), &[&x]),
604
+ &[0.0, 0.0, 0.5, 2.0],
605
+ );
606
+ close(
607
+ &output("exp", &shape, serde_json::json!({}), &[&x]),
608
+ &[(-1.0f32).exp(), 1.0, 0.5f32.exp(), 2.0f32.exp()],
609
+ );
610
+ close(
611
+ &output("tanh", &shape, serde_json::json!({}), &[&x]),
612
+ &x.map(f32::tanh),
613
+ );
614
+ close(
615
+ &output("sigmoid", &shape, serde_json::json!({}), &[&x]),
616
+ &x.map(|v| 1.0 / (1.0 + (-v).exp())),
617
+ );
618
+ close(
619
+ &output("sqrt", &[3], serde_json::json!({}), &[&[1.0, 4.0, 9.0]]),
620
+ &[1.0, 2.0, 3.0],
621
+ );
622
+ close(
623
+ &output("log", &[3], serde_json::json!({}), &[&[1.0, std::f32::consts::E, 10.0]]),
624
+ &[0.0, 1.0, 10.0f32.ln()],
625
+ );
626
+ }
627
+
628
+ #[test]
629
+ fn gelu_is_the_exact_form_rather_than_the_tanh_approximation() {
630
+ // 0.5 x (1 + erf(x / sqrt 2)). The reference implementations of
631
+ // the models this has to match use erf, and a parity check is the
632
+ // point (docs/plan.md 9.2).
633
+ let x = [-2.0f32, -0.5, 0.0, 1.0];
634
+ let want: Vec<f32> = x
635
+ .iter()
636
+ .map(|v| {
637
+ // erf through the relation to the normal CDF, computed here
638
+ // by a series good enough for a tolerance of 1e-5.
639
+ let t = v / std::f32::consts::SQRT_2;
640
+ 0.5 * v * (1.0 + erf(t))
641
+ })
642
+ .collect();
643
+ close(&output("gelu", &[4], serde_json::json!({}), &[&x]), &want);
644
+ }
645
+
646
+ /// Abramowitz and Stegun 7.1.26, accurate to about 1.5e-7.
647
+ fn erf(x: f32) -> f32 {
648
+ let sign = if x < 0.0 { -1.0 } else { 1.0 };
649
+ let x = x.abs();
650
+ let t = 1.0 / (1.0 + 0.3275911 * x);
651
+ let y = 1.0
652
+ - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t
653
+ + 0.254829592)
654
+ * t
655
+ * (-x * x).exp();
656
+ sign * y
657
+ }
658
+
659
+ #[test]
660
+ fn softmax_sums_to_one_along_its_axis() {
661
+ let got = output("softmax", &[2, 3], serde_json::json!({"axis": -1}),
662
+ &[&[1.0, 2.0, 3.0, 0.0, 0.0, 0.0]]);
663
+ let want = {
664
+ let e: Vec<f32> = [1.0f32, 2.0, 3.0].iter().map(|v| v.exp()).collect();
665
+ let total: f32 = e.iter().sum();
666
+ let mut v: Vec<f32> = e.iter().map(|x| x / total).collect();
667
+ v.extend([1.0 / 3.0; 3]);
668
+ v
669
+ };
670
+ close(&got, &want);
671
+ }
672
+
673
+ #[test]
674
+ fn reshape_rearranges_without_moving_anything() {
675
+ // What multi-head attention needs: [seq, heads * head] becomes
676
+ // [seq, heads, head], reading in order.
677
+ let got = output(
678
+ "reshape",
679
+ &[2, 4],
680
+ serde_json::json!({"shape": [2, 2, 2]}),
681
+ &[&[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]],
682
+ );
683
+ close(&got, &[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]);
684
+ }
685
+
686
+ #[test]
687
+ fn slice_takes_a_run_of_one_axis() {
688
+ let got = output(
689
+ "slice",
690
+ &[2, 4],
691
+ serde_json::json!({"axis": 1, "start": 1, "length": 2}),
692
+ &[&[0.0, 1.0, 2.0, 3.0, 10.0, 11.0, 12.0, 13.0]],
693
+ );
694
+ close(&got, &[1.0, 2.0, 11.0, 12.0]);
695
+ }
696
+
697
+ #[test]
698
+ fn sum_reduces_the_axes_it_is_given() {
699
+ let data = [1.0f32, 2.0, 3.0, 4.0];
700
+ close(
701
+ &output("sum", &[2, 2], serde_json::json!({"axes": [1], "keepdims": false}), &[&data]),
702
+ &[3.0, 7.0],
703
+ );
704
+ close(
705
+ &output("sum", &[2, 2], serde_json::json!({"axes": null, "keepdims": false}), &[&data]),
706
+ &[10.0],
707
+ );
708
+ }
709
+
710
+ #[test]
711
+ fn layer_norm_centres_and_scales_the_last_axis() {
712
+ // Two rows, gain 1: each row becomes mean 0 and variance 1.
713
+ let got = output(
714
+ "layer_norm",
715
+ &[2, 3],
716
+ serde_json::json!({"eps": 0.0}),
717
+ &[&[1.0, 2.0, 3.0, 10.0, 20.0, 30.0], &[1.0, 1.0, 1.0, 1.0, 1.0, 1.0]],
718
+ );
719
+ // (x - mean) / sqrt(variance). Both rows come out the same,
720
+ // because normalizing is scale-free and the second row is the
721
+ // first times ten.
722
+ let s = (2.0f32 / 3.0).sqrt();
723
+ let row = [-1.0 / s, 0.0, 1.0 / s];
724
+ close(&got, &[row[0], row[1], row[2], row[0], row[1], row[2]]);
725
+ }
726
+
727
+ #[test]
728
+ fn rms_norm_scales_without_centring() {
729
+ // rms of [3, 4] is sqrt((9 + 16) / 2) = 3.5355, and no mean is
730
+ // subtracted: that is what makes it not layer_norm.
731
+ let got = output(
732
+ "rms_norm",
733
+ &[1, 2],
734
+ serde_json::json!({"eps": 0.0}),
735
+ &[&[3.0, 4.0], &[1.0, 1.0]],
736
+ );
737
+ let rms = ((9.0f32 + 16.0) / 2.0).sqrt();
738
+ close(&got, &[3.0 / rms, 4.0 / rms]);
739
+ }
740
+
741
+ #[test]
742
+ fn sdpa_with_one_key_returns_the_value_it_attends_to() {
743
+ // One query, one key: softmax over a single score is 1, so the
744
+ // answer is v exactly, whatever q and k are. Rank 4, which is
745
+ // what attention is: [batch, heads, positions, head_dim].
746
+ let got = output(
747
+ "sdpa",
748
+ &[1, 1, 1, 2],
749
+ serde_json::json!({"scale": null, "causal": false}),
750
+ &[&[0.3, -0.7], &[1.1, 2.2], &[5.0, 6.0]],
751
+ );
752
+ close(&got, &[5.0, 6.0]);
753
+ }
754
+
755
+ /// Why the fused kernel is trusted in a trainer.
756
+ ///
757
+ /// A fused op is only usable here if it differentiates, and this is
758
+ /// the check that it does. It is also where grouped-query attention
759
+ /// is answered: four query heads over two key heads, with k and v
760
+ /// untiled, which is the arrangement every decoder since Llama 2 has.
761
+ #[test]
762
+ fn the_fused_attention_differentiates_and_groups_queries() {
763
+ use crate::mlxc::transforms::value_and_grad_with_argnums;
764
+ use crate::mlxc::Array;
765
+
766
+ let q = Array::from_slice(&[0.1f32; 24], &[1, 4, 2, 3]).unwrap();
767
+ let k = Array::from_slice(&[0.2f32; 12], &[1, 2, 2, 3]).unwrap();
768
+ let v = Array::from_slice(&[0.3f32; 12], &[1, 2, 2, 3]).unwrap();
769
+
770
+ let forward = |args: &[Array]| -> Vec<Array> {
771
+ let out = crate::mlxc::fast::scaled_dot_product_attention(
772
+ &args[0], &args[1], &args[2], 0.5, None, None,
773
+ )
774
+ .expect("fused attention");
775
+ vec![out.sum(false).expect("sum")]
776
+ };
777
+ let mut vg = value_and_grad_with_argnums(forward, &[0, 1, 2][..]);
778
+ let (value, grads) = vg(&[q, k, v][..]).expect("a gradient");
779
+
780
+ // Every value is 0.3, so any weighted average of them is 0.3, and
781
+ // there are 4 heads * 2 positions * 3 wide of them.
782
+ assert!((value[0].item::<f32>().unwrap() - 0.3 * 24.0).abs() < 1e-5);
783
+ assert_eq!(grads[0].shape(), &[1, 4, 2, 3]);
784
+ assert_eq!(grads[1].shape(), &[1, 2, 2, 3], "k stays untiled");
785
+ }
786
+
787
+ #[test]
788
+ fn rope_leaves_the_first_position_alone_and_rotates_the_next() {
789
+ // At position 0 every angle is 0, so the identity. At position 1
790
+ // the first pair rotates by 1 radian (theta^0 = 1).
791
+ let got = output(
792
+ "rope",
793
+ &[2, 2],
794
+ serde_json::json!({"theta": 10000.0}),
795
+ &[&[1.0, 0.0, 1.0, 0.0]],
796
+ );
797
+ close(&got, &[1.0, 0.0, 1.0f32.cos(), 1.0f32.sin()]);
798
+ }
799
+
800
+ /// A scaled rope turns by the frequencies it was handed.
801
+ ///
802
+ /// The base is still there and is still ignored: what a model scaled
803
+ /// its frequencies to is the model's arithmetic, and the engine is
804
+ /// told the answer rather than the formula (`Op::Rope`).
805
+ #[test]
806
+ fn rope_turns_by_the_frequencies_it_is_given_rather_than_the_base() {
807
+ let got = output(
808
+ "rope",
809
+ &[2, 2],
810
+ serde_json::json!({"theta": 10000.0, "freqs": [0.25]}),
811
+ &[&[1.0, 0.0, 1.0, 0.0]],
812
+ );
813
+ // Position 0 is still the identity; position 1 turns by 0.25
814
+ // rather than by the 1 radian the base alone would have given.
815
+ close(&got, &[1.0, 0.0, 0.25f32.cos(), 0.25f32.sin()]);
816
+ }
817
+
818
+ #[test]
819
+ fn a_rope_given_the_wrong_number_of_frequencies_says_so() {
820
+ // Four dimensions want two frequencies. A description handing
821
+ // over another count has miscounted its head, and the difference
822
+ // between being told and not being told is a wrong model that
823
+ // trains.
824
+ let (config, weights) = fixtures::one_op(
825
+ "rope",
826
+ serde_json::json!([2, 4]),
827
+ serde_json::json!({"theta": 10000.0, "freqs": [0.25, 0.5, 0.75]}),
828
+ 0,
829
+ );
830
+ let mut session = Session::open(&config, Weights::Inline(&weights)).unwrap();
831
+ let batch: Batch = [fixtures::field("x", &[2, 4], &[1.0f32; 8])].into_iter().collect();
832
+
833
+ let said = session
834
+ .evaluate(&batch)
835
+ .expect_err("three frequencies for four dimensions")
836
+ .to_string();
837
+
838
+ assert!(said.contains("frequencies"), "{said}");
839
+ }
840
+
841
+ /// One node over bf16 inputs, by the interpreter alone, with the dtype
842
+ /// the graph declares for it. `params` are the model's parameters, read
843
+ /// by `parameter` nodes ahead of the op.
844
+ fn through(
845
+ op: &str,
846
+ attributes: serde_json::Value,
847
+ inputs: &[(&str, Vec<i32>)],
848
+ params: Vec<crate::mlxc::Array>,
849
+ declared: &str,
850
+ ) -> Result<crate::mlxc::Array, String> {
851
+ use crate::mlxc::{Array, Dtype};
852
+ use serde_json::json;
853
+ crate::runtime::runtime()
854
+ .execute(|| {
855
+ let specs: Vec<_> = inputs
856
+ .iter()
857
+ .enumerate()
858
+ .map(|(i, (name, shape))| fixtures::input(i, name, json!(shape), "bf16"))
859
+ .collect();
860
+ let parameters: Vec<_> = params
861
+ .iter()
862
+ .enumerate()
863
+ .map(|(i, a)| {
864
+ let mut spec = fixtures::parameter(i, &format!("p{i}"), json!(a.shape()), false);
865
+ spec["dtype"] = json!("bf16");
866
+ spec
867
+ })
868
+ .collect();
869
+ let mut nodes: Vec<_> = (0..params.len())
870
+ .map(|i| fixtures::node(i, "parameter", json!([]), json!([i])))
871
+ .collect();
872
+ let reads: Vec<String> = (0..inputs.len())
873
+ .map(|i| format!("input:{i}"))
874
+ .chain((0..params.len()).map(|i| format!("node:{i}")))
875
+ .collect();
876
+ let mut under_test = fixtures::node(nodes.len(), op, json!(reads), json!([]));
877
+ under_test["attributes"] = attributes.clone();
878
+ under_test["dtype"] = json!(declared);
879
+ nodes.push(under_test);
880
+ let graph: crate::graph::Graph = serde_json::from_value(json!({
881
+ "inputs": specs, "parameters": parameters, "nodes": nodes,
882
+ "outputs": {"y": format!("node:{}", nodes.len() - 1)},
883
+ }))
884
+ .unwrap();
885
+ let program = crate::op::Program::resolve(graph, params.len(), "m").unwrap();
886
+ let fed: std::collections::BTreeMap<String, Array> = inputs
887
+ .iter()
888
+ .map(|(name, shape)| {
889
+ let count: i32 = shape.iter().product();
890
+ let values: Vec<f32> = (0..count).map(|i| (i as f32 * 0.37).sin()).collect();
891
+ let array = Array::from_slice(&values, shape)?.as_dtype(Dtype::Bfloat16)?;
892
+ Ok((name.to_string(), array))
893
+ })
894
+ .collect::<super::Result<_>>()?;
895
+ let mut collected = super::Tapped::new();
896
+ let mut watch = super::Watch::none(&mut collected);
897
+ Ok(super::evaluate_tapped(&program, &params, &fed, None, "m", &mut watch)
898
+ .map(|mut out| out.remove("y").unwrap())
899
+ .map_err(|e| e.what().to_string()))
900
+ })
901
+ .expect("the runtime should let this through")
902
+ }
903
+
904
+ fn bf16(shape: &[i32]) -> crate::mlxc::Array {
905
+ crate::mlxc::Array::ones::<f32>(shape).unwrap().as_dtype(crate::mlxc::Dtype::Bfloat16).unwrap()
906
+ }
907
+
908
+ /// A bf16 value through any op stays bf16. Every one of these used to
909
+ /// come back f32, because the number it was combined with was made
910
+ /// as an f32 array, and MLX promotes rather than narrows: the graph
911
+ /// said bf16, and the engine computed the rest of the model in f32
912
+ /// (2026-11-09).
913
+ #[test]
914
+ fn a_bf16_value_stays_bf16_through_every_op_that_adds_a_number_of_its_own() {
915
+ use crate::mlxc::Dtype;
916
+ use serde_json::json;
917
+ let row = |name: &'static str| (name, vec![2, 4]);
918
+ let cases: Vec<(&str, serde_json::Value, Vec<(&str, Vec<i32>)>, Vec<crate::mlxc::Array>)> = vec![
919
+ ("add_scalar", json!({"value": 1.0}), vec![row("x")], vec![]),
920
+ ("sub_scalar", json!({"value": 1.0}), vec![row("x")], vec![]),
921
+ ("mul_scalar", json!({"value": 2.0}), vec![row("x")], vec![]),
922
+ ("div_scalar", json!({"value": 2.0}), vec![row("x")], vec![]),
923
+ ("rdiv_scalar", json!({"value": 2.0}), vec![row("x")], vec![]),
924
+ ("relu", json!({}), vec![row("x")], vec![]),
925
+ ("gelu", json!({}), vec![row("x")], vec![]),
926
+ ("gelu_tanh", json!({}), vec![row("x")], vec![]),
927
+ ("rms_norm", json!({"eps": 1e-6}), vec![row("x")], vec![bf16(&[4])]),
928
+ ("layer_norm", json!({"eps": 1e-5}), vec![row("x")], vec![bf16(&[4]), bf16(&[4])]),
929
+ ("rope", json!({"theta": 10000.0}), vec![row("x")], vec![]),
930
+ (
931
+ "sdpa",
932
+ json!({"scale": null, "causal": false}),
933
+ vec![("q", vec![1, 2, 4]), ("k", vec![1, 2, 4]), ("v", vec![1, 2, 4]), ("mask", vec![1, 2, 2])],
934
+ vec![],
935
+ ),
936
+ ];
937
+ for (op, attributes, inputs, params) in cases {
938
+ let out = through(op, attributes, &inputs, params, "bf16").unwrap_or_else(|e| panic!("{op}: {e}"));
939
+ assert_eq!(out.dtype(), Dtype::Bfloat16, "{op}");
940
+ }
941
+ }
942
+
943
+ /// The norms take their statistics in f32 and hand back bf16: over a
944
+ /// row of 4096, the result is the f32 answer to bf16's own precision,
945
+ /// which a mean of squares summed in bf16 would not be.
946
+ #[test]
947
+ fn a_norm_of_a_bf16_row_is_computed_wide_and_returned_narrow() {
948
+ use crate::mlxc::Dtype;
949
+ let out = through("rms_norm", serde_json::json!({"eps": 0.0}), &[("x", vec![1, 4096])], vec![bf16(&[4096])], "bf16")
950
+ .unwrap();
951
+ assert_eq!(out.dtype(), Dtype::Bfloat16);
952
+ let values = crate::runtime::runtime()
953
+ .execute(|| Ok(out.as_dtype(Dtype::Float32)?.as_slice::<f32>()?.to_vec()))
954
+ .unwrap();
955
+ // The input is sin(0.37 i) held in bf16; the answer is computed
956
+ // here in f32 from the same bf16 values.
957
+ let rms = ((0..4096).map(|i| (i as f32 * 0.37).sin()).map(|v| {
958
+ let b = half_round(v);
959
+ b * b
960
+ }).sum::<f32>() / 4096.0).sqrt();
961
+ for (i, got) in values.iter().enumerate() {
962
+ let want = half_round((i as f32 * 0.37).sin()) / rms;
963
+ assert!((got - want).abs() <= 1e-2 * (1.0 + want.abs()), "{i}: {got} for {want}");
964
+ }
965
+ }
966
+
967
+ /// bf16 by truncating an f32 to its top sixteen bits, rounded to nearest.
968
+ fn half_round(v: f32) -> f32 {
969
+ let bits = v.to_bits();
970
+ let rounded = bits.wrapping_add(0x7fff + ((bits >> 16) & 1)) & 0xffff_0000;
971
+ f32::from_bits(rounded)
972
+ }
973
+
974
+ /// A node that computes another dtype than the graph declares is
975
+ /// refused where it happens, naming the node and both dtypes, rather
976
+ /// than carrying on as a different run from the one described.
977
+ #[test]
978
+ fn a_node_that_computes_another_dtype_than_declared_is_refused() {
979
+ let said = through("mul_scalar", serde_json::json!({"value": 2.0}), &[("x", vec![2, 4])], vec![], "f32")
980
+ .expect_err("a bf16 product declared f32");
981
+ assert!(said.contains("computed Bfloat16 where the graph declares Float32"), "{said}");
982
+ assert!(said.contains("node 0"), "{said}");
983
+ }
984
+ }
985
+