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
//! Stateful Variance Reduction Optimizers
//!
//! Provides struct-based, stateful wrappers around the SVRG, SARAH, and SPIDER
//! algorithms. Unlike the functional forms in `variance_reduction.rs`, these
//! types hold their snapshot/auxiliary state internally and operate directly on
//! `Vec<f64>` parameter vectors via a user-supplied gradient closure.
//!
//! # Motivation
//! Standard mini-batch SGD has O(1/√T) convergence on strongly-convex
//! problems. Variance-reduced methods achieve *linear* convergence O((1-μ/L)ᵀ)
//! by periodically correcting for mini-batch noise with a reference gradient.
//!
//! # Algorithms
//!
//! | Type | Reference | Gradient cost |
//! |------|-----------|---------------|
//! | `SvrgOptimizer` | Johnson & Zhang (2013) | n + 2·inner |
//! | `SarahOptimizer` | Nguyen et al. (2017) | n + inner |
//! | `SpiderOptimizer` | Fang et al. (2018) | n + batch·inner |

use crate::error::OptimizeError;

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

/// SVRG — Stochastic Variance Reduced Gradient.
///
/// At the start of each epoch the optimizer computes the full gradient at a
/// "snapshot" θ̃, and uses it as a control variate during inner-loop SGD steps:
///
/// ```text
/// snapshot gradient:  μ̃ = ∇f(θ̃)   [full batch once per epoch]
/// inner update:       g_s = ∇f_s(θ) − ∇f_s(θ̃) + μ̃
///                     θ   = θ − α·g_s
/// ```
///
/// Reference: Johnson & Zhang (2013).
#[derive(Debug, Clone)]
pub struct SvrgOptimizer {
    /// Step size α
    pub lr: f64,
    /// Number of inner SGD steps per epoch
    pub inner_iters: usize,
    /// Current snapshot parameter vector
    snapshot: Vec<f64>,
    /// Full gradient at the snapshot
    full_grad: Vec<f64>,
    /// Inner step counter
    inner_step: usize,
}

impl SvrgOptimizer {
    /// Create a new SVRG optimizer.
    ///
    /// # Arguments
    /// * `lr` - Step size (learning rate)
    /// * `inner_iters` - Number of inner SGD iterations per epoch
    pub fn new(lr: f64, inner_iters: usize) -> Self {
        Self {
            lr,
            inner_iters,
            snapshot: Vec::new(),
            full_grad: Vec::new(),
            inner_step: 0,
        }
    }

    /// Update the snapshot and recompute the full gradient.
    ///
    /// Call this at the start of each epoch with the current parameters and
    /// the *full-batch* gradient.
    ///
    /// # Arguments
    /// * `params` - Current parameter vector
    /// * `full_gradient` - Full-batch gradient at `params`
    pub fn update_snapshot(&mut self, params: &[f64], full_gradient: Vec<f64>) {
        self.snapshot = params.to_vec();
        self.full_grad = full_gradient;
        self.inner_step = 0;
    }

    /// Perform one inner SVRG update step.
    ///
    /// # Arguments
    /// * `params` - Mutable parameter vector; updated in-place
    /// * `stoch_grad_current` - Mini-batch gradient at `params`
    /// * `stoch_grad_snapshot` - Mini-batch gradient at the *same* mini-batch
    ///   evaluated at the current snapshot θ̃
    ///
    /// # Errors
    /// Returns `OptimizeError::ValueError` if any vector lengths differ.
    pub fn step(
        &mut self,
        params: &mut Vec<f64>,
        stoch_grad_current: &[f64],
        stoch_grad_snapshot: &[f64],
    ) -> Result<(), OptimizeError> {
        let n = params.len();
        if stoch_grad_current.len() != n || stoch_grad_snapshot.len() != n {
            return Err(OptimizeError::ValueError(format!(
                "length mismatch: params={}, current_grad={}, snapshot_grad={}",
                n,
                stoch_grad_current.len(),
                stoch_grad_snapshot.len()
            )));
        }
        if self.full_grad.len() != n {
            return Err(OptimizeError::ValueError(
                "Snapshot not initialised; call update_snapshot first".to_string(),
            ));
        }

        for i in 0..n {
            // SVRG control variate: g = ∇f_s(θ) − ∇f_s(θ̃) + μ̃
            let g = stoch_grad_current[i] - stoch_grad_snapshot[i] + self.full_grad[i];
            params[i] -= self.lr * g;
        }
        self.inner_step += 1;
        Ok(())
    }

    /// Returns `true` if the epoch's inner loop is complete.
    pub fn epoch_done(&self) -> bool {
        self.inner_step >= self.inner_iters
    }

    /// Reset all state.
    pub fn reset(&mut self) {
        self.snapshot.clear();
        self.full_grad.clear();
        self.inner_step = 0;
    }

    /// Reference to the current snapshot.
    pub fn snapshot(&self) -> &[f64] {
        &self.snapshot
    }

    /// Convenience: run a complete epoch using a gradient closure.
    ///
    /// The closure receives `(params, snapshot)` and returns
    /// `(stoch_grad_current, stoch_grad_snapshot)`.
    pub fn run_epoch<F>(
        &mut self,
        params: &mut Vec<f64>,
        full_gradient: Vec<f64>,
        mut grad_fn: F,
    ) -> Result<(), OptimizeError>
    where
        F: FnMut(&[f64], &[f64]) -> (Vec<f64>, Vec<f64>),
    {
        self.update_snapshot(params, full_gradient);
        let snapshot_copy = self.snapshot.clone();
        for _ in 0..self.inner_iters {
            let (gc, gs) = grad_fn(params, &snapshot_copy);
            self.step(params, &gc, &gs)?;
        }
        Ok(())
    }
}

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

/// SARAH — Stochastic Recursive gradient Algorithm with Historical gradient.
///
/// Unlike SVRG, SARAH uses a recursively-updated gradient estimate instead of
/// a snapshot + full-gradient correction. The estimator has lower variance but
/// is biased; in practice it achieves similar linear convergence.
///
/// ```text
/// at start:  v₀ = ∇f(θ₀)   [full gradient]
/// inner:     v_t = ∇f_s(θ_t) − ∇f_s(θ_{t-1}) + v_{t-1}
///            θ_{t+1} = θ_t − α·v_t
/// ```
///
/// Reference: Nguyen et al. (2017). "SARAH: A Novel Method for Machine Learning
/// Problems Using Stochastic Recursive Gradient". *ICML*.
#[derive(Debug, Clone)]
pub struct SarahOptimizer {
    /// Step size α
    pub lr: f64,
    /// Number of inner iterations before snapshot refresh
    pub inner_iters: usize,
    /// Current recursive gradient estimate v_t
    v: Vec<f64>,
    /// Previous parameter snapshot θ_{t-1}
    prev_params: Vec<f64>,
    /// Inner step counter
    inner_step: usize,
}

impl SarahOptimizer {
    /// Create a new SARAH optimizer.
    ///
    /// # Arguments
    /// * `lr` - Step size
    /// * `inner_iters` - Inner iterations per outer epoch
    pub fn new(lr: f64, inner_iters: usize) -> Self {
        Self {
            lr,
            inner_iters,
            v: Vec::new(),
            prev_params: Vec::new(),
            inner_step: 0,
        }
    }

    /// Initialise (or refresh) the recursive gradient estimate.
    ///
    /// Call at the start of each outer epoch with the full-batch gradient.
    pub fn init_epoch(&mut self, params: &[f64], full_gradient: Vec<f64>) {
        self.prev_params = params.to_vec();
        self.v = full_gradient;
        self.inner_step = 0;
    }

    /// Perform one SARAH inner step.
    ///
    /// # Arguments
    /// * `params` - Current parameters; updated in-place
    /// * `grad_current` - Mini-batch gradient at `params`
    /// * `grad_prev` - Mini-batch gradient at `prev_params` (same mini-batch)
    ///
    /// # Errors
    /// Returns `OptimizeError::ValueError` on length mismatch or uninitialised state.
    pub fn step(
        &mut self,
        params: &mut Vec<f64>,
        grad_current: &[f64],
        grad_prev: &[f64],
    ) -> Result<(), OptimizeError> {
        let n = params.len();
        if grad_current.len() != n || grad_prev.len() != n {
            return Err(OptimizeError::ValueError(format!(
                "length mismatch: params={}, grad_current={}, grad_prev={}",
                n,
                grad_current.len(),
                grad_prev.len()
            )));
        }
        if self.v.len() != n {
            return Err(OptimizeError::ValueError(
                "SARAH not initialised; call init_epoch first".to_string(),
            ));
        }

        for i in 0..n {
            // Recursive gradient update
            self.v[i] = grad_current[i] - grad_prev[i] + self.v[i];
            params[i] -= self.lr * self.v[i];
        }
        self.prev_params = params.clone();
        self.inner_step += 1;
        Ok(())
    }

    /// Whether the inner loop is done.
    pub fn epoch_done(&self) -> bool {
        self.inner_step >= self.inner_iters
    }

    /// Reset all state.
    pub fn reset(&mut self) {
        self.v.clear();
        self.prev_params.clear();
        self.inner_step = 0;
    }

    /// Reference to previous parameters.
    pub fn prev_params(&self) -> &[f64] {
        &self.prev_params
    }

    /// Convenience: run a complete epoch using a gradient closure.
    ///
    /// The closure receives `(params, prev_params)` and returns
    /// `(grad_current, grad_prev)`.
    pub fn run_epoch<F>(
        &mut self,
        params: &mut Vec<f64>,
        full_gradient: Vec<f64>,
        mut grad_fn: F,
    ) -> Result<(), OptimizeError>
    where
        F: FnMut(&[f64], &[f64]) -> (Vec<f64>, Vec<f64>),
    {
        self.init_epoch(params, full_gradient);
        for _ in 0..self.inner_iters {
            let prev = self.prev_params.clone();
            let (gc, gp) = grad_fn(params, &prev);
            self.step(params, &gc, &gp)?;
        }
        Ok(())
    }
}

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

/// SPIDER — Stochastic Path-Integrated Differential Estimator.
///
/// Similar to SARAH but with a mini-batch size schedule and provable
/// near-optimal complexity for non-convex objectives.
///
/// ```text
/// every q steps:  v = (1/n)·Σ ∇f_i(θ)   [large batch refresh]
/// otherwise:      v = ∇f_B(θ_t) − ∇f_B(θ_{t-1}) + v_{t-1}   [small batch recursive]
/// θ_{t+1} = θ_t − α·v_t
/// ```
///
/// Reference: Fang et al. (2018). "SPIDER: Near-Optimal Non-Convex Optimization
/// via Stochastic Path-Integrated Differential Estimator". *NeurIPS*.
#[derive(Debug, Clone)]
pub struct SpiderOptimizer {
    /// Step size α
    pub lr: f64,
    /// Mini-batch size for recursive updates
    pub batch_size: usize,
    /// Number of inner iterations before a full-gradient refresh
    pub inner_iters: usize,
    /// Current gradient estimate v
    v: Vec<f64>,
    /// Previous parameter vector θ_{t-1}
    prev_params: Vec<f64>,
    /// Inner step counter
    inner_step: usize,
}

impl SpiderOptimizer {
    /// Create a new SPIDER optimizer.
    ///
    /// # Arguments
    /// * `lr` - Step size
    /// * `batch_size` - Mini-batch size for recursive updates
    /// * `inner_iters` - Recursive inner steps before next large-batch refresh
    pub fn new(lr: f64, batch_size: usize, inner_iters: usize) -> Self {
        Self {
            lr,
            batch_size,
            inner_iters,
            v: Vec::new(),
            prev_params: Vec::new(),
            inner_step: 0,
        }
    }

    /// Refresh the gradient estimate using a large/full batch.
    ///
    /// Call at the start of each outer iteration or whenever `refresh_needed()` returns `true`.
    pub fn refresh(&mut self, params: &[f64], large_batch_grad: Vec<f64>) {
        self.prev_params = params.to_vec();
        self.v = large_batch_grad;
        self.inner_step = 0;
    }

    /// Whether a large-batch refresh is due.
    pub fn refresh_needed(&self) -> bool {
        self.inner_step >= self.inner_iters || self.v.is_empty()
    }

    /// Perform one SPIDER recursive inner step.
    ///
    /// # Arguments
    /// * `params` - Current parameters; updated in-place
    /// * `grad_current` - Mini-batch gradient at `params`
    /// * `grad_prev` - Same mini-batch gradient at `prev_params`
    ///
    /// # Errors
    /// Returns `OptimizeError::ValueError` on length mismatch.
    pub fn step(
        &mut self,
        params: &mut Vec<f64>,
        grad_current: &[f64],
        grad_prev: &[f64],
    ) -> Result<(), OptimizeError> {
        let n = params.len();
        if grad_current.len() != n || grad_prev.len() != n {
            return Err(OptimizeError::ValueError(format!(
                "length mismatch: params={}, grad_current={}, grad_prev={}",
                n,
                grad_current.len(),
                grad_prev.len()
            )));
        }
        if self.v.len() != n {
            return Err(OptimizeError::ValueError(
                "SPIDER not initialised; call refresh first".to_string(),
            ));
        }

        for i in 0..n {
            self.v[i] = grad_current[i] - grad_prev[i] + self.v[i];
            params[i] -= self.lr * self.v[i];
        }
        self.prev_params = params.clone();
        self.inner_step += 1;
        Ok(())
    }

    /// Reset all state.
    pub fn reset(&mut self) {
        self.v.clear();
        self.prev_params.clear();
        self.inner_step = 0;
    }

    /// Reference to previous parameters.
    pub fn prev_params(&self) -> &[f64] {
        &self.prev_params
    }

    /// Convenience: run one outer iteration (refresh + inner loop) using closures.
    ///
    /// `large_grad_fn` computes a full/large-batch gradient at a parameter vector.
    /// `mini_grad_fn` computes `(grad_current, grad_prev)` for a mini-batch.
    pub fn run_outer_iter<F, G>(
        &mut self,
        params: &mut Vec<f64>,
        mut large_grad_fn: F,
        mut mini_grad_fn: G,
    ) -> Result<(), OptimizeError>
    where
        F: FnMut(&[f64]) -> Vec<f64>,
        G: FnMut(&[f64], &[f64]) -> (Vec<f64>, Vec<f64>),
    {
        let large_grad = large_grad_fn(params);
        self.refresh(params, large_grad);
        for _ in 0..self.inner_iters {
            let prev = self.prev_params.clone();
            let (gc, gp) = mini_grad_fn(params, &prev);
            self.step(params, &gc, &gp)?;
        }
        Ok(())
    }
}

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

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

    #[test]
    fn test_svrg_converges() {
        let mut opt = SvrgOptimizer::new(0.05, 20);
        let mut params = vec![2.0, -1.5];

        for _epoch in 0..50 {
            let fg = full_grad(&params);
            opt.run_epoch(&mut params, fg, |p, snap| {
                (full_grad(p), full_grad(snap))
            })
            .expect("epoch failed");
        }
        for &p in &params {
            assert_abs_diff_eq!(p, 0.0, epsilon = 1e-3);
        }
    }

    #[test]
    fn test_svrg_epoch_done() {
        let mut opt = SvrgOptimizer::new(0.1, 5);
        let params = vec![1.0, 1.0];
        let fg = full_grad(&params);
        opt.update_snapshot(&params, fg);
        assert!(!opt.epoch_done());
        for _ in 0..5 {
            let snap = opt.snapshot().to_vec();
            let mut p = params.clone();
            let fg = full_grad(&p);
            let sg = full_grad(&snap);
            opt.step(&mut p, &fg, &sg)
                .expect("step failed");
        }
        assert!(opt.epoch_done());
    }

    #[test]
    fn test_sarah_converges() {
        let mut opt = SarahOptimizer::new(0.05, 20);
        let mut params = vec![3.0, -1.0];

        for _epoch in 0..50 {
            let fg = full_grad(&params);
            opt.run_epoch(&mut params, fg, |p, prev| {
                (full_grad(p), full_grad(prev))
            })
            .expect("epoch failed");
        }
        for &p in &params {
            assert_abs_diff_eq!(p, 0.0, epsilon = 1e-2);
        }
    }

    #[test]
    fn test_spider_converges() {
        let mut opt = SpiderOptimizer::new(0.05, 10, 10);
        let mut params = vec![2.0, -2.0];

        for _outer in 0..50 {
            opt.run_outer_iter(
                &mut params,
                |p| full_grad(p),
                |p, prev| (full_grad(p), full_grad(prev)),
            )
            .expect("outer iter failed");
        }
        for &p in &params {
            assert_abs_diff_eq!(p, 0.0, epsilon = 1e-2);
        }
    }

    #[test]
    fn test_svrg_length_mismatch() {
        let mut opt = SvrgOptimizer::new(0.1, 5);
        let params = vec![1.0, 2.0];
        opt.update_snapshot(&params, vec![0.0, 0.0]);
        let mut p = params.clone();
        // wrong length gradient
        let result = opt.step(&mut p, &[0.1], &[0.1, 0.2]);
        assert!(result.is_err());
    }
}