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
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
//! Factored stochastic variational GPR.

use std::marker::PhantomData;

use faer::Mat;

use crate::kernel::{KernelSpec, ModelKernel, NoSupply, PointKernel};

use crate::error::GprError;
use crate::policy::with_kernel_exp;
use crate::sparse::{
    PredictScratch, SparseCore, SparseScratch, sparse_core_accessors, sparse_kernel_accessor,
    sparse_point_accessors,
};

use crate::precision::{DoublePrecision, GpScalar, ModelPrecision};
use crate::{PredictOptions, Prediction, PredictiveCovariance};

use super::factor::{
    SvgpSystem, assemble_data_terms, assemble_kmm, assemble_svgp, pack_q, predict_svgp_covariance,
    predict_svgp_into, q_param_len, svgp_neg_elbo, svgp_value_and_gradient, unpack_q,
};

/// Represents the factored stochastic variational GPR at the `θ` used by [`crate::Svgp<Fixed>::factor`] or [`crate::Svgp<crate::Adam>::fit`].
///
/// The type parameters are the precision `P` and the kernel `K` of the
/// [`crate::Svgp`] it came from. A [`KernelSpec`] model holds inducing
/// coordinates `Z` ([`Self::z`]); a [`crate::kernel::DistanceKernel`] model
/// holds the indices of the training points that are its inducing points,
/// and the supplied `n × m` squared distances to them (see
/// [`crate::Svgp`]).
///
/// Stores the LLT of `K_mm = k(Z, Z)` and a whitened variational posterior
/// `q(v) = N(m, L Lᵀ)` used by [`Self::predict`] and [`Self::neg_elbo`].
/// Observation noise is not added to `K_mm`. Hyperparameters are kernel `θ`,
/// likelihood `θ`, the whitened mean vector, then the packed column-major
/// lower triangle of `L`.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{KernelSpec, RbfKernel};
/// use gprx::{
///     GaussianLikelihood, JitterPolicy, KernelExp, PredictOptions, Prediction, Svgp, VarianceKind,
/// };
///
/// # fn main() -> Result<(), gprx::GprError> {
/// // Column-major `X` (n = 4, d = 1) and the inducing coordinates `Z` (m = 2).
/// let (x, y, z) = ([0.0, 1.0, 2.0, 3.0], [0.0, 1.0, 0.5, 0.25], [0.5, 2.5]);
/// let mut fitted = Svgp::new(KernelSpec::from(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
///     .factor(&x, 4, 1, &y, &z, 2)
///     .map_err(|(_, e)| e)?;
///
/// // The training data, `Z`, and the settings carried from the trainer.
/// assert_eq!((fitted.n(), fitted.m(), fitted.d()), (4, 2, 1));
/// assert_eq!(fitted.x(), &x);
/// assert_eq!(fitted.y(), &y);
/// assert_eq!(fitted.z(), &z);
/// assert_eq!(fitted.math(), KernelExp::Accurate);
/// assert!(matches!(fitted.jitter_policy(), JitterPolicy::Adaptive(_)));
///
/// // Kernel θ, likelihood θ, the whitened mean (m), then packed `L` (m(m + 1) / 2).
/// let mut params = vec![0.0; fitted.num_params()];
/// fitted.get_params(&mut params)?;
/// assert_eq!(params.len(), fitted.kernel().num_params() + 1 + 2 + 3);
/// assert!((params[1] - fitted.likelihood().log_noise_variance()).abs() < 1e-12);
///
/// // Latent variance (no σn²) for each kind of query.
/// let latent = PredictOptions { variance_kind: VarianceKind::Latent };
/// let xs = [0.25, 0.75];
/// let mut out = Prediction::default();
/// fitted.predict_with_into(&xs, 2, 1, latent, &mut out)?;
/// assert_eq!(out, fitted.predict_with(&xs, 2, 1, latent)?);
/// let cov = fitted.predict_covariance_with(&xs, 2, 1, latent)?;
/// assert_eq!(cov.covariance.len(), 4);
/// assert_eq!(fitted.sample(&xs, 2, 1, 3, 7)?.len(), 6);
/// assert_eq!(fitted.sample_with(&xs, 2, 1, latent, 3, 7)?.len(), 6);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct FittedSvgp<P: ModelPrecision = DoublePrecision, K: ModelKernel = KernelSpec> {
    pub(super) core: SparseCore<K::Supply>,
    /// Kernel scratch kept between `&mut self` calls.
    pub(super) scratch: SparseScratch<P::Storage, K::Supply>,
    /// Lower `L_mm` from `K_mm = L_mm L_mmᵀ`.
    pub(super) k_mm_l: Mat<P::Storage>,
    /// `A = L_mm⁻¹ K(Z, X)` (`m × n`).
    pub(super) a: Mat<P::Storage>,
    pub(super) q_mean: Vec<f64>,
    /// Lower `L` from the whitened `S = L Lᵀ`.
    pub(super) q_l: Mat<f64>,
    pub(super) k_diag: Vec<P::Storage>,
    pub(super) _kernel: PhantomData<K>,
}

impl<P, K: ModelKernel> FittedSvgp<P, K>
where
    P: GpScalar,
{
    sparse_core_accessors!();

    /// The training data, settings, and fitted transforms.
    pub(crate) fn core(&self) -> &SparseCore<K::Supply> {
        &self.core
    }

    /// The whitened variational mean and lower `L` of `q(u)`.
    pub(crate) fn q(&self) -> (&[f64], faer::MatRef<'_, f64>) {
        (&self.q_mean, self.q_l.as_ref())
    }

    /// Returns the concatenated parameter count.
    ///
    /// Kernel `θ`, likelihood `θ`, the whitened mean (`m` scalars), then the
    /// packed lower triangle of `L` (`m(m + 1) / 2` scalars).
    ///
    /// See the example on [`FittedSvgp`].
    pub fn num_params(&self) -> usize {
        self.core.theta_len() + q_param_len(self.core.m)
    }

    /// Writes kernel `θ`, likelihood `θ`, the whitened mean, and packed `L`.
    ///
    /// `L` is packed column-major lower triangle: column 0 (`L_{00}`,
    /// `L_{10}`, …), then column 1 (`L_{11}`, `L_{21}`, …), and so on.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if `out` is the wrong length
    /// or a custom leaf rejects the write.
    ///
    /// See the example on [`FittedSvgp`].
    pub fn get_params(&self, out: &mut [f64]) -> Result<(), GprError> {
        crate::data::require_count(out.len(), self.num_params(), "parameters")?;
        let n_theta = self.core.theta_len();
        self.core.read_theta(&mut out[..n_theta])?;
        pack_q(&self.q_mean, self.q_l.as_ref(), &mut out[n_theta..]);
        Ok(())
    }

    fn same_stored_params(&self, params: &[f64]) -> Result<bool, GprError> {
        let mut current = vec![0.0; params.len()];
        self.get_params(&mut current)?;
        Ok(current == params)
    }

    /// Sets kernel then likelihood `θ` and the whitened `q`, then rebuilds.
    ///
    /// `params` matches [`Self::get_params`]. Training `X` / `y` and inducing
    /// `Z` are not changed. The diagonal of `L` must be strictly positive.
    /// Values are committed together only after `K_mm` factors.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if `params` is the wrong
    /// length or an `L` diagonal entry is not positive,
    /// [`GprError::NonFiniteInput`] if a variational value is not finite,
    /// [`GprError::InvalidHyperparameter`] or
    /// [`GprError::InvalidNoiseVariance`] if a kernel or likelihood `θ` is
    /// not finite or its `exp` is not a positive finite value,
    /// [`GprError::InvalidInterval`] if a value is outside the interval of
    /// its parameter (see [`crate::BoundedParam`] and
    /// [`crate::GaussianLikelihood::bounds`]), or
    /// [`GprError::CholeskyFailed`] if `K_mm` cannot be factored. A custom
    /// kernel leaf returns its own error. A rejected
    /// slice or a Cholesky failure leaves stored `θ` and `q` unchanged.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{GaussianLikelihood, Svgp};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let mut fitted = Svgp::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .factor(&[0.0, 1.0], 2, 1, &[0.0, 1.0], &[0.0, 1.0], 2)
    /// .map_err(|(_, e)| e)?;
    /// let mut params = [0.0; 7];
    /// fitted.get_params(&mut params)?;
    /// params[2] = 0.1;
    /// fitted.set_params(&params)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_params(&mut self, params: &[f64]) -> Result<(), GprError> {
        let n_theta = self.core.theta_len();
        crate::data::require_count(params.len(), self.num_params(), "parameters")?;
        if self.same_stored_params(params)? {
            return Ok(());
        }
        let (kernel, likelihood) = self.core.stage_theta(&params[..n_theta])?;
        let q = unpack_q(&params[n_theta..], self.core.m)?;
        let state = with_kernel_exp!(self.core.math, M => assemble_svgp::<M, P::Storage, K::Supply>(
            &kernel,
            self.core.jitter,
            self.core.data(),
            Some(q),
            &mut self.scratch.storage,
        ))?;
        self.core.kernel = kernel;
        self.core.likelihood = likelihood;
        self.k_mm_l = state.k_mm_l;
        self.a = state.a;
        self.q_mean = state.q_mean;
        self.q_l = state.q_l;
        self.k_diag = state.k_diag;
        Ok(())
    }

    /// One mini-batch step's update: `θ`, the factor of `K_mm`, and `q`.
    ///
    /// Leaves `A` and `k_diag`, which cost `O(n)`, stale until
    /// [`Self::rebuild_data_terms`]: a mini-batch gradient forms the terms of
    /// its own points and never reads them. Committed together only after
    /// `K_mm` factors, like [`Self::set_params`].
    pub(crate) fn set_params_light(&mut self, params: &[f64]) -> Result<(), GprError> {
        let n_theta = self.core.theta_len();
        crate::data::require_count(params.len(), self.num_params(), "parameters")?;
        let (kernel, likelihood) = self.core.stage_theta(&params[..n_theta])?;
        let (q_mean, q_l) = unpack_q(&params[n_theta..], self.core.m)?;
        let k_mm_l = with_kernel_exp!(self.core.math, M => assemble_kmm::<M, P::Storage, K::Supply>(
            &kernel,
            self.core.jitter,
            self.core.data(),
            &mut self.scratch.storage,
        ))?;
        self.core.kernel = kernel;
        self.core.likelihood = likelihood;
        self.k_mm_l = k_mm_l;
        self.q_mean = q_mean;
        self.q_l = q_l;
        Ok(())
    }

    /// `A` and `k_diag` for every training point at the stored `θ`, `Z`, and
    /// `K_mm` factor (after [`Self::set_params_light`] steps).
    pub(crate) fn rebuild_data_terms(&mut self) -> Result<(), GprError> {
        let (a, k_diag) = with_kernel_exp!(self.core.math, M => assemble_data_terms::<M, P::Storage, K::Supply>(
            &self.core.kernel,
            self.core.data(),
            self.k_mm_l.as_ref(),
            &mut self.scratch.storage,
        ))?;
        self.a = a;
        self.k_diag = k_diag;
        Ok(())
    }

    /// Returns the negative variational ELBO on the full training set.
    ///
    /// This is the un-collapsed bound. At the Titsias-optimal whitened `q`
    /// it matches [`crate::FittedSgpr::neg_log_marginal_likelihood`] on
    /// the same `θ`, `X`, and `Z`.
    ///
    /// # Errors
    ///
    /// The stored factors are already valid, so this returns `Ok`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{GaussianLikelihood, Svgp};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let fitted = Svgp::new(kernel, likelihood)
    ///     .factor(&[0.0, 1.0], 2, 1, &[0.0, 1.0], &[0.0, 1.0], 2)
    ///     .map_err(|(_, e)| e)?;
    /// let value = fitted.neg_elbo()?;
    /// assert!(value.is_finite());
    /// # Ok(())
    /// # }
    /// ```
    pub fn neg_elbo(&self) -> Result<f64, GprError> {
        Ok(svgp_neg_elbo(
            self.a.as_ref(),
            &self.q_mean,
            self.q_l.as_ref(),
            &self.core.y_train,
            &self.k_diag,
            self.core.likelihood.noise_variance(),
            self.core.n,
            self.core.m,
        ))
    }

    /// Sets parameters, rebuilds `K_mm` / `q`, and writes `∂/∂θ` of the full-data negative ELBO.
    ///
    /// `params` and `out` match [`Self::get_params`]. The returned value is
    /// the same as [`Self::neg_elbo`] after a successful call. Mini-batch
    /// scaling lives in [`crate::Svgp<crate::Adam>::fit`], not here.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if a slice length is wrong
    /// or an `L` diagonal entry is not positive,
    /// [`GprError::NonFiniteInput`] if a variational value is not finite,
    /// the parameter errors of [`Self::set_params`]
    /// ([`GprError::InvalidHyperparameter`],
    /// [`GprError::InvalidNoiseVariance`], [`GprError::InvalidInterval`]) if
    /// a `θ` is rejected, or [`GprError::CholeskyFailed`] if `K_mm` cannot
    /// be factored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{GaussianLikelihood, Svgp};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let mut fitted = Svgp::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .factor(&[0.0, 1.0], 2, 1, &[0.0, 1.0], &[0.0, 1.0], 2)
    /// .map_err(|(_, e)| e)?;
    /// let mut params = [0.0; 7];
    /// fitted.get_params(&mut params)?;
    /// let mut grad = [0.0; 7];
    /// let value = fitted.value_and_gradient_into(&params, &mut grad)?;
    /// assert!(value.is_finite());
    /// # Ok(())
    /// # }
    /// ```
    pub fn value_and_gradient_into(
        &mut self,
        params: &[f64],
        out: &mut [f64],
    ) -> Result<f64, GprError> {
        let n_params = self.num_params();
        crate::data::require_count(params.len(), n_params, "parameters")?;
        crate::data::require_count(out.len(), n_params, "parameters")?;
        self.set_params(params)?;
        let batch: Vec<usize> = (0..self.core.n).collect();
        let mut scratch = std::mem::take(&mut self.scratch);
        let result = with_kernel_exp!(
            self.core.math,
            M => svgp_value_and_gradient::<M, _, K>(self, out, &batch, &mut scratch)
        );
        self.scratch = scratch;
        result
    }
}

impl<P, K> FittedSvgp<P, K>
where
    P: GpScalar,
    K: PointKernel,
{
    sparse_point_accessors!();
}

impl<P: GpScalar, K: ModelKernel> FittedSvgp<P, K> {
    /// The model of a persist directory: `K_mm` and `A` factored at the
    /// saved `θ` and `Z`, with the saved whitened `q(u)`.
    ///
    /// # Errors
    ///
    /// Same as [`crate::Svgp<crate::Fixed>::factor`].
    pub(crate) fn from_persisted(
        core: SparseCore<K::Supply>,
        q_mean: Vec<f64>,
        q_l: Mat<f64>,
    ) -> Result<Self, GprError> {
        with_kernel_exp!(core.math, M => super::factor::assemble_fitted::<M, P, K>(
            core,
            Some((q_mean, q_l))
        ))
    }
}

impl<P> FittedSvgp<P>
where
    P: GpScalar,
{
    sparse_kernel_accessor!();

    /// Writes this model to `dir` as `config.json` and `model.safetensors`.
    ///
    /// Stores the kernel, likelihood, kernel `exp`, `K_mm` jitter policy,
    /// precision, transforms (unfitted and fitted), the original `X`, `y`,
    /// and `Z`, and `Z` in transformed coordinates, and the whitened `q(u)`. The factors are
    /// not stored; [`crate::LoadedSvgp::load`] factors the system again at the saved `θ`
    /// and `Z`. Caller-defined kernels and transforms need their
    /// `persist_id` / `persist_state` and a [`crate::PersistRegistry`] entry.
    /// The optimizer is not stored.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::PersistFailed`] when the directory cannot be
    /// written or a kernel or transform has no persist form.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{GaussianLikelihood, Svgp};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let model = Svgp::new(KernelSpec::from(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
    ///     .factor(&[0.0, 1.0, 2.0], 3, 1, &[0.0, 1.0, 0.5], &[0.5, 1.5], 2)
    ///     .map_err(|(_, e)| e)?;
    /// let dir = std::env::temp_dir().join(format!("gprx-doctest-save-svgp-{}", std::process::id()));
    /// let _ = std::fs::remove_dir_all(&dir);
    /// model.save(&dir)?;
    /// let loaded = gprx::LoadedSvgp::load(&dir, &gprx::PersistRegistry::new())?;
    /// assert_eq!(loaded.n(), model.n());
    /// let _ = std::fs::remove_dir_all(&dir);
    /// # Ok(())
    /// # }
    /// ```
    pub fn save(&self, dir: impl AsRef<std::path::Path>) -> Result<(), GprError> {
        crate::persist::save_svgp(self, dir.as_ref())
    }

    /// Predicts at `xs` with [`PredictOptions::default`] (observation variance).
    ///
    /// `xs` is column-major with `n_rows` query points and `n_cols` features.
    /// Returns the diagonal SVGP predictive mean and variance.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::DimensionMismatch`] if `n_cols` differs from the
    /// training features, [`GprError::EmptyInput`] if a dimension is zero, or
    /// [`GprError::LengthMismatch`] / [`GprError::NonFiniteInput`] for a
    /// badly packed or non-finite `xs`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{GaussianLikelihood, Svgp};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let fitted = Svgp::new(kernel, likelihood)
    ///     .factor(&[0.0, 1.0], 2, 1, &[0.0, 1.0], &[0.0, 1.0], 2)
    ///     .map_err(|(_, e)| e)?;
    /// let pred = fitted.predict(&[0.5], 1, 1)?;
    /// assert_eq!(pred.mean.len(), 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn predict(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
    ) -> Result<Prediction<P::Refine>, GprError> {
        self.predict_with(xs, n_rows, n_cols, PredictOptions::default())
    }

    /// Predicts at `xs` with an explicit variance kind.
    ///
    /// Latent variance is the SVGP predictive variance of `f*`. Observation
    /// variance adds `σn²`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::predict`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{GaussianLikelihood, PredictOptions, Svgp, VarianceKind};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let fitted = Svgp::new(kernel, likelihood)
    ///     .factor(&[0.0, 1.0], 2, 1, &[0.0, 1.0], &[0.0, 1.0], 2)
    ///     .map_err(|(_, e)| e)?;
    /// let pred = fitted.predict_with(
    ///     &[0.5],
    ///     1,
    ///     1,
    ///     PredictOptions {
    ///         variance_kind: VarianceKind::Latent,
    ///     },
    /// )?;
    /// assert_eq!(pred.variance_kind, VarianceKind::Latent);
    /// # Ok(())
    /// # }
    /// ```
    pub fn predict_with(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<Prediction<P::Refine>, GprError> {
        let mut out = Prediction::default();
        predict_svgp_into::<P, NoSupply>(
            &self.core,
            &SvgpSystem::new(
                &self.core,
                self.k_mm_l.as_ref(),
                &self.q_mean,
                self.q_l.as_ref(),
            ),
            xs,
            n_rows,
            n_cols,
            std::iter::empty(),
            options,
            &mut PredictScratch::default(),
            &mut out,
        )?;
        Ok(out)
    }

    /// Returns the predictive mean and query–query covariance at `xs`.
    ///
    /// Default [`PredictOptions`] uses [`crate::VarianceKind::Observation`]:
    /// `σn²` is added on the diagonal in the transformed space. The diagonal
    /// is exactly the variance of [`Self::predict`] for the same query. This
    /// path allocates an `m × m` matrix; [`Self::predict`] stays diagonal.
    ///
    /// # Errors
    ///
    /// Same as [`Self::predict`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{GaussianLikelihood, Svgp};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let fitted = Svgp::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .factor(&[0.0, 1.0, 2.0], 3, 1, &[0.0, 1.0, 0.5], &[0.5, 1.5], 2)
    /// .map_err(|(_, e)| e)?;
    /// let cov = fitted.predict_covariance(&[0.25, 0.75], 2, 1)?;
    /// assert_eq!(cov.covariance.len(), 4);
    /// assert_eq!(cov.covariance[0], fitted.predict(&[0.25, 0.75], 2, 1)?.variance[0]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn predict_covariance(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
    ) -> Result<PredictiveCovariance<P::Refine>, GprError> {
        self.predict_covariance_with(xs, n_rows, n_cols, PredictOptions::default())
    }

    /// Returns query–query covariance with an explicit variance kind.
    ///
    /// The SVGP posterior covariance is `K** − K*m K_mm⁻¹ Km* + K*m L⁻ᵀ S L⁻¹ Km*`
    /// with the whitened `q(u) = N(m, S)` and `K_mm = L Lᵀ`.
    /// Latent diagonals are clipped at 0. Observation adds `σn²` on the
    /// diagonal in the transformed space, then the target transform scales
    /// the whole matrix.
    ///
    /// # Errors
    ///
    /// Same as [`Self::predict`].
    ///
    /// See the example on [`FittedSvgp`].
    pub fn predict_covariance_with(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<PredictiveCovariance<P::Refine>, GprError> {
        predict_svgp_covariance::<P, NoSupply>(
            &self.core,
            &SvgpSystem::new(
                &self.core,
                self.k_mm_l.as_ref(),
                &self.q_mean,
                self.q_l.as_ref(),
            ),
            xs,
            n_rows,
            n_cols,
            std::iter::empty(),
            std::iter::empty(),
            options,
        )
    }

    /// Draws posterior samples at `xs` from [`Self::predict_covariance`].
    ///
    /// Each column of the returned column-major `m × n_draws` matrix is
    /// `μ + L z` with `z ∼ N(0, I)` and `L` the Cholesky factor of the
    /// posterior covariance, the same draw as [`crate::FittedGpr::sample`].
    /// `seed` is the start state of gprx's seeded generator (Xoshiro256++; the same seed gives the same draws on every platform). Zero draws
    /// returns an empty vector after the covariance is formed.
    ///
    /// # Errors
    ///
    /// Same as [`Self::predict`], plus [`GprError::CholeskyFailed`] with
    /// [`CholeskyStage::Predict`](crate::CholeskyStage::Predict) if the
    /// posterior covariance cannot be factored after the retries of
    /// [`Self::jitter_policy`].
    ///
    /// See the example on [`FittedSvgp`].
    pub fn sample(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        n_draws: usize,
        seed: u64,
    ) -> Result<Vec<P::Refine>, GprError> {
        self.sample_with(xs, n_rows, n_cols, PredictOptions::default(), n_draws, seed)
    }

    /// Draws posterior samples with an explicit variance kind.
    ///
    /// # Errors
    ///
    /// Same as [`Self::sample`].
    ///
    /// See the example on [`FittedSvgp`].
    pub fn sample_with(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
        n_draws: usize,
        seed: u64,
    ) -> Result<Vec<P::Refine>, GprError> {
        self.predict_covariance_with(xs, n_rows, n_cols, options)?
            .draw(n_draws, seed, self.core.jitter)
    }

    /// Predicts at `xs` with [`PredictOptions::default`] into `out`.
    ///
    /// Same values as [`Self::predict`]. The buffers are kept on the model
    /// and `out` keeps its capacity, so a call after one with the same
    /// shapes allocates nothing, except under [`crate::MixedPrecision`],
    /// which refines each mean in `f64`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::predict`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{GaussianLikelihood, Prediction, Svgp};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let mut fitted = Svgp::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .factor(&[0.0, 1.0, 2.0, 3.0], 4, 1, &[0.0, 1.0, 0.5, 0.25], &[0.5, 2.5], 2)
    /// .map_err(|(_, e)| e)?;
    /// let mut pred = Prediction::default();
    /// fitted.predict_into(&[0.5], 1, 1, &mut pred)?;
    /// assert_eq!(pred, fitted.predict(&[0.5], 1, 1)?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn predict_into(
        &mut self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        out: &mut Prediction<P::Refine>,
    ) -> Result<(), GprError> {
        self.predict_with_into(xs, n_rows, n_cols, PredictOptions::default(), out)
    }

    /// Predicts at `xs` with an explicit variance kind into `out`.
    ///
    /// Same values as [`Self::predict_with`], with the buffers of
    /// [`Self::predict_into`].
    ///
    /// # Errors
    ///
    /// Same as [`Self::predict`].
    ///
    /// See the example on [`FittedSvgp`].
    pub fn predict_with_into(
        &mut self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
        out: &mut Prediction<P::Refine>,
    ) -> Result<(), GprError> {
        predict_svgp_into::<P, NoSupply>(
            &self.core,
            &SvgpSystem::new(
                &self.core,
                self.k_mm_l.as_ref(),
                &self.q_mean,
                self.q_l.as_ref(),
            ),
            xs,
            n_rows,
            n_cols,
            std::iter::empty(),
            options,
            &mut self.scratch.predict,
            out,
        )
    }
}