mathverse-ai 0.1.2

AI/ML mathematical primitives: tensors, activations, losses, optimizers, attention, autograd, layers, models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Stateful optimizers: SGD (with momentum + weight decay), Adam, AdamW,
//! and learning rate schedulers.

/// SGD with momentum and optional weight decay.
pub struct Sgd {
    /// Learning rate.
    pub lr: f64,
    /// Momentum factor in `[0, 1)`.
    pub momentum: f64,
    /// L2 weight decay coefficient.
    pub weight_decay: f64,
    velocity: Vec<f64>,
    initialized: bool,
}

impl Sgd {
    /// Create a new SGD optimizer.
    pub fn new(lr: f64, momentum: f64, weight_decay: f64) -> Self {
        Self { lr, momentum, weight_decay, velocity: Vec::new(), initialized: false }
    }

    /// Perform one optimization step. `params` and `grads` must have same length.
    pub fn step(&mut self, params: &mut [f64], grads: &[f64]) {
        debug_assert_eq!(params.len(), grads.len(), "Sgd: params/grads length mismatch");
        if params.len() != grads.len() { return; }
        if !self.initialized {
            self.velocity = vec![0.0; params.len()];
            self.initialized = true;
        }
        for (i, (p, g)) in params.iter_mut().zip(grads).enumerate() {
            let mut grad = *g;
            if self.weight_decay > 0.0 {
                grad += self.weight_decay * *p;
            }
            self.velocity[i] = self.momentum * self.velocity[i] + grad;
            *p -= self.lr * self.velocity[i];
        }
    }
}

/// Adam optimizer.
pub struct Adam {
    /// Learning rate.
    pub lr: f64,
    /// Exponential decay rate for first moment estimates.
    pub beta1: f64,
    /// Exponential decay rate for second moment estimates.
    pub beta2: f64,
    /// Small value added to the denominator for numerical stability.
    pub eps: f64,
    /// L2 weight decay coefficient (coupled to gradient, Adam-style).
    pub weight_decay: f64,
    m: Vec<f64>,
    v: Vec<f64>,
    t: i32,
    initialized: bool,
}

impl Adam {
    /// Create a new Adam optimizer.
    pub fn new(lr: f64, beta1: f64, beta2: f64, eps: f64, weight_decay: f64) -> Self {
        Self { lr, beta1, beta2, eps, weight_decay, m: Vec::new(), v: Vec::new(), t: 0, initialized: false }
    }

    /// Perform one optimization step. `params` and `grads` must have the same length.
    pub fn step(&mut self, params: &mut [f64], grads: &[f64]) {
        debug_assert_eq!(params.len(), grads.len(), "Adam: params/grads length mismatch");
        if params.len() != grads.len() { return; }
        if !self.initialized {
            self.m = vec![0.0; params.len()];
            self.v = vec![0.0; params.len()];
            self.initialized = true;
        }
        self.t += 1;
        let bc1 = 1.0 - self.beta1.powi(self.t);
        let bc2 = 1.0 - self.beta2.powi(self.t);
        for (i, (p, g)) in params.iter_mut().zip(grads).enumerate() {
            let mut grad = *g;
            if self.weight_decay > 0.0 {
                grad += self.weight_decay * *p;
            }
            self.m[i] = self.beta1 * self.m[i] + (1.0 - self.beta1) * grad;
            self.v[i] = self.beta2 * self.v[i] + (1.0 - self.beta2) * grad * grad;
            let m_hat = self.m[i] / bc1;
            let v_hat = self.v[i] / bc2;
            *p -= self.lr * m_hat / (v_hat.sqrt() + self.eps);
        }
    }

    /// Zero moment buffers in place (keeps allocations).
    pub fn zero_grad(&mut self) { self.t = 0; self.m.iter_mut().for_each(|x| *x = 0.0); self.v.iter_mut().for_each(|x| *x = 0.0); }
}

/// AdamW optimizer (decoupled weight decay).
pub struct AdamW {
    /// Learning rate.
    pub lr: f64,
    /// Exponential decay rate for first moment estimates.
    pub beta1: f64,
    /// Exponential decay rate for second moment estimates.
    pub beta2: f64,
    /// Small value added to the denominator for numerical stability.
    pub eps: f64,
    /// Decoupled weight decay coefficient.
    pub weight_decay: f64,
    m: Vec<f64>,
    v: Vec<f64>,
    t: i32,
    initialized: bool,
}

impl AdamW {
    /// Create a new AdamW optimizer.
    pub fn new(lr: f64, beta1: f64, beta2: f64, eps: f64, weight_decay: f64) -> Self {
        Self { lr, beta1, beta2, eps, weight_decay, m: Vec::new(), v: Vec::new(), t: 0, initialized: false }
    }

    /// Perform one optimization step. `params` and `grads` must have the same length.
    pub fn step(&mut self, params: &mut [f64], grads: &[f64]) {
        debug_assert_eq!(params.len(), grads.len(), "AdamW: params/grads length mismatch");
        if params.len() != grads.len() { return; }
        if !self.initialized {
            self.m = vec![0.0; params.len()];
            self.v = vec![0.0; params.len()];
            self.initialized = true;
        }
        self.t += 1;
        let bc1 = 1.0 - self.beta1.powi(self.t);
        let bc2 = 1.0 - self.beta2.powi(self.t);
        for (i, (p, g)) in params.iter_mut().zip(grads).enumerate() {
            // Decoupled weight decay: decay applied directly to params, not via grad
            if self.weight_decay > 0.0 {
                *p *= 1.0 - self.lr * self.weight_decay;
            }
            self.m[i] = self.beta1 * self.m[i] + (1.0 - self.beta1) * *g;
            self.v[i] = self.beta2 * self.v[i] + (1.0 - self.beta2) * *g * *g;
            let m_hat = self.m[i] / bc1;
            let v_hat = self.v[i] / bc2;
            *p -= self.lr * m_hat / (v_hat.sqrt() + self.eps);
        }
    }

    /// Zero moment buffers in place (keeps allocations).
    pub fn zero_grad(&mut self) { self.t = 0; self.m.iter_mut().for_each(|x| *x = 0.0); self.v.iter_mut().for_each(|x| *x = 0.0); }
}

// ---------------------------------------------------------------------------
// Learning rate schedulers
// ---------------------------------------------------------------------------

/// Learning rate schedule type.
pub enum Schedule {
    /// Constant learning rate of `1.0` (scale externally if needed).
    Constant,
    /// Multiply the learning rate by `gamma` every `step_size` steps.
    StepDecay { step_size: usize, gamma: f64 },
    /// Cosine annealing between `1.0` and `eta_min` with period `t_max`.
    CosineAnnealing { t_max: usize, eta_min: f64 },
    /// Linear warmup from `base_lr` to `target_lr` for `warmup_steps` steps.
    LinearWarmup { warmup_steps: usize, base_lr: f64, target_lr: f64 },
}

/// Learning rate scheduler driven by a [`Schedule`].
pub struct LrScheduler {
    schedule: Schedule,
    step_count: usize,
}

impl LrScheduler {
    /// Create a new scheduler.
    pub fn new(schedule: Schedule) -> Self {
        Self { schedule, step_count: 0 }
    }

    /// Get current learning rate.
    pub fn get_lr(&self) -> f64 {
        match &self.schedule {
            Schedule::Constant => 1.0,
            Schedule::StepDecay { step_size, gamma } => {
                gamma.powf((self.step_count / step_size) as f64)
            }
            Schedule::CosineAnnealing { t_max, eta_min } => {
                let t = (self.step_count % t_max) as f64;
                eta_min + 0.5 * (1.0 - eta_min) * (1.0 + (std::f64::consts::PI * t / *t_max as f64).cos())
            }
            Schedule::LinearWarmup { warmup_steps, base_lr, target_lr } => {
                if self.step_count < *warmup_steps {
                    base_lr + (target_lr - base_lr) * self.step_count as f64 / *warmup_steps as f64
                } else {
                    *target_lr
                }
            }
        }
    }

    /// Advance the schedule by one step.
    pub fn step(&mut self) { self.step_count += 1; }
}

// ---------------------------------------------------------------------------
// Additional optimizers
// ---------------------------------------------------------------------------

/// RMSprop optimizer.
pub struct RMSprop {
    /// Learning rate.
    pub lr: f64,
    /// Exponential decay rate for squared gradients.
    pub alpha: f64,
    /// Small value added to the denominator for numerical stability.
    pub eps: f64,
    /// L2 weight decay coefficient.
    pub weight_decay: f64,
    /// Momentum factor applied to the normalized gradient.
    pub momentum: f64,
    avg_sq: Vec<f64>,
    velocity: Vec<f64>,
    initialized: bool,
}

impl RMSprop {
    /// Create a new RMSprop optimizer.
    pub fn new(lr: f64, alpha: f64, eps: f64, weight_decay: f64, momentum: f64) -> Self {
        Self { lr, alpha, eps, weight_decay, momentum, avg_sq: Vec::new(), velocity: Vec::new(), initialized: false }
    }

    /// Perform one optimization step. `params` and `grads` must have the same length.
    pub fn step(&mut self, params: &mut [f64], grads: &[f64]) {
        debug_assert_eq!(params.len(), grads.len(), "RMSprop: params/grads length mismatch");
        if params.len() != grads.len() { return; }
        if !self.initialized {
            self.avg_sq = vec![0.0; params.len()];
            self.velocity = vec![0.0; params.len()];
            self.initialized = true;
        }
        for (i, (p, g)) in params.iter_mut().zip(grads).enumerate() {
            let mut grad = *g;
            if self.weight_decay > 0.0 { grad += self.weight_decay * *p; }
            self.avg_sq[i] = self.alpha * self.avg_sq[i] + (1.0 - self.alpha) * grad * grad;
            self.velocity[i] = self.momentum * self.velocity[i] + grad / (self.avg_sq[i].sqrt() + self.eps);
            *p -= self.lr * self.velocity[i];
        }
    }

    /// Reset running averages and momentum state.
    pub fn zero_grad(&mut self) { self.avg_sq.iter_mut().for_each(|x| *x = 0.0); self.velocity.iter_mut().for_each(|x| *x = 0.0); }
}

/// Lion optimizer (EvoLved Sign Momentum).
pub struct Lion {
    /// Learning rate.
    pub lr: f64,
    /// First momentum coefficient.
    pub beta1: f64,
    /// Second momentum coefficient.
    pub beta2: f64,
    /// L2 weight decay coefficient.
    pub weight_decay: f64,
    m: Vec<f64>,
    initialized: bool,
}

impl Lion {
    /// Create a new Lion optimizer.
    pub fn new(lr: f64, beta1: f64, beta2: f64, weight_decay: f64) -> Self {
        Self { lr, beta1, beta2, weight_decay, m: Vec::new(), initialized: false }
    }

    /// Perform one optimization step. `params` and `grads` must have the same length.
    pub fn step(&mut self, params: &mut [f64], grads: &[f64]) {
        debug_assert_eq!(params.len(), grads.len(), "Lion: params/grads length mismatch");
        if params.len() != grads.len() { return; }
        if !self.initialized {
            self.m = vec![0.0; params.len()];
            self.initialized = true;
        }
        for (i, (p, g)) in params.iter_mut().zip(grads).enumerate() {
            let update = self.m[i] * self.beta1 + *g * (1.0 - self.beta1);
            let sign = update.signum();
            *p -= self.lr * (*p * self.weight_decay + sign);
            self.m[i] = self.m[i] * self.beta2 + *g * (1.0 - self.beta2);
        }
    }

    /// Reset internal momentum state.
    pub fn zero_grad(&mut self) { self.m.iter_mut().for_each(|x| *x = 0.0); }
}

/// AdaGrad optimizer.
pub struct AdaGrad {
    /// Learning rate.
    pub lr: f64,
    /// Small value added to the denominator for numerical stability.
    pub eps: f64,
    /// L2 weight decay coefficient.
    pub weight_decay: f64,
    sum_sq: Vec<f64>,
    initialized: bool,
}

impl AdaGrad {
    /// Create a new AdaGrad optimizer.
    pub fn new(lr: f64, eps: f64, weight_decay: f64) -> Self {
        Self { lr, eps, weight_decay, sum_sq: Vec::new(), initialized: false }
    }

    /// Perform one optimization step. `params` and `grads` must have the same length.
    pub fn step(&mut self, params: &mut [f64], grads: &[f64]) {
        debug_assert_eq!(params.len(), grads.len(), "AdaGrad: params/grads length mismatch");
        if params.len() != grads.len() { return; }
        if !self.initialized {
            self.sum_sq = vec![0.0; params.len()];
            self.initialized = true;
        }
        for (i, (p, g)) in params.iter_mut().zip(grads).enumerate() {
            let mut grad = *g;
            if self.weight_decay > 0.0 { grad += self.weight_decay * *p; }
            self.sum_sq[i] += grad * grad;
            *p -= self.lr * grad / (self.sum_sq[i].sqrt() + self.eps);
        }
    }

    /// Reset accumulated squared gradients.
    pub fn zero_grad(&mut self) { self.sum_sq.iter_mut().for_each(|x| *x = 0.0); }
}

/// AdaDelta optimizer.
pub struct AdaDelta {
    /// Learning rate.
    pub lr: f64,
    /// Decay rate for moving averages.
    pub rho: f64,
    /// Small value added to the denominator for numerical stability.
    pub eps: f64,
    /// L2 weight decay coefficient.
    pub weight_decay: f64,
    avg_sq: Vec<f64>,
    avg_dx: Vec<f64>,
    initialized: bool,
}

impl AdaDelta {
    /// Create a new AdaDelta optimizer.
    pub fn new(lr: f64, rho: f64, eps: f64, weight_decay: f64) -> Self {
        Self { lr, rho, eps, weight_decay, avg_sq: Vec::new(), avg_dx: Vec::new(), initialized: false }
    }

    /// Perform one optimization step. `params` and `grads` must have the same length.
    pub fn step(&mut self, params: &mut [f64], grads: &[f64]) {
        debug_assert_eq!(params.len(), grads.len(), "AdaDelta: params/grads length mismatch");
        if params.len() != grads.len() { return; }
        if !self.initialized {
            self.avg_sq = vec![0.0; params.len()];
            self.avg_dx = vec![0.0; params.len()];
            self.initialized = true;
        }
        for (i, (p, g)) in params.iter_mut().zip(grads).enumerate() {
            let mut grad = *g;
            if self.weight_decay > 0.0 { grad += self.weight_decay * *p; }
            self.avg_sq[i] = self.rho * self.avg_sq[i] + (1.0 - self.rho) * grad * grad;
            let dx = (self.avg_dx[i] + self.eps).sqrt() / (self.avg_sq[i] + self.eps).sqrt() * grad;
            self.avg_dx[i] = self.rho * self.avg_dx[i] + (1.0 - self.rho) * dx * dx;
            *p -= self.lr * dx;
        }
    }

    /// Reset running averages.
    pub fn zero_grad(&mut self) { self.avg_sq.iter_mut().for_each(|x| *x = 0.0); self.avg_dx.iter_mut().for_each(|x| *x = 0.0); }
}

/// Nadam optimizer (Nesterov-accelerated Adam).
pub struct Nadam {
    /// Learning rate.
    pub lr: f64,
    /// Exponential decay rate for first moment estimates.
    pub beta1: f64,
    /// Exponential decay rate for second moment estimates.
    pub beta2: f64,
    /// Small value added to the denominator for numerical stability.
    pub eps: f64,
    /// L2 weight decay coefficient.
    pub weight_decay: f64,
    m: Vec<f64>,
    v: Vec<f64>,
    t: i32,
    initialized: bool,
}

impl Nadam {
    /// Create a new Nadam optimizer.
    pub fn new(lr: f64, beta1: f64, beta2: f64, eps: f64, weight_decay: f64) -> Self {
        Self { lr, beta1, beta2, eps, weight_decay, m: Vec::new(), v: Vec::new(), t: 0, initialized: false }
    }

    /// Perform one optimization step. `params` and `grads` must have the same length.
    pub fn step(&mut self, params: &mut [f64], grads: &[f64]) {
        debug_assert_eq!(params.len(), grads.len(), "Nadam: params/grads length mismatch");
        if params.len() != grads.len() { return; }
        if !self.initialized {
            self.m = vec![0.0; params.len()];
            self.v = vec![0.0; params.len()];
            self.initialized = true;
        }
        self.t += 1;
        let bc1 = 1.0 - self.beta1.powi(self.t);
        let bc2 = 1.0 - self.beta2.powi(self.t);
        let bc1_next = 1.0 - self.beta1.powi(self.t + 1);
        for (i, (p, g)) in params.iter_mut().zip(grads).enumerate() {
            let mut grad = *g;
            if self.weight_decay > 0.0 { grad += self.weight_decay * *p; }
            self.m[i] = self.beta1 * self.m[i] + (1.0 - self.beta1) * grad;
            self.v[i] = self.beta2 * self.v[i] + (1.0 - self.beta2) * grad * grad;
            let m_hat = self.m[i] / bc1;
            let v_hat = self.v[i] / bc2;
            let m_nesterov = self.beta1 * m_hat + (1.0 - self.beta1) * grad / bc1_next;
            *p -= self.lr * m_nesterov / (v_hat.sqrt() + self.eps);
        }
    }

    /// Zero moment buffers in place (keeps allocations).
    pub fn zero_grad(&mut self) { self.t = 0; self.m.iter_mut().for_each(|x| *x = 0.0); self.v.iter_mut().for_each(|x| *x = 0.0); }
}

#[cfg(test)]
mod tests {
    use super::*;
    const E: f64 = 1e-6;

    #[test]
    fn sgd_converges() {
        // Minimize f(x) = x² → grad = 2x, optimum at x=0
        let mut opt = Sgd::new(0.1, 0.9, 0.0);
        let mut x = [10.0];
        for _ in 0..200 {
            let g = [2.0 * x[0]];
            opt.step(&mut x, &g);
        }
        assert!(x[0].abs() < 0.1);
    }

    #[test]
    fn adam_converges() {
        let mut opt = Adam::new(0.1, 0.9, 0.999, 1e-8, 0.0);
        let mut x = [10.0];
        for _ in 0..300 {
            let g = [2.0 * x[0]];
            opt.step(&mut x, &g);
        }
        assert!(x[0].abs() < 0.01);
    }

    #[test]
    fn adamw_converges() {
        let mut opt = AdamW::new(0.1, 0.9, 0.999, 1e-8, 0.01);
        let mut x = [10.0];
        for _ in 0..500 {
            let g = [2.0 * x[0]];
            opt.step(&mut x, &g);
        }
        assert!(x[0].abs() < 0.1);
    }

    #[test]
    fn adam_vs_adamw_weight_decay() {
        // With weight decay, AdamW converges faster on simple problems
        let mut adam = Adam::new(0.01, 0.9, 0.999, 1e-8, 0.1);
        let mut adamw = AdamW::new(0.01, 0.9, 0.999, 1e-8, 0.1);
        let mut x_adam = [10.0];
        let mut x_adamw = [10.0];
        for _ in 0..200 {
            let g1 = [2.0 * x_adam[0]];
            adam.step(&mut x_adam, &g1);
            let g2 = [2.0 * x_adamw[0]];
            adamw.step(&mut x_adamw, &g2);
        }
        // Both should converge, AdamW should be at least as good
        assert!(x_adamw[0].abs() < x_adam[0].abs() + 0.5);
    }

    #[test]
    fn step_decay_test() {
        let mut s = LrScheduler::new(Schedule::StepDecay { step_size: 10, gamma: 0.5 });
        assert!((s.get_lr() - 1.0).abs() < E);
        for _ in 0..10 { s.step(); }
        assert!((s.get_lr() - 0.5).abs() < E);
        for _ in 0..10 { s.step(); }
        assert!((s.get_lr() - 0.25).abs() < E);
    }

    #[test]
    fn cosine_annealing_test() {
        let mut s = LrScheduler::new(Schedule::CosineAnnealing { t_max: 100, eta_min: 0.0 });
        for _ in 0..50 { s.step(); }
        let lr_mid = s.get_lr();
        assert!((lr_mid - 0.5).abs() < 0.01);
        for _ in 0..49 { s.step(); }
        let lr_end = s.get_lr();
        assert!(lr_end < 0.01); // near eta_min at end of cycle
    }

    #[test]
    fn linear_warmup_test() {
        let mut s = LrScheduler::new(Schedule::LinearWarmup {
            warmup_steps: 100, base_lr: 0.0, target_lr: 1.0,
        });
        for _ in 0..50 { s.step(); }
        assert!((s.get_lr() - 0.5).abs() < E);
        for _ in 0..50 { s.step(); }
        assert!((s.get_lr() - 1.0).abs() < E);
    }
}