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,1007 @@
1
+ //! What a run accumulates: parameters, optimizer slots, the RNG, and the
2
+ //! counters. Everything that a checkpoint has to carry, and nothing that a
3
+ //! GraphConfig already says.
4
+ //!
5
+ //! The plan (`crate::plan`) is fixed when a run opens; this is the part
6
+ //! that moves. It moves in one place, [`TrainState::advance`], which is
7
+ //! written as a transaction: the next state is built and evaluated in full
8
+ //! before any of it is assigned, so a step that fails leaves the run
9
+ //! exactly as it was (docs/plan.md section 5A.4).
10
+
11
+ use anyhow::{Context, Result};
12
+ use crate::mlxc::quantized::dequantize;
13
+ use crate::mlxc::transforms::eval;
14
+ use crate::mlxc::{Array, Dtype};
15
+
16
+ use crate::checkpoint;
17
+ use crate::optimizer::{global_norm, scaled, Config as OptimizerConfig, Optimizer};
18
+ use crate::plan::{Pattern, Plan};
19
+ use crate::tensor::{to_tensor, Tensor};
20
+
21
+ /// One pass's view of the state: what the executor reads, and nothing
22
+ /// more.
23
+ ///
24
+ /// These three used to be public fields, which meant a caller assembled
25
+ /// them itself and could put them out of step with each other. The
26
+ /// invariant they are under (the optimizer's slots are parallel to
27
+ /// `argnums`, and `params` is indexed by it) is this module's to keep.
28
+ pub struct Pass<'a> {
29
+ pub params: &'a [Array],
30
+ pub argnums: &'a [i32],
31
+ pub rng: &'a Array,
32
+ }
33
+
34
+ pub struct TrainState {
35
+ /// Every parameter of every model, model by model in name order. This
36
+ /// order is `Plan::paths`, and the contract the Ruby side follows.
37
+ params: Vec<Array>,
38
+ /// Positions in `params` that autodiff differentiates now. A subset of
39
+ /// `Plan::candidates`; moves when the window freezes or unfreezes.
40
+ argnums: Vec<i32>,
41
+ /// The update rule and its slots. Half of what a checkpoint restores.
42
+ optimizer: Optimizer,
43
+ /// The RNG, held as state rather than left to a global. Every step
44
+ /// splits it, so the sequence of draws is a function of the seed and
45
+ /// the step count, and a resumed run draws what a continuous one would
46
+ /// (docs/plan.md section 11.1).
47
+ rng: Array,
48
+ seed: u64,
49
+ step: usize,
50
+ last_loss: f32,
51
+ /// The L2 norm of the last step's gradients, before any clipping, so a
52
+ /// watcher can see how close a run is to its cap rather than having to
53
+ /// guess. NaN until a step is taken, and when a step is skipped.
54
+ last_grad_norm: f32,
55
+ /// Gradients waiting for a step. Held here rather than by the caller
56
+ /// because they are device arrays parallel to `argnums`, which is this
57
+ /// module's invariant to keep: a caller holding them could freeze a
58
+ /// parameter between two of them and hand back a vector that no longer
59
+ /// lines up.
60
+ accumulated: Accumulator,
61
+ }
62
+
63
+ /// Gradients summed across the parts of a batch, and the losses they came
64
+ /// from, waiting for one step.
65
+ ///
66
+ /// A batch that does not fit is trained as several that do, summing their
67
+ /// gradients and updating once. The gradients of a sum are the sum of the
68
+ /// gradients, so that reaches where one step over the whole batch would.
69
+ #[derive(Default)]
70
+ struct Accumulator {
71
+ /// One per differentiated parameter, in `argnums` order; empty when
72
+ /// nothing is waiting.
73
+ grads: Vec<Array>,
74
+ /// The losses that produced them, so a step can report their mean.
75
+ losses: Vec<f32>,
76
+ }
77
+
78
+ impl Accumulator {
79
+ fn parts(&self) -> usize {
80
+ self.losses.len()
81
+ }
82
+
83
+ /// Adds one part. The new sums are built and evaluated before they
84
+ /// replace the old ones, so a part that fails leaves what was already
85
+ /// held as it was. Evaluated rather than left lazy: ten parts should be
86
+ /// ten sums, not a graph ten deep.
87
+ fn add(&mut self, loss: f32, grads: &[Array]) -> Result<()> {
88
+ let sums: Vec<Array> = if self.grads.is_empty() {
89
+ grads.to_vec()
90
+ } else {
91
+ self.grads
92
+ .iter()
93
+ .zip(grads)
94
+ .map(|(held, new)| held.add(new))
95
+ .collect::<std::result::Result<_, _>>()?
96
+ };
97
+ eval(sums.iter())?;
98
+ self.grads = sums;
99
+ self.losses.push(loss);
100
+ Ok(())
101
+ }
102
+
103
+ /// The summed gradients and the mean loss, or `None` when nothing is
104
+ /// waiting. Left in place: they go only once the step they are for has
105
+ /// been taken.
106
+ fn waiting(&self) -> Option<(Vec<Array>, f32)> {
107
+ if self.losses.is_empty() {
108
+ return None;
109
+ }
110
+ let mean = self.losses.iter().sum::<f32>() / self.losses.len() as f32;
111
+ Some((self.grads.clone(), mean))
112
+ }
113
+ }
114
+
115
+ /// What a step came to, before any of it is the state's: the RNG and the
116
+ /// numbers always, and the new parameters and optimizer when the step is
117
+ /// taken.
118
+ struct StepOutcome {
119
+ rng: Array,
120
+ loss: f32,
121
+ grad_norm: f32,
122
+ update: Option<(Vec<Array>, Optimizer)>,
123
+ }
124
+
125
+ impl StepOutcome {
126
+ /// A step not taken: the counters and the RNG still move, the
127
+ /// parameters and the optimizer do not.
128
+ fn skipped(rng: Array, loss: f32, grad_norm: f32) -> Result<Self> {
129
+ eval(std::iter::once(&rng))?;
130
+ Ok(Self {
131
+ rng,
132
+ loss,
133
+ grad_norm,
134
+ update: None,
135
+ })
136
+ }
137
+ }
138
+
139
+ impl TrainState {
140
+ /// The state a plan starts in: the given parameters, everything the
141
+ /// plan declared trainable differentiated, and fresh optimizer slots.
142
+ pub fn new(
143
+ plan: &Plan,
144
+ params: Vec<Array>,
145
+ optimizer: OptimizerConfig,
146
+ seed: u64,
147
+ ) -> Result<Self> {
148
+ let argnums = plan.candidates.clone();
149
+ let optimizer = Optimizer::new(optimizer, &params, &argnums)?;
150
+ Ok(Self {
151
+ params,
152
+ argnums,
153
+ optimizer,
154
+ rng: crate::mlxc::random::key(seed)?,
155
+ seed,
156
+ step: 0,
157
+ last_loss: f32::NAN,
158
+ last_grad_norm: f32::NAN,
159
+ accumulated: Accumulator::default(),
160
+ })
161
+ }
162
+
163
+ /// What a pass reads. The only way out of here for the three of them.
164
+ pub fn pass(&self) -> Pass<'_> {
165
+ Pass {
166
+ params: &self.params,
167
+ argnums: &self.argnums,
168
+ rng: &self.rng,
169
+ }
170
+ }
171
+
172
+ /// What a pass reads, with `rng` in place of the step's own: the key of a part that is
173
+ /// not the first of an accumulated step (`Self::part_rng`).
174
+ pub fn pass_with<'a>(&'a self, rng: &'a Array) -> Pass<'a> {
175
+ Pass { params: &self.params, argnums: &self.argnums, rng }
176
+ }
177
+
178
+ /// The key the next part to be accumulated draws with: the step's own for the first, so
179
+ /// that a step of one part is what it always was, and another for each after it. Without
180
+ /// that, every part of a batch split to fit in memory would draw the same dropout masks,
181
+ /// which is a regularizer a fraction as strong as the one asked for. A function of the
182
+ /// step's key and how many parts are waiting, so a resumed run draws what a continuous
183
+ /// one would.
184
+ pub fn part_rng(&self) -> Result<Option<Array>> {
185
+ match self.accumulated() {
186
+ 0 => Ok(None),
187
+ n => Ok(Some(crate::mlxc::random::part(&self.rng, n as i32)?)),
188
+ }
189
+ }
190
+
191
+ /// Which parameters autodiff differentiates now, as positions.
192
+ /// Every parameter, in `Plan::paths` order.
193
+ pub fn params(&self) -> &[Array] {
194
+ &self.params
195
+ }
196
+
197
+ pub fn argnums(&self) -> &[i32] {
198
+ &self.argnums
199
+ }
200
+
201
+ pub fn step(&self) -> usize {
202
+ self.step
203
+ }
204
+
205
+ pub fn loss(&self) -> f32 {
206
+ self.last_loss
207
+ }
208
+
209
+ pub fn lr(&self) -> f32 {
210
+ self.optimizer.config().lr()
211
+ }
212
+
213
+ /// A knob: effect begins with the next step.
214
+ pub fn set_lr(&mut self, lr: f32) {
215
+ self.optimizer.config_mut().set_lr(lr);
216
+ }
217
+
218
+ /// The norm of the last step's gradients, before clipping. NaN before
219
+ /// the first step and on a step that was skipped.
220
+ pub fn grad_norm(&self) -> f32 {
221
+ self.last_grad_norm
222
+ }
223
+
224
+ /// The largest gradient norm a step may carry, or `None`.
225
+ pub fn clip(&self) -> Option<f32> {
226
+ self.optimizer.config().clip()
227
+ }
228
+
229
+ /// A knob: effect begins with the next step. `None` is no cap.
230
+ pub fn set_clip(&mut self, clip: Option<f32>) {
231
+ self.optimizer.config_mut().set_clip(clip);
232
+ }
233
+
234
+ /// The L2 norm of every parameter, over the whole model.
235
+ ///
236
+ /// On demand rather than per step: it is a reduction over all the
237
+ /// weights, and unlike the gradient norm nothing in a step reads it.
238
+ /// Frozen parameters count, so this is the size of the model and not
239
+ /// of what is being trained.
240
+ /// Over the numbers the run holds: a packed quantized weight is
241
+ /// words, not weights, and is left out.
242
+ pub fn param_norm(&self) -> Result<f32> {
243
+ let numbers: Vec<Array> = self
244
+ .params
245
+ .iter()
246
+ .filter(|array| array.dtype() != Dtype::Uint32)
247
+ .cloned()
248
+ .collect();
249
+ global_norm(&numbers)
250
+ }
251
+
252
+ /// What update rule this run uses, as data.
253
+ pub fn optimizer_config(&self) -> &OptimizerConfig {
254
+ self.optimizer.config()
255
+ }
256
+
257
+ pub fn seed(&self) -> u64 {
258
+ self.seed
259
+ }
260
+
261
+ /// Restarts the RNG. A knob like any other: after this the draws are a
262
+ /// function of the new seed alone.
263
+ pub fn set_seed(&mut self, seed: u64) -> Result<()> {
264
+ self.seed = seed;
265
+ self.rng = crate::mlxc::random::key(seed)?;
266
+ Ok(())
267
+ }
268
+
269
+ /// Freezes or unfreezes parameters whose path matches `pattern`, and
270
+ /// returns those that moved.
271
+ ///
272
+ /// Not a scalar knob (docs/plan.md section 5A.1): changing it changes
273
+ /// what autodiff differentiates, so the optimizer's slots have to
274
+ /// follow (kept for what stays, dropped for what freezes, started at
275
+ /// zero for what thaws). Which is why this lives here rather than in a
276
+ /// setter.
277
+ pub fn set_frozen(&mut self, plan: &Plan, pattern: &str, frozen: bool) -> Result<Vec<String>> {
278
+ let matcher = Pattern::parse(pattern)?;
279
+ let mut wanted: Vec<i32> = Vec::new();
280
+ let mut moved = Vec::new();
281
+ let mut matched_any = false;
282
+ for &i in &plan.candidates {
283
+ let path = &plan.paths[i as usize];
284
+ let matches = matcher.matches(path);
285
+ matched_any |= matches;
286
+ let currently = self.argnums.contains(&i);
287
+ let next = if matches { !frozen } else { currently };
288
+ if next != currently {
289
+ moved.push(path.clone());
290
+ }
291
+ if next {
292
+ wanted.push(i);
293
+ }
294
+ }
295
+ anyhow::ensure!(
296
+ !moved.is_empty() || matched_any,
297
+ "no parameter matches {pattern:?} (this run has {:?})",
298
+ plan.candidate_paths()
299
+ );
300
+ if moved.is_empty() {
301
+ return Ok(moved);
302
+ }
303
+ // The waiting gradients are one per differentiated parameter, in
304
+ // this order. Moving the set would leave them meaning something
305
+ // else, and a caller that froze in the middle of a batch has lost
306
+ // track of which half is which.
307
+ anyhow::ensure!(
308
+ self.accumulated.parts() == 0,
309
+ "{} parts are accumulated and freezing changes what a gradient is for. \
310
+ Apply them or discard them first",
311
+ self.accumulated()
312
+ );
313
+ anyhow::ensure!(
314
+ !wanted.is_empty(),
315
+ "freezing {pattern:?} would leave nothing to train"
316
+ );
317
+
318
+ self.optimizer.refit(&self.argnums, &wanted, &self.params)?;
319
+ self.argnums = wanted;
320
+ Ok(moved)
321
+ }
322
+
323
+ /// Writes one parameter, by qualified path, from a copy. The window's
324
+ /// B capability (docs/plan.md section 8.3).
325
+ pub fn put(&mut self, plan: &Plan, path: &str, tensor: &Tensor) -> Result<()> {
326
+ let index = plan
327
+ .index_of(path)
328
+ .with_context(|| format!("no parameter named {path:?}"))?;
329
+ anyhow::ensure!(
330
+ self.params[index].dtype() != Dtype::Uint32,
331
+ "parameter {path:?} is a packed quantized weight, which is not replaced: it came \
332
+ from a file with the scales that read it, and numbers put here would not. A base \
333
+ that is to be moved is declared in bf16."
334
+ );
335
+ let array = tensor.to_array()?;
336
+ anyhow::ensure!(
337
+ array.shape() == self.params[index].shape(),
338
+ "parameter {path:?}: given shape {:?} is not {:?}",
339
+ array.shape(),
340
+ self.params[index].shape()
341
+ );
342
+ // Converted rather than refused, for the reason importing is: the
343
+ // boundary carries f32 and a parameter may be held in something
344
+ // else, so what a caller can say is the numbers, not the width.
345
+ let array = array.as_dtype(self.params[index].dtype())?;
346
+ eval(std::iter::once(&array))?;
347
+ self.params[index] = array;
348
+ Ok(())
349
+ }
350
+
351
+ /// A copy of one parameter, by qualified path. Copies, not handles:
352
+ /// nothing that lives on the device escapes this crate.
353
+ ///
354
+ /// A packed quantized weight comes back as the numbers it stands for,
355
+ /// in f32, as every other parameter does: the label says what the
356
+ /// payload is (docs/plan.md 15.51), and what a caller asking for a
357
+ /// weight wants is the weight, not its words. The scales and biases
358
+ /// that read it are the ones the graph's `quantized_matmul` names.
359
+ pub fn fetch(&self, plan: &Plan, path: &str) -> Result<Tensor> {
360
+ let index = plan
361
+ .index_of(path)
362
+ .with_context(|| format!("no parameter named {path:?}"))?;
363
+ let array = &self.params[index];
364
+ if array.dtype() != Dtype::Uint32 {
365
+ return to_tensor(array);
366
+ }
367
+ let packed = plan.packed.get(&index).with_context(|| {
368
+ format!(
369
+ "parameter {path:?} is a packed u32 weight that no quantized_matmul in the graph \
370
+ reads, so nothing says how to read it back as numbers"
371
+ )
372
+ })?;
373
+ let numbers = dequantize(
374
+ array,
375
+ &self.params[packed.scales],
376
+ packed.biases.map(|i| &self.params[i]),
377
+ packed.quantization,
378
+ None,
379
+ )?;
380
+ to_tensor(&numbers)
381
+ }
382
+
383
+ /// One optimizer step from a loss and its gradients, as a transaction:
384
+ /// the next parameters, slots and key are built and evaluated first,
385
+ /// and only then does this state become them. A step that fails leaves
386
+ /// everything as it was, which is what StepError promises.
387
+ ///
388
+ /// **A step whose loss is not finite is not taken.** Its gradients are
389
+ /// not finite either, so taking it would put NaN into every parameter
390
+ /// and nothing after it could recover; the only way back would be a
391
+ /// checkpoint, which is why the plan listed a rollback knob. Not going
392
+ /// there is cheaper than coming back, and free: the loss is already
393
+ /// evaluated by the time this is called. A finite loss with a
394
+ /// non-finite gradient is refused the same way, which is why the norm
395
+ /// is taken before the update rather than only when clipping is on.
396
+ ///
397
+ /// **Gradients are clipped to `clip`, if one is set.** The norm is
398
+ /// global over every differentiated parameter, taken in f32, and when
399
+ /// it exceeds the cap every gradient is scaled by the same factor: the
400
+ /// direction of the step is untouched and only its length is bounded.
401
+ /// The cap is recorded with the optimizer, and `grad_norm()` reports
402
+ /// what the norm was, so a run can say how close it came.
403
+ ///
404
+ /// The counters still move. A step was attempted, its batch was
405
+ /// consumed, and the RNG was drawn from during the forward, so the draw
406
+ /// belongs to the step count exactly as it would have; a resumed run
407
+ /// has to see the same sequence. What does not move is the parameters
408
+ /// and the optimizer's slots, so a policy that lowers the rate and
409
+ /// carries on has something clean to carry on from.
410
+ pub fn advance(&mut self, loss: &Array, grads: &[Array]) -> Result<f32> {
411
+ let outcome = self.outcome(loss, grads)?;
412
+ Ok(self.commit(outcome))
413
+ }
414
+
415
+ /// What one step comes to, built and evaluated in full, with none of
416
+ /// it this state's yet.
417
+ fn outcome(&self, loss: &Array, grads: &[Array]) -> Result<StepOutcome> {
418
+ let loss = loss.item::<f32>()?;
419
+ let (rng, _) = crate::mlxc::random::split(&self.rng, 2)?;
420
+ if !loss.is_finite() {
421
+ return StepOutcome::skipped(rng, loss, f32::NAN);
422
+ }
423
+ let norm = global_norm(grads)?;
424
+ if !norm.is_finite() {
425
+ return StepOutcome::skipped(rng, loss, norm);
426
+ }
427
+
428
+ let grads: Vec<Array> = match self.optimizer.config().clip() {
429
+ Some(max) if norm > max => scaled(grads, max / norm)?,
430
+ _ => grads.to_vec(),
431
+ };
432
+ let mut params = self.params.clone();
433
+ let optimizer = self.optimizer.next(&mut params, &self.argnums, &grads)?;
434
+ eval(params.iter().chain(optimizer.arrays()).chain(std::iter::once(&rng)))?;
435
+ Ok(StepOutcome {
436
+ rng,
437
+ loss,
438
+ grad_norm: norm,
439
+ update: Some((params, optimizer)),
440
+ })
441
+ }
442
+
443
+ /// Makes a step's outcome this state's. Cannot fail, which is what lets
444
+ /// everything that can fail happen first: whether or not the update is
445
+ /// taken, the counters and the RNG move exactly once.
446
+ fn commit(&mut self, outcome: StepOutcome) -> f32 {
447
+ if let Some((params, optimizer)) = outcome.update {
448
+ self.params = params;
449
+ self.optimizer = optimizer;
450
+ }
451
+ self.rng = outcome.rng;
452
+ self.last_loss = outcome.loss;
453
+ self.last_grad_norm = outcome.grad_norm;
454
+ self.step += 1;
455
+ outcome.loss
456
+ }
457
+
458
+ /// Adds one batch's gradients to what is waiting, and reports its
459
+ /// loss. No step is taken and no counter moves.
460
+ ///
461
+ /// What this is for: a batch too large to hold is trained as several
462
+ /// that fit. The gradients of a sum are the sum of the gradients, so
463
+ /// accumulating and then stepping reaches where one step over the
464
+ /// whole batch would have. Whether the parts are a mean or a sum of
465
+ /// each other is the caller's arithmetic (a loss that is a mean over
466
+ /// its rows wants the parts weighted), and this does not guess.
467
+ ///
468
+ /// A part whose loss is not finite is not added, for the reason
469
+ /// `advance` does not take such a step: its gradients are not finite
470
+ /// either, and one of them would poison the sum. The loss is still
471
+ /// reported, so a caller sees it happen.
472
+ ///
473
+ /// The RNG does not move. A draw belongs to a step, and this is a
474
+ /// fraction of one; the step that applies these makes the draw.
475
+ pub fn accumulate(&mut self, loss: &Array, grads: &[Array]) -> Result<f32> {
476
+ let value = loss.item::<f32>()?;
477
+ anyhow::ensure!(
478
+ grads.len() == self.argnums.len(),
479
+ "these gradients are for {} parameters and {} are differentiated",
480
+ grads.len(),
481
+ self.argnums.len()
482
+ );
483
+ if !value.is_finite() {
484
+ return Ok(value);
485
+ }
486
+
487
+ self.accumulated.add(value, grads)?;
488
+ Ok(value)
489
+ }
490
+
491
+ /// Takes the step the accumulated gradients ask for, and reports the
492
+ /// mean of the losses they came from.
493
+ ///
494
+ /// Refuses when nothing is waiting: a step from no gradients is not a
495
+ /// step of zero, it is a caller that has lost track of where it is.
496
+ pub fn apply(&mut self) -> Result<f32> {
497
+ let Some((grads, mean)) = self.accumulated.waiting() else {
498
+ anyhow::bail!("nothing has been accumulated, so there is no step to take");
499
+ };
500
+ // A step that fails leaves the run as it was, and that includes
501
+ // what was waiting for it.
502
+ let loss = self.advance(&Array::from_f32(mean)?, &grads)?;
503
+ self.accumulated = Accumulator::default();
504
+ Ok(loss)
505
+ }
506
+
507
+ /// How many parts are waiting for a step.
508
+ pub fn accumulated(&self) -> usize {
509
+ self.accumulated.parts()
510
+ }
511
+
512
+ /// Throws away what was accumulated, for a caller abandoning a batch
513
+ /// part way through. Returns how many parts went.
514
+ pub fn discard(&mut self) -> usize {
515
+ let parts = self.accumulated.parts();
516
+ self.accumulated = Accumulator::default();
517
+ parts
518
+ }
519
+
520
+ /// Writes the run's state: parameters, optimizer slots, counters, the
521
+ /// description they belong to, and whatever the caller wants recorded
522
+ /// alongside. Atomic (docs/plan.md section 11.2).
523
+ ///
524
+ /// `run` is the caller's half of the record. Epoch, batch position,
525
+ /// sampler state and dataset identity are not the engine's to know
526
+ /// (it is handed a batch, it does not fetch one), so they travel as
527
+ /// JSON that is written verbatim and read back verbatim.
528
+ pub fn save(&self, plan: &Plan, dir: &str, run: &str) -> Result<String> {
529
+ self.save_as(plan, dir, run, false)
530
+ }
531
+
532
+ /// [`TrainState::save`], and `light` writes the trained parameters only.
533
+ pub fn save_as(&self, plan: &Plan, dir: &str, run: &str, light: bool) -> Result<String> {
534
+ // A checkpoint is a whole run record, and gradients waiting for a
535
+ // step are not in it: restoring one would silently be a run that
536
+ // had dropped half a batch. Refusing says so while the caller can
537
+ // still choose.
538
+ anyhow::ensure!(
539
+ self.accumulated.parts() == 0,
540
+ "{} parts are accumulated and a checkpoint does not hold them. \
541
+ Apply them or discard them first",
542
+ self.accumulated()
543
+ );
544
+ let run: serde_json::Value = if run.trim().is_empty() {
545
+ serde_json::Value::Null
546
+ } else {
547
+ serde_json::from_str(run).context("the run metadata is not JSON")?
548
+ };
549
+ let state = checkpoint::State {
550
+ config_digest: &plan.config_digest,
551
+ graph_json: &plan.graph_json,
552
+ semantics_version: plan.semantics_version,
553
+ step: self.step,
554
+ optimizer: self.optimizer.config(),
555
+ optimizer_steps: self.optimizer.steps_taken(),
556
+ parameters: plan.paths.iter().cloned().zip(self.params.iter()).collect(),
557
+ argnums: &self.argnums,
558
+ slots: self.optimizer.slots(),
559
+ rng: &self.rng,
560
+ seed: self.seed,
561
+ run,
562
+ light,
563
+ };
564
+ Ok(checkpoint::write(dir, state)?.display().to_string())
565
+ }
566
+
567
+ /// Restores state written by [`TrainState::save`], refusing anything
568
+ /// that does not belong to this run: another description, another
569
+ /// optimizer, a parameter of another shape, a missing slot.
570
+ ///
571
+ /// Returns what the caller recorded in `run`, so that whoever owns the
572
+ /// data can put its sampler back where the checkpoint left it.
573
+ ///
574
+ /// Reading and accepting is [`checkpoint::Loaded::accept`]; this is the
575
+ /// commit. They are separate so that "nothing moves until everything is
576
+ /// checked" is a fact about the types rather than a claim in a comment:
577
+ /// an [`checkpoint::Accepted`] only exists if every check passed.
578
+ pub fn restore(&mut self, plan: &Plan, dir: &str) -> Result<String> {
579
+ let accepted = checkpoint::read(dir)?.accept(&checkpoint::Run {
580
+ plan,
581
+ params: &self.params,
582
+ argnums: &self.argnums,
583
+ optimizer: &self.optimizer,
584
+ })?;
585
+
586
+ // Everything is here and consistent; make it real before touching
587
+ // this state, so a failure below cannot leave it half restored.
588
+ eval(
589
+ accepted
590
+ .params
591
+ .iter()
592
+ .chain(accepted.moments.arrays())
593
+ .chain(std::iter::once(&accepted.rng)),
594
+ )?;
595
+
596
+ self.params = accepted.params;
597
+ self.optimizer
598
+ .restore(accepted.moments, accepted.optimizer_steps);
599
+ self.rng = accepted.rng;
600
+ self.seed = accepted.seed;
601
+ self.step = accepted.step;
602
+ self.last_loss = f32::NAN;
603
+ // Gradients for parameters that are no longer there. Going back is
604
+ // the answer to a batch that went wrong, so they are dropped
605
+ // rather than refused.
606
+ self.accumulated = Accumulator::default();
607
+ Ok(accepted.run)
608
+ }
609
+
610
+ }
611
+
612
+ #[cfg(test)]
613
+ mod tests {
614
+ use super::*;
615
+ use crate::executor;
616
+ use crate::interp::Taps;
617
+ use crate::fixtures;
618
+ use crate::plan::Weights;
619
+ use crate::tensor::{Tensor, Values};
620
+
621
+ fn open(which: (String, String), optimizer: OptimizerConfig) -> (Plan, TrainState) {
622
+ let (config, weights) = which;
623
+ let (plan, params) = Plan::open(&config, Weights::Inline(&weights)).unwrap();
624
+ let state = TrainState::new(&plan, params, optimizer, 0).unwrap();
625
+ (plan, state)
626
+ }
627
+
628
+ fn sgd(lr: f32) -> OptimizerConfig {
629
+ OptimizerConfig::Sgd { lr, clip: None }
630
+ }
631
+
632
+ fn adamw() -> OptimizerConfig {
633
+ OptimizerConfig::AdamW {
634
+ lr: 0.1,
635
+ beta1: 0.9,
636
+ beta2: 0.999,
637
+ eps: 1e-8,
638
+ weight_decay: 0.0,
639
+ clip: None,
640
+ }
641
+ }
642
+
643
+ fn values(t: &Tensor) -> Vec<f32> {
644
+ match &t.values {
645
+ Values::F32(v) => v.clone(),
646
+ Values::I32(v) => v.iter().map(|&i| i as f32).collect(),
647
+ }
648
+ }
649
+
650
+ /// One step, the way a session takes it.
651
+ fn step(plan: &Plan, state: &mut TrainState, rows: &[f32]) -> f32 {
652
+ let batch = fixtures::batch_x(rows);
653
+ let fields = plan.bind(&batch).unwrap();
654
+ let (loss, grads, _) =
655
+ executor::differentiate(plan, state.pass(), &fields, &Taps::new()).unwrap();
656
+ state.advance(&loss, &grads).unwrap()
657
+ }
658
+
659
+ fn open_quantized(dir: &std::path::Path) -> (Plan, TrainState) {
660
+ let files = std::collections::BTreeMap::from([("m".to_string(), fixtures::quantized::file(dir, true))]);
661
+ let (plan, params) =
662
+ Plan::open(&fixtures::quantized::config(), Weights::Pretrained { files: &files, fresh: &[] }).unwrap();
663
+ let state = TrainState::new(&plan, params, sgd(0.1), 0).unwrap();
664
+ (plan, state)
665
+ }
666
+
667
+ fn step_quantized(plan: &Plan, state: &mut TrainState) -> f32 {
668
+ let batch: std::collections::BTreeMap<_, _> = [fixtures::field(
669
+ "x",
670
+ &[2, fixtures::quantized::D_IN as i32],
671
+ &vec![0.5; 2 * fixtures::quantized::D_IN],
672
+ )]
673
+ .into_iter()
674
+ .collect();
675
+ let fields = plan.bind(&batch).unwrap();
676
+ let (loss, grads, _) = executor::differentiate(plan, state.pass(), &fields, &Taps::new()).unwrap();
677
+ state.advance(&loss, &grads).unwrap()
678
+ }
679
+
680
+ /// What a caller asking for the weight wants is the weight: the
681
+ /// numbers the packed words stand for, in the shape the linear has,
682
+ /// within a step of the grid of what they were made from.
683
+ #[test]
684
+ fn a_packed_weight_is_fetched_as_the_numbers_it_stands_for() {
685
+ use fixtures::quantized::{weight, D_IN, D_OUT};
686
+ let dir = tempfile::tempdir().unwrap();
687
+ let (plan, state) = open_quantized(dir.path());
688
+ let fetched = state.fetch(&plan, "m.proj.weight").unwrap();
689
+ assert_eq!(fetched.shape, vec![D_OUT as i32, D_IN as i32]);
690
+ for (got, want) in values(&fetched).iter().zip(weight(D_OUT)) {
691
+ assert!((got - want).abs() <= 2.0 / 15.0, "{got} came back for {want}");
692
+ }
693
+ // The scales are bf16-or-f32 numbers and come back as they are.
694
+ assert_eq!(state.fetch(&plan, "m.proj.scales").unwrap().shape, vec![D_OUT as i32, (D_IN / 32) as i32]);
695
+ }
696
+
697
+ /// A step through a quantized base moves the adapter side (here, the
698
+ /// head) and nothing of the base: not the words, not the scales, not
699
+ /// the biases. The loss itself ran through the packed matmul.
700
+ #[test]
701
+ fn a_step_through_a_packed_base_leaves_the_base_where_it_was() {
702
+ let dir = tempfile::tempdir().unwrap();
703
+ let (plan, mut state) = open_quantized(dir.path());
704
+ let before: Vec<Vec<f32>> = ["m.proj.weight", "m.proj.scales", "m.proj.biases"]
705
+ .iter()
706
+ .map(|path| values(&state.fetch(&plan, path).unwrap()))
707
+ .collect();
708
+ let head_before = values(&state.fetch(&plan, "m.head.weight").unwrap());
709
+
710
+ let loss = step_quantized(&plan, &mut state);
711
+ assert!(loss.is_finite(), "{loss}");
712
+ assert_eq!(state.step(), 1);
713
+
714
+ let after: Vec<Vec<f32>> = ["m.proj.weight", "m.proj.scales", "m.proj.biases"]
715
+ .iter()
716
+ .map(|path| values(&state.fetch(&plan, path).unwrap()))
717
+ .collect();
718
+ assert_eq!(before, after, "the base did not move");
719
+ assert_ne!(head_before, values(&state.fetch(&plan, "m.head.weight").unwrap()), "the head did");
720
+ assert_eq!(state.argnums(), vec![plan.index_of("m.head.weight").unwrap() as i32]);
721
+ }
722
+
723
+ /// The words of a packed weight are not weights: the norm is over the
724
+ /// numbers, and `put` is refused rather than writing numbers where
725
+ /// words are read.
726
+ #[test]
727
+ fn a_packed_weight_is_neither_counted_nor_replaced() {
728
+ let dir = tempfile::tempdir().unwrap();
729
+ let (plan, mut state) = open_quantized(dir.path());
730
+
731
+ let numbers: Vec<Array> = ["m.proj.scales", "m.proj.biases", "m.emb.weight", "m.head.weight"]
732
+ .iter()
733
+ .map(|path| state.fetch(&plan, path).unwrap().to_array().unwrap())
734
+ .collect();
735
+ let want = crate::optimizer::global_norm(&numbers).unwrap();
736
+ assert!((state.param_norm().unwrap() - want).abs() < 1e-3 * want.max(1.0));
737
+
738
+ let words = Tensor {
739
+ shape: vec![fixtures::quantized::D_OUT as i32, (fixtures::quantized::D_IN * 4 / 32) as i32],
740
+ values: Values::F32(vec![0.0; fixtures::quantized::D_OUT * fixtures::quantized::D_IN * 4 / 32]),
741
+ };
742
+ let said = state.put(&plan, "m.proj.weight", &words).unwrap_err().to_string();
743
+ assert!(said.contains("packed quantized weight"), "{said}");
744
+ }
745
+
746
+ #[test]
747
+ fn a_new_state_differentiates_everything_the_plan_allows() {
748
+ let (plan, state) = open(fixtures::teacher_and_student(), sgd(0.1));
749
+ assert_eq!(state.argnums(), plan.candidates);
750
+ assert_eq!(state.step(), 0);
751
+ assert!(state.loss().is_nan());
752
+ assert_eq!(state.seed(), 0);
753
+ }
754
+
755
+ #[test]
756
+ fn a_step_moves_only_what_is_differentiated() {
757
+ let (plan, mut state) = open(fixtures::teacher_and_student(), sgd(0.1));
758
+ step(&plan, &mut state, &[1.0, 1.0, 1.0, 1.0]);
759
+ assert_eq!(state.step(), 1);
760
+ // The teacher is frozen, so its parameter is exactly as given.
761
+ let teacher = state.fetch(&plan, "teacher.scale").unwrap();
762
+ assert_eq!(values(&teacher), vec![3.0, 4.0]);
763
+ let student = state.fetch(&plan, "student.scale").unwrap();
764
+ assert_ne!(values(&student), vec![1.0, 1.0]);
765
+ }
766
+
767
+ #[test]
768
+ fn the_lr_knob_takes_effect_from_the_next_step() {
769
+ let (plan, mut state) = open(fixtures::scaled_mean(), sgd(0.5));
770
+ assert_eq!(state.lr(), 0.5);
771
+ state.set_lr(0.25);
772
+ assert_eq!(state.lr(), 0.25);
773
+ // d(mean(x*w))/dw with x = [[2, 2]] is [1, 1] (two values, mean
774
+ // over both), so one step at 0.25 lands at w - 0.25.
775
+ step(&plan, &mut state, &[2.0, 2.0]);
776
+ let w = values(&state.fetch(&plan, "m.w").unwrap());
777
+ assert!((w[0] - 0.75).abs() < 1e-6, "{w:?}");
778
+ }
779
+
780
+ #[test]
781
+ fn the_gradient_norm_is_reported_whether_or_not_a_clip_is_set() {
782
+ let (plan, mut state) = open(fixtures::scaled_mean(), sgd(0.5));
783
+ assert_eq!(state.clip(), None);
784
+ assert!(state.grad_norm().is_nan());
785
+ step(&plan, &mut state, &[2.0, 2.0]);
786
+ // The gradient is [1, 1], so the norm is sqrt(2).
787
+ assert!((state.grad_norm() - 2.0f32.sqrt()).abs() < 1e-5);
788
+ }
789
+
790
+ #[test]
791
+ fn a_clip_bounds_the_norm_of_the_step_and_leaves_its_direction() {
792
+ let (plan, mut state) = open(fixtures::scaled_mean(), sgd(0.5));
793
+ state.set_clip(Some(0.1));
794
+ assert_eq!(state.clip(), Some(0.1));
795
+ step(&plan, &mut state, &[2.0, 2.0]);
796
+ // The norm is still reported as it was before clipping, so a
797
+ // watcher sees how far past the cap the run went.
798
+ assert!((state.grad_norm() - 2.0f32.sqrt()).abs() < 1e-5);
799
+ // The step is lr * (clip / norm) * [1, 1], whose own norm is
800
+ // lr * clip = 0.05. The weights start at [1, 2] and both move by
801
+ // the same amount, since one factor scales the whole vector.
802
+ let w = values(&state.fetch(&plan, "m.w").unwrap());
803
+ let moved = ((1.0 - w[0]).powi(2) + (2.0 - w[1]).powi(2)).sqrt();
804
+ assert!((moved - 0.5 * 0.1).abs() < 1e-5, "{w:?}");
805
+ assert!(((1.0 - w[0]) - (2.0 - w[1])).abs() < 1e-6, "{w:?}");
806
+ }
807
+
808
+ #[test]
809
+ fn the_parameter_norm_is_over_the_whole_model() {
810
+ let (plan, mut state) = open(fixtures::scaled_mean(), sgd(0.1));
811
+ // The one parameter holds [1.0, 2.0].
812
+ assert!((state.param_norm().unwrap() - 5.0f32.sqrt()).abs() < 1e-5);
813
+ // A step moves it, so the norm it reports moves too.
814
+ step(&plan, &mut state, &[2.0, 2.0]);
815
+ assert!((state.param_norm().unwrap() - 5.0f32.sqrt()).abs() > 1e-4);
816
+ }
817
+
818
+ #[test]
819
+ fn reseeding_restarts_the_draws() {
820
+ let (_, mut state) = open(fixtures::scaled_mean(), sgd(0.1));
821
+ let first = state.rng.clone();
822
+ state.set_seed(7).unwrap();
823
+ assert_eq!(state.seed(), 7);
824
+ let seven = crate::tensor::to_tensor(state.pass().rng).unwrap();
825
+ state.set_seed(0).unwrap();
826
+ let zero = crate::tensor::to_tensor(state.pass().rng).unwrap();
827
+ assert_eq!(values(&zero), values(&crate::tensor::to_tensor(&first).unwrap()));
828
+ assert_ne!(values(&seven), values(&zero));
829
+ }
830
+
831
+ #[test]
832
+ fn freezing_moves_what_autodiff_differentiates() {
833
+ let (plan, mut state) = open(fixtures::teacher_and_student(), adamw());
834
+ assert_eq!(plan.paths_of(state.argnums()), vec!["student.scale"]);
835
+ let moved = state.set_frozen(&plan, "student.*", true);
836
+ // Nothing would be left to train, so it is refused whole.
837
+ let e = moved.unwrap_err().to_string();
838
+ assert!(e.contains("would leave nothing to train"), "{e}");
839
+ assert_eq!(plan.paths_of(state.argnums()), vec!["student.scale"]);
840
+ }
841
+
842
+ #[test]
843
+ fn freezing_a_pattern_that_matches_nothing_is_refused() {
844
+ let (plan, mut state) = open(fixtures::teacher_and_student(), sgd(0.1));
845
+ let e = state
846
+ .set_frozen(&plan, "nowhere.*", true)
847
+ .unwrap_err()
848
+ .to_string();
849
+ assert!(e.contains("no parameter matches"), "{e}");
850
+ }
851
+
852
+ #[test]
853
+ fn freezing_a_frozen_parameter_is_a_no_op_not_an_error() {
854
+ // "teacher.scale" is a real path but not a candidate: the pattern
855
+ // matched, so this is nothing to do rather than a mistake.
856
+ let (plan, mut state) = open(fixtures::teacher_and_student(), sgd(0.1));
857
+ let moved = state.set_frozen(&plan, "student.scale", false).unwrap();
858
+ assert!(moved.is_empty());
859
+ }
860
+
861
+ #[test]
862
+ fn put_writes_a_parameter_and_refuses_a_mismatch() {
863
+ let (plan, mut state) = open(fixtures::scaled_mean(), sgd(0.1));
864
+ let good = Tensor {
865
+ shape: vec![2],
866
+ values: Values::F32(vec![9.0, 9.0]),
867
+ };
868
+ state.put(&plan, "m.w", &good).unwrap();
869
+ assert_eq!(values(&state.fetch(&plan, "m.w").unwrap()), vec![9.0, 9.0]);
870
+
871
+ let wrong_shape = Tensor {
872
+ shape: vec![3],
873
+ values: Values::F32(vec![0.0; 3]),
874
+ };
875
+ let e = state
876
+ .put(&plan, "m.w", &wrong_shape)
877
+ .unwrap_err()
878
+ .to_string();
879
+ assert!(e.contains("is not"), "{e}");
880
+ // Refused, and the parameter is still what it was.
881
+ assert_eq!(values(&state.fetch(&plan, "m.w").unwrap()), vec![9.0, 9.0]);
882
+
883
+ // The other payload the boundary carries is converted to what
884
+ // the parameter holds rather than refused: what a caller can say
885
+ // is the numbers, and the width is the graph's.
886
+ let integers = Tensor {
887
+ shape: vec![2],
888
+ values: Values::I32(vec![7, 8]),
889
+ };
890
+ state.put(&plan, "m.w", &integers).unwrap();
891
+ assert_eq!(values(&state.fetch(&plan, "m.w").unwrap()), vec![7.0, 8.0]);
892
+
893
+ assert!(state.put(&plan, "m.nowhere", &good).is_err());
894
+ assert!(state.fetch(&plan, "m.nowhere").is_err());
895
+ }
896
+
897
+ #[test]
898
+ fn a_restored_run_steps_where_a_continuous_one_would() {
899
+ let dir = tempfile::tempdir().unwrap();
900
+ let path = dir.path().join("ckpt").display().to_string();
901
+ let rows = [1.0f32, 2.0, 3.0, 4.0];
902
+
903
+ let (plan, mut straight) = open(fixtures::teacher_and_student(), adamw());
904
+ for _ in 0..2 {
905
+ step(&plan, &mut straight, &rows);
906
+ }
907
+ straight.save(&plan, &path, "").unwrap();
908
+ for _ in 0..3 {
909
+ step(&plan, &mut straight, &rows);
910
+ }
911
+
912
+ let (plan2, mut resumed) = open(fixtures::teacher_and_student(), adamw());
913
+ resumed.restore(&plan2, &path).unwrap();
914
+ assert_eq!(resumed.step(), 2);
915
+ assert!(resumed.loss().is_nan(), "a restore has taken no step yet");
916
+ for _ in 0..3 {
917
+ step(&plan2, &mut resumed, &rows);
918
+ }
919
+
920
+ assert_eq!(resumed.step(), straight.step());
921
+ let want = values(&straight.fetch(&plan, "student.scale").unwrap());
922
+ let got = values(&resumed.fetch(&plan2, "student.scale").unwrap());
923
+ for (w, g) in want.iter().zip(&got) {
924
+ assert!((w - g).abs() < 1e-6, "{want:?} against {got:?}");
925
+ }
926
+ }
927
+
928
+ #[test]
929
+ fn a_checkpoint_of_another_graph_is_refused() {
930
+ let dir = tempfile::tempdir().unwrap();
931
+ let path = dir.path().join("ckpt").display().to_string();
932
+ let (plan, state) = open(fixtures::scaled_mean(), sgd(0.1));
933
+ state.save(&plan, &path, "").unwrap();
934
+
935
+ let (other, mut into) = open(fixtures::teacher_and_student(), sgd(0.1));
936
+ let e = into.restore(&other, &path).unwrap_err().to_string();
937
+ assert!(e.contains("belongs to another graph"), "{e}");
938
+ }
939
+
940
+ #[test]
941
+ fn a_checkpoint_of_another_optimizer_is_refused() {
942
+ let dir = tempfile::tempdir().unwrap();
943
+ let path = dir.path().join("ckpt").display().to_string();
944
+ let (plan, state) = open(fixtures::scaled_mean(), sgd(0.1));
945
+ state.save(&plan, &path, "").unwrap();
946
+
947
+ let (plan2, mut into) = open(fixtures::scaled_mean(), adamw());
948
+ let e = into.restore(&plan2, &path).unwrap_err().to_string();
949
+ assert!(e.contains("different optimizer"), "{e}");
950
+ }
951
+
952
+ #[test]
953
+ fn an_adamw_checkpoint_without_its_slots_is_refused() {
954
+ let dir = tempfile::tempdir().unwrap();
955
+ let path = dir.path().join("ckpt").display().to_string();
956
+ let (plan, mut state) = open(fixtures::scaled_mean(), adamw());
957
+ step(&plan, &mut state, &[1.0, 2.0]);
958
+ let written = state.save(&plan, &path, "").unwrap();
959
+ std::fs::remove_file(std::path::Path::new(&written).join("optimizer.safetensors")).unwrap();
960
+
961
+ let (plan2, mut into) = open(fixtures::scaled_mean(), adamw());
962
+ let e = into.restore(&plan2, &path).unwrap_err().to_string();
963
+ assert!(e.contains("no optimizer state"), "{e}");
964
+ // Refused before anything moved.
965
+ assert_eq!(into.step(), 0);
966
+ }
967
+
968
+ #[test]
969
+ fn a_refused_restore_leaves_the_run_exactly_as_it_was() {
970
+ let dir = tempfile::tempdir().unwrap();
971
+ let path = dir.path().join("ckpt").display().to_string();
972
+ let (plan, state) = open(fixtures::scaled_mean(), sgd(0.1));
973
+ state.save(&plan, &path, "").unwrap();
974
+
975
+ let (plan2, mut into) = open(fixtures::scaled_mean(), sgd(0.1));
976
+ step(&plan2, &mut into, &[1.0, 2.0]);
977
+ let before = values(&into.fetch(&plan2, "m.w").unwrap());
978
+
979
+ // A parameter file the manifest promises but the directory lacks.
980
+ std::fs::remove_file(
981
+ std::path::Path::new(&path).join("parameters.safetensors"),
982
+ )
983
+ .unwrap();
984
+ assert!(into.restore(&plan2, &path).is_err());
985
+ assert_eq!(into.step(), 1);
986
+ assert_eq!(values(&into.fetch(&plan2, "m.w").unwrap()), before);
987
+ }
988
+
989
+
990
+ /// A part that cannot be added leaves what was already waiting as it
991
+ /// was: the sums are built before they replace the old ones.
992
+ #[test]
993
+ fn a_part_that_fails_to_add_leaves_what_was_accumulated() {
994
+ let (_, mut state) = open(fixtures::scaled_mean(), sgd(0.5));
995
+ let loss = Array::from_f32(1.0).unwrap();
996
+ let fits = [Array::from_slice(&[1.0f32, 1.0], &[2]).unwrap()];
997
+ let does_not = [Array::from_slice(&[1.0f32, 1.0, 1.0], &[3]).unwrap()];
998
+
999
+ state.accumulate(&loss, &fits).unwrap();
1000
+ assert!(state.accumulate(&loss, &does_not).is_err(), "2 and 3 do not add");
1001
+
1002
+ assert_eq!(state.accumulated(), 1);
1003
+ state.apply().unwrap();
1004
+ assert_eq!(state.step(), 1);
1005
+ }
1006
+
1007
+ }