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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
//! Factored collapsed variational SGPR.

use std::marker::PhantomData;

use faer::Mat;
#[cfg(test)]
use faer::MatRef;

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::kernel::{KernelScalar, KernelSpec, ModelKernel};
use crate::optimizer::{Fixed, Lbfgs, OptResult, Optimizer};
use crate::param::Interval;
use crate::precision::{DoublePrecision, ModelPrecision};
use crate::sgpr::SgprObjective;
use crate::{PredictOptions, Prediction, PredictiveCovariance};

use super::factor::{
    VfeExact, VfeState, VfeSystem, analytic_gradient, analytic_hessian, assemble_vfe,
    fill_z_intervals, predict_vfe_covariance, predict_vfe_into, publish_sgpr_weights, vfe_loo,
    vfe_neg_log_marginal_likelihood,
};
use super::model::Sgpr;
use super::online::OnlineSgpr;
use super::{FixedInducing, InducingLayout};
use crate::kernel::NoSupply;

/// Represents the factored collapsed variational SGPR at the `θ` used by [`Sgpr::fit`] or [`Sgpr<Fixed>::factor`].
///
/// The type parameters are those of the [`Sgpr`] it came from: the
/// optimizer `O`, the inducing layout `I`, the precision `P`, and the
/// kernel `K`. 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 [`Sgpr`]).
///
/// Stores the LLT of `K_mm = k(Z, Z)` and the VFE factors used by
/// [`Self::predict`] and [`Self::neg_log_marginal_likelihood`]. Observation
/// noise is not added to `K_mm`. Hyperparameters are kernel `θ` then
/// likelihood `θ`. [`FreeInducing`](crate::FreeInducing) then appends column-major `Z`.
/// [`Self::into_online`] yields [`OnlineSgpr`] for training-point and
/// inducing-point updates.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{KernelSpec, RbfKernel};
/// use gprx::{
///     Fixed, GaussianLikelihood, JitterPolicy, KernelExp, PredictOptions, Prediction, Sgpr,
///     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 = Sgpr::new(KernelSpec::from(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
///     .with_optimizer(Fixed)
///     .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(_)));
///
/// // θ is the kernel's log-lengthscale, then the likelihood's log σn².
/// let mut theta = vec![0.0; fitted.num_params()];
/// fitted.get_params(&mut theta)?;
/// assert_eq!(theta.len(), fitted.kernel().num_params() + 1);
/// assert!((theta[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);
/// assert_eq!(fitted.loo_predict_with(latent)?.mean.len(), 4);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct FittedSgpr<
    O = Lbfgs,
    I = FixedInducing,
    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>,
    pub(super) optimizer: O,
    pub(super) inducing: PhantomData<I>,
    pub(super) _kernel: PhantomData<K>,
    /// Lower `L` from `K_mm + j I = L Lᵀ`.
    pub(super) k_mm_l: Mat<P::Storage>,
    /// `L` in `f64` beside a rounded `k_mm_l` (`f32` storage): the factor
    /// the assembly formed, which an online `X` insert solves against.
    pub(super) k_mm_l_f64: <P::Storage as crate::kernel::ScalarOps>::F64Factor,
    /// The offset `j` the factor `k_mm_l` took under the jitter policy.
    pub(super) k_mm_jitter: f64,
    /// `A = L_mm⁻¹ K(Z, X)` (`m × n`).
    pub(super) a: Mat<P::Storage>,
    /// Lower `L_B` from `B = σn² I + A Aᵀ`.
    pub(super) b_l: Mat<P::Storage>,
    /// Storage solve `B w = A y`. Marginal likelihood uses this.
    pub(super) w: Vec<P::Storage>,
    /// Predict weights. [`DoublePrecision`] and [`crate::SinglePrecision`]
    /// promote `w`. [`crate::MixedPrecision`] stores the refined `f64` weights.
    pub(super) predict_w: Vec<P::Refine>,
    pub(super) k_diag_sum: P::Storage,
    pub(super) a_frobenius2: P::Storage,
    /// The `f64` factor of `B`, `w`, and the sums the assembly rounded
    /// (`f32` storage): where [`Self::into_online`] starts the `f64`
    /// system its `X` steps update.
    pub(super) exact: <P::Storage as crate::kernel::ScalarOps>::F64Held<VfeExact>,
}

impl<O, I: InducingLayout<K::Supply>, P, K> FittedSgpr<O, I, P, K>
where
    P: crate::precision::GpScalar,
    K: ModelKernel,
{
    sparse_core_accessors!();

    /// Returns the concatenated parameter count.
    ///
    /// Kernel `θ` then likelihood `θ`. [`FreeInducing`](crate::FreeInducing) also counts
    /// column-major `Z` (`m × d`).
    ///
    /// See the example on [`FittedSgpr`].
    pub fn num_params(&self) -> usize {
        self.core.theta_len() + I::z_params(self.core.m, self.core.d)
    }

    /// Writes kernel `θ`, likelihood `θ`, and (when free) column-major `Z`.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if `out` is the wrong length
    /// or a custom leaf rejects the write.
    ///
    /// See the example on [`FittedSgpr`].
    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])?;
        if I::z_params(self.core.m, self.core.d) > 0 {
            out[n_theta..].copy_from_slice(&self.core.z_train);
        }
        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 rebuilds the VFE factors.
    ///
    /// `params` matches [`Self::get_params`]. [`FreeInducing`](crate::FreeInducing) also writes
    /// column-major `Z` from the tail of the slice. Training `X` / `y` are
    /// not changed. Values are committed together only after the VFE system
    /// factors.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if `params` is the wrong
    /// length, [`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` or `B` cannot be factored. A
    /// custom kernel leaf returns its own error. A rejected slice or a Cholesky failure leaves stored `θ`
    /// and the VFE factors unchanged.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let mut fitted = Sgpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .with_optimizer(Fixed)
    /// .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; 2];
    /// fitted.get_params(&mut params)?;
    /// params[0] = 0.5_f64.ln();
    /// 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 free_z = I::z_params(self.core.m, self.core.d) > 0;
        let z = if free_z {
            params[n_theta..].to_vec()
        } else {
            self.core.z_train.clone()
        };
        let z_obs = if free_z {
            self.core.inducing_obs(&z, self.core.m)?
        } else {
            self.core.z_obs.clone()
        };
        let data = crate::sparse::SparseData {
            z: &z,
            ..self.core.data()
        };
        let state = with_kernel_exp!(self.core.math, M => assemble_vfe::<M, _, K::Supply>(
            &kernel,
            self.core.jitter,
            likelihood,
            data,
            &mut self.scratch.storage,
            &mut self.scratch.f64,
        ))?;
        self.core.kernel = kernel;
        self.core.likelihood = likelihood;
        self.core.z_train = z;
        self.core.z_obs = z_obs;
        self.apply_vfe(state);
        Ok(())
    }

    pub(crate) fn fill_intervals(&self, out: &mut [Interval]) -> Result<(), GprError> {
        crate::data::require_count(out.len(), self.num_params(), "intervals")?;
        let n_theta = self.core.theta_len();
        self.core.theta_intervals(&mut out[..n_theta])?;
        if I::z_params(self.core.m, self.core.d) > 0 {
            fill_z_intervals(
                &self.core.x_train,
                self.core.n,
                self.core.d,
                &mut out[n_theta..],
            )?;
        }
        Ok(())
    }

    /// Sets parameters, rebuilds the VFE system, and writes `∂L/∂θ` of the negative ELBO.
    ///
    /// `params` and `out` match [`Self::get_params`]. When inducing points
    /// are fixed and `Z = X` the gradient matches
    /// [`crate::FittedGpr::value_and_gradient_into`]. The returned value is
    /// the same as [`Self::neg_log_marginal_likelihood`] after a successful
    /// call.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if a slice length is wrong, the
    /// parameter errors of [`Self::set_params`]
    /// ([`GprError::InvalidHyperparameter`],
    /// [`GprError::InvalidNoiseVariance`], [`GprError::InvalidInterval`]) if
    /// `params` is rejected, or [`GprError::CholeskyFailed`] if the VFE
    /// system cannot be factored. Kernel and likelihood `θ` are committed together only after the
    /// system factors.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let mut fitted = Sgpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .with_optimizer(Fixed)
    /// .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; 2];
    /// fitted.get_params(&mut params)?;
    /// let mut grad = [0.0; 2];
    /// let nlml = fitted.value_and_gradient_into(&params, &mut grad)?;
    /// assert!(nlml.is_finite());
    /// # Ok(())
    /// # }
    /// ```
    pub fn value_and_gradient_into(
        &mut self,
        params: &[f64],
        out: &mut [f64],
    ) -> Result<f64, GprError>
    where
        P: crate::precision::GpScalar,
    {
        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 value = self.neg_log_marginal_likelihood()?;
        let mut ks = std::mem::take(&mut self.scratch.storage);
        let result = with_kernel_exp!(self.core.math, M => analytic_gradient::<M, _, _, _, _>(
            self, out, &mut ks
        ));
        self.scratch.storage = ks;
        result?;
        Ok(value)
    }

    /// Writes the Hessian of the negative ELBO (row-major `p×p`) into `out`.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if a slice length is wrong, the
    /// parameter errors of [`Self::set_params`]
    /// ([`GprError::InvalidHyperparameter`],
    /// [`GprError::InvalidNoiseVariance`], [`GprError::InvalidInterval`]) if
    /// `params` is rejected, or [`GprError::CholeskyFailed`] if the VFE
    /// system cannot be factored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let mut fitted = Sgpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .with_optimizer(Fixed)
    /// .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; 2];
    /// fitted.get_params(&mut params)?;
    /// let mut hess = [0.0; 4];
    /// fitted.hessian_into(&params, &mut hess)?;
    /// assert!(hess.iter().all(|h| h.is_finite()));
    /// # Ok(())
    /// # }
    /// ```
    pub fn hessian_into(&mut self, params: &[f64], out: &mut [f64]) -> Result<(), GprError>
    where
        P: crate::precision::GpScalar,
    {
        let n_params = self.num_params();
        crate::data::require_count(params.len(), n_params, "parameters")?;
        crate::data::require_count(out.len(), n_params * n_params, "parameters")?;
        self.set_params(params)?;
        let mut ks = std::mem::take(&mut self.scratch.storage);
        let result = with_kernel_exp!(self.core.math, M => analytic_hessian::<M, _, _, _, _>(
            self, out, &mut ks
        ));
        self.scratch.storage = ks;
        result?;
        Ok(())
    }

    pub(crate) fn refresh_predict_w(&mut self) -> Result<(), GprError> {
        self.predict_w = with_kernel_exp!(self.core.math, M => publish_sgpr_weights::<M, P, K::Supply>(
            &self.core.kernel,
            self.core.jitter,
            self.a.as_ref(),
            self.b_l.as_ref(),
            &self.w,
            self.core.data(),
            self.core.likelihood.noise_variance(),
        ))?;
        Ok(())
    }

    pub(crate) fn apply_vfe(&mut self, state: VfeState<P::Storage>) {
        self.predict_w = promote_predict_w::<P>(&state.w);
        self.k_mm_l = state.k_mm_l;
        self.k_mm_l_f64 = state.k_mm_l_f64;
        self.k_mm_jitter = state.k_mm_jitter;
        self.a = state.a;
        self.b_l = state.b_l;
        self.w = state.w;
        self.k_diag_sum = state.k_diag_sum;
        self.a_frobenius2 = state.a_frobenius2;
        self.exact = state.exact;
    }

    /// `w` and the lower `L_B` of `B`, for the SVGP-at-Titsias checks.
    #[cfg(test)]
    pub(crate) fn vfe_w_and_b_l(&self) -> (&[P::Storage], MatRef<'_, P::Storage>) {
        (&self.w, self.b_l.as_ref())
    }

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

    pub(crate) fn into_trainer(self) -> Sgpr<O, I, P, K> {
        Sgpr {
            spec: self.core.spec(),
            optimizer: self.optimizer,
            inducing: PhantomData,
            _precision: PhantomData,
            _kernel: PhantomData,
        }
    }

    pub(crate) fn optimize_hyperparameters(&mut self) -> Result<(), GprError>
    where
        O: Clone + for<'a> Optimizer<SgprObjective<'a, O, I, P, K>>,
    {
        let mut init = vec![0.0; self.num_params()];
        self.get_params(&mut init)?;
        let optimizer = self.optimizer.clone();
        let result = {
            let mut obj = SgprObjective::new(self);
            optimizer.minimize(&mut obj, &init)
        };
        self.commit_or_revert_optimize(&init, result)
    }

    /// Takes the optimizer's result, or rebuilds the model at `init` (the
    /// parameters before the search) when the search failed.
    ///
    /// Only the parameters are kept for the way back, not a copy of the
    /// model: the VFE system at `init` factored before the search, so it is
    /// assembled again from them.
    fn commit_or_revert_optimize(
        &mut self,
        init: &[f64],
        result: Result<OptResult, GprError>,
    ) -> Result<(), GprError> {
        let committed = match result {
            Ok(opt) if opt.params.len() != self.num_params() || !opt.value.is_finite() => {
                Err(GprError::OptimizationNotConverged {
                    iterations: opt.iterations as usize,
                })
            }
            Ok(opt) => self
                .set_params(&opt.params)
                .and_then(|()| self.refresh_predict_w()),
            Err(err) => Err(err),
        };
        if let Err(err) = committed {
            self.revert_to(init);
            return Err(err);
        }
        Ok(())
    }

    fn revert_to(&mut self, init: &[f64]) {
        // `init` factored before the search; a failure here would leave the
        // model at the last factored point, which is still consistent.
        if self.set_params(init).is_ok() {
            let _ = self.refresh_predict_w();
        }
    }

    /// Returns the negative VFE evidence lower bound (the sparse NLML).
    ///
    /// When `Z = X` and the kernel has no White leaf, this matches
    /// [`crate::FittedGpr::neg_log_marginal_likelihood`] of
    /// [`crate::Gpr<Fixed>::factor`] on the same data. `K(Z, X)` never holds
    /// a White leaf's diagonal, so the bound does not jump when `Z` moves off
    /// `X`.
    ///
    /// # Errors
    ///
    /// The stored factors are already valid, so this returns `Ok`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let fitted = Sgpr::new(kernel, likelihood)
    ///     .with_optimizer(Fixed)
    ///     .factor(&[0.0, 1.0], 2, 1, &[0.0, 1.0], &[0.0, 1.0], 2)
    ///     .map_err(|(_, e)| e)?;
    /// let nlml = fitted.neg_log_marginal_likelihood()?;
    /// assert!(nlml.is_finite());
    /// # Ok(())
    /// # }
    /// ```
    pub fn neg_log_marginal_likelihood(&self) -> Result<f64, GprError> {
        vfe_neg_log_marginal_likelihood(
            self.a.as_ref(),
            self.b_l.as_ref(),
            &self.w,
            &self.core.y_train,
            self.k_diag_sum,
            self.a_frobenius2,
            self.core.likelihood.noise_variance(),
            self.core.n,
            self.core.m,
        )
    }

    /// Returns the leave-one-out mean and observation variance at every training point.
    ///
    /// `p(y_i | X, y_{-i}, θ, Z)` of the collapsed VFE posterior: the
    /// optimal `q(u)` without point `i` at fixed `θ` and `Z`, predicted at
    /// `x_i`. It is a rank-1 downdate of `B = σn² I + A Aᵀ` per point
    /// (Sherman–Morrison), `O(n m²)` in all. At `Z = X` it matches
    /// [`crate::FittedGpr::loo_predict`]. Mean and variance are
    /// inverse-transformed like [`Self::predict`].
    ///
    /// # Errors
    ///
    /// Returns [`GprError::NonPositiveDefiniteMatrix`] if a downdated `B` is
    /// not positive definite, or [`GprError::CholeskyFailed`] if an `f32` storage cannot factor `K_mm` again in `f64`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let fitted = Sgpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .with_optimizer(Fixed)
    /// .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 loo = fitted.loo_predict()?;
    /// assert_eq!(loo.mean.len(), fitted.n());
    /// # Ok(())
    /// # }
    /// ```
    pub fn loo_predict(&self) -> Result<Prediction<P::Refine>, GprError> {
        self.loo_predict_with(PredictOptions::default())
    }

    /// Returns leave-one-out mean and variance with an explicit variance kind.
    ///
    /// Latent variance is the VFE variance of `f(x_i)` without point `i`;
    /// observation variance adds `σn²`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::loo_predict`].
    ///
    /// See the example on [`FittedSgpr`].
    pub fn loo_predict_with(
        &self,
        options: PredictOptions,
    ) -> Result<Prediction<P::Refine>, GprError> {
        vfe_loo::<P, K::Supply>(
            &self.core,
            self.a.as_ref(),
            self.b_l.as_ref(),
            &self.w,
            options,
        )
    }

    #[cfg(test)]
    pub(crate) fn k_mm_l(&self) -> MatRef<'_, P::Storage> {
        self.k_mm_l.as_ref()
    }
}

impl<O, I, P, K> FittedSgpr<O, I, P, K>
where
    P: crate::precision::GpScalar,
    K: crate::kernel::PointKernel,
{
    sparse_point_accessors!();
}

impl<O, I: InducingLayout<NoSupply>, P> FittedSgpr<O, I, P>
where
    P: crate::precision::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. The factors are
    /// not stored; [`crate::LoadedSgpr::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 and the inducing-point search are 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::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let model = Sgpr::new(KernelSpec::from(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
    ///     .with_optimizer(Fixed)
    ///     .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-sgpr-{}", std::process::id()));
    /// let _ = std::fs::remove_dir_all(&dir);
    /// model.save(&dir)?;
    /// let loaded = gprx::LoadedSgpr::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_sgpr(self, dir.as_ref())
    }

    /// Converts this model into an online sparse GPR.
    ///
    /// [`OnlineSgpr`] can append or drop training points and inducing
    /// points. [`FixedInducing`] and [`FreeInducing`](crate::FreeInducing) both produce
    /// [`OnlineSgpr<O>`] whose parameters are kernel then likelihood
    /// `θ`. The stored VFE factors are reused.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let fitted = Sgpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .with_optimizer(Fixed)
    /// .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 online = fitted.into_online();
    /// online.insert(&[4.0], 0.1)?;
    /// assert_eq!(online.n(), 5);
    /// # Ok(())
    /// # }
    /// ```
    pub fn into_online(self) -> OnlineSgpr<O, P> {
        OnlineSgpr::from_fitted(self)
    }

    /// Predicts at `xs` with [`PredictOptions::default`] (observation variance).
    ///
    /// `xs` is column-major with `n_rows` query points and `n_cols` features.
    /// Returns the diagonal VFE 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::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let fitted = Sgpr::new(kernel, likelihood)
    ///     .with_optimizer(Fixed)
    ///     .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 VFE predictive variance of `f*`. Observation
    /// variance adds `σn²`.
    ///
    /// # Errors
    ///
    /// Same as [`Self::predict`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Fixed, GaussianLikelihood, PredictOptions, Sgpr, VarianceKind};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let fitted = Sgpr::new(kernel, likelihood)
    ///     .with_optimizer(Fixed)
    ///     .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_vfe_into::<P, crate::kernel::NoSupply>(
            &self.core,
            &VfeSystem::new(
                &self.core,
                self.k_mm_l.as_ref(),
                self.b_l.as_ref(),
                &self.predict_w,
            ),
            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::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let fitted = Sgpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .with_optimizer(Fixed)
    /// .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 VFE posterior covariance is `K** − Q** + K*m Σ Km*` with
    /// `Q** = K*m K_mm⁻¹ Km*` and `Σ = (K_mm + σn⁻² K_mn K_nm)⁻¹`.
    /// 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 [`FittedSgpr`].
    pub fn predict_covariance_with(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<PredictiveCovariance<P::Refine>, GprError> {
        predict_vfe_covariance::<P, crate::kernel::NoSupply>(
            &self.core,
            &VfeSystem::new(
                &self.core,
                self.k_mm_l.as_ref(),
                self.b_l.as_ref(),
                &self.predict_w,
            ),
            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 [`FittedSgpr`].
    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 [`FittedSgpr`].
    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.
    ///
    /// # Errors
    ///
    /// Same as [`Self::predict`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Fixed, GaussianLikelihood, Prediction, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let mut fitted = Sgpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .with_optimizer(Fixed)
    /// .factor(&[0.0, 1.0], 2, 1, &[0.0, 1.0], &[0.0, 1.0], 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 [`FittedSgpr`].
    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_vfe_into::<P, crate::kernel::NoSupply>(
            &self.core,
            &VfeSystem::new(
                &self.core,
                self.k_mm_l.as_ref(),
                self.b_l.as_ref(),
                &self.predict_w,
            ),
            xs,
            n_rows,
            n_cols,
            std::iter::empty(),
            options,
            &mut self.scratch.predict,
            out,
        )
    }
}

impl<P: crate::precision::GpScalar, K: ModelKernel> FittedSgpr<Fixed, FixedInducing, P, K> {
    /// The model of a persist directory: the VFE system factored at the
    /// saved `θ` and `Z`, as [`Sgpr<Fixed>::factor`] does.
    ///
    /// # Errors
    ///
    /// Same as [`Sgpr<Fixed>::factor`].
    pub(crate) fn from_persisted(core: SparseCore<K::Supply>) -> Result<Self, GprError> {
        with_kernel_exp!(core.math, M => super::factor::assemble_fitted::<Fixed, FixedInducing, M, P, K>(
            core, Fixed
        ))
    }
}

pub(crate) fn promote_predict_w<P: ModelPrecision>(w: &[P::Storage]) -> Vec<P::Refine> {
    w.iter()
        .map(|value| P::Refine::from_f64(value.to_f64()))
        .collect()
}