gprx 0.2.0

Gaussian process regression in Rust: exact GPR, sparse GPR (VFE), and SVGP.
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
//! Defines the trust-region optimizer that uses the analytic Hessian and the Steihaug subproblem.

use std::num::NonZeroU32;

use argmin::core::{
    Error as ArgminError, IterState, KV, Problem, Solver, TerminationReason, TerminationStatus,
};
use argmin::solver::trustregion::{Steihaug, TrustRegion as ArgminTrustRegion};

use crate::error::GprError;
use crate::objective::TwiceDifferentiable;

use super::adapter::{
    CachedProblem, EvalCache, RunEnd, WithHessian, best_value, consider_logit_run, run_argmin,
};
use super::logit::{log_theta_to_z, sample_log_uniform_z};
use super::{OptResult, Optimizer, Restarts};

/// Searches hyperparameters with a trust-region method and the Steihaug conjugate-gradient subproblem.
///
/// It uses the analytic Hessian ([`crate::TwiceDifferentiable`]).
///
/// The step is the minimizer of the quadratic model inside a ball whose
/// radius grows and shrinks with how well the model predicted the decrease, so
/// an indefinite or singular Hessian and a step that leaves the bounds are
/// handled by the method: the region shrinks. The Hessian lives in
/// unconstrained logit coordinates. A run that hits the iteration cap returns
/// its best point.
///
/// See the example on [`Self::new`].
#[derive(Clone, Debug, PartialEq)]
pub struct TrustRegion {
    max_iterations: u64,
    tolerance: f64,
    initial_radius: f64,
    max_radius: f64,
    restarts: Option<Restarts>,
}

impl Default for TrustRegion {
    fn default() -> Self {
        Self {
            max_iterations: 100,
            tolerance: f64::EPSILON.sqrt(),
            initial_radius: 1.0,
            max_radius: 100.0,
            restarts: None,
        }
    }
}

impl TrustRegion {
    /// Builds a trust-region optimizer with 100 iterations, gradient tolerance `sqrt(ε)`, initial radius 1, and maximum radius 100 (logit coordinates).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::num::NonZeroU32;
    /// use gprx::TrustRegion;
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let _optimizer = TrustRegion::new()
    ///     .with_max_iterations(50)
    ///     .with_tolerance(1e-8)?
    ///     .with_radii(1.0, 100.0)?
    ///     .with_restarts(NonZeroU32::MIN, 0);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the iteration cap (default 100).
    ///
    /// See the example on [`Self::new`].
    pub fn with_max_iterations(mut self, max_iterations: u64) -> Self {
        self.max_iterations = max_iterations;
        self
    }

    /// Sets the gradient-norm tolerance (default `sqrt(ε)`).
    ///
    /// # Errors
    ///
    /// Returns [`GprError::InvalidConfig`] if `tolerance` is not finite
    /// or is negative.
    ///
    /// See the example on [`Self::new`].
    pub fn with_tolerance(mut self, tolerance: f64) -> Result<Self, GprError> {
        if !tolerance.is_finite() || tolerance < 0.0 {
            return Err(GprError::InvalidConfig {
                reason: "trust-region gradient tolerance must be finite and >= 0".to_owned(),
            });
        }
        self.tolerance = tolerance;
        Ok(self)
    }

    /// Sets the initial and the maximum trust radius (defaults 1 and 100).
    ///
    /// # Errors
    ///
    /// Returns [`GprError::InvalidConfig`] unless
    /// `0 < initial_radius <= max_radius` and both are finite.
    ///
    /// See the example on [`Self::new`].
    pub fn with_radii(mut self, initial_radius: f64, max_radius: f64) -> Result<Self, GprError> {
        let ok = initial_radius.is_finite()
            && max_radius.is_finite()
            && initial_radius > 0.0
            && initial_radius <= max_radius;
        if !ok {
            return Err(GprError::InvalidConfig {
                reason: "trust radii must satisfy 0 < initial <= max, both finite".to_owned(),
            });
        }
        self.initial_radius = initial_radius;
        self.max_radius = max_radius;
        Ok(self)
    }

    /// Adds `n` extra log-uniform starts (`n ≥ 1`) and keeps the lowest NLML.
    ///
    /// See the example on [`Self::new`].
    pub fn with_restarts(mut self, n: NonZeroU32, seed: u64) -> Self {
        self.restarts = Some(Restarts { n, seed });
        self
    }

    #[cfg(test)]
    pub(crate) fn minimize_unconstrained<P: TwiceDifferentiable>(
        &self,
        objective: &mut P,
        init: &[f64],
    ) -> Result<OptResult, GprError> {
        run_trust_region(self, objective, init)
    }
}

impl<P: TwiceDifferentiable> Optimizer<P> for TrustRegion {
    fn minimize(&self, objective: &mut P, init: &[f64]) -> Result<OptResult, GprError> {
        super::minimize_with_restarts(
            objective,
            init,
            self.restarts,
            log_theta_to_z,
            sample_log_uniform_z,
            |objective, intervals, z, _restart, best| {
                consider_logit_run(objective, intervals, z, best, |mapped, z| {
                    run_trust_region(self, mapped, z)
                })
            },
        )
    }
}

fn run_trust_region<P: TwiceDifferentiable>(
    optimizer: &TrustRegion,
    objective: &mut P,
    init: &[f64],
) -> Result<OptResult, GprError> {
    let n = objective.num_params();
    super::require_params(init, n)?;
    let mut cache = EvalCache::<_, WithHessian>::new(objective, n);
    // The start must be evaluable; an error there is the caller's, not a
    // failure to make progress.
    cache.try_eval(init)?;
    let subproblem = Steihaug::<Vec<f64>, f64>::new().with_max_iters(4 * n as u64 + 10);
    let inner = ArgminTrustRegion::new(subproblem)
        .with_radius(optimizer.initial_radius)
        .and_then(|tr| tr.with_max_radius(optimizer.max_radius))
        .map_err(|e| GprError::InvalidConfig {
            reason: e.to_string(),
        })?;
    let solver = GradNormStop {
        inner,
        tolerance: optimizer.tolerance,
    };
    let RunEnd {
        params,
        cost,
        iterations,
    } = run_argmin(
        CachedProblem::new(cache),
        solver,
        init,
        optimizer.max_iterations,
    )?;
    let value = best_value(cost, iterations, || {
        let mut grad = vec![0.0; n];
        objective.value_and_gradient_into(&params, &mut grad)
    })?;
    Ok(OptResult {
        params,
        value,
        iterations,
    })
}

/// Stops on the gradient norm.
struct GradNormStop<S> {
    inner: S,
    tolerance: f64,
}

type TrState = IterState<Vec<f64>, Vec<f64>, (), Vec<Vec<f64>>, (), f64>;

impl<O, S> Solver<O, TrState> for GradNormStop<S>
where
    S: Solver<O, TrState>,
{
    fn name(&self) -> &str {
        self.inner.name()
    }

    fn init(
        &mut self,
        problem: &mut Problem<O>,
        state: TrState,
    ) -> Result<(TrState, Option<KV>), ArgminError> {
        self.inner.init(problem, state)
    }

    fn next_iter(
        &mut self,
        problem: &mut Problem<O>,
        state: TrState,
    ) -> Result<(TrState, Option<KV>), ArgminError> {
        self.inner.next_iter(problem, state)
    }

    fn terminate(&mut self, state: &TrState) -> TerminationStatus {
        if let Some(grad) = state.get_gradient() {
            let norm = grad.iter().map(|g| g * g).sum::<f64>().sqrt();
            if norm <= self.tolerance {
                return TerminationStatus::Terminated(TerminationReason::SolverConverged);
            }
        }
        self.inner.terminate(state)
    }
}

#[cfg(test)]
mod tests {
    use super::TrustRegion;
    use crate::error::GprError;
    use crate::gpr::Gpr;
    use crate::kernel::{KernelSpec, RbfKernel};
    use crate::likelihood::GaussianLikelihood;
    use crate::objective::{Differentiable, Objective, TwiceDifferentiable};
    use crate::optimizer::{Fixed, Optimizer};

    const TOL: f64 = 1e-6;

    use crate::test_check::assert_close;

    struct Quadratic;

    impl Objective for Quadratic {
        fn num_params(&self) -> usize {
            2
        }

        fn value(&mut self, params: &[f64]) -> Result<f64, GprError> {
            let mut dummy = [0.0; 2];
            self.value_and_gradient_into(params, &mut dummy)
        }
    }

    impl Differentiable for Quadratic {
        fn gradient_into(&mut self, params: &[f64], out: &mut [f64]) -> Result<(), GprError> {
            self.value_and_gradient_into(params, out).map(|_| ())
        }

        fn value_and_gradient_into(
            &mut self,
            params: &[f64],
            out: &mut [f64],
        ) -> Result<f64, GprError> {
            if params.len() != 2 || out.len() != 2 {
                return Err(GprError::ShapeMismatch {
                    reason: "quadratic is 2-D".to_owned(),
                });
            }
            out[0] = params[0];
            out[1] = params[1];
            Ok(0.5 * (params[0] * params[0] + params[1] * params[1]))
        }
    }

    impl TwiceDifferentiable for Quadratic {
        fn hessian_into(&mut self, params: &[f64], out: &mut [f64]) -> Result<(), GprError> {
            if params.len() != 2 || out.len() != 4 {
                return Err(GprError::ShapeMismatch {
                    reason: "quadratic Hessian is 2x2".to_owned(),
                });
            }
            out[0] = 1.0;
            out[1] = 0.0;
            out[2] = 0.0;
            out[3] = 1.0;
            Ok(())
        }
    }

    #[test]
    fn trust_region_minimizes_quadratic_bowl() {
        let mut obj = Quadratic;
        let result = TrustRegion::new()
            .with_max_iterations(50)
            .minimize_unconstrained(&mut obj, &[1.0, -0.5])
            .expect("bowl");
        assert_close(result.params[0], 0.0, TOL);
        assert_close(result.params[1], 0.0, TOL);
        assert!(result.value < 1e-12);
    }

    #[test]
    fn trust_region_lowers_gpr_nlml() {
        let kernel = KernelSpec::from(RbfKernel::new(1.25).expect("valid"));
        let likelihood = GaussianLikelihood::new(0.16).expect("valid");
        let x = [0.0, 0.8, 1.7];
        let y = [0.4, -0.2, 0.9];
        let mut gpr = Gpr::new(kernel, likelihood)
            .with_optimizer(Fixed)
            .factor(&x, 3, 1, &y)
            .unwrap_or_else(|(_, e)| panic!("{e}"));
        let mut init = [0.0; 2];
        gpr.get_params(&mut init).expect("len 2");
        let start;
        let result;
        {
            let mut obj = gpr.objective();
            start = obj.value(&init).expect("spd");
            result = TrustRegion::new()
                .with_max_iterations(30)
                .minimize(&mut obj, &init)
                .expect("newton");
        }
        assert!(
            result.value < start,
            "start={start}, newton={}",
            result.value
        );
        let fitted = Gpr::new(
            KernelSpec::from(RbfKernel::new(1.25).expect("valid")),
            GaussianLikelihood::new(0.16).expect("valid"),
        )
        .with_optimizer(TrustRegion::new().with_max_iterations(30))
        .fit(&x, 3, 1, &y)
        .unwrap_or_else(|(_, e)| panic!("{e}"));
        assert!(fitted.neg_log_marginal_likelihood().expect("fitted") < start);
    }

    /// `√(1 + x²)`: a plain Newton step from `|x| > 1` jumps away (`x → −x³`); values
    /// beyond `|x| = 50` cannot be evaluated.
    struct Sqrt1PlusSquare;

    impl Objective for Sqrt1PlusSquare {
        fn num_params(&self) -> usize {
            1
        }

        fn value(&mut self, params: &[f64]) -> Result<f64, GprError> {
            let mut dummy = [0.0; 1];
            self.value_and_gradient_into(params, &mut dummy)
        }
    }

    impl Differentiable for Sqrt1PlusSquare {
        fn gradient_into(&mut self, params: &[f64], out: &mut [f64]) -> Result<(), GprError> {
            self.value_and_gradient_into(params, out).map(|_| ())
        }

        fn value_and_gradient_into(
            &mut self,
            params: &[f64],
            out: &mut [f64],
        ) -> Result<f64, GprError> {
            let x = params[0];
            if x.abs() > 50.0 {
                return Err(GprError::NonFiniteKernelValue);
            }
            let root = (1.0 + x * x).sqrt();
            out[0] = x / root;
            Ok(root)
        }
    }

    impl TwiceDifferentiable for Sqrt1PlusSquare {
        fn hessian_into(&mut self, params: &[f64], out: &mut [f64]) -> Result<(), GprError> {
            let x = params[0];
            out[0] = (1.0 + x * x).powf(-1.5);
            Ok(())
        }
    }

    #[test]
    fn trust_region_converges_where_the_plain_newton_step_diverges() {
        for start in [1.5, 2.0, 4.0, -3.0] {
            let mut obj = Sqrt1PlusSquare;
            let result = TrustRegion::new()
                .with_max_iterations(200)
                .minimize_unconstrained(&mut obj, &[start])
                .expect("safeguarded newton");
            assert_close(result.params[0], 0.0, 1e-6);
        }
    }

    /// The Hessian of `−cos(x)` at `x = 2` is negative: the Newton step
    /// ascends; the trust-region step still descends.
    struct NegativeCurvature;

    impl Objective for NegativeCurvature {
        fn num_params(&self) -> usize {
            1
        }

        fn value(&mut self, params: &[f64]) -> Result<f64, GprError> {
            Ok(-params[0].cos())
        }
    }

    impl Differentiable for NegativeCurvature {
        fn gradient_into(&mut self, params: &[f64], out: &mut [f64]) -> Result<(), GprError> {
            out[0] = params[0].sin();
            Ok(())
        }

        fn value_and_gradient_into(
            &mut self,
            params: &[f64],
            out: &mut [f64],
        ) -> Result<f64, GprError> {
            out[0] = params[0].sin();
            Ok(-params[0].cos())
        }
    }

    impl TwiceDifferentiable for NegativeCurvature {
        fn hessian_into(&mut self, params: &[f64], out: &mut [f64]) -> Result<(), GprError> {
            out[0] = params[0].cos();
            Ok(())
        }
    }

    #[test]
    fn trust_region_descends_when_the_hessian_is_not_positive_definite() {
        let mut obj = NegativeCurvature;
        let result = TrustRegion::new()
            .with_max_iterations(200)
            .minimize_unconstrained(&mut obj, &[2.0])
            .expect("falls back to steepest descent");
        assert!(result.value < -0.999, "value {}", result.value);
    }

    #[test]
    fn trust_region_rejects_bad_radii() {
        assert!(TrustRegion::new().with_radii(0.0, 1.0).is_err());
        assert!(TrustRegion::new().with_radii(2.0, 1.0).is_err());
        assert!(TrustRegion::new().with_radii(1.0, f64::INFINITY).is_err());
    }

    /// Quadratic bowl that counts which entry points a solver uses.
    #[derive(Default)]
    struct CountingBowl {
        separate_gradients: usize,
        separate_hessians: usize,
        joint: usize,
    }

    impl Objective for CountingBowl {
        fn num_params(&self) -> usize {
            2
        }

        fn value(&mut self, params: &[f64]) -> Result<f64, GprError> {
            Ok((params[0] - 0.3).powi(2) + 2.0 * (params[1] + 0.2).powi(2))
        }
    }

    impl Differentiable for CountingBowl {
        fn gradient_into(&mut self, params: &[f64], out: &mut [f64]) -> Result<(), GprError> {
            self.separate_gradients += 1;
            out[0] = 2.0 * (params[0] - 0.3);
            out[1] = 4.0 * (params[1] + 0.2);
            Ok(())
        }
    }

    impl TwiceDifferentiable for CountingBowl {
        fn hessian_into(&mut self, _params: &[f64], out: &mut [f64]) -> Result<(), GprError> {
            self.separate_hessians += 1;
            out.copy_from_slice(&[2.0, 0.0, 0.0, 4.0]);
            Ok(())
        }

        fn value_gradient_hessian_into(
            &mut self,
            params: &[f64],
            grad: &mut [f64],
            hess: &mut [f64],
        ) -> Result<f64, GprError> {
            self.joint += 1;
            grad[0] = 2.0 * (params[0] - 0.3);
            grad[1] = 4.0 * (params[1] + 0.2);
            hess.copy_from_slice(&[2.0, 0.0, 0.0, 4.0]);
            self.value(params)
        }
    }

    #[test]
    fn trust_region_evaluates_each_candidate_through_the_joint_entry_point() {
        let mut bowl = CountingBowl::default();
        let result = TrustRegion::new()
            .minimize_unconstrained(&mut bowl, &[2.0, 1.0])
            .expect("minimize");
        assert_close(result.params[0], 0.3, TOL);
        assert_close(result.params[1], -0.2, TOL);
        assert!(bowl.joint > 0);
        assert_eq!(
            bowl.separate_hessians, 0,
            "a candidate's Hessian is part of the joint call"
        );
        assert_eq!(
            bowl.separate_gradients, 0,
            "a candidate's gradient is part of the joint call"
        );
    }
}