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,405 @@
1
+ //! MLX's quantized matrices: a weight held in a few bits per value, with
2
+ //! a scale and a bias per group of values, and a matmul that reads it
3
+ //! packed (docs/qlora.md).
4
+ //!
5
+ //! Three calls, all of `mlx_quantize`'s family. None of them is an IR op:
6
+ //! `quantize` is what a bf16 file becomes when it is read into a run that
7
+ //! declared its base quantized, `dequantize` is how such a weight is read
8
+ //! back as numbers, and `quantized_matmul` is the one that appears in a
9
+ //! graph. The shape rules live in the IR (`lib/torobi/shape.rb`); what is
10
+ //! here is the call and what MLX says when it refuses.
11
+ //!
12
+ //! **The gradient.** MLX's `QuantizedMatmul` differentiates with respect
13
+ //! to `x`, and with respect to the scales and biases, and refuses the
14
+ //! packed weight: there is no gradient to a rounded integer. Torobi never
15
+ //! asks for any of the three (they are declared `trainable: false`, and a
16
+ //! declaration that says otherwise is refused when the graph is built), so
17
+ //! what the tests below fix is which refusals are MLX's and which are
18
+ //! Torobi's own.
19
+
20
+ use std::ffi::CStr;
21
+
22
+ use super::error::{check, Exception, Result};
23
+ use super::handle::{NoArray, Stream, Vector};
24
+ use super::{sys, Array, Dtype};
25
+
26
+ /// How the values in a group are mapped to the integers that stand for
27
+ /// them. Only `affine` (`q = round((w - bias) / scale)`), which is what
28
+ /// every published `*-4bit` checkpoint uses; MLX also has the block
29
+ /// floating-point modes (`mxfp4`, `mxfp8`, `nvfp4`), which carry no bias
30
+ /// and are not read anywhere here yet.
31
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
32
+ pub enum Mode {
33
+ Affine,
34
+ }
35
+
36
+ impl Mode {
37
+ /// The mode by the name a checkpoint's `config.json` gives it.
38
+ pub fn parse(name: &str) -> Result<Mode> {
39
+ match name {
40
+ "affine" => Ok(Mode::Affine),
41
+ other => Err(Exception::custom(format!(
42
+ "quantization mode {other:?} is not one this engine reads; affine is"
43
+ ))),
44
+ }
45
+ }
46
+
47
+ pub fn name(self) -> &'static str {
48
+ match self {
49
+ Mode::Affine => "affine",
50
+ }
51
+ }
52
+
53
+ fn as_cstr(self) -> &'static CStr {
54
+ match self {
55
+ Mode::Affine => c"affine",
56
+ }
57
+ }
58
+ }
59
+
60
+ /// What a quantized matrix was made with, which every call that reads it
61
+ /// has to be told again: nothing in the three arrays says.
62
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
63
+ pub struct Quantization {
64
+ /// How many consecutive values along the last axis share one scale
65
+ /// and one bias. MLX's kernels exist for 32, 64 and 128.
66
+ pub group_size: i32,
67
+ /// Bits per value. MLX's kernels exist for 2, 3, 4, 5, 6 and 8.
68
+ pub bits: i32,
69
+ pub mode: Mode,
70
+ }
71
+
72
+ impl Quantization {
73
+ /// How many values one `u32` of the packed weight holds, which is what
74
+ /// turns the packed shape `[d_out, d_in × bits / 32]` back into
75
+ /// `[d_out, d_in]`.
76
+ pub fn values_per_word(self) -> i32 {
77
+ 32 / self.bits
78
+ }
79
+ }
80
+
81
+ /// A matrix as `quantize` leaves it: packed `u32` values of shape
82
+ /// `[d_out, d_in × bits / 32]`, and a scale and bias per group of shape
83
+ /// `[d_out, d_in / group_size]` in the matrix's own dtype. The biases are
84
+ /// what the affine mode has and the block floating-point modes do not.
85
+ pub struct Quantized {
86
+ pub weight: Array,
87
+ pub scales: Array,
88
+ pub biases: Option<Array>,
89
+ }
90
+
91
+ fn some(value: i32) -> sys::mlx_optional_int {
92
+ sys::mlx_optional_int { value, has_value: true }
93
+ }
94
+
95
+ fn dtype_or_default(dtype: Option<Dtype>) -> sys::mlx_optional_dtype {
96
+ match dtype {
97
+ Some(dtype) => sys::mlx_optional_dtype { value: dtype.to_raw(), has_value: true },
98
+ None => sys::mlx_optional_dtype { value: Dtype::Float32.to_raw(), has_value: false },
99
+ }
100
+ }
101
+
102
+ /// `w` quantized along its last axis: `mlx_quantize`. The last dimension
103
+ /// must be a multiple of the group size, and MLX says so when it is not.
104
+ ///
105
+ /// `global_scale` is passed empty: it belongs to `nvfp4` alone.
106
+ pub fn quantize(w: impl AsRef<Array>, quantization: Quantization) -> Result<Quantized> {
107
+ let stream = Stream::current()?;
108
+ let none = NoArray::new();
109
+ let mut out = Vector::new();
110
+ check(
111
+ unsafe {
112
+ sys::mlx_quantize(
113
+ out.as_out(),
114
+ w.as_ref().as_raw(),
115
+ some(quantization.group_size),
116
+ some(quantization.bits),
117
+ quantization.mode.as_cstr().as_ptr(),
118
+ none.as_raw(),
119
+ stream.as_raw(),
120
+ )
121
+ },
122
+ "mlx_quantize",
123
+ )?;
124
+ let mut arrays = out.arrays()?;
125
+ // Affine hands back three (weight, scales, biases); the block
126
+ // floating-point modes hand back two. Read from the back so the two
127
+ // that are always there are named right either way.
128
+ let biases = if arrays.len() == 3 { arrays.pop() } else { None };
129
+ let scales = arrays
130
+ .pop()
131
+ .ok_or_else(|| Exception::custom("mlx_quantize returned no scales"))?;
132
+ let weight = arrays
133
+ .pop()
134
+ .ok_or_else(|| Exception::custom("mlx_quantize returned no weight"))?;
135
+ Ok(Quantized { weight, scales, biases })
136
+ }
137
+
138
+ /// The numbers a quantized matrix stands for, as `[d_out, d_in]` in
139
+ /// `dtype`, or in the scales' dtype when none is asked for:
140
+ /// `mlx_dequantize`.
141
+ pub fn dequantize(
142
+ weight: impl AsRef<Array>,
143
+ scales: impl AsRef<Array>,
144
+ biases: Option<&Array>,
145
+ quantization: Quantization,
146
+ dtype: Option<Dtype>,
147
+ ) -> Result<Array> {
148
+ let none = NoArray::new();
149
+ let (w, s, b) = (weight.as_ref().as_raw(), scales.as_ref().as_raw(), none.or(biases));
150
+ Array::on_stream("mlx_dequantize", |res, stream| unsafe {
151
+ sys::mlx_dequantize(
152
+ res,
153
+ w,
154
+ s,
155
+ b,
156
+ some(quantization.group_size),
157
+ some(quantization.bits),
158
+ quantization.mode.as_cstr().as_ptr(),
159
+ none.as_raw(),
160
+ dtype_or_default(dtype),
161
+ stream,
162
+ )
163
+ })
164
+ }
165
+
166
+ /// `x @ dequantize(w)ᵀ` (with `transpose`, which is how a linear's
167
+ /// `[d_out, d_in]` weight is read) or `x @ dequantize(w)`, computed from
168
+ /// the packed weight without unpacking it: `mlx_quantized_matmul`.
169
+ pub fn quantized_matmul(
170
+ x: impl AsRef<Array>,
171
+ weight: impl AsRef<Array>,
172
+ scales: impl AsRef<Array>,
173
+ biases: Option<&Array>,
174
+ transpose: bool,
175
+ quantization: Quantization,
176
+ ) -> Result<Array> {
177
+ let none = NoArray::new();
178
+ let (x, w, s, b) = (
179
+ x.as_ref().as_raw(),
180
+ weight.as_ref().as_raw(),
181
+ scales.as_ref().as_raw(),
182
+ none.or(biases),
183
+ );
184
+ Array::on_stream("mlx_quantized_matmul", |res, stream| unsafe {
185
+ sys::mlx_quantized_matmul(
186
+ res,
187
+ x,
188
+ w,
189
+ s,
190
+ b,
191
+ transpose,
192
+ some(quantization.group_size),
193
+ some(quantization.bits),
194
+ quantization.mode.as_cstr().as_ptr(),
195
+ stream,
196
+ )
197
+ })
198
+ }
199
+
200
+ #[cfg(test)]
201
+ mod tests {
202
+ use super::*;
203
+ use crate::mlxc::transforms::value_and_grad_with_argnums;
204
+ use crate::runtime;
205
+
206
+ fn run<R>(f: impl FnOnce() -> Result<R>) -> R {
207
+ runtime::runtime()
208
+ .execute(|| Ok(f()?))
209
+ .expect("the runtime should let this through")
210
+ }
211
+
212
+ fn values(a: &Array) -> Vec<f32> {
213
+ a.as_dtype(Dtype::Float32).unwrap().contiguous().unwrap().as_slice::<f32>().unwrap().to_vec()
214
+ }
215
+
216
+ /// The quantization every published `*-4bit` checkpoint was made with.
217
+ const FOUR_BIT_G64: Quantization = Quantization { group_size: 64, bits: 4, mode: Mode::Affine };
218
+
219
+ /// A `[d_out, d_in]` matrix with a different spread in every row, so a
220
+ /// group's scale and bias both matter: row r holds values in
221
+ /// `[-(r + 1) / d_out, (r + 1) / d_out]`, not on the grid.
222
+ fn weight(d_out: usize, d_in: usize) -> Vec<f32> {
223
+ (0..d_out * d_in)
224
+ .map(|i| {
225
+ let (r, c) = (i / d_in, i % d_in);
226
+ let range = (r + 1) as f32 / d_out as f32;
227
+ range * ((c as f32 * 0.37 + r as f32 * 1.3).sin())
228
+ })
229
+ .collect()
230
+ }
231
+
232
+ fn matrix(d_out: usize, d_in: usize) -> Result<Array> {
233
+ Array::from_slice(&weight(d_out, d_in), &[d_out as i32, d_in as i32])
234
+ }
235
+
236
+ fn close(got: &[f32], want: &[f32], tolerance: f32) {
237
+ assert_eq!(got.len(), want.len());
238
+ for (g, w) in got.iter().zip(want) {
239
+ assert!(
240
+ (g - w).abs() <= tolerance * (1.0 + w.abs()),
241
+ "{g} against {w} (tolerance {tolerance})"
242
+ );
243
+ }
244
+ }
245
+
246
+ /// The three arrays have the shapes and dtypes docs/qlora.md section
247
+ /// 2.4 says, which are the shapes a checkpoint holds them in.
248
+ #[test]
249
+ fn a_quantized_matrix_is_a_packed_weight_and_a_scale_and_bias_per_group() {
250
+ let (w, s, b) = run(|| {
251
+ let q = quantize(matrix(8, 128)?, FOUR_BIT_G64)?;
252
+ let b = q.biases.expect("affine has biases");
253
+ Ok((
254
+ (q.weight.dtype(), q.weight.shape().to_vec()),
255
+ (q.scales.dtype(), q.scales.shape().to_vec()),
256
+ (b.dtype(), b.shape().to_vec()),
257
+ ))
258
+ });
259
+ assert_eq!(w, (Dtype::Uint32, vec![8, 128 * 4 / 32]));
260
+ assert_eq!(s, (Dtype::Float32, vec![8, 2]));
261
+ assert_eq!(b, (Dtype::Float32, vec![8, 2]));
262
+ }
263
+
264
+ /// Four bits put sixteen points across a group's range, so nothing
265
+ /// comes back further from where it was than one step of that grid,
266
+ /// and something comes back moved: a round trip that lost nothing
267
+ /// would mean the test is not quantizing.
268
+ #[test]
269
+ fn the_round_trip_error_is_within_one_step_of_the_grid() {
270
+ let (d_out, d_in) = (8, 128);
271
+ let original = weight(d_out, d_in);
272
+ let back = run(|| {
273
+ let q = quantize(matrix(d_out, d_in)?, FOUR_BIT_G64)?;
274
+ Ok(values(&dequantize(&q.weight, &q.scales, q.biases.as_ref(), FOUR_BIT_G64, None)?))
275
+ });
276
+ assert_eq!(back.len(), original.len());
277
+ let mut moved = false;
278
+ for r in 0..d_out {
279
+ for g in 0..d_in / 64 {
280
+ let group = r * d_in + g * 64..r * d_in + (g + 1) * 64;
281
+ let (lo, hi) = original[group.clone()]
282
+ .iter()
283
+ .fold((f32::MAX, f32::MIN), |(lo, hi), &v| (lo.min(v), hi.max(v)));
284
+ let step = (hi - lo) / 15.0;
285
+ for i in group {
286
+ let error = (back[i] - original[i]).abs();
287
+ assert!(error <= step + 1e-6, "row {r}: {} came back as {} (step {step})", original[i], back[i]);
288
+ moved |= error > 1e-6;
289
+ }
290
+ }
291
+ }
292
+ assert!(moved, "a 4-bit round trip changes something");
293
+ }
294
+
295
+ /// The packed matmul and the unpacked one are the same product. In
296
+ /// f32 to the accumulation order; in bf16, the dtype a model is held
297
+ /// in, to one rounding of the output.
298
+ ///
299
+ /// The reference is taken in f32 either way. The kernel unpacks each
300
+ /// weight as `scale · q + bias` in f32 and rounds only its result,
301
+ /// while a bf16 `dequantize` rounds every weight before the product:
302
+ /// 128 of those roundings summed came to 2 % where one rounding of
303
+ /// the output is 0.4 %, which is what the first version of this test
304
+ /// found (2026-11-08).
305
+ #[test]
306
+ fn quantized_matmul_is_the_matmul_of_the_dequantized_weight() {
307
+ for (dtype, tolerance) in [(Dtype::Float32, 1e-4), (Dtype::Bfloat16, 1e-2)] {
308
+ let (got, want) = run(|| {
309
+ let w = matrix(8, 128)?.as_dtype(dtype)?;
310
+ let x = Array::from_slice(&weight(3, 128), &[3, 128])?.as_dtype(dtype)?;
311
+ let q = quantize(&w, FOUR_BIT_G64)?;
312
+ let packed = quantized_matmul(&x, &q.weight, &q.scales, q.biases.as_ref(), true, FOUR_BIT_G64)?;
313
+ let unpacked =
314
+ dequantize(&q.weight, &q.scales, q.biases.as_ref(), FOUR_BIT_G64, Some(Dtype::Float32))?;
315
+ let plain = x.as_dtype(Dtype::Float32)?.matmul(unpacked.transpose_axes(&[1, 0])?)?;
316
+ assert_eq!(packed.dtype(), dtype);
317
+ assert_eq!(packed.shape(), &[3, 8]);
318
+ Ok((values(&packed), values(&plain)))
319
+ });
320
+ close(&got, &want, tolerance);
321
+ }
322
+ }
323
+
324
+ /// d/dx of sum(x Wᵀ) is a row of column sums of W, for every row of
325
+ /// x: the gradient a LoRA's activations need, and the one MLX has.
326
+ #[test]
327
+ fn the_gradient_with_respect_to_x_comes_back() {
328
+ let (grad, shape, want) = run(|| {
329
+ let q = quantize(matrix(8, 128)?, FOUR_BIT_G64)?;
330
+ let x = Array::from_slice(&weight(3, 128), &[3, 128])?;
331
+ let unpacked = dequantize(&q.weight, &q.scales, q.biases.as_ref(), FOUR_BIT_G64, None)?;
332
+ let want = values(&unpacked.sum_axes(&[0], false)?);
333
+ let biases = q.biases.as_ref();
334
+ let f = |inputs: &[Array]| -> Result<Vec<Array>> {
335
+ Ok(vec![quantized_matmul(&inputs[0], &q.weight, &q.scales, biases, true, FOUR_BIT_G64)?.sum(false)?])
336
+ };
337
+ let (_, grads) = value_and_grad_with_argnums(f, &[0])(std::slice::from_ref(&x))?;
338
+ Ok((values(&grads[0]), grads[0].shape().to_vec(), want))
339
+ });
340
+ assert_eq!(shape, vec![3, 128]);
341
+ for row in grad.chunks(128) {
342
+ close(row, &want, 1e-4);
343
+ }
344
+ }
345
+
346
+ /// There is no gradient to the packed weight, and MLX is the one that
347
+ /// says so. This is the fact docs/qlora.md section 3.2 rests on: a
348
+ /// quantized weight cannot be trained, so a graph that declares one
349
+ /// trainable is refused before MLX would be asked.
350
+ #[test]
351
+ fn the_gradient_with_respect_to_the_packed_weight_is_mlx_s_refusal() {
352
+ let said = run(|| {
353
+ let q = quantize(matrix(8, 128)?, FOUR_BIT_G64)?;
354
+ let x = Array::from_slice(&weight(3, 128), &[3, 128])?;
355
+ let biases = q.biases.expect("affine has biases");
356
+ let f = |inputs: &[Array]| -> Result<Vec<Array>> {
357
+ Ok(vec![quantized_matmul(&inputs[0], &inputs[1], &inputs[2], Some(&inputs[3]), true, FOUR_BIT_G64)?
358
+ .sum(false)?])
359
+ };
360
+ let refused = value_and_grad_with_argnums(f, &[1])(&[x, q.weight, q.scales, biases]);
361
+ Ok(refused.err().map(|e| e.what().to_string()))
362
+ });
363
+ assert!(said.is_some(), "MLX differentiated a packed weight");
364
+ }
365
+
366
+ /// The scales and biases do have a gradient in MLX. Torobi does not
367
+ /// train them either, and that is Torobi's policy rather than MLX's
368
+ /// limit, which is why this is pinned next to the refusal above: if
369
+ /// MLX ever stops handing these back, section 3.2 has to change with
370
+ /// this test, not quietly.
371
+ #[test]
372
+ fn the_gradients_with_respect_to_scales_and_biases_are_mlx_s_to_give() {
373
+ let shapes = run(|| {
374
+ let q = quantize(matrix(8, 128)?, FOUR_BIT_G64)?;
375
+ let x = Array::from_slice(&weight(3, 128), &[3, 128])?;
376
+ let biases = q.biases.expect("affine has biases");
377
+ let f = |inputs: &[Array]| -> Result<Vec<Array>> {
378
+ Ok(vec![quantized_matmul(&inputs[0], &inputs[1], &inputs[2], Some(&inputs[3]), true, FOUR_BIT_G64)?
379
+ .sum(false)?])
380
+ };
381
+ let (_, grads) = value_and_grad_with_argnums(f, &[2, 3])(&[x, q.weight, q.scales, biases])?;
382
+ Ok(grads.iter().map(|g| (g.dtype(), g.shape().to_vec())).collect::<Vec<_>>())
383
+ });
384
+ assert_eq!(shapes, vec![(Dtype::Float32, vec![8, 2]), (Dtype::Float32, vec![8, 2])]);
385
+ }
386
+
387
+ /// A last dimension the group size does not divide is MLX's refusal,
388
+ /// in MLX's words. The IR refuses it earlier, with the linear's name;
389
+ /// this fixes what the engine would say if something got past.
390
+ #[test]
391
+ fn a_width_the_group_size_does_not_divide_is_refused_by_mlx() {
392
+ let said = run(|| Ok(quantize(matrix(4, 48)?, FOUR_BIT_G64).err().map(|e| e.what().to_string())));
393
+ let said = said.expect("48 is not a multiple of 64");
394
+ assert!(said.contains("quantize") || said.contains("group"), "{said}");
395
+ }
396
+
397
+ #[test]
398
+ fn a_mode_is_read_by_the_name_a_checkpoint_gives_it() {
399
+ assert_eq!(Mode::parse("affine").unwrap(), Mode::Affine);
400
+ assert_eq!(Mode::Affine.name(), "affine");
401
+ let said = Mode::parse("mxfp4").unwrap_err();
402
+ assert!(said.what().contains("mxfp4"), "{}", said.what());
403
+ assert_eq!(FOUR_BIT_G64.values_per_word(), 8);
404
+ }
405
+ }
@@ -0,0 +1,161 @@
1
+ //! Keys and draws.
2
+ //!
3
+ //! Every draw takes its key from the caller, by type: there is no global
4
+ //! state to fall back on. mlx-rs kept one, seeded from a clock, and on
5
+ //! Linux that clock is what failed to link (docs/vendoring.md). The engine
6
+ //! never wanted it, because a run is reproducible only if every draw comes
7
+ //! from the run's seed.
8
+
9
+ use super::error::Result;
10
+ use super::{sys, Array, ArrayElement};
11
+
12
+ /// A key from a seed.
13
+ pub fn key(seed: u64) -> Result<Array> {
14
+ Array::try_from_op("mlx_random_key", |res| unsafe { sys::mlx_random_key(res, seed) })
15
+ }
16
+
17
+ /// Two keys from one, as mlx-rs returned them: split `num` ways, then the
18
+ /// first and second of those. The engine asks for two and uses both.
19
+ pub fn split(key: &Array, num: i32) -> Result<(Array, Array)> {
20
+ let keys = Array::on_stream("mlx_random_split_num", |res, s| unsafe {
21
+ sys::mlx_random_split_num(res, key.as_raw(), num, s)
22
+ })?;
23
+ Ok((keys.take_axis(Array::from_i32(0)?, 0)?, keys.take_axis(Array::from_i32(1)?, 0)?))
24
+ }
25
+
26
+ /// The `part`th key of `key` (`part` of 1 or more): split `part + 2` ways and take the
27
+ /// last. Another key for each part of a step that is accumulated, so that the parts do not
28
+ /// all draw the masks the step's first one draws. Not the second of a two-way split, which is
29
+ /// the draw a pass makes for its own first random op.
30
+ pub fn part(key: &Array, part: i32) -> Result<Array> {
31
+ let keys = Array::on_stream("mlx_random_split_num", |res, s| unsafe {
32
+ sys::mlx_random_split_num(res, key.as_raw(), part + 2, s)
33
+ })?;
34
+ keys.take_axis(Array::from_i32(part + 1)?, 0)
35
+ }
36
+
37
+ /// Uniform on [lower, upper), in `T`'s dtype.
38
+ pub fn uniform<T: ArrayElement>(lower: f32, upper: f32, shape: &[i32], key: &Array) -> Result<Array> {
39
+ let (lower, upper) = (Array::from_f32(lower)?, Array::from_f32(upper)?);
40
+ Array::on_stream("mlx_random_uniform", |res, s| unsafe {
41
+ sys::mlx_random_uniform(
42
+ res,
43
+ lower.as_raw(),
44
+ upper.as_raw(),
45
+ shape.as_ptr(),
46
+ shape.len(),
47
+ T::DTYPE.to_raw(),
48
+ key.as_raw(),
49
+ s,
50
+ )
51
+ })
52
+ }
53
+
54
+ /// Normal with mean `loc` and standard deviation `scale`, in `T`'s dtype.
55
+ pub fn normal<T: ArrayElement>(shape: &[i32], loc: f32, scale: f32, key: &Array) -> Result<Array> {
56
+ Array::on_stream("mlx_random_normal", |res, s| unsafe {
57
+ sys::mlx_random_normal(res, shape.as_ptr(), shape.len(), T::DTYPE.to_raw(), loc, scale, key.as_raw(), s)
58
+ })
59
+ }
60
+
61
+ /// `true` with probability `p` at each position of `shape`.
62
+ pub fn bernoulli(p: &Array, shape: &[i32], key: &Array) -> Result<Array> {
63
+ Array::on_stream("mlx_random_bernoulli", |res, s| unsafe {
64
+ sys::mlx_random_bernoulli(res, p.as_raw(), shape.as_ptr(), shape.len(), key.as_raw(), s)
65
+ })
66
+ }
67
+
68
+ #[cfg(test)]
69
+ mod tests {
70
+ use super::*;
71
+ use crate::mlxc::Dtype;
72
+ use crate::runtime;
73
+
74
+ fn run<R>(f: impl FnOnce() -> Result<R>) -> R {
75
+ runtime::runtime()
76
+ .execute(|| Ok(f()?))
77
+ .expect("the runtime should let this through")
78
+ }
79
+
80
+ /// The numbers a seed draws are MLX's, and not the binding's to
81
+ /// change: a checkpoint written before the move resumes into the same
82
+ /// dropout masks after it. These are what mlx-rs 0.32.0 drew from
83
+ /// seed 42, recorded through it before the move.
84
+ ///
85
+ /// The keys and the keep/drop mask are integers and exact on every
86
+ /// backend. The float draws are MLX's sampler in that backend's
87
+ /// arithmetic: on Metal they match the recording to the bit, and on
88
+ /// CUDA they differ in the last place or two. The same seed is the
89
+ /// same stream, not the same bits (docs/plan.md section 9.2).
90
+ #[test]
91
+ fn a_seed_draws_what_it_drew_through_mlx_rs() {
92
+ let (key, first, second, normal, uniform, kept) = run(|| {
93
+ let root = key(42)?;
94
+ let (first, second) = split(&root, 2)?;
95
+ let normal = super::normal::<f32>(&[3], 0.0, 0.02, &first)?;
96
+ let uniform = super::uniform::<f32>(-0.5, 0.5, &[3], &second)?;
97
+ let kept = bernoulli(&Array::from_f32(0.75)?, &[8], &first)?;
98
+ Ok((
99
+ root.as_slice::<u32>()?.to_vec(),
100
+ first.as_slice::<u32>()?.to_vec(),
101
+ second.as_slice::<u32>()?.to_vec(),
102
+ normal.as_slice::<f32>()?.to_vec(),
103
+ uniform.as_slice::<f32>()?.to_vec(),
104
+ kept.as_slice::<bool>()?.to_vec(),
105
+ ))
106
+ });
107
+ assert_eq!(key, RECORDED.key);
108
+ assert_eq!(first, RECORDED.first);
109
+ assert_eq!(second, RECORDED.second);
110
+ assert_draw(&normal, &RECORDED.normal);
111
+ assert_draw(&uniform, &RECORDED.uniform);
112
+ assert_eq!(kept, RECORDED.kept);
113
+ }
114
+
115
+ /// The recorded draw to the bit on the backend it was recorded on,
116
+ /// and within f32 rounding elsewhere.
117
+ #[cfg(target_os = "macos")]
118
+ fn assert_draw(got: &[f32], want: &[f32]) {
119
+ assert_eq!(got, want);
120
+ }
121
+
122
+ #[cfg(not(target_os = "macos"))]
123
+ fn assert_draw(got: &[f32], want: &[f32]) {
124
+ assert_eq!(got.len(), want.len());
125
+ for (got, want) in got.iter().zip(want) {
126
+ assert!(
127
+ (got - want).abs() <= 1e-6 * want.abs().max(1.0),
128
+ "{got} is not within f32 rounding of {want}"
129
+ );
130
+ }
131
+ }
132
+
133
+ struct Recorded {
134
+ key: [u32; 2],
135
+ first: [u32; 2],
136
+ second: [u32; 2],
137
+ normal: [f32; 3],
138
+ uniform: [f32; 3],
139
+ kept: [bool; 8],
140
+ }
141
+
142
+ const RECORDED: Recorded = Recorded {
143
+ key: [0, 42],
144
+ first: [2465931498, 3679230171],
145
+ second: [255383827, 267815257],
146
+ normal: [0.012666016, 0.019221846, 0.02725154],
147
+ uniform: [-0.21482974, 0.111944914, -0.32434744],
148
+ kept: [true, true, true, false, true, true, false, true],
149
+ };
150
+
151
+ #[test]
152
+ fn a_draw_has_the_shape_and_dtype_it_was_asked_for() {
153
+ let got = run(|| {
154
+ let k = key(1)?;
155
+ let n = normal::<f32>(&[2, 3], 0.0, 1.0, &k)?;
156
+ let b = bernoulli(&Array::from_f32(0.5)?, &[4], &k)?;
157
+ Ok((n.shape().to_vec(), n.dtype(), b.shape().to_vec(), b.dtype()))
158
+ });
159
+ assert_eq!(got, (vec![2, 3], Dtype::Float32, vec![4], Dtype::Bool));
160
+ }
161
+ }