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,1638 @@
1
+ //! What a run is going to do, decided once when it opens.
2
+ //!
3
+ //! A GraphConfig says which models exist, which are trained, and how the
4
+ //! objective reads them. None of that changes while a run goes, so it is
5
+ //! settled here: the models in order, where each one's parameters sit in
6
+ //! the flat vector, what the batch must supply, and which positions
7
+ //! autodiff differentiates.
8
+ //!
9
+ //! Separating it from the state (`TrainState`) and from the running
10
+ //! (`Executor`) is what lets each be read on its own.
11
+
12
+ use std::collections::BTreeMap;
13
+ use std::ops::Range;
14
+ use std::path::Path;
15
+
16
+ use anyhow::{Context, Result};
17
+ use crate::mlxc::quantized::{dequantize, quantize, Mode, Quantization, Quantized};
18
+ use crate::mlxc::transforms::eval;
19
+ use crate::mlxc::{Array, Dtype};
20
+ use serde::Deserialize;
21
+
22
+ use crate::graph::{GraphConfig, InputSpec, ParameterSpec, Ref};
23
+ use crate::op::{qualified, Op, Program, OBJECTIVE};
24
+ use crate::tensor::{dtype_named, Tensor};
25
+
26
+ /// How many bytes of parameters are made between two evaluations when a
27
+ /// run opens.
28
+ ///
29
+ /// One evaluation for every parameter at once was what the plan did
30
+ /// first, and it held the whole file at the peak: MLX starts every read
31
+ /// before any quantize that consumes one has run, so opening a bf16
32
+ /// Qwen2.5-0.5B as a 4-bit model peaked at 1.03 GiB for 0.44 GiB of
33
+ /// result (2026-11-08), which on a 7B is 14 GiB for 4.7. Evaluating every
34
+ /// so many bytes lets each batch of reads be consumed and freed before
35
+ /// the next starts, so the peak is what has been made plus about this
36
+ /// much more of what it is made from (3.5 times it, where the bytes made
37
+ /// are packed 4-bit and the bytes read are bf16). Small enough that the
38
+ /// overshoot is noise against a model worth quantizing; large enough
39
+ /// that a 0.5B model is a handful of evaluations, not hundreds.
40
+ pub const EVAL_BUDGET: usize = 64 << 20;
41
+
42
+ /// Where a run's initial parameters come from.
43
+ ///
44
+ /// Named rather than inferred from a type, because there will be more than
45
+ /// two: a GraphConfig already declares an initializer per parameter, so a
46
+ /// run that starts from those and a seed is a natural third.
47
+ pub enum Weights<'a> {
48
+ /// Values, as JSON: {"params": {path => {"shape": [..], "data": [..]}}}.
49
+ /// What a spike and a test use, and what the boundary carried when
50
+ /// there was nothing else. Not for a real model: 130M parameters as
51
+ /// JSON numbers is gigabytes of text on a path that is measured in
52
+ /// milliseconds per step.
53
+ Inline(&'a str),
54
+ /// A safetensors file, read by the engine. Its keys are the qualified
55
+ /// paths the graph declares ("student.linear.weight"), which is also
56
+ /// how a checkpoint names them, so a run can start from what another
57
+ /// run reached.
58
+ File(&'a Path),
59
+ /// One published checkpoint per model, by model name.
60
+ ///
61
+ /// A model published on its own does not know it will be called
62
+ /// "student" here, so its tensors are named without that: ruri-v3's
63
+ /// file holds `embeddings.tok_embeddings.weight`, not
64
+ /// `student.embeddings...`. Naming a file per model is what lets a
65
+ /// published checkpoint be imported with no renaming at all, and it is
66
+ /// the shape a distillation wants anyway, having two of them.
67
+ ///
68
+ /// `fresh` names the parameters that are *expected* to be in no file
69
+ /// and are built from their declared initializers instead: the
70
+ /// classification head put on top of a published encoder exists in no
71
+ /// checkpoint. Patterns, as freezing uses them
72
+ /// ("student.head.*"), and everything they do not name must be in its
73
+ /// file. Saying which are new is the caller's intent; a name missing
74
+ /// because it was mistyped should still be an error, and it is.
75
+ ///
76
+ /// A weight the file holds quantized (a packed u32 `.weight` with a
77
+ /// `.scales` beside it, as mlx-lm publishes them) and the graph
78
+ /// declares as numbers is read as the numbers it stands for
79
+ /// (docs/qlora.md section 3.4 (A')). A published 4-bit checkpoint
80
+ /// quantizes its embedding too, and Torobi holds embeddings in bf16.
81
+ ///
82
+ /// The other way round as well: a weight the graph declares packed
83
+ /// (three parameters read by one `quantized_matmul`) and the file
84
+ /// holds as numbers is quantized as it is read, once per weight,
85
+ /// to what the matmul says (section 3.4 (B)). That is how a bf16
86
+ /// checkpoint opens as a quantized model.
87
+ Pretrained {
88
+ files: &'a BTreeMap<String, std::path::PathBuf>,
89
+ fresh: &'a [String],
90
+ },
91
+ }
92
+
93
+ /// How a packed u32 parameter is read back as the numbers it stands for:
94
+ /// the quantization the `quantized_matmul` that consumes it names, and
95
+ /// where that matmul's scales and biases sit in the parameter vector.
96
+ /// The three arrays themselves say none of this.
97
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
98
+ pub struct Packed {
99
+ pub quantization: Quantization,
100
+ pub scales: usize,
101
+ pub biases: Option<usize>,
102
+ }
103
+
104
+ /// One model as the plan holds it: its program, and where its parameters
105
+ /// sit in the run's flat parameter vector.
106
+ pub struct Model {
107
+ pub name: String,
108
+ /// Resolved when the plan opened, so a step reads values rather than
109
+ /// JSON (`crate::op`).
110
+ pub program: Program,
111
+ /// Range into the parameter vector, in the order the config declared.
112
+ pub slice: Range<usize>,
113
+ }
114
+
115
+ /// One initial parameter as JSON carries it. Parameters are f32 (the
116
+ /// engine differentiates them), so this needs no dtype; a batch does, and
117
+ /// travels packed instead.
118
+ #[derive(Deserialize)]
119
+ struct InitialTensor {
120
+ shape: Vec<i32>,
121
+ data: Vec<f32>,
122
+ }
123
+
124
+ #[derive(Deserialize)]
125
+ struct WeightsJson {
126
+ params: BTreeMap<String, InitialTensor>,
127
+ }
128
+
129
+ /// The shape of a run: everything settled before the first step.
130
+ pub struct Plan {
131
+ pub models: Vec<Model>,
132
+ /// The program that reaches the loss. When a config declares none, the
133
+ /// single model's own output is the loss.
134
+ pub objective: Option<Program>,
135
+ /// Qualified paths ("student.head.weight"), parallel to the parameter
136
+ /// vector. This order is the contract checkpoints follow.
137
+ pub paths: Vec<String>,
138
+ /// Positions the config declared trainable: the bounds within which
139
+ /// freezing moves.
140
+ pub candidates: Vec<i32>,
141
+ /// The digest of exactly the bytes the caller handed over, which is
142
+ /// what the Ruby side computed and what a checkpoint records.
143
+ pub config_digest: String,
144
+ /// Those bytes themselves. A checkpoint carries them, so that what it
145
+ /// holds can be read without the run that wrote it: a digest names a
146
+ /// description, it does not reconstruct one (docs/plan.md 11.2).
147
+ pub graph_json: String,
148
+ pub semantics_version: u32,
149
+ /// Every batch field the run reads, sorted and without repeats.
150
+ /// Settled here rather than derived per step: this module's whole
151
+ /// claim is that it does not move after `open`.
152
+ input_names: Vec<String>,
153
+ /// Every name a tap could ask for.
154
+ node_names: Vec<String>,
155
+ output_names: Vec<String>,
156
+ /// What each parameter is declared as, parallel to `paths`: what the
157
+ /// parameters are made from when the plan is materialized.
158
+ specs: Vec<ParameterSpec>,
159
+ /// The packed quantized weights, by position, with what reads each
160
+ /// one back as numbers (`TrainState::fetch`).
161
+ pub packed: BTreeMap<usize, Packed>,
162
+ }
163
+
164
+ impl Plan {
165
+ /// Reads a GraphConfig and its initial parameters, returning the plan
166
+ /// and the parameters in the order the plan names them.
167
+ ///
168
+ /// Seedless, so only for the tests: a run states its seed, because a
169
+ /// parameter built from its declaration is drawn from where the first
170
+ /// step will draw from.
171
+ #[cfg(test)]
172
+ pub fn open(graph_json: &str, weights: Weights<'_>) -> Result<(Self, Vec<Array>)> {
173
+ Self::open_seeded(graph_json, weights, 0)
174
+ }
175
+
176
+ /// The same, with the seed the fresh parameters are drawn from.
177
+ ///
178
+ /// Explicit because a run that starts partly from initializers is
179
+ /// reproducible only if that draw is (docs/plan.md 11.1).
180
+ pub fn open_seeded(
181
+ graph_json: &str,
182
+ weights: Weights<'_>,
183
+ seed: u64,
184
+ ) -> Result<(Self, Vec<Array>)> {
185
+ Self::open_budgeted(graph_json, weights, seed, EVAL_BUDGET)
186
+ }
187
+
188
+ /// The same, evaluating every `budget` bytes of parameters rather than
189
+ /// at [`EVAL_BUDGET`]: what the tests measure the peak with.
190
+ pub(crate) fn open_budgeted(
191
+ graph_json: &str,
192
+ weights: Weights<'_>,
193
+ seed: u64,
194
+ budget: usize,
195
+ ) -> Result<(Self, Vec<Array>)> {
196
+ let plan = Self::resolve(graph_json)?;
197
+ let mut source = Source::read(weights)?;
198
+ source.seed(seed)?;
199
+ // `materialize` consumes the source: a file's arrays are lazy
200
+ // until asked, and evaluating is what reads them. Nothing but the
201
+ // parameters themselves may hold them by then, or a weight the
202
+ // file holds in one form and the run in another (a bf16 embedding
203
+ // published quantized, docs/qlora.md 3.4) would be held twice
204
+ // until the source went. It evaluates as it goes, every `budget`
205
+ // bytes, which is what bounds the peak (`EVAL_BUDGET`).
206
+ let params = source.materialize(&plan, budget)?;
207
+ // Whatever is left since the last evaluation.
208
+ eval(params.iter())?;
209
+ Ok((plan, params))
210
+ }
211
+
212
+ /// The description, resolved and checked, and nothing made: no file is
213
+ /// read and MLX is not reached. What the parameters will be is decided
214
+ /// here (their paths, which are trainable, what each is declared as);
215
+ /// making them is `Source::materialize`'s.
216
+ pub fn resolve(graph_json: &str) -> Result<Self> {
217
+ let config_digest = crate::graph::digest(graph_json);
218
+ let config: GraphConfig = serde_json::from_str(graph_json).context("parsing the graph")?;
219
+ anyhow::ensure!(!config.models.is_empty(), "the graph has no models");
220
+
221
+ let mut models = Vec::new();
222
+ let mut paths = Vec::new();
223
+ let mut specs = Vec::new();
224
+ let mut candidates = Vec::new();
225
+ let mut packed = BTreeMap::new();
226
+ for (name, mut graph) in config.models {
227
+ let trained = config.train.contains(&name);
228
+ let start = paths.len();
229
+ for spec in std::mem::take(&mut graph.parameters) {
230
+ if trained && spec.trainable {
231
+ candidates.push(paths.len() as i32);
232
+ }
233
+ paths.push(format!("{name}.{}", spec.path));
234
+ specs.push(spec);
235
+ }
236
+ let slice = start..paths.len();
237
+ let program = Program::resolve(graph, slice.len(), &name)?;
238
+ packed.extend(packed_weights(&program, start));
239
+ models.push(Model {
240
+ name,
241
+ program,
242
+ slice,
243
+ });
244
+ }
245
+ // A run that names no model differentiates nothing, and has said
246
+ // so: a graph opened to be read (a loss over representations from
247
+ // somewhere else) trains nothing by design. Naming models and
248
+ // then having no parameters among them is still the mistake it
249
+ // was, and is still refused here rather than at step one.
250
+ anyhow::ensure!(
251
+ !candidates.is_empty() || config.train.is_empty(),
252
+ "nothing to train: no model in {:?} has trainable parameters",
253
+ config.train
254
+ );
255
+
256
+ let objective = config
257
+ .objective
258
+ .map(|graph| Program::resolve(graph, 0, OBJECTIVE))
259
+ .transpose()?;
260
+ Ok(Self {
261
+ input_names: input_names(&models, objective.as_ref()),
262
+ node_names: node_names(&models, objective.as_ref()),
263
+ output_names: output_names(&models),
264
+ models,
265
+ objective,
266
+ paths,
267
+ candidates,
268
+ config_digest,
269
+ graph_json: graph_json.to_string(),
270
+ semantics_version: config.semantics_version,
271
+ specs,
272
+ packed,
273
+ })
274
+ }
275
+
276
+ /// Every program a run evaluates, models first.
277
+ pub fn programs(&self) -> impl Iterator<Item = &Program> {
278
+ self.models
279
+ .iter()
280
+ .map(|m| &m.program)
281
+ .chain(self.objective.iter())
282
+ }
283
+
284
+ /// Every batch field the run reads.
285
+ pub fn input_names(&self) -> &[String] {
286
+ &self.input_names
287
+ }
288
+
289
+ /// Every name a tap could ask for.
290
+ pub fn node_names(&self) -> &[String] {
291
+ &self.node_names
292
+ }
293
+
294
+ /// Every model output a forward pass can be asked for, qualified by
295
+ /// the model that declares it.
296
+ pub fn output_names(&self) -> &[String] {
297
+ &self.output_names
298
+ }
299
+
300
+ /// The model and the output a qualified name refers to.
301
+ ///
302
+ /// **Found rather than parsed.** The names are made here, by joining
303
+ /// with a dot, and an output's own name may hold one: a two-tower
304
+ /// model declares "queries.embedding", so "m.queries.embedding"
305
+ /// cannot be taken apart by looking at it. Splitting at the first dot
306
+ /// is right only while no model name holds one, which is a promise
307
+ /// the caller makes and this side should not depend on.
308
+ pub fn output_named(&self, name: &str) -> Option<(&str, &str)> {
309
+ self.models.iter().find_map(|model| {
310
+ model
311
+ .program
312
+ .outputs
313
+ .iter()
314
+ .find(|(output, _)| qualified(&model.name, output) == name)
315
+ .map(|(output, _)| (model.name.as_str(), output.as_str()))
316
+ })
317
+ }
318
+
319
+ pub fn index_of(&self, path: &str) -> Option<usize> {
320
+ self.paths.iter().position(|p| p == path)
321
+ }
322
+
323
+ /// The qualified paths at the given positions, in that order.
324
+ pub fn paths_of(&self, positions: &[i32]) -> Vec<String> {
325
+ positions
326
+ .iter()
327
+ .map(|&i| self.paths[i as usize].clone())
328
+ .collect()
329
+ }
330
+
331
+ /// Every parameter a model declared trainable, whether or not it is
332
+ /// frozen right now: the set freezing and unfreezing move within.
333
+ pub fn candidate_paths(&self) -> Vec<String> {
334
+ self.paths_of(&self.candidates)
335
+ }
336
+
337
+ /// Turns a batch into the fields the run reads, refusing anything no
338
+ /// graph declared and anything a graph declared but the batch omits.
339
+ /// A null dimension is symbolic and may differ from step to step
340
+ /// (docs/plan.md 6.2).
341
+ pub fn bind(&self, batch: &BTreeMap<String, Tensor>) -> Result<BTreeMap<String, Array>> {
342
+ self.bind_programs(batch, self.programs())
343
+ }
344
+
345
+ /// The same, for the models alone.
346
+ ///
347
+ /// What a forward pass needs: it stops before the objective, so the
348
+ /// objective's own fields (the labels, a teacher's scores) are not
349
+ /// something to ask a caller for. A batch that carries them anyway is
350
+ /// still accepted, since they are fields this run reads.
351
+ pub fn bind_models(&self, batch: &BTreeMap<String, Tensor>) -> Result<BTreeMap<String, Array>> {
352
+ self.bind_programs(batch, self.models.iter().map(|m| &m.program))
353
+ }
354
+
355
+ fn bind_programs<'a>(
356
+ &self,
357
+ batch: &BTreeMap<String, Tensor>,
358
+ programs: impl Iterator<Item = &'a Program>,
359
+ ) -> Result<BTreeMap<String, Array>> {
360
+ for name in batch.keys() {
361
+ anyhow::ensure!(
362
+ self.input_names.iter().any(|w| w == name),
363
+ "no input named {name:?} is read here (this run reads {:?})",
364
+ self.input_names
365
+ );
366
+ }
367
+
368
+ let mut fields = BTreeMap::new();
369
+ for program in programs {
370
+ for spec in &program.inputs {
371
+ let Some(field) = spec.batch_field() else {
372
+ continue;
373
+ };
374
+ if fields.contains_key(field) {
375
+ continue;
376
+ }
377
+ let given = batch
378
+ .get(field)
379
+ .with_context(|| format!("the batch is missing input {field:?}"))?;
380
+ fields.insert(field.to_string(), bind_one(field, spec, given)?);
381
+ }
382
+ }
383
+ Ok(fields)
384
+ }
385
+ }
386
+
387
+ /// One field, checked against what the graph declared and converted.
388
+ ///
389
+ /// Five things have to hold, and each of them is a way a batch can be
390
+ /// wrong that nothing downstream would say plainly: the rank, every
391
+ /// concrete dimension, the dtype, and that the payload is as long as the
392
+ /// shape says. A null dimension is symbolic and may differ from step to
393
+ /// step (docs/plan.md 6.2), which is the one thing here that is allowed
394
+ /// to vary.
395
+ fn bind_one(field: &str, spec: &InputSpec, given: &Tensor) -> Result<Array> {
396
+ anyhow::ensure!(
397
+ given.shape.len() == spec.shape.len(),
398
+ "input {field:?}: rank {} does not match the declared {}",
399
+ given.shape.len(),
400
+ spec.shape.len()
401
+ );
402
+ for (axis, (given, declared)) in given.shape.iter().zip(&spec.shape).enumerate() {
403
+ if let Some(declared) = declared {
404
+ anyhow::ensure!(
405
+ given == declared,
406
+ "input {field:?}: dimension {axis} is {given}, declared {declared}"
407
+ );
408
+ }
409
+ }
410
+ let declared = crate::tensor::dtype_named(&spec.dtype)
411
+ .with_context(|| format!("input {field:?}: unknown dtype in the graph"))?;
412
+ anyhow::ensure!(
413
+ given.dtype() == declared,
414
+ "input {field:?}: given {:?}, declared {}",
415
+ given.dtype(),
416
+ spec.dtype
417
+ );
418
+ let expected: usize = given.shape.iter().map(|d| *d as usize).product();
419
+ anyhow::ensure!(
420
+ given.values.len() == expected,
421
+ "input {field:?}: {} values for shape {:?}",
422
+ given.values.len(),
423
+ given.shape
424
+ );
425
+ given.to_array()
426
+ }
427
+
428
+ /// Initial parameters, read and waiting to be matched to what the graph
429
+ /// declared.
430
+ enum Source {
431
+ Inline(BTreeMap<String, InitialTensor>),
432
+ /// Keyed by qualified path.
433
+ File(std::collections::HashMap<String, Array>),
434
+ /// Keyed by model, then by that model's own path, with the patterns
435
+ /// naming what is expected to come from an initializer instead.
436
+ Pretrained {
437
+ files: BTreeMap<String, std::collections::HashMap<String, Array>>,
438
+ fresh: Vec<Pattern>,
439
+ /// Split per parameter as they are built, so what one draws does
440
+ /// not depend on how many came before it.
441
+ key: Option<Array>,
442
+ /// Weights the file held as numbers and the graph holds packed,
443
+ /// quantized once each and handed out to the three parameters
444
+ /// that share them, by qualified module path ("m.layers.0.q_proj").
445
+ /// Goes with the source, before anything is evaluated.
446
+ quantized: std::collections::HashMap<String, Quantized>,
447
+ },
448
+ }
449
+
450
+ /// Which of a packed weight's three parameters a declaration is.
451
+ #[derive(Clone, Copy)]
452
+ enum Piece {
453
+ Weight,
454
+ Scales,
455
+ Biases,
456
+ }
457
+
458
+ impl Piece {
459
+ /// The piece the parameter at `index` is, with where its packed
460
+ /// weight sits, when it is one of a `quantized_matmul`'s three.
461
+ fn of(plan: &Plan, index: usize) -> Option<(usize, Piece)> {
462
+ if plan.packed.contains_key(&index) {
463
+ return Some((index, Piece::Weight));
464
+ }
465
+ let path = &plan.paths[index];
466
+ let (module, piece) = path
467
+ .strip_suffix(".scales")
468
+ .map(|module| (module, Piece::Scales))
469
+ .or_else(|| path.strip_suffix(".biases").map(|module| (module, Piece::Biases)))?;
470
+ let weight = plan.index_of(&format!("{module}.weight"))?;
471
+ let packed = plan.packed.get(&weight)?;
472
+ let mine = match piece {
473
+ Piece::Scales => packed.scales == index,
474
+ Piece::Biases => packed.biases == Some(index),
475
+ Piece::Weight => unreachable!(),
476
+ };
477
+ mine.then_some((weight, piece))
478
+ }
479
+
480
+ fn take(self, quantized: &Quantized, path: &str) -> Result<Array> {
481
+ Ok(match self {
482
+ Piece::Weight => quantized.weight.clone(),
483
+ Piece::Scales => quantized.scales.clone(),
484
+ Piece::Biases => quantized
485
+ .biases
486
+ .clone()
487
+ .with_context(|| format!("parameter {path:?}: this quantization has no biases"))?,
488
+ })
489
+ }
490
+ }
491
+
492
+ impl Source {
493
+ fn read(weights: Weights<'_>) -> Result<Self> {
494
+ Ok(match weights {
495
+ Weights::Inline(json) => {
496
+ let parsed: WeightsJson =
497
+ serde_json::from_str(json).context("parsing the initial parameters")?;
498
+ Source::Inline(parsed.params)
499
+ }
500
+ Weights::File(path) => Source::File(read_safetensors(path)?),
501
+ Weights::Pretrained { files, fresh } => Source::Pretrained {
502
+ files: files
503
+ .iter()
504
+ .map(|(model, path)| {
505
+ Ok((
506
+ model.clone(),
507
+ read_safetensors(path)
508
+ .with_context(|| format!("model {model:?}"))?,
509
+ ))
510
+ })
511
+ .collect::<Result<_>>()?,
512
+ fresh: fresh.iter().map(|p| Pattern::parse(p)).collect::<Result<_>>()?,
513
+ key: None,
514
+ quantized: std::collections::HashMap::new(),
515
+ },
516
+ })
517
+ }
518
+
519
+ /// Every parameter the plan declares, from this source, in the order
520
+ /// the plan names them.
521
+ ///
522
+ /// Consumes the source. A file's arrays are handed over to the
523
+ /// parameters as they are matched, and whatever the plan did not ask
524
+ /// for goes with the source, before anything is evaluated.
525
+ ///
526
+ /// Evaluates every `budget` bytes of what it has made, so the reads
527
+ /// behind them are consumed and freed before the next ones start
528
+ /// (`EVAL_BUDGET`); what is left over is the caller's to evaluate.
529
+ fn materialize(mut self, plan: &Plan, budget: usize) -> Result<Vec<Array>> {
530
+ let mut params: Vec<Array> = Vec::with_capacity(plan.paths.len());
531
+ let (mut pending, mut since) = (0usize, 0usize);
532
+ for model in &plan.models {
533
+ for i in model.slice.clone() {
534
+ let param = self.parameter(&model.name, plan, i)?;
535
+ pending += param.nbytes();
536
+ params.push(param);
537
+ if pending >= budget {
538
+ eval(params[since..].iter())?;
539
+ since = params.len();
540
+ pending = 0;
541
+ }
542
+ }
543
+ }
544
+ Ok(params)
545
+ }
546
+
547
+ /// Where the fresh parameters are drawn from.
548
+ fn seed(&mut self, seed: u64) -> Result<()> {
549
+ if let Source::Pretrained { key, fresh, .. } = self {
550
+ if !fresh.is_empty() {
551
+ *key = Some(crate::mlxc::random::key(seed)?);
552
+ }
553
+ }
554
+ Ok(())
555
+ }
556
+
557
+ /// The one parameter a declaration asks for, checked against it.
558
+ ///
559
+ /// Shape has to match: a parameter of another shape is another
560
+ /// parameter. Dtype does not, and is converted. Importing is starting
561
+ /// somewhere, not resuming: a model published in bf16 is a perfectly
562
+ /// good place to start an f32 run, and refusing it would be refusing
563
+ /// the point of the exercise. `TrainState::restore` is the other case
564
+ /// and refuses, because a resumed run has to be the same run.
565
+ fn parameter(&mut self, model: &str, plan: &Plan, index: usize) -> Result<Array> {
566
+ let (path, spec) = (plan.paths[index].as_str(), &plan.specs[index]);
567
+ let declared = dtype_named(&spec.dtype)
568
+ .with_context(|| format!("parameter {path:?}: unknown dtype {:?}", spec.dtype))?;
569
+ let array = match self {
570
+ Source::Inline(params) => {
571
+ let t = params
572
+ .get(path)
573
+ .with_context(|| format!("missing parameter {path:?}"))?;
574
+ anyhow::ensure!(
575
+ t.shape == spec.shape,
576
+ "parameter {path:?}: given shape {:?} is not the declared {:?}",
577
+ t.shape,
578
+ spec.shape
579
+ );
580
+ let expected: usize = t.shape.iter().map(|d| *d as usize).product();
581
+ anyhow::ensure!(
582
+ t.data.len() == expected,
583
+ "parameter {path:?}: {} values for shape {:?}",
584
+ t.data.len(),
585
+ t.shape
586
+ );
587
+ Array::from_slice(&t.data, &t.shape)?
588
+ }
589
+ Source::File(arrays) => {
590
+ let array = arrays.get(path).with_context(|| {
591
+ format!(
592
+ "the file has no parameter {path:?}. One file holds every \
593
+ model's parameters under their qualified paths, which is how \
594
+ a checkpoint writes them; a published model, which does not \
595
+ know what it will be called here, is named per model instead."
596
+ )
597
+ })?;
598
+ shaped(array, path, spec)?
599
+ }
600
+ Source::Pretrained { files, fresh, key, quantized } => {
601
+ if let Some(pattern) = fresh.iter().find(|p| p.matches(path)) {
602
+ let key = key.as_ref().with_context(|| {
603
+ format!("parameter {path:?} matches {pattern:?} but no seed was set")
604
+ })?;
605
+ // Its own key, split from the run's by the path, so a
606
+ // parameter draws the same numbers wherever it sits in
607
+ // the declaration order.
608
+ let (_, mine) = crate::mlxc::random::split(key, 2)?;
609
+ // Drawn in f32, as every initializer draws, and held in
610
+ // the declared dtype like anything read from a file.
611
+ // Returned as drawn, a bf16 adapter's matrices started
612
+ // f32 (2026-11-09).
613
+ let drawn = crate::init::build(spec, &mine)?;
614
+ return Ok(if drawn.dtype() == declared { drawn } else { drawn.as_dtype(declared)? });
615
+ }
616
+ let arrays = files.get_mut(model).with_context(|| {
617
+ format!("no file was given for model {model:?}")
618
+ })?;
619
+ if let Some(piece) = quantized_on_read(arrays, quantized, plan, index)? {
620
+ // Quantized in the file's dtype; the declared one is
621
+ // applied below, as to anything read from a file.
622
+ piece
623
+ } else {
624
+ // The model's own path, without the name this run gives
625
+ // it. Taken out of the map rather than read: from here on
626
+ // the parameter is the only thing that holds it.
627
+ let array = arrays.remove(&spec.path).with_context(|| {
628
+ format!(
629
+ "model {model:?}'s file has no parameter {:?}. If it is meant \
630
+ to be new, name it: a head put on a published encoder is in \
631
+ no checkpoint, and saying so is what tells a typo from a \
632
+ fresh parameter.",
633
+ spec.path
634
+ )
635
+ })?;
636
+ match dequantized(arrays, path, spec, &array, declared)? {
637
+ Some(numbers) => numbers,
638
+ None => shaped(&array, path, spec)?,
639
+ }
640
+ }
641
+ }
642
+ };
643
+ Ok(if array.dtype() == declared {
644
+ array
645
+ } else {
646
+ array.as_dtype(declared)?
647
+ })
648
+ }
649
+ }
650
+
651
+ /// The packed weights a program reads, by their position in the parameter
652
+ /// vector (`start` is where the model's parameters begin), each with the
653
+ /// `quantized_matmul` that reads it. A weight read by two matmuls is read
654
+ /// the same way by both, since one set of scales fits one quantization.
655
+ fn packed_weights(program: &Program, start: usize) -> BTreeMap<usize, Packed> {
656
+ let parameter_at = |reference: &Ref| match reference {
657
+ Ref::Node(id) => match program.nodes[*id].op {
658
+ Op::Parameter(index) => Some(start + index),
659
+ _ => None,
660
+ },
661
+ Ref::Input(_) => None,
662
+ };
663
+ program
664
+ .nodes
665
+ .iter()
666
+ .filter_map(|node| match node.op {
667
+ Op::QuantizedMatmul(quantization) => {
668
+ let weight = parameter_at(&node.inputs[1])?;
669
+ let scales = parameter_at(&node.inputs[2])?;
670
+ let biases = node.inputs.get(3).and_then(parameter_at);
671
+ Some((weight, Packed { quantization, scales, biases }))
672
+ }
673
+ _ => None,
674
+ })
675
+ .collect()
676
+ }
677
+
678
+ /// Every batch field the run reads, once each and in order.
679
+ ///
680
+ /// Free functions rather than methods, because they are how a `Plan` is
681
+ /// built rather than something one answers: what this type promises is
682
+ /// that everything in it was settled before the first step, and a plan
683
+ /// that had to be filled in after construction would not have been.
684
+ fn input_names(models: &[Model], objective: Option<&Program>) -> Vec<String> {
685
+ let mut names: Vec<String> = models
686
+ .iter()
687
+ .map(|m| &m.program)
688
+ .chain(objective)
689
+ .flat_map(|p| p.inputs.iter().filter_map(|i| i.batch_field()))
690
+ .map(str::to_string)
691
+ .collect();
692
+ names.sort();
693
+ names.dedup();
694
+ names
695
+ }
696
+
697
+ /// Every name a tap may ask for, qualified by the graph it is in.
698
+ ///
699
+ /// Qualified for the same reason a parameter path is: a distillation runs
700
+ /// two models of one architecture, so "hidden" names a node in both of
701
+ /// them and "student.hidden" names one.
702
+ fn node_names(models: &[Model], objective: Option<&Program>) -> Vec<String> {
703
+ models
704
+ .iter()
705
+ .flat_map(|m| m.program.node_names().map(|n| qualified(&m.name, n)))
706
+ .chain(
707
+ objective
708
+ .into_iter()
709
+ .flat_map(|o| o.node_names().map(|n| qualified(OBJECTIVE, n))),
710
+ )
711
+ .collect()
712
+ }
713
+
714
+ /// Every model output, qualified ("student.embedding").
715
+ ///
716
+ /// The objective's outputs are not among them: its output is the loss,
717
+ /// which `evaluate` returns, and what this names is what a model
718
+ /// produces. Qualified for the reason a parameter path is: two models of
719
+ /// one architecture both declare "embedding".
720
+ fn output_names(models: &[Model]) -> Vec<String> {
721
+ models
722
+ .iter()
723
+ .flat_map(|m| {
724
+ m.program
725
+ .outputs
726
+ .iter()
727
+ .map(|(name, _)| qualified(&m.name, name))
728
+ })
729
+ .collect()
730
+ }
731
+
732
+ /// The arrays of a published model, however it is split up.
733
+ ///
734
+ /// One safetensors file, or several: a model past a few billion
735
+ /// parameters is published as `model-00001-of-00004.safetensors` and so
736
+ /// on, with `model.safetensors.index.json` saying which tensor is in
737
+ /// which. The path may be the file, the index, or the directory holding
738
+ /// either; the arrays come back under one map either way, since the
739
+ /// shards are an artifact of the upload and not of the model.
740
+ fn read_safetensors(path: &Path) -> Result<std::collections::HashMap<String, Array>> {
741
+ let path = if path.is_dir() {
742
+ let whole = path.join("model.safetensors");
743
+ let index = path.join("model.safetensors.index.json");
744
+ if whole.is_file() {
745
+ whole
746
+ } else if index.is_file() {
747
+ index
748
+ } else {
749
+ anyhow::bail!(
750
+ "no parameters in {}: neither model.safetensors nor model.safetensors.index.json",
751
+ path.display()
752
+ );
753
+ }
754
+ } else {
755
+ path.to_path_buf()
756
+ };
757
+ anyhow::ensure!(
758
+ path.is_file(),
759
+ "no parameters at {} (a safetensors file was expected)",
760
+ path.display()
761
+ );
762
+ if path.extension().and_then(|e| e.to_str()) == Some("json") {
763
+ return read_sharded(&path);
764
+ }
765
+ Array::load_safetensors(&path).with_context(|| format!("reading {}", path.display()))
766
+ }
767
+
768
+ /// The shards an index names, as one map. A tensor named in two shards
769
+ /// is refused: the index is what says where each one is, and two
770
+ /// answers is none.
771
+ fn read_sharded(index: &Path) -> Result<std::collections::HashMap<String, Array>> {
772
+ #[derive(Deserialize)]
773
+ struct Index {
774
+ weight_map: BTreeMap<String, String>,
775
+ }
776
+ let text = std::fs::read_to_string(index).with_context(|| format!("reading {}", index.display()))?;
777
+ let parsed: Index = serde_json::from_str(&text).with_context(|| format!("parsing {}", index.display()))?;
778
+ let dir = index.parent().unwrap_or(Path::new("."));
779
+ let mut shards: Vec<&String> = parsed.weight_map.values().collect();
780
+ shards.sort();
781
+ shards.dedup();
782
+ let mut arrays = std::collections::HashMap::new();
783
+ for shard in shards {
784
+ let file = dir.join(shard);
785
+ let loaded = Array::load_safetensors(&file).with_context(|| format!("reading shard {}", file.display()))?;
786
+ for (name, array) in loaded {
787
+ anyhow::ensure!(
788
+ !arrays.contains_key(&name),
789
+ "{name:?} is in more than one shard of {}",
790
+ index.display()
791
+ );
792
+ arrays.insert(name, array);
793
+ }
794
+ }
795
+ anyhow::ensure!(!arrays.is_empty(), "{} names no shards", index.display());
796
+ Ok(arrays)
797
+ }
798
+
799
+ /// The array, if its shape is the one the graph declared.
800
+ /// A weight the graph holds packed and the file holds as numbers,
801
+ /// quantized as it is read (docs/qlora.md section 3.4 (B)): how a bf16
802
+ /// checkpoint opens as a quantized model.
803
+ ///
804
+ /// The parameter at `index` is one of a `quantized_matmul`'s three
805
+ /// (`Piece::of`), the file has the module's `.weight` and no `.scales`,
806
+ /// so what it holds is numbers. They are quantized once, to what the
807
+ /// matmul says, and the three declarations are handed their pieces from
808
+ /// the one result. The file's array goes out of its map on the way, and
809
+ /// the result goes with the source, so after evaluation the packed form
810
+ /// is the only one in memory.
811
+ ///
812
+ /// `None` when this is not such a parameter, or the file holds the
813
+ /// weight packed already ((A) applies: the shapes have to match as
814
+ /// declared). An error when the numbers are not the shape the packed
815
+ /// declaration unpacks to, saying both.
816
+ fn quantized_on_read(
817
+ arrays: &mut std::collections::HashMap<String, Array>,
818
+ quantized: &mut std::collections::HashMap<String, Quantized>,
819
+ plan: &Plan,
820
+ index: usize,
821
+ ) -> Result<Option<Array>> {
822
+ let Some((weight, piece)) = Piece::of(plan, index) else {
823
+ return Ok(None);
824
+ };
825
+ let path = &plan.paths[index];
826
+ let module = plan.paths[weight].strip_suffix(".weight").unwrap_or(&plan.paths[weight]);
827
+ if let Some(done) = quantized.get(module) {
828
+ return piece.take(done, path).map(Some);
829
+ }
830
+ let own = plan.specs[weight].path.strip_suffix(".weight").unwrap_or(&plan.specs[weight].path);
831
+ let packed = plan.packed[&weight];
832
+ let numbers = match arrays.get(&format!("{own}.weight")) {
833
+ Some(array) if array.dtype() != Dtype::Uint32 && !arrays.contains_key(&format!("{own}.scales")) => {
834
+ arrays.remove(&format!("{own}.weight")).expect("just seen")
835
+ }
836
+ _ => return Ok(None),
837
+ };
838
+ let declared = &plan.specs[weight].shape;
839
+ let unpacked = match declared.as_slice() {
840
+ [d_out, cols] => vec![*d_out, cols * 32 / packed.quantization.bits],
841
+ _ => declared.clone(),
842
+ };
843
+ anyhow::ensure!(
844
+ numbers.shape() == unpacked.as_slice(),
845
+ "parameter {:?}: the file holds {own}.weight as {:?} {:?}, which is neither the packed \
846
+ {declared:?} u32 the graph declares nor the {unpacked:?} it would be quantized from \
847
+ ({} bits in groups of {})",
848
+ plan.paths[weight],
849
+ numbers.dtype(),
850
+ numbers.shape(),
851
+ packed.quantization.bits,
852
+ packed.quantization.group_size
853
+ );
854
+ let done = quantize(&numbers, packed.quantization)
855
+ .with_context(|| format!("parameter {:?}: quantizing what the file holds", plan.paths[weight]))?;
856
+ let mine = piece.take(&done, path)?;
857
+ quantized.insert(module.to_string(), done);
858
+ Ok(Some(mine))
859
+ }
860
+
861
+ /// A weight the file holds quantized and the graph declares as numbers,
862
+ /// read as the numbers it stands for (docs/qlora.md section 3.4 (A')).
863
+ ///
864
+ /// The file says how it was quantized by its shapes alone: a packed
865
+ /// `[d_out, d_in × bits / 32]` against the declared `[d_out, d_in]` gives
866
+ /// the bits, and `[d_out, d_in / group_size]` scales give the group. The
867
+ /// mode is affine, which is the one mlx-lm publishes and the one that
868
+ /// carries biases. `None` when the file holds the weight as numbers, so
869
+ /// the usual shape check applies; an error when it is packed in a way
870
+ /// the shapes cannot account for.
871
+ ///
872
+ /// The scales and biases are taken out of the file's map as the weight
873
+ /// was: once the numbers are built, nothing else should hold them.
874
+ fn dequantized(
875
+ arrays: &mut std::collections::HashMap<String, Array>,
876
+ path: &str,
877
+ spec: &ParameterSpec,
878
+ weight: &Array,
879
+ declared: Dtype,
880
+ ) -> Result<Option<Array>> {
881
+ if weight.dtype() != Dtype::Uint32 || declared == Dtype::Uint32 {
882
+ return Ok(None);
883
+ }
884
+ let Some(module) = spec.path.strip_suffix(".weight") else {
885
+ return Ok(None);
886
+ };
887
+ let scales = arrays.remove(&format!("{module}.scales")).with_context(|| {
888
+ format!(
889
+ "parameter {path:?}: the file holds a packed u32 weight {:?} and no {module}.scales \
890
+ to read it with; the graph declares {:?} {}",
891
+ weight.shape(),
892
+ spec.shape,
893
+ spec.dtype
894
+ )
895
+ })?;
896
+ let biases = arrays.remove(&format!("{module}.biases"));
897
+ let said = || {
898
+ format!(
899
+ "parameter {path:?}: the file holds a packed u32 weight {:?} with scales {:?}, which \
900
+ is not {:?} {} quantized at any group size and bits this engine reads (groups of 32, \
901
+ 64 or 128 at 2 to 8 bits)",
902
+ weight.shape(),
903
+ scales.shape(),
904
+ spec.shape,
905
+ spec.dtype
906
+ )
907
+ };
908
+ let (&[d_out, d_in], &[packed_rows, packed], &[scale_rows, groups]) =
909
+ (spec.shape.as_slice(), weight.shape(), scales.shape())
910
+ else {
911
+ anyhow::bail!(said());
912
+ };
913
+ anyhow::ensure!(
914
+ packed_rows == d_out && scale_rows == d_out && packed > 0 && groups > 0,
915
+ said()
916
+ );
917
+ anyhow::ensure!((packed * 32) % d_in == 0 && d_in % groups == 0, said());
918
+ let bits = packed * 32 / d_in;
919
+ let group_size = d_in / groups;
920
+ anyhow::ensure!(
921
+ [2, 3, 4, 5, 6, 8].contains(&bits) && [32, 64, 128].contains(&group_size),
922
+ said()
923
+ );
924
+ let quantization = Quantization { group_size, bits, mode: Mode::Affine };
925
+ let numbers = dequantize(weight, &scales, biases.as_ref(), quantization, Some(declared))
926
+ .with_context(|| format!("parameter {path:?}: dequantizing what the file holds"))?;
927
+ Ok(Some(numbers))
928
+ }
929
+
930
+ fn shaped(array: &Array, path: &str, spec: &ParameterSpec) -> Result<Array> {
931
+ anyhow::ensure!(
932
+ array.shape() == spec.shape,
933
+ "parameter {path:?}: the file holds shape {:?}, the graph declares {:?}",
934
+ array.shape(),
935
+ spec.shape
936
+ );
937
+ Ok(array.clone())
938
+ }
939
+
940
+ /// A parameter pattern: a path, or a prefix ending in `*`. The one small
941
+ /// language both freezing and a pretrained run's fresh parameters are named
942
+ /// in.
943
+ ///
944
+ /// Deliberately small. A path names one parameter, `student.*` names a
945
+ /// model's, `student.layers.3.*` names a block's; anything more expressive
946
+ /// would be a query language nobody asked for.
947
+ pub struct Pattern {
948
+ text: String,
949
+ prefix: String,
950
+ exact: bool,
951
+ }
952
+
953
+ impl Pattern {
954
+ pub fn parse(pattern: &str) -> Result<Self> {
955
+ anyhow::ensure!(!pattern.is_empty(), "a parameter pattern must not be empty");
956
+ let (prefix, exact) = match pattern.strip_suffix('*') {
957
+ Some(prefix) => (prefix, false),
958
+ None => (pattern, true),
959
+ };
960
+ Ok(Self {
961
+ text: pattern.to_string(),
962
+ prefix: prefix.to_string(),
963
+ exact,
964
+ })
965
+ }
966
+
967
+ pub fn matches(&self, path: &str) -> bool {
968
+ if self.exact {
969
+ path == self.prefix
970
+ } else {
971
+ path.starts_with(&self.prefix)
972
+ }
973
+ }
974
+ }
975
+
976
+ impl std::fmt::Debug for Pattern {
977
+ /// As it was written, which is how an error should quote it.
978
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
979
+ write!(f, "{:?}", self.text)
980
+ }
981
+ }
982
+
983
+ #[cfg(test)]
984
+ mod tests {
985
+ use super::*;
986
+ use crate::fixtures;
987
+ use crate::tensor::Values;
988
+ use crate::mlxc::Dtype;
989
+ use serde_json::{json, Value};
990
+
991
+ /// The common case in these tests: parameters as JSON.
992
+ fn open(config: &str, weights: &str) -> Result<(Plan, Vec<Array>)> {
993
+ Plan::open(config, Weights::Inline(weights))
994
+ }
995
+
996
+ /// The message from an open that should have failed. `unwrap_err`
997
+ /// would want Debug on a Plan, which is a lot of Array to print.
998
+ fn refusal(config: &str, weights: &str) -> String {
999
+ match open(config, weights) {
1000
+ Ok(_) => panic!("this should not have opened"),
1001
+ Err(e) => e.to_string(),
1002
+ }
1003
+ }
1004
+
1005
+ #[test]
1006
+ fn parameters_are_ordered_by_model_name_then_declaration() {
1007
+ let (config, weights) = fixtures::teacher_and_student();
1008
+ let (plan, params) = open(&config, &weights).unwrap();
1009
+ // "student" sorts before "teacher", which is the order a
1010
+ // checkpoint's parameter list has to follow.
1011
+ assert_eq!(plan.paths, vec!["student.scale", "teacher.scale"]);
1012
+ assert_eq!(params.len(), 2);
1013
+ assert_eq!(plan.models[0].slice, 0..1);
1014
+ assert_eq!(plan.models[1].slice, 1..2);
1015
+ }
1016
+
1017
+ #[test]
1018
+ fn only_a_trained_models_parameters_are_candidates() {
1019
+ let (config, weights) = fixtures::teacher_and_student();
1020
+ let (plan, _) = open(&config, &weights).unwrap();
1021
+ assert_eq!(plan.candidates, vec![0]);
1022
+ assert_eq!(plan.candidate_paths(), vec!["student.scale"]);
1023
+ }
1024
+
1025
+ #[test]
1026
+ fn the_digest_is_of_the_bytes_handed_over() {
1027
+ let (config, weights) = fixtures::scaled_mean();
1028
+ let (plan, _) = open(&config, &weights).unwrap();
1029
+ let same = open(&config, &weights).unwrap().0;
1030
+ assert_eq!(plan.config_digest, same.config_digest);
1031
+ assert_eq!(plan.config_digest.len(), 64);
1032
+
1033
+ // Whitespace is part of the bytes, not of the meaning; the Ruby
1034
+ // side digests the canonical form, and the engine digests whatever
1035
+ // it was actually given. They agree because they see the same bytes.
1036
+ let spaced = format!("{config} ");
1037
+ let other = open(&spaced, &weights).unwrap().0;
1038
+ assert_ne!(plan.config_digest, other.config_digest);
1039
+ }
1040
+
1041
+ #[test]
1042
+ fn a_missing_parameter_is_named() {
1043
+ let (config, _) = fixtures::scaled_mean();
1044
+ let e = refusal(&config, r#"{"params":{}}"#);
1045
+ assert!(e.contains("m.w"), "{e}");
1046
+ }
1047
+
1048
+ #[test]
1049
+ fn a_parameter_of_the_wrong_shape_is_refused() {
1050
+ let (config, _) = fixtures::scaled_mean();
1051
+ let weights = json!({"params": {"m.w": {"shape": [3], "data": [1.0, 2.0, 3.0]}}});
1052
+ let e = refusal(&config, &weights.to_string());
1053
+ assert!(e.contains("is not the declared"), "{e}");
1054
+ }
1055
+
1056
+ #[test]
1057
+ fn a_parameter_with_too_few_values_is_refused_rather_than_read_past() {
1058
+ let (config, _) = fixtures::scaled_mean();
1059
+ let weights = json!({"params": {"m.w": {"shape": [2], "data": [1.0]}}});
1060
+ let e = refusal(&config, &weights.to_string());
1061
+ assert!(e.contains("1 values for shape"), "{e}");
1062
+ }
1063
+
1064
+ #[test]
1065
+ fn a_run_that_names_a_model_with_nothing_trainable_is_refused() {
1066
+ let (config, weights) = fixtures::teacher_and_student();
1067
+ let untrainable = config.replace(r#""trainable":true"#, r#""trainable":false"#);
1068
+ assert_ne!(untrainable, config, "the fixture's parameters moved");
1069
+ let e = refusal(&untrainable, &weights);
1070
+ assert!(e.contains("nothing to train"), "{e}");
1071
+ }
1072
+
1073
+ /// The same emptiness, said on purpose. A graph opened to be read
1074
+ /// (a loss over representations computed elsewhere) trains nothing and
1075
+ /// has a use; what is refused is meaning to train and finding out at
1076
+ /// step one that there was nothing to.
1077
+ #[test]
1078
+ fn a_run_that_names_no_model_to_train_opens() {
1079
+ let (config, weights) = fixtures::teacher_and_student();
1080
+ let read_only = config.replace(r#""train":["student"]"#, r#""train":[]"#);
1081
+ assert_ne!(read_only, config, "the fixture's train list moved");
1082
+
1083
+ let (plan, params) = open(&read_only, &weights).unwrap();
1084
+
1085
+ assert!(plan.candidates.is_empty());
1086
+ assert_eq!(params.len(), 2, "the parameters are still there to read");
1087
+ }
1088
+
1089
+ #[test]
1090
+ fn a_config_with_no_models_is_refused() {
1091
+ let config = fixtures::config(json!({}), Value::Null, json!([]));
1092
+ let e = refusal(&config, r#"{"params":{}}"#);
1093
+ assert!(e.contains("no models"), "{e}");
1094
+ }
1095
+
1096
+ #[test]
1097
+ fn input_names_are_sorted_and_deduplicated_across_graphs() {
1098
+ let (config, weights) = fixtures::teacher_and_student();
1099
+ let (plan, _) = open(&config, &weights).unwrap();
1100
+ // Both models read the same field; the objective reads neither.
1101
+ assert_eq!(plan.input_names(), vec!["x"]);
1102
+ }
1103
+
1104
+ #[test]
1105
+ fn node_names_are_what_a_tap_may_ask_for() {
1106
+ let (config, weights) = fixtures::scaled_mean();
1107
+ let (plan, _) = open(&config, &weights).unwrap();
1108
+ assert_eq!(plan.node_names(), vec!["m.scaled"]);
1109
+ }
1110
+
1111
+ fn tensor(shape: Vec<i32>, values: Values) -> Tensor {
1112
+ Tensor { shape, values }
1113
+ }
1114
+
1115
+ fn plan_for_bind() -> Plan {
1116
+ let (config, weights) = fixtures::scaled_mean();
1117
+ open(&config, &weights).unwrap().0
1118
+ }
1119
+
1120
+ #[test]
1121
+ fn a_symbolic_dimension_may_differ_from_batch_to_batch() {
1122
+ let plan = plan_for_bind();
1123
+ for rows in [1, 5] {
1124
+ let batch: BTreeMap<String, Tensor> = [(
1125
+ "x".to_string(),
1126
+ tensor(vec![rows, 2], Values::F32(vec![0.0; rows as usize * 2])),
1127
+ )]
1128
+ .into_iter()
1129
+ .collect();
1130
+ assert!(plan.bind(&batch).is_ok(), "{rows} rows should bind");
1131
+ }
1132
+ }
1133
+
1134
+ #[test]
1135
+ fn a_fixed_dimension_may_not() {
1136
+ let plan = plan_for_bind();
1137
+ let batch = [(
1138
+ "x".to_string(),
1139
+ tensor(vec![2, 3], Values::F32(vec![0.0; 6])),
1140
+ )]
1141
+ .into_iter()
1142
+ .collect();
1143
+ let e = plan.bind(&batch).unwrap_err();
1144
+ assert!(e.to_string().contains("dimension 1 is 3"), "{e}");
1145
+ }
1146
+
1147
+ #[test]
1148
+ fn a_batch_of_the_wrong_rank_is_refused() {
1149
+ let plan = plan_for_bind();
1150
+ let batch = [("x".to_string(), tensor(vec![4], Values::F32(vec![0.0; 4])))]
1151
+ .into_iter()
1152
+ .collect();
1153
+ let e = plan.bind(&batch).unwrap_err();
1154
+ assert!(e.to_string().contains("rank 1"), "{e}");
1155
+ }
1156
+
1157
+ #[test]
1158
+ fn a_batch_of_the_wrong_dtype_is_refused() {
1159
+ let plan = plan_for_bind();
1160
+ let batch = [("x".to_string(), tensor(vec![2, 2], Values::I32(vec![0; 4])))]
1161
+ .into_iter()
1162
+ .collect();
1163
+ let e = plan.bind(&batch).unwrap_err();
1164
+ assert!(e.to_string().contains("declared f32"), "{e}");
1165
+ }
1166
+
1167
+ #[test]
1168
+ fn a_batch_whose_values_do_not_fill_its_shape_is_refused() {
1169
+ let plan = plan_for_bind();
1170
+ let batch = [(
1171
+ "x".to_string(),
1172
+ tensor(vec![2, 2], Values::F32(vec![0.0; 3])),
1173
+ )]
1174
+ .into_iter()
1175
+ .collect();
1176
+ let e = plan.bind(&batch).unwrap_err();
1177
+ assert!(e.to_string().contains("3 values for shape"), "{e}");
1178
+ }
1179
+
1180
+ #[test]
1181
+ fn a_field_no_graph_reads_is_refused_rather_than_ignored() {
1182
+ let plan = plan_for_bind();
1183
+ let batch = [
1184
+ ("x".to_string(), tensor(vec![1, 2], Values::F32(vec![0.0; 2]))),
1185
+ ("y".to_string(), tensor(vec![1], Values::F32(vec![0.0]))),
1186
+ ]
1187
+ .into_iter()
1188
+ .collect();
1189
+ let e = plan.bind(&batch).unwrap_err();
1190
+ assert!(e.to_string().contains("no input named \"y\""), "{e}");
1191
+ }
1192
+
1193
+ #[test]
1194
+ fn a_field_a_graph_reads_but_the_batch_omits_is_refused() {
1195
+ let plan = plan_for_bind();
1196
+ let e = plan.bind(&BTreeMap::new()).unwrap_err();
1197
+ assert!(e.to_string().contains("missing input \"x\""), "{e}");
1198
+ }
1199
+
1200
+ /// Writes what the graph declares into a safetensors file, the way a
1201
+ /// checkpoint does: keyed by qualified path.
1202
+ fn write_parameters(dir: &std::path::Path, named: &[(&str, Array)]) -> std::path::PathBuf {
1203
+ let path = dir.join("parameters.safetensors");
1204
+ Array::save_safetensors(named.iter().map(|(n, a)| (n, a)), None, &path).unwrap();
1205
+ path
1206
+ }
1207
+
1208
+ #[test]
1209
+ fn parameters_can_come_from_a_file_named_the_way_the_graph_names_them() {
1210
+ let dir = tempfile::tempdir().unwrap();
1211
+ let file = write_parameters(
1212
+ dir.path(),
1213
+ &[("m.w", Array::from_slice(&[5.0f32, 6.0], &[2]).unwrap())],
1214
+ );
1215
+
1216
+ let (config, _) = fixtures::scaled_mean();
1217
+ let (plan, params) = Plan::open(&config, Weights::File(&file)).unwrap();
1218
+ assert_eq!(plan.paths, vec!["m.w"]);
1219
+ assert_eq!(crate::tensor::to_tensor(&params[0]).unwrap().shape, vec![2]);
1220
+ }
1221
+
1222
+ fn pretrained(dir: &std::path::Path, embedding_packed: bool) -> Result<(Plan, Vec<Array>)> {
1223
+ let files = BTreeMap::from([("m".to_string(), fixtures::quantized::file(dir, embedding_packed))]);
1224
+ Plan::open(&fixtures::quantized::config(), Weights::Pretrained { files: &files, fresh: &[] })
1225
+ }
1226
+
1227
+ fn f32s(array: &Array) -> Vec<f32> {
1228
+ array.contiguous().unwrap().as_slice::<f32>().unwrap().to_vec()
1229
+ }
1230
+
1231
+ /// A published 4-bit file holds its embedding packed, and the graph
1232
+ /// holds its embedding in numbers (docs/qlora.md 3.4 (A')): the file's
1233
+ /// three arrays become the one the graph declared, in its dtype and
1234
+ /// shape, within a step of the grid of what they were made from. The
1235
+ /// linear the graph does hold packed is read as the file has it.
1236
+ #[test]
1237
+ fn a_weight_the_file_holds_quantized_is_read_as_the_numbers_it_stands_for() {
1238
+ use fixtures::quantized::{weight, D_IN, D_OUT, EMB_ROWS};
1239
+ let dir = tempfile::tempdir().unwrap();
1240
+ let (plan, params) = pretrained(dir.path(), true).unwrap();
1241
+
1242
+ let emb = plan.index_of("m.emb.weight").unwrap();
1243
+ assert_eq!(params[emb].dtype(), Dtype::Float32);
1244
+ assert_eq!(params[emb].shape(), &[EMB_ROWS as i32, D_IN as i32]);
1245
+ let (got, want) = (f32s(&params[emb]), weight(EMB_ROWS));
1246
+ let mut moved = false;
1247
+ for (g, w) in got.iter().zip(&want) {
1248
+ assert!((g - w).abs() <= 2.0 / 15.0, "{g} came back for {w}");
1249
+ moved |= (g - w).abs() > 1e-6;
1250
+ }
1251
+ assert!(moved, "the numbers went through 4 bits");
1252
+
1253
+ let w = plan.index_of("m.proj.weight").unwrap();
1254
+ assert_eq!(params[w].dtype(), Dtype::Uint32);
1255
+ assert_eq!(params[w].shape(), &[D_OUT as i32, (D_IN * 4 / 32) as i32]);
1256
+ assert_eq!(
1257
+ plan.packed.get(&w),
1258
+ Some(&Packed {
1259
+ quantization: fixtures::quantized::QUANTIZATION,
1260
+ scales: plan.index_of("m.proj.scales").unwrap(),
1261
+ biases: Some(plan.index_of("m.proj.biases").unwrap()),
1262
+ })
1263
+ );
1264
+ assert_eq!(plan.packed.len(), 1, "the embedding is numbers now, not a packed weight");
1265
+ }
1266
+
1267
+ /// The same model from a file that holds the embedding as numbers
1268
+ /// reads the same way: (A') applies only where the file is packed.
1269
+ #[test]
1270
+ fn a_weight_the_file_holds_as_numbers_is_read_as_before() {
1271
+ let dir = tempfile::tempdir().unwrap();
1272
+ let (plan, params) = pretrained(dir.path(), false).unwrap();
1273
+ let emb = plan.index_of("m.emb.weight").unwrap();
1274
+ assert_eq!(f32s(&params[emb]), fixtures::quantized::weight(fixtures::quantized::EMB_ROWS));
1275
+ }
1276
+
1277
+ /// Packed with nothing to read it by, or packed in a way the declared
1278
+ /// shape cannot account for: refused with both shapes, before anything
1279
+ /// is dequantized.
1280
+ #[test]
1281
+ fn a_packed_weight_the_shapes_cannot_account_for_is_refused() {
1282
+ use fixtures::quantized::{file_with, D_IN, EMB_ROWS};
1283
+ let packed = |cols: i32| Array::zeros::<u32>(&[EMB_ROWS as i32, cols]).unwrap();
1284
+ let scales = |groups: i32| Array::zeros::<f32>(&[EMB_ROWS as i32, groups]).unwrap();
1285
+ let open = |emb: Vec<(&str, Array)>| {
1286
+ let dir = tempfile::tempdir().unwrap();
1287
+ let files = BTreeMap::from([("m".to_string(), file_with(dir.path(), emb))]);
1288
+ match Plan::open(&fixtures::quantized::config(), Weights::Pretrained { files: &files, fresh: &[] }) {
1289
+ Ok(_) => panic!("this file should not have opened"),
1290
+ Err(e) => format!("{e:#}"),
1291
+ }
1292
+ };
1293
+
1294
+ let no_scales = open(vec![("emb.weight", packed((D_IN * 4 / 32) as i32))]);
1295
+ assert!(no_scales.contains("no emb.scales"), "{no_scales}");
1296
+ assert!(no_scales.contains("[4, 64] f32"), "{no_scales}");
1297
+
1298
+ let odd_width = open(vec![("emb.weight", packed(5)), ("emb.scales", scales(2))]);
1299
+ assert!(odd_width.contains("is not [4, 64] f32 quantized"), "{odd_width}");
1300
+ assert!(odd_width.contains("[4, 5]"), "{odd_width}");
1301
+
1302
+ let odd_groups = open(vec![("emb.weight", packed(8)), ("emb.scales", scales(3))]);
1303
+ assert!(odd_groups.contains("is not [4, 64] f32 quantized"), "{odd_groups}");
1304
+ }
1305
+
1306
+ /// A bf16 checkpoint opens as a quantized model: the weight the graph
1307
+ /// holds packed is quantized as it is read, and what comes out is bit
1308
+ /// for bit what MLX's `quantize` gives on the same array, since it is
1309
+ /// the same call (docs/qlora.md 3.4 (B)). The three parameters that
1310
+ /// share it are handed the pieces of one quantization.
1311
+ #[test]
1312
+ fn a_weight_the_file_holds_as_numbers_is_quantized_as_it_is_read() {
1313
+ use crate::mlxc::quantized::quantize;
1314
+ use fixtures::quantized::{D_IN, D_OUT, QUANTIZATION};
1315
+ let dir = tempfile::tempdir().unwrap();
1316
+ let (file, written) = fixtures::quantized::file_bf16(dir.path());
1317
+ let files = BTreeMap::from([("m".to_string(), file)]);
1318
+ let (plan, params) =
1319
+ Plan::open(&fixtures::quantized::config(), Weights::Pretrained { files: &files, fresh: &[] }).unwrap();
1320
+
1321
+ let want = quantize(&written, QUANTIZATION).unwrap();
1322
+ let at = |path: &str| &params[plan.index_of(path).unwrap()];
1323
+ let weight = at("m.proj.weight");
1324
+ assert_eq!(weight.dtype(), Dtype::Uint32);
1325
+ assert_eq!(weight.shape(), &[D_OUT as i32, (D_IN * 4 / 32) as i32]);
1326
+ assert_eq!(
1327
+ weight.contiguous().unwrap().as_slice::<u32>().unwrap(),
1328
+ want.weight.contiguous().unwrap().as_slice::<u32>().unwrap(),
1329
+ "the packed words are MLX's own"
1330
+ );
1331
+ for (path, wanted) in [("m.proj.scales", &want.scales), ("m.proj.biases", want.biases.as_ref().unwrap())] {
1332
+ let got = at(path);
1333
+ // Declared f32 here, so the bf16 scales the file's dtype gave
1334
+ // are widened; the numbers are the same.
1335
+ assert_eq!(got.dtype(), Dtype::Float32, "{path}");
1336
+ assert_eq!(f32s(got), f32s(&wanted.as_dtype(Dtype::Float32).unwrap()), "{path}");
1337
+ }
1338
+ // `head` and `emb` are read as before.
1339
+ assert_eq!(f32s(at("m.head.weight")), vec![1.0; D_OUT]);
1340
+ }
1341
+
1342
+ /// What quantizing on read is for: once a bf16 file is open as a
1343
+ /// quantized model, what is held is the packed form, not the numbers
1344
+ /// it came from. The file's array leaves its map as it is read and
1345
+ /// the source goes before evaluation, so the bf16 copy is freed with
1346
+ /// the lazy graph that consumed it. Measured as what MLX holds after
1347
+ /// opening against what the bf16 numbers alone would take: a weight
1348
+ /// of a megabyte, so the allocator's rounding is noise against it.
1349
+ ///
1350
+ /// Not measured at once. The device keeps a kernel's inputs until the
1351
+ /// command buffer that ran it completes, and releases them from a
1352
+ /// completion handler that may run after `eval` has returned; read
1353
+ /// straight after opening, the bf16 input was still counted (one
1354
+ /// megabyte exactly, 2026-11-08). So the number is polled for a
1355
+ /// moment. A copy something still referenced would never go, and the
1356
+ /// assertion would still fail.
1357
+ #[test]
1358
+ fn opening_a_bf16_file_as_a_quantized_model_does_not_keep_the_numbers() {
1359
+ use crate::mlxc::memory;
1360
+ let (d_out, d_in) = (512usize, 1024usize);
1361
+ let dir = tempfile::tempdir().unwrap();
1362
+ let (file, written) = fixtures::quantized::file_bf16_sized(dir.path(), d_out, d_in);
1363
+ drop(written);
1364
+ let files = BTreeMap::from([("m".to_string(), file)]);
1365
+
1366
+ let settled = || {
1367
+ let mut active = memory::active().unwrap();
1368
+ for _ in 0..200 {
1369
+ std::thread::sleep(std::time::Duration::from_millis(5));
1370
+ let again = memory::active().unwrap();
1371
+ if again == active {
1372
+ break;
1373
+ }
1374
+ active = again;
1375
+ }
1376
+ active
1377
+ };
1378
+ let before = settled();
1379
+ let (plan, params) =
1380
+ Plan::open(&fixtures::quantized::config_sized(d_out, d_in), Weights::Pretrained { files: &files, fresh: &[] })
1381
+ .unwrap();
1382
+ let numbers = d_out * d_in * 2;
1383
+ let packed = d_out * d_in / 2 + 2 * d_out * (d_in / 32) * 4;
1384
+ let mut held = memory::active().unwrap().saturating_sub(before);
1385
+ for _ in 0..200 {
1386
+ if held < numbers {
1387
+ break;
1388
+ }
1389
+ std::thread::sleep(std::time::Duration::from_millis(5));
1390
+ held = memory::active().unwrap().saturating_sub(before);
1391
+ }
1392
+ assert!(
1393
+ held < numbers,
1394
+ "{held} bytes held a second after opening; the bf16 numbers alone are {numbers}, the \
1395
+ packed form {packed}"
1396
+ );
1397
+ assert_eq!(params[plan.index_of("m.proj.weight").unwrap()].dtype(), Dtype::Uint32);
1398
+ }
1399
+
1400
+ /// The peak while a run opens, which is what decides whether a model
1401
+ /// opens at all. Opening a bf16 file as a quantized model with one
1402
+ /// evaluation for everything held the whole file at the peak
1403
+ /// (measured on Qwen2.5-0.5B: 1.03 GiB for 0.44 GiB of result);
1404
+ /// evaluating as it goes holds what has been made and one batch of
1405
+ /// what it is made from. Eight weights of half a megabyte each in
1406
+ /// bf16, evaluated one at a time: the peak stays below the file.
1407
+ #[test]
1408
+ fn evaluating_as_a_run_opens_keeps_the_peak_below_the_file() {
1409
+ use crate::mlxc::memory;
1410
+ let (n, d_out, d_in) = (8usize, 256usize, 1024usize);
1411
+ let dir = tempfile::tempdir().unwrap();
1412
+ let (config, file) = fixtures::quantized::stack(dir.path(), n, d_out, d_in);
1413
+ let files = BTreeMap::from([("m".to_string(), file)]);
1414
+ let bf16 = n * d_out * d_in * 2;
1415
+ let packed_each = d_out * d_in / 2 + 2 * d_out * (d_in / 32) * 4;
1416
+
1417
+ let peak_of = |budget: usize| {
1418
+ memory::clear_cache().unwrap();
1419
+ let before = memory::active().unwrap();
1420
+ memory::reset_peak().unwrap();
1421
+ let opened = Plan::open_budgeted(&config, Weights::Pretrained { files: &files, fresh: &[] }, 0, budget).unwrap();
1422
+ let peak = memory::peak().unwrap().saturating_sub(before);
1423
+ drop(opened);
1424
+ peak
1425
+ };
1426
+ let bounded = peak_of(packed_each);
1427
+ assert!(
1428
+ bounded < bf16,
1429
+ "opening one weight at a time peaked at {bounded} bytes; the bf16 file is {bf16}, the \
1430
+ packed result {}",
1431
+ n * packed_each
1432
+ );
1433
+ // What it is bounded against, printed rather than asserted: how
1434
+ // MLX schedules one evaluation of everything is MLX's business.
1435
+ eprintln!("peak opening one at a time: {bounded}; all at once: {}", peak_of(usize::MAX));
1436
+ }
1437
+
1438
+ /// Numbers of a shape the packed declaration does not unpack to are
1439
+ /// a weight quantized some other way, or another weight: refused,
1440
+ /// with the declared shape, the shape it would be quantized from,
1441
+ /// and what the file holds.
1442
+ #[test]
1443
+ fn numbers_that_do_not_unpack_to_the_declared_shape_are_refused() {
1444
+ let open = |proj: Array| {
1445
+ let dir = tempfile::tempdir().unwrap();
1446
+ let files = BTreeMap::from([("m".to_string(), fixtures::quantized::file_with_proj(dir.path(), proj))]);
1447
+ match Plan::open(&fixtures::quantized::config(), Weights::Pretrained { files: &files, fresh: &[] }) {
1448
+ Ok(_) => panic!("this file should not have opened"),
1449
+ Err(e) => format!("{e:#}"),
1450
+ }
1451
+ };
1452
+ let narrow = open(Array::zeros::<f32>(&[8, 60]).unwrap());
1453
+ assert!(narrow.contains("neither the packed [8, 8] u32"), "{narrow}");
1454
+ assert!(narrow.contains("nor the [8, 64] it would be quantized from"), "{narrow}");
1455
+ assert!(narrow.contains("Float32 [8, 60]"), "{narrow}");
1456
+
1457
+ // The packed shape in a float dtype is not a packed weight.
1458
+ let float_words = open(Array::zeros::<f32>(&[8, 8]).unwrap());
1459
+ assert!(float_words.contains("Float32 [8, 8]"), "{float_words}");
1460
+ }
1461
+
1462
+ /// A model published in shards (an index and several files) reads as
1463
+ /// one, given the index or the directory holding it. A tensor named
1464
+ /// in two shards is refused.
1465
+ #[test]
1466
+ fn a_sharded_checkpoint_reads_as_one_whether_named_by_its_index_or_its_directory() {
1467
+ let dir = tempfile::tempdir().unwrap();
1468
+ let (config, _) = fixtures::teacher_and_student();
1469
+ let shard = |name: &str, tensors: &[(&str, Array)]| {
1470
+ Array::save_safetensors(tensors.iter().map(|(n, a)| (*n, a)), None, dir.path().join(name)).unwrap();
1471
+ };
1472
+ shard("model-00001-of-00002.safetensors", &[("scale", Array::from_slice(&[3.0f32, 4.0], &[2]).unwrap())]);
1473
+ shard("model-00002-of-00002.safetensors", &[("other", Array::from_slice(&[1.0f32], &[1]).unwrap())]);
1474
+ let index = dir.path().join("model.safetensors.index.json");
1475
+ std::fs::write(
1476
+ &index,
1477
+ json!({"metadata": {}, "weight_map": {
1478
+ "scale": "model-00001-of-00002.safetensors",
1479
+ "other": "model-00002-of-00002.safetensors",
1480
+ }})
1481
+ .to_string(),
1482
+ )
1483
+ .unwrap();
1484
+
1485
+ for given in [index.clone(), dir.path().to_path_buf()] {
1486
+ let files = BTreeMap::from([("teacher".to_string(), given.clone()), ("student".to_string(), given)]);
1487
+ let (plan, params) = Plan::open(&config, Weights::Pretrained { files: &files, fresh: &[] }).unwrap();
1488
+ assert_eq!(f32s(&params[plan.index_of("teacher.scale").unwrap()]), vec![3.0, 4.0]);
1489
+ }
1490
+
1491
+ std::fs::write(
1492
+ &index,
1493
+ json!({"weight_map": {
1494
+ "scale": "model-00001-of-00002.safetensors",
1495
+ "other": "model-00001-of-00002.safetensors",
1496
+ }})
1497
+ .to_string(),
1498
+ )
1499
+ .unwrap();
1500
+ shard("model-00001-of-00002.safetensors", &[("scale", Array::from_slice(&[3.0f32, 4.0], &[2]).unwrap())]);
1501
+ shard("model-00002-of-00002.safetensors", &[("scale", Array::from_slice(&[0.0f32, 0.0], &[2]).unwrap())]);
1502
+ std::fs::write(
1503
+ &index,
1504
+ json!({"weight_map": {
1505
+ "scale": "model-00001-of-00002.safetensors",
1506
+ "other": "model-00002-of-00002.safetensors",
1507
+ }})
1508
+ .to_string(),
1509
+ )
1510
+ .unwrap();
1511
+ let files = BTreeMap::from([("teacher".to_string(), index.clone()), ("student".to_string(), index.clone())]);
1512
+ let said = match Plan::open(&config, Weights::Pretrained { files: &files, fresh: &[] }) {
1513
+ Ok(_) => panic!("two shards hold \"scale\""),
1514
+ Err(e) => format!("{e:#}"),
1515
+ };
1516
+ assert!(said.contains("more than one shard"), "{said}");
1517
+
1518
+ let empty = tempfile::tempdir().unwrap();
1519
+ let files = BTreeMap::from([("teacher".to_string(), empty.path().to_path_buf()), ("student".to_string(), empty.path().to_path_buf())]);
1520
+ let said = match Plan::open(&config, Weights::Pretrained { files: &files, fresh: &[] }) {
1521
+ Ok(_) => panic!("an empty directory holds nothing"),
1522
+ Err(e) => format!("{e:#}"),
1523
+ };
1524
+ assert!(said.contains("neither model.safetensors nor"), "{said}");
1525
+ }
1526
+
1527
+ /// A parameter drawn from its initializer (`fresh:`) is held in the
1528
+ /// dtype it is declared in, as one read from a file is: a bf16 LoRA's
1529
+ /// matrices are bf16, not the f32 the draw is made in.
1530
+ #[test]
1531
+ fn a_fresh_parameter_is_held_in_its_declared_dtype() {
1532
+ let (config, _) = fixtures::scaled_mean();
1533
+ let mut graph: serde_json::Value = serde_json::from_str(&config).unwrap();
1534
+ graph["models"]["m"]["parameters"][0]["dtype"] = json!("bf16");
1535
+ graph["models"]["m"]["parameters"][0]["initializer"] = json!({"type": "normal", "std": 0.02});
1536
+ let dir = tempfile::tempdir().unwrap();
1537
+ let file = write_parameters(dir.path(), &[("unrelated", Array::from_f32(1.0).unwrap())]);
1538
+ let files = BTreeMap::from([("m".to_string(), file)]);
1539
+ let fresh = vec!["m.w".to_string()];
1540
+ let (plan, params) =
1541
+ Plan::open(&graph.to_string(), Weights::Pretrained { files: &files, fresh: &fresh }).unwrap();
1542
+ assert_eq!(params[plan.index_of("m.w").unwrap()].dtype(), Dtype::Bfloat16);
1543
+ }
1544
+
1545
+ #[test]
1546
+ fn a_file_missing_a_parameter_says_which_and_what_the_names_should_be() {
1547
+ let dir = tempfile::tempdir().unwrap();
1548
+ let file = write_parameters(
1549
+ dir.path(),
1550
+ &[("something.else", Array::from_slice(&[0.0f32, 0.0], &[2]).unwrap())],
1551
+ );
1552
+
1553
+ let (config, _) = fixtures::scaled_mean();
1554
+ let e = match Plan::open(&config, Weights::File(&file)) {
1555
+ Ok(_) => panic!("this should not have opened"),
1556
+ Err(e) => format!("{e:#}"),
1557
+ };
1558
+ assert!(e.contains("m.w"), "{e}");
1559
+ assert!(e.contains("qualified paths"), "{e}");
1560
+ }
1561
+
1562
+ #[test]
1563
+ fn a_file_holding_another_shape_is_refused() {
1564
+ let dir = tempfile::tempdir().unwrap();
1565
+ let file = write_parameters(
1566
+ dir.path(),
1567
+ &[("m.w", Array::from_slice(&[1.0f32, 2.0, 3.0], &[3]).unwrap())],
1568
+ );
1569
+
1570
+ let (config, _) = fixtures::scaled_mean();
1571
+ let e = match Plan::open(&config, Weights::File(&file)) {
1572
+ Ok(_) => panic!("this should not have opened"),
1573
+ Err(e) => format!("{e:#}"),
1574
+ };
1575
+ assert!(e.contains("the graph declares"), "{e}");
1576
+ }
1577
+
1578
+ #[test]
1579
+ fn a_file_in_another_precision_is_converted_rather_than_refused() {
1580
+ // Importing is starting somewhere, not resuming: a model published
1581
+ // in bf16 is a fine place to start an f32 run.
1582
+ let dir = tempfile::tempdir().unwrap();
1583
+ let half = Array::from_slice(&[0.5f32, 2.0], &[2]).unwrap()
1584
+ .as_dtype(Dtype::Bfloat16)
1585
+ .unwrap();
1586
+ let file = write_parameters(dir.path(), &[("m.w", half)]);
1587
+
1588
+ let (config, _) = fixtures::scaled_mean();
1589
+ let (_, params) = Plan::open(&config, Weights::File(&file)).unwrap();
1590
+ assert_eq!(params[0].dtype(), Dtype::Float32);
1591
+ let held = crate::tensor::to_tensor(&params[0]).unwrap();
1592
+ match held.values {
1593
+ Values::F32(v) => assert_eq!(v, vec![0.5, 2.0]),
1594
+ _ => panic!("a parameter is f32"),
1595
+ }
1596
+ }
1597
+
1598
+ #[test]
1599
+ fn a_file_that_is_not_there_says_so_rather_than_reporting_a_missing_parameter() {
1600
+ let (config, _) = fixtures::scaled_mean();
1601
+ let missing = std::path::Path::new("/nowhere/parameters.safetensors");
1602
+ let e = match Plan::open(&config, Weights::File(missing)) {
1603
+ Ok(_) => panic!("this should not have opened"),
1604
+ Err(e) => format!("{e:#}"),
1605
+ };
1606
+ assert!(e.contains("no parameters at"), "{e}");
1607
+ }
1608
+
1609
+ #[test]
1610
+ fn a_pattern_is_a_path_or_a_prefix() {
1611
+ let exact = Pattern::parse("a.b").unwrap();
1612
+ assert!(exact.matches("a.b"));
1613
+ assert!(!exact.matches("a.bc"));
1614
+ assert!(!exact.matches("a"));
1615
+
1616
+ let prefix = Pattern::parse("a.*").unwrap();
1617
+ assert!(prefix.matches("a.b"));
1618
+ assert!(prefix.matches("a.b.c"));
1619
+ assert!(!prefix.matches("ab.c"));
1620
+ assert_eq!(format!("{prefix:?}"), r#""a.*""#);
1621
+
1622
+ assert!(Pattern::parse("").is_err());
1623
+ }
1624
+
1625
+ /// A plan is the description alone: resolved and checked with no
1626
+ /// weights to read and nothing made, which is what lets a graph be
1627
+ /// checked before any file or device is involved.
1628
+ #[test]
1629
+ fn a_description_resolves_without_its_weights() {
1630
+ let (config, _) = fixtures::scaled_mean();
1631
+ let plan = Plan::resolve(&config).unwrap();
1632
+ assert_eq!(plan.paths, vec!["m.w".to_string()]);
1633
+ assert_eq!(plan.candidates, vec![0]);
1634
+ assert_eq!(plan.specs[0].shape, vec![2]);
1635
+ assert_eq!(plan.config_digest, crate::graph::digest(&config));
1636
+ }
1637
+
1638
+ }