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
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! Variance Reduction Methods for Stochastic Gradient Descent
//!
//! Standard SGD suffers from variance due to mini-batch noise, which prevents
//! convergence to the exact minimiser.  Variance reduction methods achieve
//! *linear* convergence on strongly convex problems by periodically correcting
//! for the gradient bias.
//!
//! # Algorithms
//!
//! | Method | Reference | Gradient evals per pass |
//! |--------|-----------|--------------------------|
//! | SVRG   | Johnson & Zhang (2013) | 2n (snapshot + inner) |
//! | SARAH  | Nguyen et al. (2017)   | n + m·b               |
//! | SPIDER | Fang et al. (2018)     | n + m·b               |
//!
//! All three maintain a recursive gradient correction that cancels the noise
//! introduced by mini-batch subsampling.
//!
//! # References
//!
//! - Johnson, R. & Zhang, T. (2013). "Accelerating Stochastic Gradient Descent
//!   using Predictive Variance Reduction". *NeurIPS*.
//! - Nguyen, L.M. et al. (2017). "SARAH: A Novel Method for Machine Learning
//!   Problems Using Stochastic Recursive Gradient". *ICML*.
//! - Fang, C. et al. (2018). "SPIDER: Near-Optimal Non-Convex Optimization
//!   via Stochastic Path-Integrated Differential Estimator". *NeurIPS*.

use crate::error::{OptimizeError, OptimizeResult};
use scirs2_core::ndarray::{Array1, ArrayView1};

// ─── Shared helpers ──────────────────────────────────────────────────────────

/// Compute a finite-difference gradient estimate for a single data point.
#[inline]
fn finite_diff_grad<F>(
    f: &mut F,
    x: &ArrayView1<f64>,
    sample: &ArrayView1<f64>,
    h: f64,
) -> Array1<f64>
where
    F: FnMut(&ArrayView1<f64>, &ArrayView1<f64>) -> f64,
{
    let n = x.len();
    let f0 = f(x, sample);
    let mut grad = Array1::<f64>::zeros(n);
    let mut x_fwd = x.to_owned();
    for i in 0..n {
        x_fwd[i] += h;
        grad[i] = (f(&x_fwd.view(), sample) - f0) / h;
        x_fwd[i] = x[i];
    }
    grad
}

/// Average gradient over a set of samples (full batch).
fn full_grad<F>(
    f: &mut F,
    x: &ArrayView1<f64>,
    samples: &[Array1<f64>],
    h: f64,
) -> Array1<f64>
where
    F: FnMut(&ArrayView1<f64>, &ArrayView1<f64>) -> f64,
{
    let n = x.len();
    if samples.is_empty() {
        return Array1::zeros(n);
    }
    let mut avg = Array1::<f64>::zeros(n);
    for s in samples {
        let g = finite_diff_grad(f, x, &s.view(), h);
        for i in 0..n {
            avg[i] += g[i];
        }
    }
    let inv_m = 1.0 / samples.len() as f64;
    avg.mapv_inplace(|v| v * inv_m);
    avg
}

// ─── SVRG ────────────────────────────────────────────────────────────────────

/// Options for the SVRG optimizer.
#[derive(Debug, Clone)]
pub struct SvrgOptions {
    /// Number of outer iterations (snapshot updates).
    pub n_epochs: usize,
    /// Number of inner SGD steps per epoch.
    pub inner_steps: usize,
    /// Step size η.
    pub step_size: f64,
    /// Convergence tolerance (gradient norm of snapshot).
    pub tol: f64,
    /// Finite-difference step for gradient approximation.
    pub fd_step: f64,
}

impl Default for SvrgOptions {
    fn default() -> Self {
        Self {
            n_epochs: 50,
            inner_steps: 100,
            step_size: 1e-3,
            tol: 1e-6,
            fd_step: 1e-5,
        }
    }
}

/// Result from SVRG optimisation.
#[derive(Debug, Clone)]
pub struct SvrgResult {
    /// Approximate minimiser.
    pub x: Array1<f64>,
    /// Final full-gradient norm.
    pub grad_norm: f64,
    /// Total number of gradient evaluations.
    pub n_grad_evals: usize,
    /// Whether tolerance was met.
    pub converged: bool,
}

/// Stochastic Variance Reduced Gradient (SVRG) optimizer.
///
/// At the start of each epoch, a full-gradient μ̃ = ∇f(x̃) is computed at a
/// snapshot x̃.  Each inner step uses the variance-reduced direction:
///
/// v = ∇fᵢ(x) - ∇fᵢ(x̃) + μ̃
///
/// which has zero variance when x = x̃.
///
/// # Arguments
///
/// * `f`       – per-sample loss: (x, sample) → f64
/// * `x0`      – starting point
/// * `samples` – full dataset (each element is one sample parameter vector)
/// * `opts`    – SVRG options
pub fn svrg<F>(
    f: &mut F,
    x0: &ArrayView1<f64>,
    samples: &[Array1<f64>],
    opts: &SvrgOptions,
) -> OptimizeResult<SvrgResult>
where
    F: FnMut(&ArrayView1<f64>, &ArrayView1<f64>) -> f64,
{
    let n = x0.len();
    if n == 0 {
        return Err(OptimizeError::ValueError(
            "x0 must be non-empty".to_string(),
        ));
    }
    if samples.is_empty() {
        return Err(OptimizeError::ValueError(
            "samples must be non-empty".to_string(),
        ));
    }

    let m = samples.len();
    let mut x = x0.to_owned();
    let mut converged = false;
    let mut total_evals: usize = 0;
    // LCG for sample selection
    let mut rng: u64 = 987654321;

    for _ in 0..opts.n_epochs {
        // Snapshot: x̃ ← x, compute full gradient μ̃
        let x_tilde = x.clone();
        let mu_tilde = full_grad(f, &x_tilde.view(), samples, opts.fd_step);
        total_evals += m * (n + 1);

        let grad_norm = mu_tilde.iter().map(|v| v * v).sum::<f64>().sqrt();
        if grad_norm < opts.tol {
            converged = true;
            return Ok(SvrgResult {
                x,
                grad_norm,
                n_grad_evals: total_evals,
                converged,
            });
        }

        // Inner loop
        for _ in 0..opts.inner_steps {
            // Pick random sample index via LCG
            rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
            let idx = (rng >> 33) as usize % m;
            let s = &samples[idx];

            let g_x = finite_diff_grad(f, &x.view(), &s.view(), opts.fd_step);
            let g_tilde = finite_diff_grad(f, &x_tilde.view(), &s.view(), opts.fd_step);
            total_evals += 2 * (n + 1);

            // SVRG direction: v = g(x) - g(x̃) + μ̃
            for i in 0..n {
                x[i] -= opts.step_size * (g_x[i] - g_tilde[i] + mu_tilde[i]);
            }
        }
    }

    let grad_norm = full_grad(f, &x.view(), samples, opts.fd_step)
        .iter()
        .map(|v| v * v)
        .sum::<f64>()
        .sqrt();

    Ok(SvrgResult {
        x,
        grad_norm,
        n_grad_evals: total_evals,
        converged,
    })
}

// ─── SARAH ───────────────────────────────────────────────────────────────────

/// Options for the SARAH optimizer.
#[derive(Debug, Clone)]
pub struct SarahOptions {
    /// Number of outer iterations.
    pub n_outer: usize,
    /// Inner loop length m.
    pub inner_steps: usize,
    /// Step size η.
    pub step_size: f64,
    /// Convergence tolerance (full gradient norm).
    pub tol: f64,
    /// Finite-difference step.
    pub fd_step: f64,
}

impl Default for SarahOptions {
    fn default() -> Self {
        Self {
            n_outer: 50,
            inner_steps: 50,
            step_size: 1e-3,
            tol: 1e-6,
            fd_step: 1e-5,
        }
    }
}

/// Result from SARAH optimisation.
#[derive(Debug, Clone)]
pub struct SarahResult {
    /// Approximate minimiser.
    pub x: Array1<f64>,
    /// Final full-gradient norm.
    pub grad_norm: f64,
    /// Total gradient evaluations (approximate).
    pub n_grad_evals: usize,
    /// Whether tolerance was met.
    pub converged: bool,
}

/// StochAstic Recursive grAdient algoritHm (SARAH).
///
/// SARAH maintains a recursive gradient estimator:
///
///   v₀ = ∇f(x₀)   (full gradient)
///   vₜ = ∇fᵢₜ(xₜ) - ∇fᵢₜ(xₜ₋₁) + vₜ₋₁   (recursive update)
///   xₜ₊₁ = xₜ - η vₜ
///
/// This recursive estimator converges to the true gradient, enabling linear
/// convergence on strongly-convex problems.
///
/// # Arguments
///
/// * `f`       – per-sample loss: (x, sample) → f64
/// * `x0`      – starting point
/// * `samples` – full dataset
/// * `opts`    – SARAH options
pub fn sarah<F>(
    f: &mut F,
    x0: &ArrayView1<f64>,
    samples: &[Array1<f64>],
    opts: &SarahOptions,
) -> OptimizeResult<SarahResult>
where
    F: FnMut(&ArrayView1<f64>, &ArrayView1<f64>) -> f64,
{
    let n = x0.len();
    if n == 0 {
        return Err(OptimizeError::ValueError(
            "x0 must be non-empty".to_string(),
        ));
    }
    if samples.is_empty() {
        return Err(OptimizeError::ValueError(
            "samples must be non-empty".to_string(),
        ));
    }

    let m = samples.len();
    let mut x = x0.to_owned();
    let mut converged = false;
    let mut total_evals: usize = 0;
    let mut rng: u64 = 11111111111111111;

    for _ in 0..opts.n_outer {
        // v₀ = full gradient at current x
        let mut v = full_grad(f, &x.view(), samples, opts.fd_step);
        total_evals += m * (n + 1);

        let g_norm = v.iter().map(|vi| vi * vi).sum::<f64>().sqrt();
        if g_norm < opts.tol {
            converged = true;
            return Ok(SarahResult {
                x,
                grad_norm: g_norm,
                n_grad_evals: total_evals,
                converged,
            });
        }

        // x₀ of inner loop
        for i in 0..n {
            x[i] -= opts.step_size * v[i];
        }

        let mut x_prev = x.clone();

        for _ in 0..opts.inner_steps {
            rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
            let idx = (rng >> 33) as usize % m;
            let s = &samples[idx];

            let g_curr = finite_diff_grad(f, &x.view(), &s.view(), opts.fd_step);
            let g_prev = finite_diff_grad(f, &x_prev.view(), &s.view(), opts.fd_step);
            total_evals += 2 * (n + 1);

            // Recursive update: vₜ = ∇fᵢ(x) - ∇fᵢ(x_prev) + v_{t-1}
            let v_new: Array1<f64> = g_curr
                .iter()
                .zip(g_prev.iter())
                .zip(v.iter())
                .map(|((&gc, &gp), &vp)| gc - gp + vp)
                .collect();

            x_prev = x.clone();
            for i in 0..n {
                x[i] -= opts.step_size * v_new[i];
            }
            v = v_new;
        }
    }

    let g_norm = full_grad(f, &x.view(), samples, opts.fd_step)
        .iter()
        .map(|v| v * v)
        .sum::<f64>()
        .sqrt();

    Ok(SarahResult {
        x,
        grad_norm: g_norm,
        n_grad_evals: total_evals,
        converged,
    })
}

// ─── SPIDER ──────────────────────────────────────────────────────────────────

/// Options for the SPIDER optimizer.
#[derive(Debug, Clone)]
pub struct SpiderOptions {
    /// Number of outer iterations (full gradient recomputes).
    pub n_outer: usize,
    /// Inner steps per outer iteration.
    pub inner_steps: usize,
    /// Step size η.
    pub step_size: f64,
    /// Convergence tolerance (gradient estimator norm).
    pub tol: f64,
    /// Finite-difference step.
    pub fd_step: f64,
    /// Mini-batch size b for inner gradient updates.
    pub mini_batch: usize,
}

impl Default for SpiderOptions {
    fn default() -> Self {
        Self {
            n_outer: 30,
            inner_steps: 50,
            step_size: 5e-4,
            tol: 1e-6,
            fd_step: 1e-5,
            mini_batch: 4,
        }
    }
}

/// Result from SPIDER optimisation.
#[derive(Debug, Clone)]
pub struct SpiderResult {
    /// Approximate minimiser.
    pub x: Array1<f64>,
    /// Norm of the last gradient estimator.
    pub grad_norm: f64,
    /// Total gradient evaluations (approximate).
    pub n_grad_evals: usize,
    /// Whether tolerance was met.
    pub converged: bool,
}

/// SPIDER (Stochastic Path-Integrated Differential EstimatoR) optimizer.
///
/// SPIDER extends SARAH with mini-batch gradient differences, achieving
/// near-optimal oracle complexity for non-convex stochastic optimisation.
///
/// The estimator update:
///   vₜ = (1/b) Σᵢ∈Bₜ [∇fᵢ(xₜ) - ∇fᵢ(xₜ₋₁)] + vₜ₋₁
///
/// # Arguments
///
/// * `f`       – per-sample loss: (x, sample) → f64
/// * `x0`      – starting point
/// * `samples` – full dataset
/// * `opts`    – SPIDER options
pub fn spider<F>(
    f: &mut F,
    x0: &ArrayView1<f64>,
    samples: &[Array1<f64>],
    opts: &SpiderOptions,
) -> OptimizeResult<SpiderResult>
where
    F: FnMut(&ArrayView1<f64>, &ArrayView1<f64>) -> f64,
{
    let n = x0.len();
    if n == 0 {
        return Err(OptimizeError::ValueError(
            "x0 must be non-empty".to_string(),
        ));
    }
    if samples.is_empty() {
        return Err(OptimizeError::ValueError(
            "samples must be non-empty".to_string(),
        ));
    }

    let m = samples.len();
    let b = opts.mini_batch.max(1).min(m);
    let mut x = x0.to_owned();
    let mut converged = false;
    let mut total_evals: usize = 0;
    let mut rng: u64 = 999999999999;

    for _ in 0..opts.n_outer {
        // Full gradient at start of outer epoch
        let mut v = full_grad(f, &x.view(), samples, opts.fd_step);
        total_evals += m * (n + 1);

        let g_norm = v.iter().map(|vi| vi * vi).sum::<f64>().sqrt();
        if g_norm < opts.tol {
            converged = true;
            return Ok(SpiderResult {
                x,
                grad_norm: g_norm,
                n_grad_evals: total_evals,
                converged,
            });
        }

        // Descend with v₀
        for i in 0..n {
            x[i] -= opts.step_size * v[i];
        }

        let mut x_prev = x.clone();

        for _ in 0..opts.inner_steps {
            // Sample mini-batch B of size b
            let mut batch_indices = Vec::with_capacity(b);
            for _ in 0..b {
                rng = rng.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
                batch_indices.push((rng >> 33) as usize % m);
            }

            // Mini-batch gradient difference
            let mut diff = Array1::<f64>::zeros(n);
            for &idx in &batch_indices {
                let s = &samples[idx];
                let g_curr = finite_diff_grad(f, &x.view(), &s.view(), opts.fd_step);
                let g_prev = finite_diff_grad(f, &x_prev.view(), &s.view(), opts.fd_step);
                total_evals += 2 * (n + 1);
                for i in 0..n {
                    diff[i] += (g_curr[i] - g_prev[i]) / b as f64;
                }
            }

            // Recursive estimator update
            let v_new: Array1<f64> = diff.iter().zip(v.iter()).map(|(&d, &vp)| d + vp).collect();
            x_prev = x.clone();
            for i in 0..n {
                x[i] -= opts.step_size * v_new[i];
            }
            v = v_new;

            let cur_norm = v.iter().map(|vi| vi * vi).sum::<f64>().sqrt();
            if cur_norm < opts.tol {
                converged = true;
                return Ok(SpiderResult {
                    x,
                    grad_norm: cur_norm,
                    n_grad_evals: total_evals,
                    converged,
                });
            }
        }
    }

    let g_norm = v_norm_approx(&full_grad(f, &x.view(), samples, opts.fd_step));

    Ok(SpiderResult {
        x,
        grad_norm: g_norm,
        n_grad_evals: total_evals,
        converged,
    })
}

#[inline]
fn v_norm_approx(v: &Array1<f64>) -> f64 {
    v.iter().map(|vi| vi * vi).sum::<f64>().sqrt()
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use scirs2_core::ndarray::array;

    /// Generate a simple quadratic dataset: f(x, ξ) = (x₀ - ξ₀)² + (x₁ - ξ₁)²
    /// Minimiser at E[ξ] = (1, 2).
    fn make_samples() -> Vec<Array1<f64>> {
        vec![
            array![0.9, 1.8],
            array![1.1, 2.2],
            array![1.0, 2.0],
            array![0.8, 1.9],
            array![1.2, 2.1],
            array![1.0, 2.0],
            array![0.95, 1.95],
            array![1.05, 2.05],
        ]
    }

    fn sample_loss(x: &ArrayView1<f64>, s: &ArrayView1<f64>) -> f64 {
        (x[0] - s[0]).powi(2) + (x[1] - s[1]).powi(2)
    }

    #[test]
    fn test_svrg_quadratic() {
        let samples = make_samples();
        let x0 = array![0.0, 0.0];
        let opts = SvrgOptions {
            n_epochs: 100,
            inner_steps: 50,
            step_size: 0.1,
            tol: 1e-4,
            fd_step: 1e-5,
        };
        let res = svrg(&mut |x, s| sample_loss(x, s), &x0.view(), &samples, &opts).expect("failed to create res");
        assert!(
            (res.x[0] - 1.0).abs() < 0.3,
            "SVRG: expected x[0]≈1.0, got {}",
            res.x[0]
        );
        assert!(
            (res.x[1] - 2.0).abs() < 0.3,
            "SVRG: expected x[1]≈2.0, got {}",
            res.x[1]
        );
    }

    #[test]
    fn test_sarah_quadratic() {
        let samples = make_samples();
        let x0 = array![0.0, 0.0];
        let opts = SarahOptions {
            n_outer: 80,
            inner_steps: 30,
            step_size: 0.05,
            tol: 1e-4,
            fd_step: 1e-5,
        };
        let res = sarah(&mut |x, s| sample_loss(x, s), &x0.view(), &samples, &opts).expect("failed to create res");
        assert!(
            (res.x[0] - 1.0).abs() < 0.3,
            "SARAH: expected x[0]≈1.0, got {}",
            res.x[0]
        );
        assert!(
            (res.x[1] - 2.0).abs() < 0.3,
            "SARAH: expected x[1]≈2.0, got {}",
            res.x[1]
        );
    }

    #[test]
    fn test_spider_quadratic() {
        let samples = make_samples();
        let x0 = array![0.0, 0.0];
        let opts = SpiderOptions {
            n_outer: 80,
            inner_steps: 30,
            step_size: 0.05,
            tol: 1e-4,
            fd_step: 1e-5,
            mini_batch: 2,
        };
        let res = spider(&mut |x, s| sample_loss(x, s), &x0.view(), &samples, &opts).expect("failed to create res");
        assert!(
            (res.x[0] - 1.0).abs() < 0.4,
            "SPIDER: expected x[0]≈1.0, got {}",
            res.x[0]
        );
        assert!(
            (res.x[1] - 2.0).abs() < 0.4,
            "SPIDER: expected x[1]≈2.0, got {}",
            res.x[1]
        );
    }
}