scirs2-optimize 0.4.2

Optimization module for SciRS2 (scirs2-optimize)
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
//! Stateful SGD optimizer variants
//!
//! This module provides stateful, struct-based optimizer objects that hold
//! their own parameter state across `step()` calls. These are suitable for
//! use in ML training loops where the same optimizer instance is updated
//! repeatedly.
//!
//! # Algorithms
//!
//! | Type | Description |
//! |------|-------------|
//! | `SgdOptimizer` | SGD with optional momentum (classical & Nesterov), weight decay |
//! | `AdaGradOptimizer` | Adaptive learning rates via accumulated squared gradients |
//! | `AdaDeltaOptimizer` | Adaptive learning rates without a global LR (Zeiler 2012) |
//!
//! # References
//!
//! - Polyak (1964). "Some methods of speeding up the convergence of iteration methods".
//! - Nesterov (1983). "A method of solving a convex programming problem".
//! - Duchi et al. (2011). "Adaptive Subgradient Methods for Online Learning". *JMLR*.
//! - Zeiler (2012). "ADADELTA: An Adaptive Learning Rate Method". arXiv:1212.5701.

use crate::error::OptimizeError;

// ─── SGD ─────────────────────────────────────────────────────────────────────

/// Stateful SGD optimizer with optional momentum, Nesterov momentum, and
/// L2 weight decay.
///
/// # Update rule (no Nesterov)
/// ```text
/// v_t = μ·v_{t-1} + g_t + λ·θ_{t-1}
/// θ_t = θ_{t-1} - α·v_t
/// ```
///
/// # Update rule (Nesterov)
/// ```text
/// v_t = μ·v_{t-1} + g_t + λ·θ_{t-1}
/// θ_t = θ_{t-1} - α·(g_t + μ·v_t)
/// ```
///
/// where α = `lr`, μ = `momentum`, λ = `weight_decay`.
#[derive(Debug, Clone)]
pub struct SgdOptimizer {
    /// Learning rate
    pub lr: f64,
    /// Momentum coefficient (0 = vanilla SGD)
    pub momentum: f64,
    /// Use Nesterov momentum
    pub nesterov: bool,
    /// L2 weight-decay coefficient
    pub weight_decay: f64,
    /// Velocity buffer (accumulated momentum); populated lazily on first step
    velocity: Vec<f64>,
}

impl SgdOptimizer {
    /// Create a new SGD optimizer.
    ///
    /// # Arguments
    /// * `lr` - Learning rate (must be > 0)
    /// * `momentum` - Momentum factor in [0, 1)
    /// * `nesterov` - Whether to use Nesterov lookahead momentum
    /// * `weight_decay` - L2 regularisation strength (≥ 0)
    pub fn new(lr: f64, momentum: f64, nesterov: bool, weight_decay: f64) -> Self {
        Self {
            lr,
            momentum,
            nesterov,
            weight_decay,
            velocity: Vec::new(),
        }
    }

    /// Vanilla SGD with default hyperparameters (lr=0.01, no momentum).
    pub fn vanilla(lr: f64) -> Self {
        Self::new(lr, 0.0, false, 0.0)
    }

    /// Perform one SGD update step.
    ///
    /// # Arguments
    /// * `params` - Mutable parameter vector; updated in-place
    /// * `grad` - Gradient vector (same length as `params`)
    ///
    /// # Errors
    /// Returns `OptimizeError::ValueError` if `params` and `grad` have
    /// different lengths.
    pub fn step(
        &mut self,
        params: &mut Vec<f64>,
        grad: &[f64],
    ) -> Result<(), OptimizeError> {
        let n = params.len();
        if grad.len() != n {
            return Err(OptimizeError::ValueError(format!(
                "params length {} != grad length {}",
                n,
                grad.len()
            )));
        }

        // Lazy initialisation of velocity buffer
        if self.velocity.len() != n {
            self.velocity = vec![0.0; n];
        }

        for i in 0..n {
            // Add L2 regularisation to gradient
            let g = grad[i] + self.weight_decay * params[i];

            if self.momentum == 0.0 {
                // Vanilla SGD
                params[i] -= self.lr * g;
            } else {
                // Update velocity
                self.velocity[i] = self.momentum * self.velocity[i] + g;

                if self.nesterov {
                    // Nesterov: use the "lookahead" gradient
                    params[i] -= self.lr * (g + self.momentum * self.velocity[i]);
                } else {
                    params[i] -= self.lr * self.velocity[i];
                }
            }
        }
        Ok(())
    }

    /// Reset velocity buffer (useful when restarting training).
    pub fn reset(&mut self) {
        self.velocity.clear();
    }
}

// ─── AdaGrad ─────────────────────────────────────────────────────────────────

/// AdaGrad optimizer.
///
/// Adapts the learning rate for each parameter by accumulating squared
/// gradients. Parameters that receive large, frequent gradients see smaller
/// effective learning rates.
///
/// # Update rule
/// ```text
/// G_t = G_{t-1} + g_t ⊙ g_t
/// θ_t = θ_{t-1} - α / (√G_t + ε) ⊙ g_t
/// ```
///
/// Reference: Duchi et al. (2011).
#[derive(Debug, Clone)]
pub struct AdaGradOptimizer {
    /// Global learning rate
    pub lr: f64,
    /// Numerical stability constant
    pub eps: f64,
    /// Accumulated squared gradients
    pub accum: Vec<f64>,
}

impl AdaGradOptimizer {
    /// Create a new AdaGrad optimizer.
    pub fn new(lr: f64, eps: f64) -> Self {
        Self {
            lr,
            eps,
            accum: Vec::new(),
        }
    }

    /// Create with default hyperparameters (lr=0.01, eps=1e-8).
    pub fn default_params(lr: f64) -> Self {
        Self::new(lr, 1e-8)
    }

    /// Perform one AdaGrad update step.
    ///
    /// # Errors
    /// Returns `OptimizeError::ValueError` if length mismatch.
    pub fn step(
        &mut self,
        params: &mut Vec<f64>,
        grad: &[f64],
    ) -> Result<(), OptimizeError> {
        let n = params.len();
        if grad.len() != n {
            return Err(OptimizeError::ValueError(format!(
                "params length {} != grad length {}",
                n,
                grad.len()
            )));
        }

        if self.accum.len() != n {
            self.accum = vec![0.0; n];
        }

        for i in 0..n {
            self.accum[i] += grad[i] * grad[i];
            params[i] -= self.lr / (self.accum[i].sqrt() + self.eps) * grad[i];
        }
        Ok(())
    }

    /// Reset accumulated state.
    pub fn reset(&mut self) {
        self.accum.clear();
    }
}

// ─── AdaDelta ────────────────────────────────────────────────────────────────

/// AdaDelta optimizer.
///
/// Extends AdaGrad to avoid its monotonically decreasing learning rate by
/// using an exponentially decaying window of past squared gradients.
/// Importantly, no global learning rate is required.
///
/// # Update rule
/// ```text
/// E[g²]_t    = ρ·E[g²]_{t-1}    + (1-ρ)·g_t²
/// Δθ_t       = -√(E[Δθ²]_{t-1} + ε) / √(E[g²]_t + ε) · g_t
/// E[Δθ²]_t   = ρ·E[Δθ²]_{t-1}  + (1-ρ)·Δθ_t²
/// θ_t        = θ_{t-1} + Δθ_t
/// ```
///
/// Reference: Zeiler (2012), "ADADELTA: An Adaptive Learning Rate Method".
#[derive(Debug, Clone)]
pub struct AdaDeltaOptimizer {
    /// Decay rate for running averages
    pub rho: f64,
    /// Numerical stability constant
    pub eps: f64,
    /// Running average of squared gradients: E[g²]
    pub accum_grad: Vec<f64>,
    /// Running average of squared updates: E[Δθ²]
    pub accum_update: Vec<f64>,
}

impl AdaDeltaOptimizer {
    /// Create a new AdaDelta optimizer.
    ///
    /// # Arguments
    /// * `rho` - Decay factor for exponential moving averages (typically 0.95)
    /// * `eps` - Numerical stability (typically 1e-6)
    pub fn new(rho: f64, eps: f64) -> Self {
        Self {
            rho,
            eps,
            accum_grad: Vec::new(),
            accum_update: Vec::new(),
        }
    }

    /// Create with default hyperparameters (rho=0.95, eps=1e-6).
    pub fn default_params() -> Self {
        Self::new(0.95, 1e-6)
    }

    /// Perform one AdaDelta update step.
    ///
    /// # Errors
    /// Returns `OptimizeError::ValueError` if length mismatch.
    pub fn step(
        &mut self,
        params: &mut Vec<f64>,
        grad: &[f64],
    ) -> Result<(), OptimizeError> {
        let n = params.len();
        if grad.len() != n {
            return Err(OptimizeError::ValueError(format!(
                "params length {} != grad length {}",
                n,
                grad.len()
            )));
        }

        if self.accum_grad.len() != n {
            self.accum_grad = vec![0.0; n];
            self.accum_update = vec![0.0; n];
        }

        for i in 0..n {
            // Update running average of squared gradients
            self.accum_grad[i] =
                self.rho * self.accum_grad[i] + (1.0 - self.rho) * grad[i] * grad[i];

            // Compute parameter update using RMS of past updates
            let rms_update = (self.accum_update[i] + self.eps).sqrt();
            let rms_grad = (self.accum_grad[i] + self.eps).sqrt();
            let delta = -(rms_update / rms_grad) * grad[i];

            // Update running average of squared updates
            self.accum_update[i] =
                self.rho * self.accum_update[i] + (1.0 - self.rho) * delta * delta;

            params[i] += delta;
        }
        Ok(())
    }

    /// Reset accumulated state.
    pub fn reset(&mut self) {
        self.accum_grad.clear();
        self.accum_update.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;

    fn quadratic_grad(x: &[f64]) -> Vec<f64> {
        x.iter().map(|&xi| 2.0 * xi).collect()
    }

    #[test]
    fn test_sgd_vanilla_converges() {
        let mut opt = SgdOptimizer::vanilla(0.1);
        let mut params = vec![1.0, -2.0, 0.5];
        for _ in 0..200 {
            let g = quadratic_grad(&params);
            opt.step(&mut params, &g).expect("step failed");
        }
        for &p in &params {
            assert_abs_diff_eq!(p, 0.0, epsilon = 1e-4);
        }
    }

    #[test]
    fn test_sgd_momentum_converges() {
        let mut opt = SgdOptimizer::new(0.05, 0.9, false, 0.0);
        let mut params = vec![2.0, -1.5];
        for _ in 0..300 {
            let g = quadratic_grad(&params);
            opt.step(&mut params, &g).expect("step failed");
        }
        for &p in &params {
            assert_abs_diff_eq!(p, 0.0, epsilon = 1e-3);
        }
    }

    #[test]
    fn test_sgd_nesterov_converges() {
        let mut opt = SgdOptimizer::new(0.05, 0.9, true, 0.0);
        let mut params = vec![1.5, -1.0];
        for _ in 0..300 {
            let g = quadratic_grad(&params);
            opt.step(&mut params, &g).expect("step failed");
        }
        for &p in &params {
            assert_abs_diff_eq!(p, 0.0, epsilon = 1e-3);
        }
    }

    #[test]
    fn test_sgd_weight_decay() {
        // With weight decay, minimum shifts; check that update is applied
        let mut opt = SgdOptimizer::new(0.01, 0.0, false, 0.1);
        let mut params = vec![1.0];
        let init = params[0];
        let g = vec![0.0]; // zero gradient; only weight decay should pull
        opt.step(&mut params, &g).expect("step failed");
        assert!(params[0] < init, "weight decay should reduce param");
    }

    #[test]
    fn test_sgd_length_mismatch() {
        let mut opt = SgdOptimizer::vanilla(0.1);
        let mut params = vec![1.0, 2.0];
        let grad = vec![0.1]; // wrong length
        assert!(opt.step(&mut params, &grad).is_err());
    }

    #[test]
    fn test_adagrad_converges() {
        let mut opt = AdaGradOptimizer::default_params(0.5);
        let mut params = vec![3.0, -2.0];
        for _ in 0..500 {
            let g = quadratic_grad(&params);
            opt.step(&mut params, &g).expect("step failed");
        }
        for &p in &params {
            assert_abs_diff_eq!(p, 0.0, epsilon = 0.1);
        }
    }

    #[test]
    fn test_adadelta_converges() {
        let mut opt = AdaDeltaOptimizer::default_params();
        let mut params = vec![2.0, -1.0];
        for _ in 0..2000 {
            let g = quadratic_grad(&params);
            opt.step(&mut params, &g).expect("step failed");
        }
        for &p in &params {
            assert_abs_diff_eq!(p, 0.0, epsilon = 0.5);
        }
    }

    #[test]
    fn test_adadelta_length_mismatch() {
        let mut opt = AdaDeltaOptimizer::default_params();
        let mut params = vec![1.0, 2.0];
        let grad = vec![0.1, 0.2, 0.3]; // wrong length
        assert!(opt.step(&mut params, &grad).is_err());
    }
}