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,650 @@
1
+ //! The optimizers, owned here rather than taken from mlx-rs.
2
+ //!
3
+ //! This is the one piece of the engine the plan says to keep under our own
4
+ //! tests (docs/plan.md section 5): an optimizer is small, it is where a
5
+ //! silent mistake hides best, and its state is half of what a checkpoint
6
+ //! must reproduce. The arithmetic is MLX's; the update rule is ours.
7
+
8
+ use anyhow::Result;
9
+ use crate::mlxc::ops::zeros_like;
10
+ use crate::mlxc::{Array, Dtype};
11
+ use serde::{Deserialize, Serialize};
12
+
13
+ /// How an optimizer is configured, as it appears in a journal, a manifest
14
+ /// and a checkpoint. Data, so that a run can say what it used.
15
+ #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
16
+ #[serde(tag = "kind", rename_all = "snake_case")]
17
+ pub enum Config {
18
+ Sgd {
19
+ lr: f32,
20
+ /// The largest L2 norm the gradients may have when the step is
21
+ /// taken; `None` is no cap. A setting of the update rather than
22
+ /// of the rule, and recorded with it, so a resumed run clips the
23
+ /// same way. See `TrainState::advance`.
24
+ #[serde(default)]
25
+ clip: Option<f32>,
26
+ },
27
+ /// Decoupled weight decay, as in the paper and as PyTorch's AdamW
28
+ /// implements it: the decay is applied to the parameter, not to the
29
+ /// gradient, so it does not enter the moment estimates.
30
+ #[serde(rename = "adamw")]
31
+ AdamW {
32
+ lr: f32,
33
+ #[serde(default = "default_beta1")]
34
+ beta1: f32,
35
+ #[serde(default = "default_beta2")]
36
+ beta2: f32,
37
+ #[serde(default = "default_eps")]
38
+ eps: f32,
39
+ #[serde(default)]
40
+ weight_decay: f32,
41
+ #[serde(default)]
42
+ clip: Option<f32>,
43
+ },
44
+ }
45
+
46
+ fn default_beta1() -> f32 {
47
+ 0.9
48
+ }
49
+ fn default_beta2() -> f32 {
50
+ 0.999
51
+ }
52
+ fn default_eps() -> f32 {
53
+ 1e-8
54
+ }
55
+
56
+ /// The L2 norm of a set of arrays, in f32: gradients before a step, or a
57
+ /// run's parameters at a point in time.
58
+ ///
59
+ /// Always f32, whatever the arrays are held in: squaring a bf16 value can
60
+ /// leave its exponent range, and a norm is the single number a clipping
61
+ /// decision is made from, which is not the place to lose precision. The
62
+ /// cast is skipped when there is nothing to cast, which is the common
63
+ /// case for gradients. Evaluates the arrays.
64
+ pub fn global_norm(arrays: &[Array]) -> Result<f32> {
65
+ let mut total: Option<Array> = None;
66
+ for array in arrays {
67
+ let value = if array.dtype() == Dtype::Float32 {
68
+ array.clone()
69
+ } else {
70
+ array.as_dtype(Dtype::Float32)?
71
+ };
72
+ let square = value.square()?.sum(false)?;
73
+ total = Some(match total {
74
+ None => square,
75
+ Some(so_far) => so_far.add(&square)?,
76
+ });
77
+ }
78
+ let norm = match total {
79
+ None => Array::from_f32(0.0)?,
80
+ Some(so_far) => so_far.sqrt()?,
81
+ };
82
+ Ok(norm.item::<f32>()?)
83
+ }
84
+
85
+ /// Every gradient multiplied by the same scalar, as a new slice.
86
+ pub fn scaled(grads: &[Array], scale: f32) -> Result<Vec<Array>> {
87
+ let factor = Array::from_f32(scale)?;
88
+ grads
89
+ .iter()
90
+ .map(|grad| Ok(grad.multiply(&factor)?))
91
+ .collect()
92
+ }
93
+
94
+ impl Config {
95
+ pub fn lr(&self) -> f32 {
96
+ match self {
97
+ Config::Sgd { lr, .. } | Config::AdamW { lr, .. } => *lr,
98
+ }
99
+ }
100
+
101
+ pub fn set_lr(&mut self, value: f32) {
102
+ match self {
103
+ Config::Sgd { lr, .. } | Config::AdamW { lr, .. } => *lr = value,
104
+ }
105
+ }
106
+
107
+ /// The largest gradient norm this rule will step on, or `None`.
108
+ pub fn clip(&self) -> Option<f32> {
109
+ match self {
110
+ Config::Sgd { clip, .. } | Config::AdamW { clip, .. } => *clip,
111
+ }
112
+ }
113
+
114
+ pub fn set_clip(&mut self, value: Option<f32>) {
115
+ match self {
116
+ Config::Sgd { clip, .. } | Config::AdamW { clip, .. } => *clip = value,
117
+ }
118
+ }
119
+
120
+ pub fn name(&self) -> &'static str {
121
+ match self {
122
+ Config::Sgd { .. } => "sgd",
123
+ Config::AdamW { .. } => "adamw",
124
+ }
125
+ }
126
+ }
127
+
128
+ /// What a rule remembers between steps, per differentiated parameter, in
129
+ /// the order the parameters are differentiated.
130
+ #[derive(Clone)]
131
+ pub enum Moments {
132
+ /// SGD remembers nothing.
133
+ None,
134
+ /// AdamW's first and second moments.
135
+ Adam { m: Vec<Array>, v: Vec<Array> },
136
+ }
137
+
138
+ impl Moments {
139
+ /// Every array held, first moments then second.
140
+ pub fn arrays(&self) -> impl Iterator<Item = &Array> {
141
+ let (m, v): (&[Array], &[Array]) = match self {
142
+ Moments::None => (&[], &[]),
143
+ Moments::Adam { m, v } => (m, v),
144
+ };
145
+ m.iter().chain(v)
146
+ }
147
+
148
+ /// How many parameters these are for (none for a rule with no state).
149
+ fn len(&self) -> usize {
150
+ match self {
151
+ Moments::None => 0,
152
+ Moments::Adam { m, .. } => m.len(),
153
+ }
154
+ }
155
+ }
156
+
157
+ /// An optimizer: its rule, what the rule remembers, and how many steps it
158
+ /// has taken.
159
+ #[derive(Clone)]
160
+ pub struct Optimizer {
161
+ config: Config,
162
+ moments: Moments,
163
+ /// Steps taken, for the bias correction. Part of the state a checkpoint
164
+ /// restores: resuming with t = 0 would take a wrong first step.
165
+ t: u64,
166
+ }
167
+
168
+ /// The rule and how much state it is carrying, never the slots
169
+ /// themselves: a moment is the size of the parameter it belongs to.
170
+ impl std::fmt::Debug for Optimizer {
171
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
172
+ write!(
173
+ f,
174
+ "Optimizer({}, {} slots, {} steps)",
175
+ self.config.name(),
176
+ self.moments.len(),
177
+ self.t
178
+ )
179
+ }
180
+ }
181
+
182
+ /// Zeros shaped like each differentiated parameter: a moment's start.
183
+ fn zeros_for(params: &[Array], argnums: &[i32]) -> Result<Vec<Array>> {
184
+ argnums.iter().map(|&i| slot_for(&params[i as usize])).collect()
185
+ }
186
+
187
+ impl Optimizer {
188
+ pub fn new(config: Config, params: &[Array], argnums: &[i32]) -> Result<Self> {
189
+ let moments = match config {
190
+ Config::Sgd { .. } => Moments::None,
191
+ Config::AdamW { .. } => Moments::Adam {
192
+ m: zeros_for(params, argnums)?,
193
+ v: zeros_for(params, argnums)?,
194
+ },
195
+ };
196
+ Ok(Self { config, moments, t: 0 })
197
+ }
198
+
199
+ pub fn config(&self) -> &Config {
200
+ &self.config
201
+ }
202
+
203
+ pub fn config_mut(&mut self) -> &mut Config {
204
+ &mut self.config
205
+ }
206
+
207
+ pub fn steps_taken(&self) -> u64 {
208
+ self.t
209
+ }
210
+
211
+ /// The moments, for a checkpoint: `None` for a rule that keeps none.
212
+ pub fn slots(&self) -> Option<(&[Array], &[Array])> {
213
+ match &self.moments {
214
+ Moments::None => None,
215
+ Moments::Adam { m, v } => Some((m, v)),
216
+ }
217
+ }
218
+
219
+ /// Every array the optimizer holds, for evaluating it with the rest of
220
+ /// a step.
221
+ pub fn arrays(&self) -> impl Iterator<Item = &Array> {
222
+ self.moments.arrays()
223
+ }
224
+
225
+ /// Moves the slots to follow a change in what is differentiated:
226
+ /// kept for parameters that stay, dropped for those that freeze,
227
+ /// started at zero for those that thaw.
228
+ ///
229
+ /// The step count is not reset. A thawed parameter joins a run in
230
+ /// progress, and its bias correction is that run's, not a new one's.
231
+ pub fn refit(&mut self, was: &[i32], now: &[i32], params: &[Array]) -> Result<()> {
232
+ let Moments::Adam { m, v } = &self.moments else {
233
+ return Ok(());
234
+ };
235
+ anyhow::ensure!(
236
+ m.len() == was.len(),
237
+ "the optimizer has {} slots for {} parameters",
238
+ m.len(),
239
+ was.len()
240
+ );
241
+ let (mut next_m, mut next_v) = (Vec::with_capacity(now.len()), Vec::with_capacity(now.len()));
242
+ for &i in now {
243
+ match was.iter().position(|&w| w == i) {
244
+ Some(slot) => {
245
+ next_m.push(m[slot].clone());
246
+ next_v.push(v[slot].clone());
247
+ }
248
+ None => {
249
+ next_m.push(slot_for(&params[i as usize])?);
250
+ next_v.push(slot_for(&params[i as usize])?);
251
+ }
252
+ }
253
+ }
254
+ self.moments = Moments::Adam { m: next_m, v: next_v };
255
+ Ok(())
256
+ }
257
+
258
+ /// Restores state a checkpoint held. The shapes are the caller's to
259
+ /// have checked against the parameters.
260
+ pub fn restore(&mut self, moments: Moments, t: u64) {
261
+ self.moments = moments;
262
+ self.t = t;
263
+ }
264
+
265
+ /// Whether this rule keeps per-parameter state. A checkpoint that
266
+ /// disagrees with this is refused rather than restored into a shape
267
+ /// the next step would index past.
268
+ pub fn wants_slots(&self) -> bool {
269
+ matches!(self.config, Config::AdamW { .. })
270
+ }
271
+
272
+ /// The optimizer after one update, and `params` written in place.
273
+ /// Returns a new value rather than mutating, so the caller can evaluate
274
+ /// everything before committing to it (see `TrainState::advance`).
275
+ pub fn next(&self, params: &mut [Array], argnums: &[i32], grads: &[Array]) -> Result<Self> {
276
+ let mut next = self.clone();
277
+ next.apply(params, argnums, grads)?;
278
+ Ok(next)
279
+ }
280
+
281
+ /// Applies one update in place. `grads` is parallel to `argnums`.
282
+ fn apply(&mut self, params: &mut [Array], argnums: &[i32], grads: &[Array]) -> Result<()> {
283
+ anyhow::ensure!(
284
+ argnums.len() == grads.len(),
285
+ "{} gradients for {} differentiated parameters",
286
+ grads.len(),
287
+ argnums.len()
288
+ );
289
+ anyhow::ensure!(
290
+ self.moments.len() == argnums.len() || matches!(self.moments, Moments::None),
291
+ "the optimizer has {} slots for {} differentiated parameters; \
292
+ this state did not come from this session",
293
+ self.moments.len(),
294
+ argnums.len()
295
+ );
296
+ self.t += 1;
297
+ match (self.config.clone(), &mut self.moments) {
298
+ (Config::Sgd { lr, .. }, _) => {
299
+ let lr = Array::from_f32(lr)?;
300
+ for (&i, grad) in argnums.iter().zip(grads) {
301
+ let i = i as usize;
302
+ let next = params[i].subtract(grad.multiply(&lr)?)?;
303
+ params[i] = held_as(next, &params[i])?;
304
+ }
305
+ }
306
+ (
307
+ Config::AdamW {
308
+ lr,
309
+ beta1,
310
+ beta2,
311
+ eps,
312
+ weight_decay,
313
+ ..
314
+ },
315
+ Moments::Adam { m, v },
316
+ ) => {
317
+ // Bias correction from the step count, so a resumed run
318
+ // takes the step it would have taken.
319
+ let t = self.t as f32;
320
+ let bias1 = 1.0 - beta1.powf(t);
321
+ let bias2 = 1.0 - beta2.powf(t);
322
+ let (b1, b2) = (Array::from_f32(beta1)?, Array::from_f32(beta2)?);
323
+ let (one_b1, one_b2) = (
324
+ Array::from_f32(1.0 - beta1)?,
325
+ Array::from_f32(1.0 - beta2)?,
326
+ );
327
+ let lr_a = Array::from_f32(lr)?;
328
+ let eps_a = Array::from_f32(eps)?;
329
+ let bias1_a = Array::from_f32(bias1)?;
330
+ let bias2_a = Array::from_f32(bias2)?;
331
+
332
+ for (slot, (&i, grad)) in argnums.iter().zip(grads).enumerate() {
333
+ let i = i as usize;
334
+ m[slot] = m[slot]
335
+ .multiply(&b1)?
336
+ .add(grad.multiply(&one_b1)?)?;
337
+ v[slot] = v[slot]
338
+ .multiply(&b2)?
339
+ .add(grad.square()?.multiply(&one_b2)?)?;
340
+
341
+ let m_hat = m[slot].divide(&bias1_a)?;
342
+ let v_hat = v[slot].divide(&bias2_a)?;
343
+ let denom = v_hat.sqrt()?.add(&eps_a)?;
344
+ let mut next = params[i].subtract(m_hat.divide(&denom)?.multiply(&lr_a)?)?;
345
+ if weight_decay != 0.0 {
346
+ // Decoupled: applied to the parameter, after the
347
+ // Adam step, and never through the moments.
348
+ let decay = Array::from_f32(lr * weight_decay)?;
349
+ next = next.subtract(params[i].multiply(&decay)?)?;
350
+ }
351
+ params[i] = held_as(next, &params[i])?;
352
+ }
353
+ }
354
+ (Config::AdamW { .. }, Moments::None) => {
355
+ anyhow::bail!("adamw has no moments here; this state did not come from this session")
356
+ }
357
+ }
358
+ Ok(())
359
+ }
360
+ }
361
+
362
+ /// An optimizer slot for `param`: zeros of its shape, in f32 whatever
363
+ /// the parameter is held in. The moments are running averages of
364
+ /// gradients and their squares, and bf16's eight bits are too few to
365
+ /// average in; f32 is what they would have become after the first step
366
+ /// anyway, since the update's constants are f32.
367
+ fn slot_for(param: &Array) -> Result<Array> {
368
+ let zeros = zeros_like(param)?;
369
+ Ok(if zeros.dtype() == Dtype::Float32 { zeros } else { zeros.as_dtype(Dtype::Float32)? })
370
+ }
371
+
372
+ /// The updated parameter, held as the parameter was.
373
+ ///
374
+ /// The step is computed in f32 (its learning rate, its moments), and MLX
375
+ /// promotes a bf16 parameter combined with them to f32. Left that way, a
376
+ /// bf16 model's trained parameters became f32 after its first step and
377
+ /// stayed so, against what the graph declares (docs/plan.md 15.77); the
378
+ /// engine's dtype check is what found it.
379
+ fn held_as(next: Array, param: &Array) -> Result<Array> {
380
+ Ok(if next.dtype() == param.dtype() { next } else { next.as_dtype(param.dtype())? })
381
+ }
382
+
383
+ #[cfg(test)]
384
+ mod tests {
385
+ use super::*;
386
+ use crate::mlxc::transforms::eval;
387
+
388
+ /// A bf16 parameter is still bf16 after a step, by either rule, and
389
+ /// its moments are f32 from the start.
390
+ #[test]
391
+ fn a_step_keeps_a_parameter_in_the_dtype_it_is_held_in() {
392
+ crate::runtime::runtime()
393
+ .execute(|| {
394
+ for config in [
395
+ Config::Sgd { lr: 0.1, clip: None },
396
+ Config::AdamW { lr: 0.1, beta1: 0.9, beta2: 0.999, eps: 1e-8, weight_decay: 0.01, clip: None },
397
+ ] {
398
+ let mut params = vec![array(&[1.0, 2.0]).as_dtype(Dtype::Bfloat16)?];
399
+ let grads = vec![array(&[0.5, -0.5]).as_dtype(Dtype::Bfloat16)?];
400
+ let optimizer = Optimizer::new(config.clone(), &params, &[0])?;
401
+ let next = optimizer.next(&mut params, &[0], &grads)?;
402
+ assert_eq!(params[0].dtype(), Dtype::Bfloat16, "{config:?}");
403
+ for slot in next.arrays() {
404
+ assert_eq!(slot.dtype(), Dtype::Float32, "{config:?}");
405
+ }
406
+ }
407
+ Ok(())
408
+ })
409
+ .unwrap();
410
+ }
411
+
412
+ fn array(values: &[f32]) -> Array {
413
+ Array::from_slice(values, &[values.len() as i32]).unwrap()
414
+ }
415
+
416
+ fn read(array: &Array) -> Vec<f32> {
417
+ eval(std::iter::once(array)).unwrap();
418
+ array.as_slice::<f32>().unwrap().to_vec()
419
+ }
420
+
421
+ fn close(got: &[f32], want: &[f32]) {
422
+ assert_eq!(got.len(), want.len(), "{got:?} against {want:?}");
423
+ for (g, w) in got.iter().zip(want) {
424
+ assert!((g - w).abs() < 1e-6, "{got:?} against {want:?}");
425
+ }
426
+ }
427
+
428
+ const ADAMW: Config = Config::AdamW {
429
+ lr: 0.1,
430
+ beta1: 0.9,
431
+ beta2: 0.999,
432
+ eps: 1e-8,
433
+ weight_decay: 0.0,
434
+ clip: None,
435
+ };
436
+
437
+ #[test]
438
+ fn a_config_names_itself_the_way_a_manifest_reads_it() {
439
+ // serde would have called this "adam_w"; a checkpoint written by
440
+ // one spelling and read by the other would be refused as foreign.
441
+ let json = serde_json::to_string(&ADAMW).unwrap();
442
+ assert!(json.contains(r#""kind":"adamw""#), "{json}");
443
+ let back: Config = serde_json::from_str(&json).unwrap();
444
+ assert_eq!(back, ADAMW);
445
+ }
446
+
447
+ #[test]
448
+ fn adamw_defaults_are_filled_in_from_a_bare_config() {
449
+ let back: Config = serde_json::from_str(r#"{"kind":"adamw","lr":0.5}"#).unwrap();
450
+ assert_eq!(
451
+ back,
452
+ Config::AdamW {
453
+ lr: 0.5,
454
+ beta1: 0.9,
455
+ beta2: 0.999,
456
+ eps: 1e-8,
457
+ weight_decay: 0.0,
458
+ clip: None,
459
+ }
460
+ );
461
+ }
462
+
463
+ #[test]
464
+ fn a_clip_travels_with_the_rule_it_belongs_to() {
465
+ let with = r#"{"kind":"sgd","lr":0.1,"clip":1.0}"#;
466
+ let back: Config = serde_json::from_str(with).unwrap();
467
+ assert_eq!(back.clip(), Some(1.0));
468
+ // Absent is no clip, and an old config without the key reads that
469
+ // way rather than failing.
470
+ let back: Config = serde_json::from_str(r#"{"kind":"sgd","lr":0.1}"#).unwrap();
471
+ assert_eq!(back.clip(), None);
472
+ }
473
+
474
+ #[test]
475
+ fn the_global_norm_is_over_every_gradient_at_once() {
476
+ let grads = [array(&[3.0, 4.0]), array(&[12.0, 0.0])];
477
+ // sqrt(3^2 + 4^2 + 12^2) = 13, not either gradient's own norm.
478
+ assert!((global_norm(&grads).unwrap() - 13.0).abs() < 1e-5);
479
+ // No gradients is a norm of zero, not an error.
480
+ assert_eq!(global_norm(&[]).unwrap(), 0.0);
481
+ }
482
+
483
+ #[test]
484
+ fn scaling_leaves_the_direction_and_takes_the_norm_to_the_cap() {
485
+ let grads = [array(&[3.0]), array(&[4.0])];
486
+ let norm = global_norm(&grads).unwrap();
487
+ let capped = scaled(&grads, 1.0 / norm).unwrap();
488
+ let before = [3.0 / 5.0, 4.0 / 5.0];
489
+ close(&read(&capped[0]), &before[..1]);
490
+ close(&read(&capped[1]), &before[1..]);
491
+ assert!((global_norm(&capped).unwrap() - 1.0).abs() < 1e-5);
492
+ }
493
+
494
+ #[test]
495
+ fn sgd_subtracts_the_gradient_scaled_by_the_rate() {
496
+ let opt = Optimizer::new(
497
+ Config::Sgd {
498
+ lr: 0.5,
499
+ clip: None,
500
+ },
501
+ &[array(&[1.0, 2.0])],
502
+ &[0],
503
+ )
504
+ .unwrap();
505
+ let mut params = vec![array(&[1.0, 2.0])];
506
+ let next = opt.next(&mut params, &[0], &[array(&[2.0, 4.0])]).unwrap();
507
+ close(&read(&params[0]), &[0.0, 0.0]);
508
+ assert_eq!(next.steps_taken(), 1);
509
+ // The original is untouched: a step that fails must leave the run
510
+ // as it was, which is why next() returns rather than mutates.
511
+ assert_eq!(opt.steps_taken(), 0);
512
+ }
513
+
514
+ #[test]
515
+ fn adamws_first_step_is_the_rate_regardless_of_the_gradients_size() {
516
+ // With t = 1 the bias correction cancels the moments, so the step
517
+ // is lr * g / (|g| + eps): the sign of the gradient, times lr.
518
+ // This is the property that catches a missing correction.
519
+ let params0 = vec![array(&[0.0, 0.0])];
520
+ let opt = Optimizer::new(ADAMW, &params0, &[0]).unwrap();
521
+ let mut params = params0.clone();
522
+ opt.next(&mut params, &[0], &[array(&[1e-3, -50.0])]).unwrap();
523
+ close(&read(&params[0]), &[-0.1, 0.1]);
524
+ }
525
+
526
+ #[test]
527
+ fn adamw_carries_its_step_count_so_a_resumed_run_steps_the_same() {
528
+ let params0 = vec![array(&[0.0])];
529
+ let grads = [array(&[1.0])];
530
+
531
+ let mut straight = vec![array(&[0.0])];
532
+ let mut opt = Optimizer::new(ADAMW, &params0, &[0]).unwrap();
533
+ for _ in 0..3 {
534
+ opt = opt.next(&mut straight, &[0], &grads).unwrap();
535
+ }
536
+
537
+ // The same three steps, with the state carried across a restore.
538
+ let mut resumed = vec![array(&[0.0])];
539
+ let mut a = Optimizer::new(ADAMW, &params0, &[0]).unwrap();
540
+ a = a.next(&mut resumed, &[0], &grads).unwrap();
541
+ let t = a.steps_taken();
542
+ let mut b = Optimizer::new(ADAMW, &params0, &[0]).unwrap();
543
+ b.restore(a.moments.clone(), t);
544
+ for _ in 0..2 {
545
+ b = b.next(&mut resumed, &[0], &grads).unwrap();
546
+ }
547
+
548
+ assert_eq!(b.steps_taken(), opt.steps_taken());
549
+ close(&read(&resumed[0]), &read(&straight[0]));
550
+ }
551
+
552
+ #[test]
553
+ fn a_forgotten_step_count_would_take_a_different_step() {
554
+ // Pins that the assertion above has teeth: restoring t = 0 does
555
+ // not land where a continuous run lands.
556
+ let params0 = vec![array(&[0.0])];
557
+ let grads = [array(&[1.0])];
558
+ let mut straight = vec![array(&[0.0])];
559
+ let mut opt = Optimizer::new(ADAMW, &params0, &[0]).unwrap();
560
+ for _ in 0..2 {
561
+ opt = opt.next(&mut straight, &[0], &grads).unwrap();
562
+ }
563
+
564
+ let mut wrong = vec![array(&[0.0])];
565
+ let mut a = Optimizer::new(ADAMW, &params0, &[0]).unwrap();
566
+ a = a.next(&mut wrong, &[0], &grads).unwrap();
567
+ let mut b = Optimizer::new(ADAMW, &params0, &[0]).unwrap();
568
+ b.restore(a.moments.clone(), 0);
569
+ b.next(&mut wrong, &[0], &grads).unwrap();
570
+
571
+ let (want, got) = (read(&straight[0]), read(&wrong[0]));
572
+ assert!((want[0] - got[0]).abs() > 1e-4, "{want:?} against {got:?}");
573
+ }
574
+
575
+ #[test]
576
+ fn decoupled_decay_shrinks_the_parameter_and_not_the_moments() {
577
+ let decayed = Config::AdamW {
578
+ lr: 0.1,
579
+ beta1: 0.9,
580
+ beta2: 0.999,
581
+ eps: 1e-8,
582
+ weight_decay: 0.5,
583
+ clip: None,
584
+ };
585
+ let params0 = vec![array(&[2.0])];
586
+ let opt = Optimizer::new(decayed, &params0, &[0]).unwrap();
587
+ let mut params = params0.clone();
588
+ let next = opt.next(&mut params, &[0], &[array(&[1.0])]).unwrap();
589
+ // Adam's own step is lr, and the decay is lr * wd * param.
590
+ close(&read(&params[0]), &[2.0 - 0.1 - 0.1 * 0.5 * 2.0]);
591
+ // The moment saw the gradient alone: 0.1 * 1.0.
592
+ close(&read(&next.slots().unwrap().0[0]), &[0.1]);
593
+ }
594
+
595
+ #[test]
596
+ fn refit_keeps_what_stays_zeroes_what_thaws_and_drops_what_freezes() {
597
+ let params = vec![array(&[0.0]), array(&[0.0]), array(&[0.0])];
598
+ let mut opt = Optimizer::new(ADAMW, &params, &[0, 1]).unwrap();
599
+ let mut copy = params.clone();
600
+ opt = opt
601
+ .next(&mut copy, &[0, 1], &[array(&[1.0]), array(&[2.0])])
602
+ .unwrap();
603
+ let before: Vec<Vec<f32>> = opt.slots().unwrap().0.iter().map(read).collect();
604
+ assert_eq!(before.len(), 2);
605
+
606
+ // Freeze 0, thaw 2: parameter 1's slot follows it to the front.
607
+ opt.refit(&[0, 1], &[1, 2], &params).unwrap();
608
+ let after: Vec<Vec<f32>> = opt.slots().unwrap().0.iter().map(read).collect();
609
+ assert_eq!(after.len(), 2);
610
+ close(&after[0], &before[1]);
611
+ close(&after[1], &[0.0]);
612
+ // A thawed parameter joins a run in progress; the count is the
613
+ // run's, so its bias correction is too.
614
+ assert_eq!(opt.steps_taken(), 1);
615
+ }
616
+
617
+ #[test]
618
+ fn refit_is_nothing_for_an_optimizer_with_no_slots() {
619
+ let params = vec![array(&[0.0]), array(&[0.0])];
620
+ let mut opt = Optimizer::new(Config::Sgd { lr: 0.1, clip: None }, &params, &[0]).unwrap();
621
+ opt.refit(&[0], &[0, 1], &params).unwrap();
622
+ assert!(opt.slots().is_none());
623
+ assert!(!opt.wants_slots());
624
+ }
625
+
626
+ #[test]
627
+ fn a_gradient_count_that_does_not_match_is_refused() {
628
+ let params = vec![array(&[0.0]), array(&[0.0])];
629
+ let opt = Optimizer::new(Config::Sgd { lr: 0.1, clip: None }, &params, &[0, 1]).unwrap();
630
+ let mut copy = params.clone();
631
+ let e = opt
632
+ .next(&mut copy, &[0, 1], &[array(&[1.0])])
633
+ .unwrap_err()
634
+ .to_string();
635
+ assert!(e.contains("1 gradients for 2"), "{e}");
636
+ }
637
+
638
+ #[test]
639
+ fn slots_that_do_not_belong_to_this_run_are_refused_not_indexed_past() {
640
+ let params = vec![array(&[0.0]), array(&[0.0])];
641
+ let mut opt = Optimizer::new(ADAMW, &params, &[0, 1]).unwrap();
642
+ opt.restore(Moments::Adam { m: Vec::new(), v: Vec::new() }, 7);
643
+ let mut copy = params.clone();
644
+ let e = opt
645
+ .next(&mut copy, &[0, 1], &[array(&[1.0]), array(&[1.0])])
646
+ .unwrap_err()
647
+ .to_string();
648
+ assert!(e.contains("did not come from this session"), "{e}");
649
+ }
650
+ }