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,1523 @@
1
+ //! The session: a loaded graph plus its state, and the few verbs that act
2
+ //! on it. Deliberately narrow, because this is the surface the Ruby
3
+ //! extension binds (docs/plan.md section 4).
4
+ //!
5
+ //! A session owns parameters and counters; it does not own data. Every step
6
+ //! is given its batch (docs/plan.md section 5A.2): the caller decides what
7
+ //! the model sees, and nothing here reads a file or calls back into Ruby.
8
+ //!
9
+ //! Everything below is delegation. What a run is doing lives in
10
+ //! [`crate::plan`], what it has accumulated in [`crate::state`], and how a
11
+ //! step is computed in [`crate::executor`]; this file is the vocabulary
12
+ //! those three are reachable through, and the one place a step's parts are
13
+ //! put in order.
14
+ //!
15
+ //! It comes in two halves. [`SessionCore`] holds the MLX state and does
16
+ //! the work; it is crate-private, so nothing outside can reach MLX past
17
+ //! the runtime. [`Session`] is the public face, and every one of its
18
+ //! methods that touches MLX goes through [`crate::runtime`]. Which methods
19
+ //! those are is decided here, where MLX is owned, and never by the caller
20
+ //! (notes/ENGINE_RUNTIME_BOUNDARY_PLAN.md section 4).
21
+
22
+ use std::collections::BTreeMap;
23
+
24
+ use anyhow::{Context, Result};
25
+ use crate::mlxc::transforms::eval;
26
+
27
+ use crate::executor;
28
+ use crate::interp::{Stat, Taps, Tapped, Watch};
29
+ use crate::optimizer::Config as OptimizerConfig;
30
+ use crate::plan::{Plan, Weights};
31
+ use crate::runtime::{runtime, RuntimeError};
32
+ use crate::state::TrainState;
33
+ use crate::tensor::{to_tensor, Batch, Tensor};
34
+
35
+ /// What a caller gets back: either the value, or which layer refused.
36
+ pub type Outcome<T> = std::result::Result<T, RuntimeError>;
37
+
38
+ /// A loaded run. The public face; the state is behind it.
39
+ pub struct Session {
40
+ /// Taken out by `close`, and by `Drop` if `close` never came.
41
+ core: Option<SessionCore>,
42
+ }
43
+
44
+ /// The MLX state, and the work on it. Crate-private on purpose: reaching
45
+ /// this without the runtime is the bug the runtime exists to prevent.
46
+ pub(crate) struct SessionCore {
47
+ /// What this run does, settled when it opened.
48
+ plan: Plan,
49
+ /// What it has accumulated since.
50
+ state: TrainState,
51
+ /// What the window is watching: node name to how much of it to bring
52
+ /// back. Read-only; changing the set changes what a step evaluates,
53
+ /// so it takes effect from the next one.
54
+ taps: Taps,
55
+ /// The last pass's tapped values, as copies.
56
+ tapped: BTreeMap<String, Tensor>,
57
+ }
58
+
59
+ impl SessionCore {
60
+ fn open_with(
61
+ graph_json: &str,
62
+ weights: Weights<'_>,
63
+ optimizer: OptimizerConfig,
64
+ seed: u64,
65
+ ) -> Result<Self> {
66
+ // One seed, used twice: a parameter built from its declaration is
67
+ // drawn from where the run's first step will draw from, so what a
68
+ // run does is a function of its seed and nothing else.
69
+ let (plan, params) = Plan::open_seeded(graph_json, weights, seed)?;
70
+ let state = TrainState::new(&plan, params, optimizer, seed)?;
71
+ Ok(Self {
72
+ plan,
73
+ state,
74
+ taps: Taps::new(),
75
+ tapped: BTreeMap::new(),
76
+ })
77
+ }
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+ /// Watches a named node. `stat` is "full", "mean", "norm" or "extent";
91
+ /// a reduction costs a scalar per step where "full" costs the tensor,
92
+ /// which is why a standing tap should reduce.
93
+ pub(crate) fn tap(&mut self, name: &str, stat: &str) -> Result<()> {
94
+ let stat = Stat::parse(stat)
95
+ .with_context(|| format!("{stat:?} is not a statistic (full, mean, norm, extent)"))?;
96
+ anyhow::ensure!(
97
+ self.plan.node_names().iter().any(|n| n == name),
98
+ "no value is named {name:?} here (this run has {:?})",
99
+ self.plan.node_names()
100
+ );
101
+ self.taps.insert(name.to_string(), stat);
102
+ Ok(())
103
+ }
104
+
105
+ /// Stops watching. Returns whether it was being watched.
106
+ pub(crate) fn untap(&mut self, name: &str) -> bool {
107
+ self.taps.remove(name).is_some()
108
+ }
109
+
110
+ /// What is being watched.
111
+ pub(crate) fn taps(&self) -> Vec<String> {
112
+ self.taps.keys().cloned().collect()
113
+ }
114
+
115
+
116
+
117
+ /// What the most recent pass's taps saw, by name.
118
+ ///
119
+ /// A copy of a copy: these already live on the host, and the caller
120
+ /// gets its own. A `full` tap therefore costs the tensor again here,
121
+ /// which is the other half of why a standing tap should reduce.
122
+ pub(crate) fn tapped(&self) -> Vec<(String, Tensor)> {
123
+ self.tapped.iter().map(|(name, tensor)| (name.clone(), tensor.clone())).collect()
124
+ }
125
+
126
+ /// Which parameters are currently differentiated, by qualified path.
127
+ pub(crate) fn trainable(&self) -> Vec<String> {
128
+ self.plan.paths_of(self.state.argnums())
129
+ }
130
+
131
+
132
+ /// Freezes or unfreezes parameters whose path matches `pattern`, and
133
+ /// returns those that moved.
134
+ pub(crate) fn set_frozen(&mut self, pattern: &str, frozen: bool) -> Result<Vec<String>> {
135
+ self.state.set_frozen(&self.plan, pattern, frozen)
136
+ }
137
+
138
+ /// Writes one parameter, by qualified path, from a copy. The window's
139
+ /// B capability (docs/plan.md section 8.3).
140
+ pub(crate) fn put(&mut self, path: &str, tensor: &Tensor) -> Result<()> {
141
+ self.state.put(&self.plan, path, tensor)
142
+ }
143
+
144
+ /// One step on `batch`: forward, backward, optimizer update. Long-
145
+ /// running and free of any Ruby, so the extension calls it with the GVL
146
+ /// released.
147
+ pub(crate) fn run_step(&mut self, batch: &Batch) -> Result<f32> {
148
+ self.trains()?;
149
+ let fields = self.plan.bind(batch)?;
150
+ self.update(&fields)
151
+ }
152
+
153
+ /// That there is something to differentiate at all.
154
+ ///
155
+ /// A session opened with `train: []` is for reading: it evaluates and
156
+ /// it differentiates by its inputs, and a step through it would be a
157
+ /// step over no parameters. Said here rather than left to MLX, which
158
+ /// would answer with something about empty argnums.
159
+ fn trains(&self) -> Result<()> {
160
+ anyhow::ensure!(
161
+ !self.state.pass().argnums.is_empty(),
162
+ "this session trains nothing (it was opened with no model to train), \
163
+ so there is no step to take. It can evaluate and it can report \
164
+ gradients by its inputs"
165
+ );
166
+ Ok(())
167
+ }
168
+
169
+ /// Adds one batch's gradients to what is waiting, without stepping.
170
+ ///
171
+ /// A batch too large to hold is trained as several that fit
172
+ /// (docs/plan.md section 15.35). The taps report this pass like any
173
+ /// other, so the parts of a batch can be watched as they go.
174
+ pub(crate) fn accumulate(&mut self, batch: &Batch) -> Result<f32> {
175
+ self.trains()?;
176
+ let fields = self.plan.bind(batch)?;
177
+ let part = self.state.part_rng()?;
178
+ let pass = match &part {
179
+ Some(rng) => self.state.pass_with(rng),
180
+ None => self.state.pass(),
181
+ };
182
+ let (loss, grads, tapped) =
183
+ executor::differentiate(&self.plan, pass, &fields, &self.taps)?;
184
+ let tapped = Self::to_host(tapped)?;
185
+ let loss = self.state.accumulate(&loss, &grads)?;
186
+ self.tapped = tapped;
187
+ Ok(loss)
188
+ }
189
+
190
+
191
+
192
+
193
+ /// The loss for `batch`, without taking a step.
194
+ ///
195
+ /// What a validation set is read with. No gradients, so it costs a
196
+ /// forward rather than a forward and a backward, and no randomness, so
197
+ /// dropout stands aside and the number is the model's rather than a
198
+ /// sample of it. Nothing about the run moves: not the parameters, not
199
+ /// the counters, not the RNG, and not the loss a watcher reads.
200
+ ///
201
+ /// The taps report this pass, as they report any pass.
202
+ pub(crate) fn evaluate(&mut self, batch: &Batch) -> Result<f32> {
203
+ let fields = self.plan.bind(batch)?;
204
+ let (loss, tapped) =
205
+ executor::evaluate(&self.plan, self.state.pass().params, &fields, &self.taps)?;
206
+ self.record(tapped)?;
207
+ Ok(loss.item::<f32>()?)
208
+ }
209
+
210
+ /// Named model outputs for `batch`, without taking a step.
211
+ ///
212
+ /// The forward `evaluate` runs, stopping before the objective: what
213
+ /// comes back is what a model produced (an embedding, a set of
214
+ /// logits) rather than the loss over it. No gradients, no randomness,
215
+ /// and nothing about the run moves.
216
+ ///
217
+ /// `wanted` empty asks for every output there is. The taps report the
218
+ /// pass, except any on the objective, which did not run.
219
+ pub(crate) fn forward(
220
+ &mut self,
221
+ batch: &Batch,
222
+ wanted: &[String],
223
+ ) -> Result<Vec<(String, Tensor)>> {
224
+ let names = self.wanted(wanted)?;
225
+ let fields = self.plan.bind_models(batch)?;
226
+ let mut tapped = Tapped::new();
227
+ let produced = executor::produce(
228
+ &self.plan,
229
+ self.state.pass().params,
230
+ &fields,
231
+ &mut Watch::new(&self.taps, &mut tapped),
232
+ )?;
233
+ let mut found = Vec::with_capacity(names.len());
234
+ for name in &names {
235
+ let (model, output) = self
236
+ .plan
237
+ .output_named(name)
238
+ .with_context(|| format!("no output is named {name:?} here"))?;
239
+ let value = produced
240
+ .get(&(model.to_string(), output.to_string()))
241
+ .with_context(|| format!("{name:?} was not produced by the pass"))?;
242
+ found.push((name.clone(), value.clone()));
243
+ }
244
+ eval(found.iter().map(|(_, value)| value))?;
245
+ self.record(tapped)?;
246
+ found
247
+ .into_iter()
248
+ .map(|(name, value)| Ok((name, to_tensor(&value)?)))
249
+ .collect()
250
+ }
251
+
252
+ /// Which outputs a forward was asked for, refusing a name no model
253
+ /// declares rather than returning less than was asked for.
254
+ fn wanted(&self, wanted: &[String]) -> Result<Vec<String>> {
255
+ if wanted.is_empty() {
256
+ return Ok(self.plan.output_names().to_vec());
257
+ }
258
+ for name in wanted {
259
+ anyhow::ensure!(
260
+ self.plan.output_names().iter().any(|n| n == name),
261
+ "no output is named {name:?} here (this run produces {:?})",
262
+ self.plan.output_names()
263
+ );
264
+ }
265
+ Ok(wanted.to_vec())
266
+ }
267
+
268
+ /// Gradients with respect to named batch fields, by field name.
269
+ ///
270
+ /// The parameters do not move and are not differentiated. What this is
271
+ /// for is a loss over values computed elsewhere: a gradient cache
272
+ /// needs the loss differentiated by the representations it was given,
273
+ /// so the passes that produced them can be re-run with that as their
274
+ /// seed (docs/plan.md section 15.36).
275
+ pub(crate) fn field_gradients(
276
+ &self,
277
+ batch: &Batch,
278
+ of: &[String],
279
+ ) -> Result<Vec<(String, Tensor)>> {
280
+ let fields = self.plan.bind(batch)?;
281
+ let (_, grads) =
282
+ executor::differentiate_fields(&self.plan, self.state.pass().params, &fields, of)?;
283
+ of.iter()
284
+ .cloned()
285
+ .zip(grads)
286
+ .map(|(name, grad)| Ok((name, to_tensor(&grad)?)))
287
+ .collect()
288
+ }
289
+
290
+ /// Gradients as copies, by qualified parameter path. Only differentiated
291
+ /// parameters appear: a frozen model's have none.
292
+ pub(crate) fn gradients(&self, batch: &Batch) -> Result<Vec<(String, Tensor)>> {
293
+ let fields = self.plan.bind(batch)?;
294
+ let (_, grads, _) =
295
+ executor::differentiate(&self.plan, self.state.pass(), &fields, &Taps::new())?;
296
+ self.trainable()
297
+ .into_iter()
298
+ .zip(grads)
299
+ .map(|(path, grad)| Ok((path, to_tensor(&grad)?)))
300
+ .collect()
301
+ }
302
+
303
+ /// A copy of one parameter, by qualified path. Copies, not handles:
304
+ /// nothing that lives on the device escapes this crate.
305
+ pub(crate) fn fetch(&self, path: &str) -> Result<Tensor> {
306
+ self.state.fetch(&self.plan, path)
307
+ }
308
+
309
+
310
+
311
+ /// Writes the run's state and the description it belongs to. Atomic
312
+ /// (docs/plan.md section 11.2). `run` is the caller's own record
313
+ /// (epoch, batch position, sampler state), written verbatim.
314
+ pub(crate) fn save(&self, dir: &str, run: &str) -> Result<String> {
315
+ self.save_as(dir, run, false)
316
+ }
317
+
318
+ pub(crate) fn save_as(&self, dir: &str, run: &str, light: bool) -> Result<String> {
319
+ self.state.save_as(&self.plan, dir, run, light)
320
+ }
321
+
322
+ /// Writes one model's parameters as an HF-compatible fp32 safetensors
323
+ /// file, stripping the GraphConfig model name from each path. `merge`
324
+ /// is an adapter's scale, to fold it into the weights.
325
+ pub(crate) fn export_model(&self, model: &str, dir: &str, merge: Option<f32>) -> Result<Vec<(String, String)>> {
326
+ crate::export::write(&self.plan, self.state.params(), model, dir, merge)
327
+ }
328
+
329
+ /// [`Self::export_model`] with the weights stored as `dtype` ("f32", "bf16" or "f16").
330
+ pub(crate) fn export_model_as(
331
+ &self,
332
+ model: &str,
333
+ dir: &str,
334
+ merge: Option<f32>,
335
+ dtype: &str,
336
+ ) -> Result<Vec<(String, String)>> {
337
+ let dtype = crate::export::dtype_named(dtype)?;
338
+ crate::export::write_as(&self.plan, self.state.params(), model, dir, merge, dtype)
339
+ }
340
+
341
+ /// Writes one model's adapter alone, as PEFT names it.
342
+ pub(crate) fn export_adapter(&self, model: &str, dir: &str) -> Result<Vec<(String, String)>> {
343
+ crate::export::write_adapter(&self.plan, self.state.params(), model, dir)
344
+ }
345
+
346
+ /// Restores state written by [`Session::save`], refusing anything that
347
+ /// does not belong to this session. Returns the caller's record.
348
+ pub(crate) fn restore(&mut self, dir: &str) -> Result<String> {
349
+ self.state.restore(&self.plan, dir)
350
+ }
351
+
352
+ /// One step over already-bound inputs: differentiate, read the taps,
353
+ /// then commit. The taps are converted before the state moves so that
354
+ /// a step either happens whole or not at all.
355
+ fn update(&mut self, fields: &BTreeMap<String, crate::mlxc::Array>) -> Result<f32> {
356
+ let (loss, grads, tapped) =
357
+ executor::differentiate(&self.plan, self.state.pass(), fields, &self.taps)?;
358
+ // Brought back before the state moves, so a step either happens
359
+ // whole or not at all.
360
+ let tapped = Self::to_host(tapped)?;
361
+ let loss = self.state.advance(&loss, &grads)?;
362
+ self.tapped = tapped;
363
+ Ok(loss)
364
+ }
365
+
366
+ /// Keeps what the taps saw, as host-side copies.
367
+ fn record(&mut self, tapped: Tapped) -> Result<()> {
368
+ self.tapped = Self::to_host(tapped)?;
369
+ Ok(())
370
+ }
371
+
372
+ fn to_host(tapped: Tapped) -> Result<BTreeMap<String, Tensor>> {
373
+ tapped
374
+ .iter()
375
+ .map(|(name, value)| Ok((name.clone(), to_tensor(value)?)))
376
+ .collect()
377
+ }
378
+ }
379
+
380
+ /// The public face. Every method that touches MLX goes through the
381
+ /// runtime; which ones those are is settled here rather than by whoever
382
+ /// is calling (notes/ENGINE_RUNTIME_BOUNDARY_PLAN.md section 4.3).
383
+ ///
384
+ /// The line is exact. A method belongs on the plain side only if it makes
385
+ /// no `Array`, evaluates none, copies nothing off the device, frees none,
386
+ /// and touches neither the allocator nor the stream. Everything else waits
387
+ /// its turn.
388
+ impl Session {
389
+ /// What `open` runs with: plain SGD, which has no state to restore,
390
+ /// and a seed of zero.
391
+ ///
392
+ /// Not the library's default in any binding sense. Ruby names its own
393
+ /// (`Torobi::Session::DEFAULT_OPTIMIZER`) and always states both, so
394
+ /// what this decides is the command-line tool's runs and the tests'.
395
+ /// Two places say "sgd 0.1" and neither reads the other, which is
396
+ /// fine as long as neither is mistaken for one contract in two
397
+ /// languages.
398
+ const SPIKE: (OptimizerConfig, u64) = (
399
+ OptimizerConfig::Sgd {
400
+ lr: 0.1,
401
+ clip: None,
402
+ },
403
+ 0,
404
+ );
405
+
406
+ /// Loads a GraphConfig and its initial parameters. Parameters are given
407
+ /// by qualified path ("student.head.weight"), which is also the order
408
+ /// the engine keeps them in. Data comes later, one batch per step.
409
+ ///
410
+ /// For the command-line tool and the tests: a caller that has an
411
+ /// update rule and a seed to state uses [`Session::open_with`].
412
+ pub fn open(graph_json: &str, weights: Weights<'_>) -> Outcome<Self> {
413
+ let (optimizer, seed) = Self::SPIKE;
414
+ Self::open_with(graph_json, weights, optimizer, seed)
415
+ }
416
+
417
+ /// The same, with the update rule named and the run's seed given.
418
+ ///
419
+ /// The seed is where every draw this run makes comes from: the
420
+ /// parameters a `fresh:` pattern builds at open, and the ops that draw
421
+ /// at each step. A run is reproducible from its graph, its parameters
422
+ /// and this.
423
+ pub fn open_with(
424
+ graph_json: &str,
425
+ weights: Weights<'_>,
426
+ optimizer: OptimizerConfig,
427
+ seed: u64,
428
+ ) -> Outcome<Self> {
429
+ // Opening builds every parameter, an RNG key and the optimizer's
430
+ // slots, so it waits its turn like any other MLX work.
431
+ let core =
432
+ runtime().execute(|| SessionCore::open_with(graph_json, weights, optimizer, seed))?;
433
+ Ok(Self { core: Some(core) })
434
+ }
435
+
436
+ /// Releases the run's device memory. Idempotent, and afterwards every
437
+ /// method refuses rather than pretending. Returns whether this call was
438
+ /// the one that closed it.
439
+ ///
440
+ /// In a forked child the memory is leaked rather than freed, and the
441
+ /// refusal says so; the device those handles name did not come along.
442
+ pub fn close(&mut self) -> Outcome<bool> {
443
+ let Some(core) = self.core.take() else {
444
+ return Ok(false);
445
+ };
446
+ runtime().release(core)?;
447
+ Ok(true)
448
+ }
449
+
450
+ pub fn closed(&self) -> bool {
451
+ self.core.is_none()
452
+ }
453
+
454
+ // --- plain: no Array is made, evaluated, copied or freed ---
455
+
456
+ pub fn step(&self) -> Outcome<usize> {
457
+ self.read(|core| core.state.step())
458
+ }
459
+
460
+ pub fn loss(&self) -> Outcome<f32> {
461
+ self.read(|core| core.state.loss())
462
+ }
463
+
464
+ pub fn lr(&self) -> Outcome<f32> {
465
+ self.read(|core| core.state.lr())
466
+ }
467
+
468
+ /// A knob: effect begins with the next step.
469
+ pub fn set_lr(&mut self, lr: f32) -> Outcome<()> {
470
+ self.adjust(|core| core.state.set_lr(lr))
471
+ }
472
+
473
+ /// The norm of the last step's gradients, before clipping. NaN before
474
+ /// the first step and on a step that was skipped.
475
+ pub fn grad_norm(&self) -> Outcome<f32> {
476
+ self.read(|core| core.state.grad_norm())
477
+ }
478
+
479
+ /// The largest gradient norm a step may carry, or `None`.
480
+ pub fn clip(&self) -> Outcome<Option<f32>> {
481
+ self.read(|core| core.state.clip())
482
+ }
483
+
484
+ /// A knob: effect begins with the next step. `None` is no cap.
485
+ pub fn set_clip(&mut self, clip: Option<f32>) -> Outcome<()> {
486
+ self.adjust(|core| core.state.set_clip(clip))
487
+ }
488
+
489
+ /// What update rule this session runs, as data.
490
+ pub fn optimizer_config(&self) -> Outcome<OptimizerConfig> {
491
+ self.read(|core| core.state.optimizer_config().clone())
492
+ }
493
+
494
+ pub fn seed(&self) -> Outcome<u64> {
495
+ self.read(|core| core.state.seed())
496
+ }
497
+
498
+ /// Watches a named node. `stat` is "full", "mean", "norm" or "extent";
499
+ /// a reduction costs a scalar per step where "full" costs the tensor,
500
+ /// which is why a standing tap should reduce.
501
+ pub fn tap(&mut self, name: &str, stat: &str) -> Outcome<()> {
502
+ self.adjust(|core| core.tap(name, stat))?.map_err(RuntimeError::from)
503
+ }
504
+
505
+ /// Stops watching. Returns whether it was being watched.
506
+ pub fn untap(&mut self, name: &str) -> Outcome<bool> {
507
+ self.adjust(|core| core.untap(name))
508
+ }
509
+
510
+ /// What is being watched.
511
+ pub fn taps(&self) -> Outcome<Vec<String>> {
512
+ self.read(|core| core.taps())
513
+ }
514
+
515
+ /// Every name a tap could ask for.
516
+ pub fn node_names(&self) -> Outcome<Vec<String>> {
517
+ self.read(|core| core.plan.node_names().to_vec())
518
+ }
519
+
520
+ /// What the most recent pass's taps saw. Already on the host, so this
521
+ /// copies rather than reads a device.
522
+ pub fn tapped(&self) -> Outcome<Vec<(String, Tensor)>> {
523
+ self.read(|core| core.tapped())
524
+ }
525
+
526
+ /// Which parameters are currently differentiated, by qualified path.
527
+ pub fn trainable(&self) -> Outcome<Vec<String>> {
528
+ self.read(|core| core.trainable())
529
+ }
530
+
531
+ /// Every parameter a model declared trainable, whether or not it is
532
+ /// frozen right now.
533
+ pub fn trainable_candidates(&self) -> Outcome<Vec<String>> {
534
+ self.read(|core| core.plan.candidate_paths())
535
+ }
536
+
537
+ /// Qualified parameter paths, in the order the engine keeps them.
538
+ pub fn parameter_paths(&self) -> Outcome<Vec<String>> {
539
+ self.read(|core| core.plan.paths.clone())
540
+ }
541
+
542
+ /// Every batch field the run reads.
543
+ pub fn input_names(&self) -> Outcome<Vec<String>> {
544
+ self.read(|core| core.plan.input_names().to_vec())
545
+ }
546
+
547
+ // --- MLX: through the runtime ---
548
+
549
+ /// Restarts the RNG. A knob like any other, but it builds a key.
550
+ pub fn set_seed(&mut self, seed: u64) -> Outcome<()> {
551
+ self.gated_mut(|core| core.state.set_seed(seed))
552
+ }
553
+
554
+ /// Freezes or unfreezes parameters whose path matches `pattern`, and
555
+ /// returns those that moved. Not a scalar knob: the optimizer's slots
556
+ /// follow, which means allocating and dropping them.
557
+ pub fn set_frozen(&mut self, pattern: &str, frozen: bool) -> Outcome<Vec<String>> {
558
+ self.gated_mut(|core| core.set_frozen(pattern, frozen))
559
+ }
560
+
561
+ /// Writes one parameter, by qualified path, from a copy.
562
+ pub fn put(&mut self, path: &str, tensor: &Tensor) -> Outcome<()> {
563
+ self.gated_mut(|core| core.put(path, tensor))
564
+ }
565
+
566
+ /// One step on `batch`: forward, backward, optimizer update.
567
+ pub fn run_step(&mut self, batch: &Batch) -> Outcome<f32> {
568
+ self.gated_mut(|core| core.run_step(batch))
569
+ }
570
+
571
+ /// Adds one batch's gradients to what is waiting, without stepping.
572
+ pub fn accumulate(&mut self, batch: &Batch) -> Outcome<f32> {
573
+ self.gated_mut(|core| core.accumulate(batch))
574
+ }
575
+
576
+ /// Takes the step the accumulated gradients ask for, and reports the
577
+ /// mean of the losses they came from.
578
+ pub fn apply(&mut self) -> Outcome<f32> {
579
+ self.gated_mut(|core| core.state.apply())
580
+ }
581
+
582
+ /// How many parts are waiting for a step. Touches no MLX.
583
+ pub fn accumulated(&self) -> Outcome<usize> {
584
+ self.read(|core| core.state.accumulated())
585
+ }
586
+
587
+ /// Throws away what was accumulated, and says how many parts went.
588
+ pub fn discard(&mut self) -> Outcome<usize> {
589
+ self.gated_mut(|core| Ok(core.state.discard()))
590
+ }
591
+
592
+ /// The loss for `batch` without taking a step: no gradients, no
593
+ /// randomness, nothing moved. What a validation set is read with.
594
+ pub fn evaluate(&mut self, batch: &Batch) -> Outcome<f32> {
595
+ self.gated_mut(|core| core.evaluate(batch))
596
+ }
597
+
598
+ /// Named model outputs for `batch`: the forward an evaluation runs,
599
+ /// stopping before the objective. Nothing about the run moves.
600
+ pub fn forward(&mut self, batch: &Batch, wanted: &[String]) -> Outcome<Vec<(String, Tensor)>> {
601
+ self.gated_mut(|core| core.forward(batch, wanted))
602
+ }
603
+
604
+ /// Every model output a forward can be asked for, qualified.
605
+ pub fn output_names(&self) -> Outcome<Vec<String>> {
606
+ self.read(|core| core.plan.output_names().to_vec())
607
+ }
608
+
609
+ /// Gradients with respect to named batch fields, by field name. The
610
+ /// parameters do not move.
611
+ pub fn field_gradients(
612
+ &self,
613
+ batch: &Batch,
614
+ of: &[String],
615
+ ) -> Outcome<Vec<(String, Tensor)>> {
616
+ self.gated(|core| core.field_gradients(batch, of))
617
+ }
618
+
619
+ /// Gradients as copies, by qualified parameter path. Only
620
+ /// differentiated parameters appear.
621
+ pub fn gradients(&self, batch: &Batch) -> Outcome<Vec<(String, Tensor)>> {
622
+ self.gated(|core| core.gradients(batch))
623
+ }
624
+
625
+ /// A copy of one parameter, by qualified path. Copies, not handles:
626
+ /// nothing that lives on the device escapes this crate.
627
+ pub fn fetch(&self, path: &str) -> Outcome<Tensor> {
628
+ self.gated(|core| core.fetch(path))
629
+ }
630
+
631
+ /// The L2 norm of every parameter. A reduction over the whole model, so
632
+ /// it is asked for rather than kept up to date; nothing in a step reads
633
+ /// it. Goes through the runtime like any other MLX work.
634
+ pub fn param_norm(&self) -> Outcome<f32> {
635
+ self.gated(|core| core.state.param_norm())
636
+ }
637
+
638
+ /// Writes the run's state and the description it belongs to. Atomic.
639
+ /// `run` is the caller's own record, written verbatim.
640
+ pub fn save(&self, dir: &str, run: &str) -> Outcome<String> {
641
+ self.save_as(dir, run, false)
642
+ }
643
+
644
+ pub fn save_as(&self, dir: &str, run: &str, light: bool) -> Outcome<String> {
645
+ self.gated(|core| core.save_as(dir, run, light))
646
+ }
647
+
648
+ /// Writes one model's parameters as an HF-compatible fp32 safetensors
649
+ /// file, stripping the GraphConfig model name from each path.
650
+ pub fn export_model(&self, model: &str, dir: &str, merge: Option<f32>) -> Outcome<Vec<(String, String)>> {
651
+ self.gated(|core| core.export_model(model, dir, merge))
652
+ }
653
+
654
+ /// [`Self::export_model`] with the weights stored as `dtype` ("f32", "bf16" or "f16").
655
+ pub fn export_model_as(
656
+ &self,
657
+ model: &str,
658
+ dir: &str,
659
+ merge: Option<f32>,
660
+ dtype: &str,
661
+ ) -> Outcome<Vec<(String, String)>> {
662
+ self.gated(|core| core.export_model_as(model, dir, merge, dtype))
663
+ }
664
+
665
+ /// Writes one model's adapter alone, as PEFT names it.
666
+ pub fn export_adapter(&self, model: &str, dir: &str) -> Outcome<Vec<(String, String)>> {
667
+ self.gated(|core| core.export_adapter(model, dir))
668
+ }
669
+
670
+ /// Restores state written by [`Session::save`], refusing anything that
671
+ /// does not belong to this session. Returns the caller's record.
672
+ pub fn restore(&mut self, dir: &str) -> Outcome<String> {
673
+ self.gated_mut(|core| core.restore(dir))
674
+ }
675
+
676
+ /// The RNG key as host values, for the tests that watch it move.
677
+ ///
678
+ /// Test-only: a key is state, and nothing outside has a use for it. It
679
+ /// goes through the runtime like everything else, because reading an
680
+ /// array evaluates it and copies it off the device. A test that took
681
+ /// the short way here would be submitting to MLX from a thread of its
682
+ /// own while another test's step was in flight, which is what this
683
+ /// crate's whole runtime exists to prevent.
684
+ #[cfg(test)]
685
+ pub(crate) fn rng_for_test(&self) -> Tensor {
686
+ let core = self.core.as_ref().expect("open");
687
+ runtime()
688
+ .execute(|| crate::tensor::to_tensor(core.state.pass().rng))
689
+ .expect("reading the RNG key")
690
+ }
691
+
692
+ /// A value of the open session that does not reach MLX.
693
+ fn read<R>(&self, f: impl FnOnce(&SessionCore) -> R) -> Outcome<R> {
694
+ Ok(f(self.core()?))
695
+ }
696
+
697
+ /// A change to the open session that does not reach MLX (a knob).
698
+ fn adjust<R>(&mut self, f: impl FnOnce(&mut SessionCore) -> R) -> Outcome<R> {
699
+ Ok(f(self.core_mut()?))
700
+ }
701
+
702
+ /// An operation on the open session that reaches MLX, through the
703
+ /// runtime's gate: the one way every such call goes.
704
+ fn gated<R>(&self, f: impl FnOnce(&SessionCore) -> Result<R>) -> Outcome<R> {
705
+ let core = self.core()?;
706
+ runtime().execute(|| f(core))
707
+ }
708
+
709
+ /// The same, for an operation that changes the session.
710
+ fn gated_mut<R>(&mut self, f: impl FnOnce(&mut SessionCore) -> Result<R>) -> Outcome<R> {
711
+ let core = self.core_mut()?;
712
+ runtime().execute(|| f(core))
713
+ }
714
+
715
+ fn core(&self) -> Outcome<&SessionCore> {
716
+ self.core.as_ref().ok_or_else(closed)
717
+ }
718
+
719
+ fn core_mut(&mut self) -> Outcome<&mut SessionCore> {
720
+ self.core.as_mut().ok_or_else(closed)
721
+ }
722
+ }
723
+
724
+ /// The GC frees device memory as surely as `close` does, so both go the
725
+ /// same way. A session dropped without being closed still releases under
726
+ /// the gate, and still leaks rather than frees in a forked child.
727
+ impl Drop for Session {
728
+ fn drop(&mut self) {
729
+ if let Some(core) = self.core.take() {
730
+ let _ = runtime().release(core);
731
+ }
732
+ }
733
+ }
734
+
735
+ fn closed() -> RuntimeError {
736
+ RuntimeError::Engine(anyhow::anyhow!("this session is closed"))
737
+ }
738
+
739
+ #[cfg(test)]
740
+ mod tests {
741
+ use super::*;
742
+ use crate::fixtures;
743
+ use crate::tensor::Values;
744
+
745
+ pub fn session(which: (String, String)) -> Session {
746
+ let (config, weights) = which;
747
+ Session::open(&config, Weights::Inline(&weights)).unwrap()
748
+ }
749
+
750
+ pub fn values(t: &Tensor) -> Vec<f32> {
751
+ match &t.values {
752
+ Values::F32(v) => v.clone(),
753
+ Values::I32(v) => v.iter().map(|&i| i as f32).collect(),
754
+ }
755
+ }
756
+
757
+ pub fn close(got: &[f32], want: &[f32]) {
758
+ within(got, want, 1e-6);
759
+ }
760
+
761
+ /// The same batch with its numbers scaled.
762
+ ///
763
+ /// The fixture's loss is a mean and is linear in x, so this scales the
764
+ /// loss and with it the gradients. Splitting a batch means weighting
765
+ /// its parts, and for a mean over rows the weight is the share of the
766
+ /// rows each part holds; the engine does not guess it because only the
767
+ /// caller knows what its loss is a mean of.
768
+ fn scaled(batch: &Batch, by: f32) -> Batch {
769
+ batch
770
+ .iter()
771
+ .map(|(name, tensor)| {
772
+ let values = match &tensor.values {
773
+ Values::F32(v) => Values::F32(v.iter().map(|x| x * by).collect()),
774
+ _ => panic!("this fixture is f32"),
775
+ };
776
+ (
777
+ name.clone(),
778
+ Tensor {
779
+ shape: tensor.shape.clone(),
780
+ values,
781
+ },
782
+ )
783
+ })
784
+ .collect()
785
+ }
786
+
787
+ pub fn within(got: &[f32], want: &[f32], tolerance: f32) {
788
+ assert_eq!(got.len(), want.len(), "{got:?} against {want:?}");
789
+ for (g, w) in got.iter().zip(want) {
790
+ assert!((g - w).abs() < tolerance, "{got:?} against {want:?}");
791
+ }
792
+ }
793
+
794
+ #[test]
795
+ fn the_gradient_is_the_one_the_arithmetic_says() {
796
+ // loss = mean(x * w) over four values, so d(loss)/dw_j is the sum
797
+ // of column j divided by four.
798
+ let mut session = session(fixtures::scaled_mean());
799
+ let batch = fixtures::batch_x(&[1.0, 2.0, 3.0, 4.0]);
800
+ let grads = session.gradients(&batch).unwrap();
801
+ assert_eq!(grads.len(), 1);
802
+ assert_eq!(grads[0].0, "m.w");
803
+ close(&values(&grads[0].1), &[(1.0 + 3.0) / 4.0, (2.0 + 4.0) / 4.0]);
804
+
805
+ // w = [1, 2], so x * w is [[1, 4], [3, 8]] and the mean is 4.
806
+ let loss = session.evaluate(&batch).unwrap();
807
+ assert!((loss - 4.0).abs() < 1e-6, "{loss}");
808
+ }
809
+
810
+ #[test]
811
+ fn a_frozen_model_has_no_gradient_to_report() {
812
+ let session = session(fixtures::teacher_and_student());
813
+ let grads = session.gradients(&fixtures::batch_x(&[1.0, 1.0])).unwrap();
814
+ assert_eq!(
815
+ grads.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>(),
816
+ vec!["student.scale"]
817
+ );
818
+ assert_eq!(
819
+ session.parameter_paths().unwrap(),
820
+ vec!["student.scale", "teacher.scale"]
821
+ );
822
+ assert_eq!(session.trainable().unwrap(), vec!["student.scale"]);
823
+ }
824
+
825
+ #[test]
826
+ fn a_model_that_reads_one_declared_after_it_is_refused_by_name() {
827
+ let session = session(fixtures::reader_before_producer());
828
+ let e = session
829
+ .gradients(&fixtures::batch_x(&[1.0, 1.0]))
830
+ .unwrap_err()
831
+ .to_string();
832
+ assert!(e.contains("source.out has not been produced"), "{e}");
833
+ assert!(e.contains("declared before what reads it"), "{e}");
834
+ }
835
+
836
+ #[test]
837
+ fn training_moves_the_loss_toward_the_teacher() {
838
+ let mut session = session(fixtures::teacher_and_student());
839
+ session.set_lr(0.05).unwrap();
840
+ let batch = fixtures::batch_x(&[1.0, 1.0, 2.0, 2.0]);
841
+ let first = session.run_step(&batch).unwrap();
842
+ for _ in 0..50 {
843
+ session.run_step(&batch).unwrap();
844
+ }
845
+ assert_eq!(session.step().unwrap(), 51);
846
+ assert!(session.loss().unwrap() < first * 0.1, "{} -> {}", first, session.loss().unwrap());
847
+ // It converged on the teacher's scale, which is what the objective
848
+ // asks for. Fifty steps of plain SGD get three digits, not six.
849
+ within(&values(&session.fetch("student.scale").unwrap()), &[3.0, 4.0], 1e-2);
850
+ // And the teacher did not move.
851
+ close(&values(&session.fetch("teacher.scale").unwrap()), &[3.0, 4.0]);
852
+ }
853
+
854
+ #[test]
855
+ fn a_tap_reports_what_the_step_computed() {
856
+ let mut session = session(fixtures::scaled_mean());
857
+ assert_eq!(session.node_names().unwrap(), vec!["m.scaled"]);
858
+ assert!(session.tapped().unwrap().is_empty());
859
+
860
+ session.tap("m.scaled", "mean").unwrap();
861
+ assert_eq!(session.taps().unwrap(), vec!["m.scaled"]);
862
+ // x * w with x = [[1, 1]] and w = [1, 2] is [[1, 2]], mean 1.5.
863
+ session.run_step(&fixtures::batch_x(&[1.0, 1.0])).unwrap();
864
+ let seen = session.tapped().unwrap();
865
+ assert_eq!(seen.len(), 1);
866
+ assert_eq!(seen[0].0, "m.scaled");
867
+ close(&values(&seen[0].1), &[1.5]);
868
+
869
+ assert!(session.untap("m.scaled").unwrap());
870
+ assert!(!session.untap("m.scaled").unwrap());
871
+ assert!(session.taps().unwrap().is_empty());
872
+ }
873
+
874
+ #[test]
875
+ fn a_full_tap_brings_back_the_tensor_and_a_reduction_a_scalar() {
876
+ let mut session = session(fixtures::scaled_mean());
877
+ session.tap("m.scaled", "full").unwrap();
878
+ session.run_step(&fixtures::batch_x(&[1.0, 1.0])).unwrap();
879
+ let seen = session.tapped().unwrap();
880
+ assert_eq!(seen[0].1.shape, vec![1, 2]);
881
+ close(&values(&seen[0].1), &[1.0, 2.0]);
882
+ }
883
+
884
+ /// The name a tap asks for carries the model, so a distillation can
885
+ /// watch the student and the teacher at once. Unqualified, both models
886
+ /// answer to "scaled" and one of them silently wins.
887
+ #[test]
888
+ fn two_models_of_one_shape_are_tapped_apart() {
889
+ let mut session = session(fixtures::teacher_and_student());
890
+ assert_eq!(
891
+ session.node_names().unwrap(),
892
+ vec!["student.scaled", "teacher.scaled"]
893
+ );
894
+
895
+ session.tap("student.scaled", "full").unwrap();
896
+ session.tap("teacher.scaled", "full").unwrap();
897
+ session.evaluate(&fixtures::batch_x(&[1.0, 1.0])).unwrap();
898
+
899
+ let seen = session.tapped().unwrap();
900
+ assert_eq!(seen.len(), 2);
901
+ // The student's scale is [1, 1] and the teacher's is [3, 4]: each
902
+ // tap reports its own model rather than whichever ran last.
903
+ assert_eq!(seen[0].0, "student.scaled");
904
+ close(&values(&seen[0].1), &[1.0, 1.0]);
905
+ assert_eq!(seen[1].0, "teacher.scaled");
906
+ close(&values(&seen[1].1), &[3.0, 4.0]);
907
+ }
908
+
909
+ /// The property accumulation exists for: the gradients of a sum are
910
+ /// the sum of the gradients, so a batch trained as parts reaches where
911
+ /// one step over the whole of it would have.
912
+ #[test]
913
+ fn parts_accumulated_reach_where_the_whole_batch_would() {
914
+ let whole = fixtures::batch_x(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
915
+ let mut one = session(fixtures::scaled_mean());
916
+ one.run_step(&whole).unwrap();
917
+
918
+ // The same rows, in two halves. The loss is a mean over rows, so
919
+ // each half carries half the weight of the whole; the caller's
920
+ // arithmetic, which is why the engine does not guess it.
921
+ let mut parts = session(fixtures::scaled_mean());
922
+ for half in [
923
+ fixtures::batch_x(&[1.0, 2.0, 3.0, 4.0]),
924
+ fixtures::batch_x(&[5.0, 6.0, 7.0, 8.0]),
925
+ ] {
926
+ parts.accumulate(&scaled(&half, 0.5)).unwrap();
927
+ }
928
+ assert_eq!(parts.accumulated().unwrap(), 2);
929
+ parts.apply().unwrap();
930
+ assert_eq!(parts.accumulated().unwrap(), 0);
931
+
932
+ assert_eq!(parts.step().unwrap(), 1, "applying is one step");
933
+ within(
934
+ &values(&parts.fetch("m.w").unwrap()),
935
+ &values(&one.fetch("m.w").unwrap()),
936
+ 1e-6,
937
+ );
938
+ }
939
+
940
+ #[test]
941
+ fn accumulating_moves_nothing_until_it_is_applied() {
942
+ let mut session = session(fixtures::scaled_mean());
943
+ let before = values(&session.fetch("m.w").unwrap());
944
+ session
945
+ .accumulate(&fixtures::batch_x(&[1.0, 2.0]))
946
+ .unwrap();
947
+
948
+ assert_eq!(session.step().unwrap(), 0);
949
+ close(&values(&session.fetch("m.w").unwrap()), &before);
950
+
951
+ assert_eq!(session.discard().unwrap(), 1);
952
+ assert_eq!(session.accumulated().unwrap(), 0);
953
+ close(&values(&session.fetch("m.w").unwrap()), &before);
954
+ }
955
+
956
+ /// The loss differentiated by what it was given rather than by what
957
+ /// it holds. `scaled_mean` is mean(x * w) with w = [1, 2] over two
958
+ /// elements, so the answer is w / 2 and can be read off the page.
959
+ #[test]
960
+ fn a_loss_can_be_differentiated_by_a_batch_field() {
961
+ let session = session(fixtures::scaled_mean());
962
+ let before = values(&session.fetch("m.w").unwrap());
963
+ let batch = fixtures::batch_x(&[1.0, 2.0]);
964
+
965
+ let grads = session
966
+ .field_gradients(&batch, &["x".to_string()])
967
+ .unwrap();
968
+
969
+ assert_eq!(grads.len(), 1);
970
+ assert_eq!(grads[0].0, "x");
971
+ close(&values(&grads[0].1), &[0.5, 1.0]);
972
+ // The parameters are not what was differentiated, and nothing moved.
973
+ close(&values(&session.fetch("m.w").unwrap()), &before);
974
+ assert_eq!(session.step().unwrap(), 0);
975
+ }
976
+
977
+ #[test]
978
+ fn differentiating_by_a_field_the_batch_does_not_have_is_refused() {
979
+ let session = session(fixtures::scaled_mean());
980
+ let batch = fixtures::batch_x(&[1.0, 2.0]);
981
+
982
+ let e = session
983
+ .field_gradients(&batch, &["elsewhere".to_string()])
984
+ .unwrap_err()
985
+ .to_string();
986
+
987
+ assert!(e.contains("elsewhere"), "{e}");
988
+ assert!(e.contains("\"x\""), "{e}");
989
+ }
990
+
991
+ #[test]
992
+ fn a_step_from_nothing_accumulated_is_refused() {
993
+ let mut session = session(fixtures::scaled_mean());
994
+ let e = session.apply().unwrap_err().to_string();
995
+
996
+ assert!(e.contains("nothing has been accumulated"), "{e}");
997
+ }
998
+
999
+ /// Freezing moves what a gradient is for, and a checkpoint does not
1000
+ /// hold what is waiting. Both say so rather than quietly dropping it.
1001
+ #[test]
1002
+ fn what_is_waiting_blocks_freezing_and_checkpointing() {
1003
+ let dir = tempfile::tempdir().unwrap();
1004
+ let mut session = session(fixtures::scaled_mean());
1005
+ session
1006
+ .accumulate(&fixtures::batch_x(&[1.0, 2.0]))
1007
+ .unwrap();
1008
+
1009
+ let e = session.set_frozen("m.w", true).unwrap_err().to_string();
1010
+ assert!(e.contains("accumulated"), "{e}");
1011
+ let e = session
1012
+ .save(dir.path().join("c").to_str().unwrap(), "")
1013
+ .unwrap_err()
1014
+ .to_string();
1015
+ assert!(e.contains("accumulated"), "{e}");
1016
+ }
1017
+
1018
+ /// A forward is how a run is asked what it produces, rather than what
1019
+ /// its loss is: two models, both of them answered, each qualified by
1020
+ /// the model that produced it.
1021
+ #[test]
1022
+ fn a_forward_brings_back_what_the_models_produced() {
1023
+ let mut session = session(fixtures::teacher_and_student());
1024
+ assert_eq!(
1025
+ session.output_names().unwrap(),
1026
+ vec!["student.out", "teacher.out"]
1027
+ );
1028
+
1029
+ let produced = session
1030
+ .forward(&fixtures::batch_x(&[1.0, 1.0]), &[])
1031
+ .unwrap();
1032
+ let names: Vec<_> = produced.iter().map(|(name, _)| name.as_str()).collect();
1033
+
1034
+ assert_eq!(names, vec!["student.out", "teacher.out"]);
1035
+ // x * scale, with the student's [1, 1] and the teacher's [3, 4].
1036
+ close(&values(&produced[0].1), &[1.0, 1.0]);
1037
+ close(&values(&produced[1].1), &[3.0, 4.0]);
1038
+ assert_eq!(produced[0].1.shape, vec![1, 2]);
1039
+ }
1040
+
1041
+ /// A qualified output name is found rather than parsed.
1042
+ ///
1043
+ /// The engine is handed names, not promises about them. Ruby refuses a
1044
+ /// model name holding a dot, because "a.b.out" would otherwise have
1045
+ /// two readings; this side does not depend on that, and the version
1046
+ /// that did split at the first dot panicked here, which poisoned the
1047
+ /// gate and closed the whole process to MLX.
1048
+ #[test]
1049
+ fn a_model_name_with_a_dot_is_answered_rather_than_split() {
1050
+ let graph = serde_json::json!({
1051
+ "inputs": [fixtures::input(0, "x", serde_json::json!([null, 2]), "f32")],
1052
+ "parameters": [],
1053
+ "nodes": [fixtures::node(0, "square", serde_json::json!(["input:0"]), serde_json::json!([]))],
1054
+ "outputs": {"out": "node:0"},
1055
+ });
1056
+ let config = fixtures::config(
1057
+ serde_json::json!({ "a.b": graph }),
1058
+ serde_json::Value::Null,
1059
+ serde_json::json!([]),
1060
+ );
1061
+ let mut session = session((config, "{\"params\": {}}".to_string()));
1062
+
1063
+ assert_eq!(session.output_names().unwrap(), vec!["a.b.out"]);
1064
+ let produced = session
1065
+ .forward(&fixtures::batch_x(&[3.0, 4.0]), &[])
1066
+ .unwrap();
1067
+
1068
+ assert_eq!(produced[0].0, "a.b.out");
1069
+ close(&values(&produced[0].1), &[9.0, 16.0]);
1070
+ }
1071
+
1072
+ /// And asked for one of them by name. A name no model declares is
1073
+ /// refused with what there is, rather than answered with less than was
1074
+ /// asked for.
1075
+ #[test]
1076
+ fn a_forward_answers_the_outputs_it_was_asked_for() {
1077
+ let mut session = session(fixtures::teacher_and_student());
1078
+ let batch = fixtures::batch_x(&[1.0, 1.0]);
1079
+
1080
+ let one = session.forward(&batch, &["teacher.out".to_string()]).unwrap();
1081
+
1082
+ assert_eq!(one.len(), 1);
1083
+ close(&values(&one[0].1), &[3.0, 4.0]);
1084
+
1085
+ let e = session
1086
+ .forward(&batch, &["teacher.hidden".to_string()])
1087
+ .unwrap_err()
1088
+ .to_string();
1089
+
1090
+ assert!(e.contains("no output is named"), "{e}");
1091
+ assert!(e.contains("teacher.out"), "{e}");
1092
+ }
1093
+
1094
+ /// Nothing about the run moves: it is the evaluation pass, and the
1095
+ /// counters, the loss a watcher reads and the parameters are all where
1096
+ /// they were.
1097
+ #[test]
1098
+ fn a_forward_moves_nothing() {
1099
+ let mut session = session(fixtures::scaled_mean());
1100
+ let batch = fixtures::batch_x(&[1.0, 1.0]);
1101
+ session.run_step(&batch).unwrap();
1102
+ let (step, loss) = (session.step().unwrap(), session.loss().unwrap());
1103
+ let before = session.fetch("m.w").unwrap();
1104
+
1105
+ session.forward(&batch, &[]).unwrap();
1106
+
1107
+ assert_eq!(session.step().unwrap(), step);
1108
+ assert_eq!(session.loss().unwrap(), loss);
1109
+ close(&values(&session.fetch("m.w").unwrap()), &values(&before));
1110
+ }
1111
+
1112
+ #[test]
1113
+ fn a_tap_on_a_name_no_node_carries_is_refused() {
1114
+ let mut session = session(fixtures::scaled_mean());
1115
+ let e = session.tap("nowhere", "mean").unwrap_err().to_string();
1116
+ assert!(e.contains("no value is named"), "{e}");
1117
+ let e = session.tap("m.scaled", "median").unwrap_err().to_string();
1118
+ assert!(e.contains("is not a statistic"), "{e}");
1119
+ assert!(session.taps().unwrap().is_empty());
1120
+ }
1121
+
1122
+ #[test]
1123
+ fn taps_do_not_change_what_a_step_computes() {
1124
+ let batch = fixtures::batch_x(&[1.0, 2.0, 3.0, 4.0]);
1125
+ let mut quiet = session(fixtures::scaled_mean());
1126
+ let mut watched = session(fixtures::scaled_mean());
1127
+ watched.tap("m.scaled", "norm").unwrap();
1128
+ for _ in 0..3 {
1129
+ quiet.run_step(&batch).unwrap();
1130
+ watched.run_step(&batch).unwrap();
1131
+ }
1132
+ assert_eq!(quiet.loss().unwrap(), watched.loss().unwrap());
1133
+ close(
1134
+ &values(&watched.fetch("m.w").unwrap()),
1135
+ &values(&quiet.fetch("m.w").unwrap()),
1136
+ );
1137
+ }
1138
+
1139
+ #[test]
1140
+ fn the_session_reports_what_it_reads_and_what_it_holds() {
1141
+ let session = session(fixtures::teacher_and_student());
1142
+ assert_eq!(session.input_names().unwrap(), vec!["x"]);
1143
+ assert_eq!(session.trainable_candidates().unwrap(), vec!["student.scale"]);
1144
+ assert_eq!(session.optimizer_config().unwrap().name(), "sgd");
1145
+ assert_eq!(session.seed().unwrap(), 0);
1146
+ assert!(session.loss().unwrap().is_nan());
1147
+ }
1148
+
1149
+ #[test]
1150
+ fn freezing_and_thawing_move_what_a_step_reports() {
1151
+ let (config, weights) = fixtures::teacher_and_student();
1152
+ // Train both, so there is something to freeze that leaves a rest.
1153
+ let both = config.replace(r#""train":["student"]"#, r#""train":["student","teacher"]"#);
1154
+ let mut session = Session::open(&both, Weights::Inline(&weights)).unwrap();
1155
+ assert_eq!(
1156
+ session.trainable().unwrap(),
1157
+ vec!["student.scale", "teacher.scale"]
1158
+ );
1159
+ let moved = session.set_frozen("teacher.*", true).unwrap();
1160
+ assert_eq!(moved, vec!["teacher.scale"]);
1161
+ assert_eq!(session.trainable().unwrap(), vec!["student.scale"]);
1162
+
1163
+ let grads = session.gradients(&fixtures::batch_x(&[1.0, 1.0])).unwrap();
1164
+ assert_eq!(grads.len(), 1);
1165
+ assert_eq!(grads[0].0, "student.scale");
1166
+
1167
+ assert_eq!(session.set_frozen("teacher.*", false).unwrap(), vec!["teacher.scale"]);
1168
+ assert_eq!(session.trainable().unwrap(), vec!["student.scale", "teacher.scale"]);
1169
+ }
1170
+
1171
+ #[test]
1172
+ fn a_checkpoint_round_trips_through_the_session() {
1173
+ let dir = tempfile::tempdir().unwrap();
1174
+ let path = dir.path().join("ckpt").display().to_string();
1175
+ let batch = fixtures::batch_x(&[1.0, 2.0, 3.0, 4.0]);
1176
+
1177
+ let mut session = session(fixtures::scaled_mean());
1178
+ session.run_step(&batch).unwrap();
1179
+ let written = session.save(&path, "").unwrap();
1180
+ assert!(std::path::Path::new(&written).join("manifest.json").exists());
1181
+ let want = values(&session.fetch("m.w").unwrap());
1182
+
1183
+ let mut fresh = self::session(fixtures::scaled_mean());
1184
+ fresh.restore(&path).unwrap();
1185
+ assert_eq!(fresh.step().unwrap(), 1);
1186
+ close(&values(&fresh.fetch("m.w").unwrap()), &want);
1187
+ }
1188
+ }
1189
+
1190
+ #[cfg(test)]
1191
+ mod evaluation_tests {
1192
+ use super::tests::*;
1193
+ use super::*;
1194
+ use crate::tensor::Values;
1195
+ use crate::fixtures;
1196
+
1197
+ #[test]
1198
+ fn a_step_whose_loss_is_not_finite_is_not_taken() {
1199
+ let (config, weights) = fixtures::divides_by_zero();
1200
+ let mut session = Session::open(&config, Weights::Inline(&weights)).unwrap();
1201
+ let batch = fixtures::batch_x(&[1.0, 2.0]);
1202
+
1203
+ let loss = session.run_step(&batch).unwrap();
1204
+ assert!(!loss.is_finite(), "the fixture should divide by zero");
1205
+
1206
+ // Reported, so a policy sees it. Not applied, so nothing is lost.
1207
+ assert!(session.loss().unwrap().is_nan() || session.loss().unwrap().is_infinite());
1208
+ close(&values(&session.fetch("m.w").unwrap()), &[0.0, 0.0]);
1209
+ // The counter still moves: a step was attempted and its batch
1210
+ // consumed, and a hook that fires every N steps must keep firing.
1211
+ assert_eq!(session.step().unwrap(), 1);
1212
+ }
1213
+
1214
+ #[test]
1215
+ fn a_run_recovers_once_the_parameters_are_usable_again() {
1216
+ // What a NaN policy does now: nothing was corrupted, so putting the
1217
+ // parameter somewhere sane is enough. No checkpoint is needed.
1218
+ let (config, weights) = fixtures::divides_by_zero();
1219
+ let mut session = Session::open(&config, Weights::Inline(&weights)).unwrap();
1220
+ let batch = fixtures::batch_x(&[1.0, 2.0]);
1221
+ session.run_step(&batch).unwrap();
1222
+
1223
+ session
1224
+ .put(
1225
+ "m.w",
1226
+ &Tensor {
1227
+ shape: vec![2],
1228
+ values: Values::F32(vec![1.0, 1.0]),
1229
+ },
1230
+ )
1231
+ .unwrap();
1232
+ let loss = session.run_step(&batch).unwrap();
1233
+ assert!(loss.is_finite(), "{loss}");
1234
+ assert_eq!(session.step().unwrap(), 2);
1235
+ }
1236
+
1237
+ #[test]
1238
+ fn the_rng_moves_even_on_a_step_that_was_not_taken() {
1239
+ // The forward drew from it, so the sequence belongs to the step
1240
+ // count exactly as it would have. A resumed run has to agree.
1241
+ let (config, weights) = fixtures::divides_by_zero();
1242
+ let mut session = Session::open(&config, Weights::Inline(&weights)).unwrap();
1243
+ let before = session.rng_for_test();
1244
+ session.run_step(&fixtures::batch_x(&[1.0, 2.0])).unwrap();
1245
+ let after = session.rng_for_test();
1246
+
1247
+ assert_ne!(values(&before), values(&after));
1248
+ }
1249
+
1250
+ #[test]
1251
+ fn evaluating_moves_nothing() {
1252
+ let (config, weights) = fixtures::scaled_mean();
1253
+ let mut session = Session::open(&config, Weights::Inline(&weights)).unwrap();
1254
+ let batch = fixtures::batch_x(&[1.0, 2.0, 3.0, 4.0]);
1255
+ session.run_step(&batch).unwrap();
1256
+ let (step, loss) = (session.step().unwrap(), session.loss().unwrap());
1257
+ let w = values(&session.fetch("m.w").unwrap());
1258
+ let rng = values(&session.rng_for_test());
1259
+
1260
+ let seen = session.evaluate(&batch).unwrap();
1261
+ assert!(seen.is_finite());
1262
+ assert_eq!(session.step().unwrap(), step);
1263
+ assert_eq!(session.loss().unwrap(), loss, "the training loss is not an evaluation");
1264
+ close(&values(&session.fetch("m.w").unwrap()), &w);
1265
+ assert_eq!(
1266
+ values(&session.rng_for_test()),
1267
+ rng
1268
+ );
1269
+ }
1270
+
1271
+ #[test]
1272
+ fn evaluating_reports_the_loss_the_parameters_give() {
1273
+ // mean(x * w) with w = [1, 2] over [[1, 2], [3, 4]] is
1274
+ // (1 + 4 + 3 + 8) / 4 = 4.
1275
+ let (config, weights) = fixtures::scaled_mean();
1276
+ let mut session = Session::open(&config, Weights::Inline(&weights)).unwrap();
1277
+ let seen = session.evaluate(&fixtures::batch_x(&[1.0, 2.0, 3.0, 4.0])).unwrap();
1278
+ assert!((seen - 4.0).abs() < 1e-6, "{seen}");
1279
+ }
1280
+
1281
+ #[test]
1282
+ fn evaluating_does_not_sample_dropout() {
1283
+ let (config, weights) = fixtures::with_dropout(0.5);
1284
+ let mut session = Session::open(&config, Weights::Inline(&weights)).unwrap();
1285
+ let batch = fixtures::batch_x(&[1.0, 1.0, 1.0, 1.0]);
1286
+
1287
+ // Twice the same, because no key means no draw.
1288
+ let first = session.evaluate(&batch).unwrap();
1289
+ let second = session.evaluate(&batch).unwrap();
1290
+ assert_eq!(first, second);
1291
+ // And it is the loss with everything kept: mean(x * w) = 1.
1292
+ assert!((first - 1.0).abs() < 1e-6, "{first}");
1293
+
1294
+ // Training does draw, so it does not agree with it every time.
1295
+ let mut drawn = Vec::new();
1296
+ for _ in 0..12 {
1297
+ drawn.push(session.run_step(&batch).unwrap());
1298
+ }
1299
+ assert!(
1300
+ drawn.iter().any(|l| (l - 1.0).abs() > 1e-6),
1301
+ "a training pass should sample dropout: {drawn:?}"
1302
+ );
1303
+ }
1304
+
1305
+ #[test]
1306
+ fn the_parts_of_an_accumulated_step_draw_other_masks() {
1307
+ let (config, weights) = fixtures::with_dropout(0.5);
1308
+ let batch = fixtures::batch_x(&[1.0; 16]);
1309
+
1310
+ // The same batch as every part, so a difference in what each one reads is the mask.
1311
+ let mut session = Session::open(&config, Weights::Inline(&weights)).unwrap();
1312
+ let parts: Vec<f32> = (0..6).map(|_| session.accumulate(&batch).unwrap()).collect();
1313
+ let first = parts[0];
1314
+ assert!(
1315
+ parts.iter().any(|loss| (loss - first).abs() > 1e-6),
1316
+ "every part drew the first one's mask: {parts:?}"
1317
+ );
1318
+
1319
+ // The first part is the step's own key, as a step of one part has always drawn.
1320
+ let mut alone = Session::open(&config, Weights::Inline(&weights)).unwrap();
1321
+ assert_eq!(alone.accumulate(&batch).unwrap(), first);
1322
+
1323
+ // And a run that is opened again draws the same parts.
1324
+ let mut again = Session::open(&config, Weights::Inline(&weights)).unwrap();
1325
+ let repeated: Vec<f32> = (0..6).map(|_| again.accumulate(&batch).unwrap()).collect();
1326
+ assert_eq!(parts, repeated);
1327
+ }
1328
+
1329
+ #[test]
1330
+ fn a_tap_reports_the_evaluation_it_watched() {
1331
+ let (config, weights) = fixtures::with_dropout(0.0);
1332
+ let mut session = Session::open(&config, Weights::Inline(&weights)).unwrap();
1333
+ session.tap("m.scaled", "mean").unwrap();
1334
+ session.evaluate(&fixtures::batch_x(&[1.0, 3.0])).unwrap();
1335
+
1336
+ let seen = session.tapped().unwrap();
1337
+ assert_eq!(seen.len(), 1);
1338
+ close(&values(&seen[0].1), &[2.0]);
1339
+ }
1340
+ }
1341
+
1342
+ #[cfg(test)]
1343
+ mod checkpoint_tests {
1344
+ use super::*;
1345
+ use crate::fixtures;
1346
+
1347
+ fn open(which: (String, String)) -> Session {
1348
+ Session::open(&which.0, Weights::Inline(&which.1)).unwrap()
1349
+ }
1350
+
1351
+ fn written(session: &Session, run: &str) -> (tempfile::TempDir, String) {
1352
+ let dir = tempfile::tempdir().unwrap();
1353
+ let path = dir.path().join("ckpt").display().to_string();
1354
+ session.save(&path, run).unwrap();
1355
+ (dir, path)
1356
+ }
1357
+
1358
+ fn manifest(path: &str) -> serde_json::Value {
1359
+ serde_json::from_str(&crate::checkpoint::read_manifest_json(path).unwrap()).unwrap()
1360
+ }
1361
+
1362
+ #[test]
1363
+ fn a_checkpoint_carries_the_description_and_not_only_its_digest() {
1364
+ let (config, weights) = fixtures::scaled_mean();
1365
+ let session = Session::open(&config, Weights::Inline(&weights)).unwrap();
1366
+ let (_dir, path) = written(&session, "");
1367
+
1368
+ let graph = std::fs::read_to_string(std::path::Path::new(&path).join("graph.json")).unwrap();
1369
+ assert_eq!(graph, config);
1370
+ // Which is to say: the checkpoint can be read without the run that
1371
+ // wrote it, and the digest it claims is of what is actually there.
1372
+ assert_eq!(
1373
+ manifest(&path)["config_digest"].as_str().unwrap().len(),
1374
+ 64
1375
+ );
1376
+ }
1377
+
1378
+ #[test]
1379
+ fn a_graph_that_is_not_the_one_the_manifest_claims_is_refused() {
1380
+ let session = open(fixtures::scaled_mean());
1381
+ let (_dir, path) = written(&session, "");
1382
+ let graph = std::path::Path::new(&path).join("graph.json");
1383
+ std::fs::write(&graph, fixtures::teacher_and_student().0).unwrap();
1384
+
1385
+ let mut into = open(fixtures::scaled_mean());
1386
+ let e = into.restore(&path).unwrap_err().to_string();
1387
+ assert!(e.contains("not the description this manifest claims"), "{e}");
1388
+ }
1389
+
1390
+ #[test]
1391
+ fn the_manifest_inventories_every_parameters_dtype() {
1392
+ let session = open(fixtures::teacher_and_student());
1393
+ let (_dir, path) = written(&session, "");
1394
+ let m = manifest(&path);
1395
+ let params = m["parameters"].as_array().unwrap();
1396
+ assert_eq!(params.len(), 2);
1397
+ assert_eq!(params[0]["path"], "student.scale");
1398
+ assert_eq!(params[0]["dtype"], "f32");
1399
+ assert_eq!(params[0]["shape"], serde_json::json!([2]));
1400
+ assert_eq!(params[0]["trained"], true);
1401
+ assert_eq!(params[1]["path"], "teacher.scale");
1402
+ assert_eq!(params[1]["trained"], false);
1403
+ }
1404
+
1405
+ #[test]
1406
+ fn a_parameter_whose_dtype_disagrees_with_the_manifest_is_refused() {
1407
+ let session = open(fixtures::scaled_mean());
1408
+ let (_dir, path) = written(&session, "");
1409
+ let file = std::path::Path::new(&path).join("manifest.json");
1410
+ let mut m: serde_json::Value =
1411
+ serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
1412
+ m["parameters"][0]["dtype"] = serde_json::json!("bf16");
1413
+ std::fs::write(&file, serde_json::to_vec_pretty(&m).unwrap()).unwrap();
1414
+
1415
+ let mut into =
1416
+ open(fixtures::scaled_mean());
1417
+ let e = into.restore(&path).unwrap_err().to_string();
1418
+ assert!(e.contains("the manifest says bf16"), "{e}");
1419
+ }
1420
+
1421
+ #[test]
1422
+ fn the_manifest_says_what_it_was_written_by_and_on() {
1423
+ let session = open(fixtures::scaled_mean());
1424
+ let (_dir, path) = written(&session, "");
1425
+ let m = manifest(&path);
1426
+ assert_eq!(m["schema_version"], 2);
1427
+ assert_eq!(m["semantics_version"], 3);
1428
+ assert_eq!(m["platform"]["os"], std::env::consts::OS);
1429
+ assert_eq!(m["platform"]["arch"], std::env::consts::ARCH);
1430
+ assert!(m["build"]["mlx"].is_string(), "{m}");
1431
+ assert!(m["build"]["mlx_c"].is_string(), "{m}");
1432
+ assert_eq!(m["optimizer"]["kind"], "sgd");
1433
+ }
1434
+
1435
+ #[test]
1436
+ fn what_the_caller_records_comes_back_unchanged() {
1437
+ // Epoch, batch position and sampler state are not the engine's to
1438
+ // know, so they travel opaquely. What matters is that they survive.
1439
+ let run = r#"{"epoch":3,"batch":1200,"sampler":{"kind":"shuffled","seed":9}}"#;
1440
+ let mut session =
1441
+ open(fixtures::scaled_mean());
1442
+ session.run_step(&fixtures::batch_x(&[1.0, 2.0])).unwrap();
1443
+ let (_dir, path) = written(&session, run);
1444
+
1445
+ let mut fresh =
1446
+ open(fixtures::scaled_mean());
1447
+ let back: serde_json::Value = serde_json::from_str(&fresh.restore(&path).unwrap()).unwrap();
1448
+ assert_eq!(back["epoch"], 3);
1449
+ assert_eq!(back["batch"], 1200);
1450
+ assert_eq!(back["sampler"]["seed"], 9);
1451
+ assert_eq!(fresh.step().unwrap(), 1);
1452
+ }
1453
+
1454
+ #[test]
1455
+ fn a_run_record_that_is_not_json_is_refused_before_anything_is_written() {
1456
+ let dir = tempfile::tempdir().unwrap();
1457
+ let path = dir.path().join("ckpt").display().to_string();
1458
+ let session = open(fixtures::scaled_mean());
1459
+ let e = session.save(&path, "not json").unwrap_err().to_string();
1460
+ assert!(e.contains("not JSON"), "{e}");
1461
+ assert!(!std::path::Path::new(&path).exists());
1462
+ }
1463
+
1464
+ #[test]
1465
+ fn a_checkpoint_with_no_caller_record_restores_to_null() {
1466
+ let mut session =
1467
+ open(fixtures::scaled_mean());
1468
+ let (_dir, path) = written(&session, "");
1469
+ assert_eq!(session.restore(&path).unwrap(), "null");
1470
+ }
1471
+
1472
+ #[test]
1473
+ fn a_checkpoint_of_an_older_schema_is_refused_rather_than_guessed_at() {
1474
+ let session = open(fixtures::scaled_mean());
1475
+ let (_dir, path) = written(&session, "");
1476
+ let file = std::path::Path::new(&path).join("manifest.json");
1477
+ let mut m: serde_json::Value =
1478
+ serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
1479
+ m["schema_version"] = serde_json::json!(1);
1480
+ std::fs::write(&file, serde_json::to_vec_pretty(&m).unwrap()).unwrap();
1481
+ let e = crate::checkpoint::read_manifest_json(&path).unwrap_err().to_string();
1482
+ assert!(e.contains("schema 1 is not 2"), "{e}");
1483
+ }
1484
+
1485
+ #[test]
1486
+ fn a_manifest_reads_without_a_session_to_read_it_into() {
1487
+ // What a caller consults to decide which checkpoint to resume.
1488
+ let mut session = open(fixtures::teacher_and_student());
1489
+ session.run_step(&fixtures::batch_x(&[1.0, 1.0])).unwrap();
1490
+ let (_dir, path) = written(&session, r#"{"epoch":2}"#);
1491
+ let m = manifest(&path);
1492
+ assert_eq!(m["step"], 1);
1493
+ assert_eq!(m["run"]["epoch"], 2);
1494
+ assert_eq!(m["seed"], 0);
1495
+ }
1496
+
1497
+ #[test]
1498
+ fn a_session_exports_one_models_parameters_through_the_runtime() {
1499
+ // The facade path: the runtime serializes this against any step in
1500
+ // flight, and the model name is stripped from the saved keys.
1501
+ let session = open(fixtures::teacher_and_student());
1502
+ let dir = tempfile::tempdir().unwrap();
1503
+ let out = dir.path().join("out").display().to_string();
1504
+
1505
+ let pairs = session.export_model("student", &out, None).unwrap();
1506
+ assert_eq!(pairs, vec![("student.scale".to_string(), "scale".to_string())]);
1507
+
1508
+ let arrays = crate::mlxc::Array::load_safetensors(std::path::Path::new(&out).join("model.safetensors")).unwrap();
1509
+ assert!(arrays.contains_key("scale"));
1510
+ assert!(!arrays.contains_key("student.scale"));
1511
+ assert!(!arrays.contains_key("teacher.scale"), "only one model is exported");
1512
+ }
1513
+
1514
+ #[test]
1515
+ fn a_session_refuses_to_export_a_model_that_is_not_here() {
1516
+ let session = open(fixtures::scaled_mean());
1517
+ let dir = tempfile::tempdir().unwrap();
1518
+ let e = session
1519
+ .export_model("elsewhere", &dir.path().display().to_string(), None)
1520
+ .unwrap_err();
1521
+ assert!(e.to_string().contains("no model named"), "{e}");
1522
+ }
1523
+ }