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
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
//! [`FittedGpr`]: the fitted Exact GPR and its public API.

use std::fmt;
use std::marker::PhantomData;

use dyn_stack::MemBuffer;
use faer::linalg::cholesky::llt;
use faer::{Mat, MatRef};

use crate::data::{pack_points, validate_training};
use crate::error::GprError;
use crate::error::PersistErrorKind;
use crate::gpr::GprObjective;
use crate::kernel::ScalarOps;
use crate::kernel::{
    DistanceKernel, DistanceSlot, DistanceSource, KernelScalar, KernelSpec, ModelKernel,
    ModelKernelParts, PointKernel, PointUse, SupplyViews, spec_slots,
};
use crate::likelihood::GaussianLikelihood;
use crate::linalg::{faer_par_dims, solve_llt_in_place};
use crate::optimizer::{Fixed, Lbfgs, Optimizer};
use crate::persist::{self, PersistedModel};
use crate::precision::{DoublePrecision, GpScalar, StoredFactor};
use crate::transform::IdentityInput;
use crate::transform::{TargetTransform, Transform, UnfittedTarget, UnfittedTransform};
use crate::workspace::{FitWorkspace, QueryWorkspace};
use crate::{PredictOptions, Prediction, PredictiveCovariance};

use super::shared::{ExactSupplied, Query};
use super::{ExactFit, Gpr, GprCore, LdltStore, LltStore, OnlineGpr, Policies, fit_buffers};

/// Stores a fitted Exact GPR: `L`, `α`, the training data, kernel, and transforms.
///
/// The type parameters are those of the [`Gpr`] it came from: the
/// optimizer `O` that [`Self::refit`] runs, the precision `P`, and the
/// kernel `K`. The training data is the coordinates `X` and targets `y` of a
/// [`KernelSpec`] model, or the supplied squared distances (plus `X` for the
/// coordinate leaves) and `y` of a [`DistanceKernel`] model.
///
/// [`Self::neg_log_marginal_likelihood`] is
/// `½ yᵀ α + ½ log|A| + (n/2) log(2π)` with `log|A| = 2 Σ log(L_ii)`.
/// [`Self::value_and_gradient_into`] rebuilds `L`, `α`, and `W` once and
/// writes `∂L/∂θ = -½ ⟨W, ∂A/∂θ⟩`. [`Self::predict`] returns the mean and
/// a diagonal variance; [`Self::predict_into`] writes into a reused
/// [`Prediction`](crate::Prediction) and query buffers the model keeps (not the fit workspace).
/// [`Self::predict_covariance`] returns the query–query matrix as
/// [`PredictiveCovariance`](crate::PredictiveCovariance). [`Self::sample`] draws from that posterior.
/// [`Self::loo_predict`] is the GPML leave-one-out at every
/// training point, from `L` and `α`. [`Self::refit`] re-runs the trainer's
/// optimizer (`Gpr<O>`) or re-factors (`Gpr<Fixed>`) on the same training
/// data.
///
/// [`Clone`] copies the factorization, training observations, transforms, and
/// optimizer. [`Self::kernel`] is a shared reference; writes go through
/// [`Self::set_params`].
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{KernelSpec, RbfKernel};
/// use gprx::{
///     CholeskyBuffer, DistanceCachePolicy, Fixed, GaussianLikelihood, Gpr, JitterPolicy,
///     KernelExp, PredictOptions, Prediction, VarianceKind,
/// };
///
/// # fn main() -> Result<(), gprx::GprError> {
/// // Column-major `X` with n = 3 points and d = 1 feature.
/// let (x, y) = ([0.0, 1.0, 2.0], [0.0, 1.0, 0.5]);
/// let mut fitted = Gpr::new(KernelSpec::from(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
///     .fit(&x, 3, 1, &y)
///     .map_err(|(_, e)| e)?;
/// let pred = fitted.predict(&[0.5], 1, 1)?;
/// assert_eq!(pred.mean.len(), 1);
///
/// // The training data, `α`, and the policies carried from the trainer.
/// assert_eq!((fitted.n(), fitted.d()), (3, 1));
/// assert_eq!(fitted.x(), &x);
/// assert_eq!(fitted.y(), &y);
/// assert_eq!(fitted.alpha().len(), 3);
/// assert_eq!(fitted.distance_cache_policy(), DistanceCachePolicy::Cached);
/// assert_eq!(fitted.cholesky_buffer(), CholeskyBuffer::Retain);
/// assert_eq!(fitted.math(), KernelExp::Accurate);
/// assert_eq!(fitted.jitter_policy(), JitterPolicy::default());
///
/// // θ is the kernel's parameters, 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 pred = fitted.predict_with(&xs, 2, 1, latent)?;
/// let mut out = Prediction::default();
/// fitted.predict_with_into(&xs, 2, 1, latent, &mut out)?;
/// assert_eq!(out, pred);
/// let cov = fitted.predict_covariance_with(&xs, 2, 1, latent)?;
/// assert_eq!(cov.covariance.len(), 4);
/// let draws = fitted.sample_with(&xs, 2, 1, latent, 5, 42)?;
/// assert_eq!(draws.len(), 10);
/// let loo = fitted.loo_predict_with(latent)?;
/// assert_eq!(loo.mean.len(), 3);
///
/// // Search θ again from its current value, then save `L` and `α` too.
/// fitted.refit()?;
/// let dir = std::env::temp_dir().join(format!("gprx-doctest-fitted-gpr-{}", std::process::id()));
/// let _ = std::fs::remove_dir_all(&dir);
/// fitted.save_with_factor(&dir)?;
/// let _ = std::fs::remove_dir_all(&dir);
///
/// // Back to a trainer; factor at the fitted θ and rebuild `L` and `α` there.
/// let mut fixed = fitted
///     .into_trainer()
///     .with_optimizer(Fixed)
///     .factor(&x, 3, 1, &y)
///     .map_err(|(_, e)| e)?;
/// fixed.refit()?;
/// assert_eq!(fixed.n(), 3);
/// # Ok(())
/// # }
/// ```
pub struct FittedGpr<O = Lbfgs, P: GpScalar = DoublePrecision, K: ModelKernel = KernelSpec> {
    pub(super) core: GprCore<P, K>,
    pub(super) optimizer: O,
    pub(super) store: LltStore<P>,
    pub(super) _kernel: PhantomData<K>,
}

impl<O, P, K> Clone for FittedGpr<O, P, K>
where
    O: Clone,
    P: GpScalar,
    K: ModelKernel,
{
    fn clone(&self) -> Self {
        Self {
            core: self.core.clone(),
            optimizer: self.optimizer.clone(),
            store: self.store.clone(),
            _kernel: PhantomData,
        }
    }
}

/// The training data of one fit: coordinates (`n_rows × n_cols`,
/// column-major; no columns for a kernel of supplied distances alone),
/// targets, and the sources of a distance kernel.
pub(crate) struct TrainInput<'a> {
    pub(crate) x: &'a [f64],
    pub(crate) n_rows: usize,
    pub(crate) n_cols: usize,
    pub(crate) y: &'a [f64],
    pub(crate) sources: Vec<DistanceSource<'a>>,
}

impl<'a> TrainInput<'a> {
    pub(crate) fn points(x: &'a [f64], n_rows: usize, n_cols: usize, y: &'a [f64]) -> Self {
        Self {
            x,
            n_rows,
            n_cols,
            y,
            sources: Vec::new(),
        }
    }

    /// Checks the coordinates and targets. A kernel that reads `points`
    /// needs at least one feature column.
    fn validate(&self, points: bool) -> Result<(), GprError> {
        if points {
            return validate_training(self.x, self.n_rows, self.n_cols, self.y);
        }
        crate::data::require_nonempty(self.n_rows)?;
        crate::data::require_count(self.x.len(), 0, "feature values")?;
        crate::data::require_count(self.y.len(), self.n_rows, "targets")?;
        crate::data::require_finite(self.y)
    }
}

impl<O, P, K> fmt::Debug for FittedGpr<O, P, K>
where
    O: fmt::Debug,
    P: GpScalar,
    K: ModelKernel,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FittedGpr")
            .field("n", &self.core.n)
            .field("d", &self.core.d)
            .field("kernel", &self.core.kernel)
            .field("likelihood", &self.core.likelihood)
            .field("optimizer", &self.optimizer)
            .field("distance_cache", &self.core.policies.distance_cache)
            .field("cholesky_buffer", &self.core.policies.cholesky_buffer)
            .field("math", &self.core.policies.math)
            .field("jitter_policy", &self.core.policies.jitter)
            .finish_non_exhaustive()
    }
}

impl<O, P, K> FittedGpr<O, P, K>
where
    P: GpScalar,
    K: ModelKernel,
{
    /// Checks `input`, fits the transforms, binds the training distances,
    /// and allocates the fit buffers.
    #[allow(clippy::result_large_err)] // failure returns the trainer so the caller can retry
    pub(crate) fn prepare(
        gpr: Gpr<O, P, K>,
        input: TrainInput<'_>,
    ) -> Result<Self, (Gpr<O, P, K>, GprError)> {
        if let Err(err) = input.validate(<K as ModelKernelParts>::POINTS) {
            return Err((gpr, err));
        }
        let TrainInput {
            x,
            n_rows,
            n_cols,
            y,
            sources,
        } = input;
        let supplied = <K::Supply as SupplyViews>::try_hold(|| {
            let slots = spec_slots(&gpr.kernel);
            let bound = <P::Sources as crate::kernel::SourceStore<P::Storage>>::bind(
                &slots, sources, n_rows,
            )?;
            Ok(ExactSupplied::new(bound, slots))
        });
        let supplied = match supplied {
            Ok(supplied) => supplied,
            Err(err) => return Err((gpr, err)),
        };
        let mut x_buf = x.to_vec();
        let x_fitted: Box<dyn Transform> = if n_cols == 0 {
            Box::new(IdentityInput)
        } else {
            match gpr.x_transform.clone_box().fit(&x_buf, n_rows, n_cols) {
                Ok(t) => t,
                Err(err) => return Err((gpr, err)),
            }
        };
        if n_cols > 0
            && let Err(err) = x_fitted.apply(&mut x_buf, n_rows, n_cols)
        {
            return Err((gpr, err));
        }
        let mut y_buf = y.to_vec();
        let y_fitted = match gpr.y_transform.clone_box().fit(&y_buf) {
            Ok(t) => t,
            Err(err) => return Err((gpr, err)),
        };
        if let Err(err) = y_fitted.transform(&mut y_buf) {
            return Err((gpr, err));
        }
        let compiled = gpr.kernel.compile_as::<P::Storage>();
        let workspace = match fit_buffers::<P, _>(n_rows, gpr.policies, &compiled) {
            Ok(ws) => ws,
            Err(err) => return Err((gpr, err)),
        };
        Ok(Self {
            core: GprCore {
                supplied,
                kernel: gpr.kernel,
                compiled,
                likelihood: gpr.likelihood,
                x_unfitted: gpr.x_transform,
                y_unfitted: gpr.y_transform,
                x_transform: x_fitted,
                y_transform: y_fitted,
                policies: gpr.policies,
                query: QueryWorkspace::new(),
                x_obs: x.to_vec(),
                y_obs: y.to_vec(),
                x: pack_points(&x_buf, n_rows, n_cols),
                y_train: y_buf,
                factor_alpha: vec![P::Storage::from_f64(0.0); n_rows],
                alpha: vec![P::Refine::from_f64(0.0); n_rows],
                x_cast: P::Storage::empty_cols(),
                y_cast: P::Storage::empty_rows(),
                n: n_rows,
                d: n_cols,
            },
            optimizer: gpr.optimizer,
            store: LltStore::new(workspace),
            _kernel: PhantomData,
        })
    }

    /// Drops `L` / `α` / training data and returns a trainer with the current kernel, likelihood, transforms, optimizer, and policies.
    ///
    /// See the example on [`FittedGpr`].
    pub fn into_trainer(self) -> Gpr<O, P, K> {
        self.core.into_trainer(self.optimizer)
    }

    /// Returns the number of training points.
    ///
    /// See the example on [`FittedGpr`].
    pub fn n(&self) -> usize {
        self.core.n
    }

    /// Returns the observation-noise model.
    ///
    /// See the example on [`FittedGpr`].
    pub fn likelihood(&self) -> &GaussianLikelihood {
        &self.core.likelihood
    }

    /// Returns `α = A⁻¹ y` from the last successful fit.
    ///
    /// See the example on [`FittedGpr`].
    pub fn alpha(&self) -> &[P::Refine] {
        &self.core.alpha
    }

    /// Returns the original training targets.
    ///
    /// Values are on the scale passed to fit, before the target transform.
    ///
    /// See the example on [`FittedGpr`].
    pub fn y(&self) -> &[f64] {
        &self.core.y_obs
    }

    /// Replaces the optimizer used by a later [`Self::refit`].
    ///
    /// Does not write a solver into a persist directory. A model loaded as
    /// [`crate::persist::LoadedGpr`] is [`Fixed`]; call this before `refit`
    /// to search again. Incremental rebuilds follow the same rule as
    /// [`Gpr::with_optimizer`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::persist::{LoadedGpr, PersistRegistry};
    /// use gprx::{GaussianLikelihood, Gpr, Lbfgs};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let fitted = Gpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0])
    /// .map_err(|(_, e)| e)?;
    /// let dir = std::env::temp_dir().join(format!(
    ///     "gprx-doctest-refit-{}",
    ///     std::process::id()
    /// ));
    /// let _ = std::fs::remove_dir_all(&dir);
    /// fitted.save(&dir)?;
    /// let LoadedGpr::Double(model) = LoadedGpr::load(&dir, &PersistRegistry::new())? else {
    ///     return Ok(());
    /// };
    /// let mut model = model.with_optimizer(Lbfgs::new());
    /// model.refit()?;
    /// let _ = std::fs::remove_dir_all(&dir);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_optimizer<O2>(self, optimizer: O2) -> FittedGpr<O2, P, K> {
        FittedGpr {
            core: self.core,
            optimizer,
            store: self.store,
            _kernel: PhantomData,
        }
    }

    /// Diagonal jitter the current factor was built with.
    pub(crate) fn factor_jitter(&self) -> f64 {
        self.store.buffers.core().factor_jitter
    }

    /// The state a save writes.
    pub(crate) fn core(&self) -> &GprCore<P, K> {
        &self.core
    }

    pub(crate) fn policies(&self) -> Policies {
        self.core.policies
    }

    /// Returns the distance-cache policy carried from the trainer.
    ///
    /// See the example on [`FittedGpr`].
    pub fn distance_cache_policy(&self) -> crate::DistanceCachePolicy {
        self.core.policies.distance_cache
    }

    /// Returns the Cholesky buffer policy carried from the trainer.
    ///
    /// See the example on [`FittedGpr`].
    pub fn cholesky_buffer(&self) -> crate::CholeskyBuffer {
        self.core.policies.cholesky_buffer
    }

    /// Returns the kernel `exp` used by fit and predict.
    ///
    /// See the example on [`FittedGpr`].
    pub fn math(&self) -> crate::KernelExp {
        self.core.policies.math
    }

    /// Returns the jitter retries used when `K + σn² I` fails to factor.
    ///
    /// See the example on [`FittedGpr`].
    pub fn jitter_policy(&self) -> crate::JitterPolicy {
        self.core.policies.jitter
    }

    pub(crate) fn x_unfitted(&self) -> &dyn UnfittedTransform {
        self.core.x_unfitted.as_ref()
    }

    pub(crate) fn y_unfitted(&self) -> &dyn UnfittedTarget {
        self.core.y_unfitted.as_ref()
    }

    pub(crate) fn x_transform(&self) -> &dyn Transform {
        self.core.x_transform.as_ref()
    }

    pub(crate) fn y_transform(&self) -> &dyn TargetTransform {
        self.core.y_transform.as_ref()
    }

    pub(crate) fn chol_l(&self) -> MatRef<'_, P::Storage> {
        self.store.l()
    }

    pub(crate) fn factor(&self) -> StoredFactor<'_, P::Storage> {
        StoredFactor::Llt(self.chol_l())
    }

    /// Lends the core and the LLT buffers to the fit code.
    pub(crate) fn fit_view(&mut self) -> ExactFit<'_, P, K> {
        ExactFit {
            core: &mut self.core,
            store: &mut self.store,
        }
    }

    /// Predicts `q` into `out` through the model's query buffers.
    pub(crate) fn predict_query_into(
        &mut self,
        q: Query<'_, P::Storage, K::Supply>,
        options: PredictOptions,
        out: &mut Prediction<P::Refine>,
    ) -> Result<(), GprError> {
        let (l, thread_scratch) = self.store.l_and_thread_scratch();
        self.core
            .predict_with_into(StoredFactor::Llt(l), thread_scratch, q, options, out)
    }

    /// Returns the negative log marginal likelihood of the last successful fit.
    ///
    /// Evaluates `½ yᵀ A⁻¹ y + ½ log|A| + (n/2) log(2π)` from the stored
    /// `α` and the Cholesky factor `L` in the workspace, using
    /// `log|A| = 2 Σ log(L_ii)`. `y` is the target after the target
    /// transform.
    ///
    /// # Errors
    ///
    /// The stored factor is already valid, so this returns [`Ok`] and does not return [`GprError`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Gpr, GaussianLikelihood};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let gpr = Gpr::new(kernel, likelihood);
    /// let fitted = gpr.fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0]).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> {
        Ok(self
            .core
            .neg_log_marginal_likelihood(self.factor(), &self.core.factor_alpha))
    }

    /// Returns the concatenated kernel and likelihood parameter count.
    ///
    /// See the example on [`FittedGpr`].
    pub fn num_params(&self) -> usize {
        self.core.num_params()
    }

    /// Writes kernel `θ` then likelihood `θ` into `out`.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if `out` is the wrong length
    /// or a custom leaf rejects the write.
    ///
    /// See the example on [`FittedGpr`].
    pub fn get_params(&self, out: &mut [f64]) -> Result<(), GprError> {
        self.core.get_params(out)
    }

    /// Sets kernel then likelihood `θ` and rebuilds `L` / `α`.
    ///
    /// `params` is kernel parameters followed by the likelihood parameter,
    /// matching [`Self::get_params`]. Transforms and the training data are
    /// not changed. [`Self::kernel`] stays a shared reference; this is the
    /// write path. For a [`KernelSpec`] model, `factor` of [`Gpr<Fixed>`]
    /// on [`Self::into_trainer`] with [`Self::x`] / [`Self::y`] then
    /// rebuilds the same factorization from the stored observations.
    ///
    /// # 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
    /// [`GaussianLikelihood::bounds`]), or [`GprError::CholeskyFailed`] if
    /// `A` cannot be factored. A custom kernel leaf returns its own error.
    /// Kernel and likelihood `θ` are committed together only after `A`
    /// factors. A rejected slice or a Cholesky failure leaves stored `θ`
    /// and `L` / `α` unchanged.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Fixed, GaussianLikelihood, Gpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let mut fitted = Gpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0])
    /// .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)?;
    /// let x = fitted.x().to_vec();
    /// let y = fitted.y().to_vec();
    /// let n = fitted.n();
    /// let d = fitted.d();
    /// let _fitted = fitted
    ///     .into_trainer()
    ///     .with_optimizer(Fixed)
    ///     .factor(&x, n, d, &y)
    ///     .map_err(|(_, e)| e)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_params(&mut self, params: &[f64]) -> Result<(), GprError> {
        self.fit_view().set_params(params)
    }

    #[cfg(test)]
    pub(crate) fn objective(&mut self) -> GprObjective<'_, P, K> {
        GprObjective::new(self.fit_view())
    }

    /// Sets kernel and likelihood `θ`, rebuilds `L` / `α` / `W`, and writes `∂L/∂θ`.
    ///
    /// `params` and `out` are kernel parameters followed by the likelihood
    /// parameter. One Cholesky produces `L` and `α`; `W = ααᵀ - A⁻¹` is
    /// formed from that factor. [`crate::CholeskyBuffer::Retain`] keeps `W` in a dedicated
    /// buffer. [`crate::CholeskyBuffer::Reuse`] writes `W` over `L` and this method
    /// refactors afterwards so [`Self::predict`] still sees `L`. Each
    /// kernel `∂A/∂θ` is written into a buffer the model keeps. The
    /// returned value is the same as [`Self::neg_log_marginal_likelihood`]
    /// after a successful call.
    ///
    /// The training data is the one stored by the fit. Transforms are not
    /// re-fit.
    ///
    /// # 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,
    /// [`GprError::CholeskyFailed`] if `A` cannot be factored, or
    /// [`GprError::UnsupportedKernelOperation`] if the kernel cannot
    /// evaluate its derivatives at this `θ`. Kernel and likelihood `θ` are
    /// committed together only after `A` factors. A rejected slice or a
    /// Cholesky failure leaves stored `θ` unchanged. A Cholesky failure
    /// restores `L` and `α` at the previous `θ` so this
    /// value stays a usable [`FittedGpr`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Gpr, GaussianLikelihood};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let gpr = Gpr::new(kernel, likelihood);
    /// let mut fitted = gpr.fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0]).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> {
        self.fit_view().value_and_gradient_into(params, out)
    }

    /// Writes the analytic NLML Hessian (row-major `p×p`) at `params`.
    ///
    /// `params` is kernel `θ` followed by likelihood `θ`. After a successful
    /// call the stored kernel and likelihood match `params`. [`crate::CholeskyBuffer::Reuse`]
    /// rebuilds `L` before return, matching [`Self::value_and_gradient_into`].
    ///
    /// # Errors
    ///
    /// Returns [`GprError::LengthMismatch`] if `params` is not
    /// [`Self::num_params`] long or `out` is not its square, the parameter
    /// errors of [`Self::set_params`] ([`GprError::InvalidHyperparameter`],
    /// [`GprError::InvalidNoiseVariance`], [`GprError::InvalidInterval`]) if
    /// `params` is rejected, [`GprError::CholeskyFailed`] if `A` cannot be
    /// factored, or [`GprError::UnsupportedKernelOperation`] if the kernel
    /// cannot evaluate its second derivatives at this `θ`. A custom kernel
    /// leaf returns its own error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Gpr, GaussianLikelihood};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let mut fitted = Gpr::new(kernel, likelihood)
    ///     .fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0])
    ///     .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> {
        self.fit_view().hessian_into(params, out)
    }

    /// Returns leave-one-out mean and observation variance at every training point.
    ///
    /// Uses the GPML identities `μ_i = y_i - α_i / Q_ii` and
    /// `σ_i² = 1 / Q_ii` with `Q = A⁻¹` and `A = K + σn² I`. This is
    /// `p(y_i | X, y_{-i}, θ)`, not a query at a new `x*`. Mean and
    /// variance are inverse-transformed like [`Self::predict`].
    ///
    /// # Errors
    ///
    /// Returns [`GprError::NonPositiveDefiniteMatrix`] if a diagonal of `A⁻¹`
    /// is not positive and finite.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Gpr, GaussianLikelihood};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let gpr = Gpr::new(kernel, likelihood);
    /// let fitted = gpr.fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0]).map_err(|(_, e)| e)?;
    /// let loo = fitted.loo_predict()?;
    /// assert_eq!(loo.mean.len(), 2);
    /// # 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.
    ///
    /// Observation variance is `1 / Q_ii`. Latent variance is
    /// `max(0, 1 / Q_ii - σn²)` in the transformed space, then both mean
    /// and variance are mapped back by the target transform.
    ///
    /// # Errors
    ///
    /// Same as [`Self::loo_predict`].
    ///
    /// See the example on [`FittedGpr`].
    pub fn loo_predict_with(
        &self,
        options: PredictOptions,
    ) -> Result<Prediction<P::Refine>, GprError> {
        self.core
            .loo_predict_with(self.factor(), &self.core.alpha, options)
    }
}

impl<O, P: GpScalar, K: ModelKernel> FittedGpr<O, P, K> {
    /// Converts this LLT factorization into an [`OnlineGpr`] for tail inserts.
    ///
    /// A model of supplied distances keeps its training squares; its ARD
    /// slots are packed with room to grow at the first insert.
    ///
    /// Writes `D[j] = L_jj²` and `L_ldlt[i,j] = L_llt[i,j] / L_jj`, then
    /// rebuilds `A = K + σn² I` on the online workspace. [`OnlineGpr::insert`]
    /// updates that LDLT in place.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::EmptyInput`] if `n` is zero, or
    /// [`GprError::CholeskyFailed`] if a diagonal of `L` is not positive.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Fixed, GaussianLikelihood, Gpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let fitted = Gpr::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])
    /// .map_err(|(_, e)| e)?;
    /// let mut online = fitted.into_online()?;
    /// online.insert(&[1.5], 0.5)?;
    /// let pred = online.predict(&[0.5], 1, 1)?;
    /// assert_eq!(pred.mean.len(), 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn into_online(self) -> Result<OnlineGpr<O, P, K>, GprError> {
        let n = self.core.n;
        let mut workspace = LdltStore::from_active(n)?;
        workspace.fill_ld_from_llt(self.chol_l(), n)?;
        workspace.factor_jitter = self.store.buffers.core().factor_jitter;
        LdltStore::set_f64_prefix(&mut workspace.y, &self.core.y_train);
        LdltStore::set_vector_prefix(&mut workspace.alpha, &self.core.factor_alpha);
        Ok(OnlineGpr::from_core(self.core, self.optimizer, workspace))
    }
}

impl<O, P: GpScalar, K: ModelKernel> FittedGpr<O, P, K> {
    /// Writes this fitted model to `dir/config.json` and `dir/model.safetensors`.
    ///
    /// Omits `L` and `α`. [`crate::persist::LoadedGpr::load`] rebuilds them
    /// by factorizing. The Cholesky buffer policy is not written; load
    /// reconstructs [`crate::CholeskyBuffer::Retain`].
    ///
    /// A model of a [`DistanceKernel`] also writes the training `d²` it
    /// owns, each slot's lower triangle: in `f32` for
    /// [`crate::SinglePrecision`], and in `f64` otherwise (a
    /// [`crate::MixedPrecision`] model writes the caller's `f64` values and
    /// casts them again on load). Load it with
    /// [`crate::persist::LoadedDistanceGpr::load`]; see there for its slots.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::PersistFailed`] when the directory cannot be
    /// created or a Custom leaf / caller transform has no persist form.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{GaussianLikelihood, Gpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let fitted = Gpr::new(
    ///     KernelSpec::from(RbfKernel::new(1.0)?),
    ///     GaussianLikelihood::new(0.1)?,
    /// )
    /// .fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0])
    /// .map_err(|(_, e)| e)?;
    /// let dir = std::env::temp_dir().join(format!(
    ///     "gprx-doctest-save-{}",
    ///     std::process::id()
    /// ));
    /// let _ = std::fs::remove_dir_all(&dir);
    /// fitted.save(&dir)?;
    /// let _ = std::fs::remove_dir_all(&dir);
    /// # Ok(())
    /// # }
    /// ```
    pub fn save(&self, dir: impl AsRef<std::path::Path>) -> Result<(), GprError> {
        persist::save_fitted(self, dir.as_ref(), false)
    }

    /// Writes this fitted model including the Cholesky factor `L` and `α`.
    ///
    /// `L` is stored column-major. Its dtype is `F64` when storage is `f64`
    /// and `F32` when storage is `f32`. `α` uses the predict scalar: `F32`
    /// for [`crate::SinglePrecision`], `F64` for [`crate::DoublePrecision`]
    /// and [`crate::MixedPrecision`]. [`crate::persist::LoadedGpr::load`]
    /// keeps an `f64` factor memory-mapped.
    ///
    /// # Errors
    ///
    /// Same as [`Self::save`].
    ///
    /// See the example on [`FittedGpr`].
    pub fn save_with_factor(&self, dir: impl AsRef<std::path::Path>) -> Result<(), GprError> {
        persist::save_fitted(self, dir.as_ref(), true)
    }
}

impl<O, P: GpScalar> FittedGpr<O, P> {
    /// Returns the kernel whose hyperparameters this model owns.
    ///
    /// See the example on [`FittedGpr`].
    pub fn kernel(&self) -> &KernelSpec {
        &self.core.kernel
    }

    /// Predicts at `xs` with [`PredictOptions::default`] (observation variance).
    ///
    /// `xs` is column-major with `n_rows` query points and `n_cols` features.
    /// Allocates query buffers for this call. Reuse [`Self::predict_into`]
    /// after a warmup call for a zero-allocation path.
    ///
    /// # 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`.
    ///
    /// See the example on [`FittedGpr`].
    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())
    }

    /// Writes [`Self::predict`] into `out`, reusing `mean` / `variance` capacity when the query length matches.
    ///
    /// # Errors
    ///
    /// Same as [`Self::predict`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Gpr, GaussianLikelihood, Prediction};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let gpr = Gpr::new(kernel, likelihood);
    /// let mut fitted = gpr.fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0]).map_err(|(_, e)| e)?;
    /// let mut pred = Prediction::default();
    /// fitted.predict_into(&[0.5], 1, 1, &mut pred)?;
    /// assert_eq!(pred.mean.len(), 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.
    ///
    /// Latent variance is `k(x*, x*) - ‖L⁻¹ k_*‖²`. Observation variance adds
    /// `σn²` in the transformed space, then both mean and variance are mapped
    /// back by the target transform.
    ///
    /// # Errors
    ///
    /// Same as [`Self::predict`].
    ///
    /// See the example on [`FittedGpr`].
    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();
        self.core.write_prediction(
            self.factor(),
            &self.core.alpha,
            Query::points(xs, n_rows, n_cols),
            options,
            &mut out,
        )?;
        Ok(out)
    }

    /// Writes [`Self::predict_with`] into `out`, reusing `mean` / `variance` capacity when the query length matches.
    ///
    /// # Errors
    ///
    /// Same as [`Self::predict`].
    ///
    /// See the example on [`FittedGpr`].
    pub fn predict_with_into(
        &mut self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
        out: &mut Prediction<P::Refine>,
    ) -> Result<(), GprError> {
        self.predict_query_into(Query::points(xs, n_rows, n_cols), options, 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
    /// matches [`Self::predict`] for the same query. This path allocates
    /// an `m × m` matrix; the default [`Self::predict`] stays diagonal-only.
    ///
    /// # Errors
    ///
    /// Same as [`Self::predict`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Gpr, GaussianLikelihood};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let gpr = Gpr::new(kernel, likelihood);
    /// let fitted = gpr.fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0]).map_err(|(_, e)| e)?;
    /// let cov = fitted.predict_covariance(&[0.25, 0.75], 2, 1)?;
    /// assert_eq!(cov.mean.len(), 2);
    /// assert_eq!(cov.covariance.len(), 4);
    /// # 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.
    ///
    /// Posterior covariance is `K** − VᵀV` with `V = L⁻¹ K_*`. 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 [`FittedGpr`].
    pub fn predict_covariance_with(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<PredictiveCovariance<P::Refine>, GprError> {
        self.core.write_covariance(
            self.factor(),
            &self.core.alpha,
            Query::points(xs, n_rows, n_cols),
            (),
            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. `seed` is gprx's seeded generator (Xoshiro256++, the same on every platform)
    /// start state. 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 [`crate::JitterPolicy`] retries.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel};
    /// use gprx::{Gpr, GaussianLikelihood};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let kernel = KernelSpec::from(RbfKernel::new(1.0)?);
    /// let likelihood = GaussianLikelihood::new(0.1)?;
    /// let gpr = Gpr::new(kernel, likelihood);
    /// let fitted = gpr.fit(&[0.0, 1.0], 2, 1, &[0.0, 1.0]).map_err(|(_, e)| e)?;
    /// let draws = fitted.sample(&[0.25, 0.75], 2, 1, 4, 1)?;
    /// assert_eq!(draws.len(), 8);
    /// # Ok(())
    /// # }
    /// ```
    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 [`FittedGpr`].
    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.core.sample_with(
            self.factor(),
            &self.core.alpha,
            Query::points(xs, n_rows, n_cols),
            options,
            n_draws,
            seed,
        )
    }
}

impl<O, P: GpScalar, K: PointKernel> FittedGpr<O, P, K> {
    /// Returns the feature dimension from the last successful fit.
    ///
    /// See the example on [`FittedGpr`].
    pub fn d(&self) -> usize {
        self.core.d
    }

    /// Returns the original training features in column-major order.
    ///
    /// Same packing as the `x` passed to `fit` / `factor`: `n` points by
    /// `d` features. Values are on the scale passed to fit, before the input
    /// transform.
    ///
    /// See the example on [`FittedGpr`].
    pub fn x(&self) -> &[f64] {
        &self.core.x_obs
    }
}

impl<O, P: GpScalar, C: PointUse> FittedGpr<O, P, DistanceKernel<C>> {
    /// Returns a copy of the kernel whose hyperparameters this model owns.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{DistanceSlot, RbfKernel, ScalarDistance};
    /// use gprx::{Fixed, GaussianLikelihood, Gpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// let fitted = Gpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
    ///     .with_optimizer(Fixed)
    ///     .factor([image.from_slice(&[0.0, 1.0, 1.0, 0.0])], 2, &[0.0, 1.0])
    ///     .map_err(|(_, e)| e)?;
    /// assert_eq!(fitted.to_kernel().num_params(), 1);
    /// assert_eq!(fitted.slots(), [DistanceSlot::Scalar(image)]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_kernel(&self) -> DistanceKernel<C> {
        <DistanceKernel<C> as ModelKernelParts>::from_spec(self.core.kernel.clone())
    }

    /// Returns the slots of the kernel, in the order of
    /// [`DistanceKernel::slots`]. A model loaded from disk has slots of its
    /// own; bind its supplies to these.
    ///
    /// See the example on [`Self::to_kernel`].
    pub fn slots(&self) -> Vec<DistanceSlot> {
        spec_slots(&self.core.kernel)
    }
}

impl<O, P, K> FittedGpr<O, P, K>
where
    P: GpScalar,
    K: ModelKernel,
    O: for<'a> Optimizer<GprObjective<'a, P, K>>,
{
    /// Re-runs the stored optimizer on the stored training data from the current `θ`.
    ///
    /// This is the same `O` that [`Gpr::with_optimizer`] installed. Transforms
    /// are not re-fit. `n` and `d` stay the same.
    ///
    /// # Errors
    ///
    /// Same as `fit` of the [`Gpr`] of this kernel.
    ///
    /// See the example on [`FittedGpr`].
    pub fn refit(&mut self) -> Result<(), GprError> {
        let mut view = ExactFit {
            core: &mut self.core,
            store: &mut self.store,
        };
        view.optimize(&self.optimizer)
    }
}

impl<P: GpScalar, K: ModelKernel> FittedGpr<Fixed, P, K> {
    /// Rebuilds `L` and `α` at the current `θ` without a search.
    ///
    /// Transforms are not re-fit. `n` and `d` stay the same.
    ///
    /// # Errors
    ///
    /// Same as `factor` of the [`Gpr<Fixed>`] of this kernel.
    ///
    /// See the example on [`FittedGpr`].
    pub fn refit(&mut self) -> Result<(), GprError> {
        self.fit_view().refactor()
    }

    pub(crate) fn into_online_preserving_factor(self) -> Result<OnlineGpr<Fixed, P, K>, GprError> {
        let n = self.core.n;
        let mut workspace = LdltStore::<P::Storage>::from_active(n)?;
        workspace.copy_ld_from(self.chol_l(), n)?;
        workspace.factor_jitter = self.store.buffers.core().factor_jitter;
        LdltStore::set_f64_prefix(&mut workspace.y, &self.core.y_train);
        LdltStore::set_vector_prefix(&mut workspace.alpha, &self.core.factor_alpha);
        Ok(OnlineGpr::from_core(self.core, self.optimizer, workspace))
    }
}

impl<P: GpScalar, K: ModelKernel> FittedGpr<Fixed, P, K> {
    pub(crate) fn from_persisted(mut parts: PersistedModel<P, K>) -> Result<Self, GprError> {
        let n = parts.y_obs.len();
        if n == 0 {
            return Err(GprError::EmptyInput);
        }
        if !parts.x_obs.len().is_multiple_of(n) {
            return Err(persist::persist_err(
                PersistErrorKind::Tensor,
                "persisted x length is not n * d",
            ));
        }
        let d = parts.x_obs.len() / n;
        if let Some(alpha) = &parts.alpha
            && alpha.len() != n
        {
            return Err(persist::persist_err(
                PersistErrorKind::Tensor,
                format!("alpha has {} values, expected n = {n}", alpha.len()),
            ));
        }
        let mut x_buf = parts.x_obs.clone();
        if d > 0 {
            parts.x_transform.apply(&mut x_buf, n, d)?;
        }
        let mut y_buf = parts.y_obs.clone();
        parts.y_transform.transform(&mut y_buf)?;
        // The saved maps are read back, not fitted: a map that sends the
        // data past `f64` is refused here, not later in a factor.
        crate::data::require_finite(&x_buf)?;
        crate::data::require_finite(&y_buf)?;
        let supplied = parts.supplied;
        let compiled = parts.kernel.compile_as::<P::Storage>();
        let mut workspace = fit_buffers::<P, _>(n, parts.policies, &compiled)?;
        workspace.core_mut().factor_jitter = parts.factor_jitter;
        if let Some(l) = parts.owned_l.take() {
            let mut dest = workspace.core_mut().k_matrix.as_mut();
            for col in 0..n {
                for row in 0..n {
                    dest[(row, col)] = l[(row, col)];
                }
            }
        }
        // Without a saved factor the weights are written by the refit below.
        let saved = parts.alpha.is_some();
        let (factor_alpha, alpha) = match parts.alpha {
            Some(alpha) => (
                storage_alpha_from_saved::<P>(workspace.core().k_matrix.as_ref(), &y_buf, &alpha)?,
                alpha,
            ),
            None => (
                vec![P::Storage::from_f64(0.0); n],
                vec![P::Refine::from_f64(0.0); n],
            ),
        };
        let mut model = Self {
            core: GprCore {
                supplied,
                kernel: parts.kernel,
                compiled,
                likelihood: parts.likelihood,
                x_unfitted: parts.x_unfitted,
                y_unfitted: parts.y_unfitted,
                x_transform: parts.x_transform,
                y_transform: parts.y_transform,
                policies: parts.policies,
                query: QueryWorkspace::new(),
                x_obs: parts.x_obs,
                y_obs: parts.y_obs,
                x: pack_points(&x_buf, n, d),
                y_train: y_buf,
                factor_alpha,
                alpha,
                x_cast: P::Storage::empty_cols(),
                y_cast: P::Storage::empty_rows(),
                n,
                d,
            },
            optimizer: Fixed,
            store: LltStore::with_mapped(workspace, parts.mapped),
            _kernel: PhantomData,
        };
        if !saved {
            model.refit()?;
        }
        Ok(model)
    }
}

fn storage_alpha_from_saved<P: GpScalar>(
    l: MatRef<'_, P::Storage>,
    y: &[f64],
    saved: &[P::Refine],
) -> Result<Vec<P::Storage>, GprError> {
    let mixed = P::REFINES_IN_F64;
    if !mixed {
        return Ok(saved
            .iter()
            .map(|weight| P::Storage::from_f64(weight.to_f64()))
            .collect());
    }
    let n = y.len();
    let mut rhs = Mat::<P::Storage>::zeros(n, 1);
    for (i, &yi) in y.iter().enumerate() {
        rhs[(i, 0)] = P::Storage::from_f64(yi);
    }
    let par = faer_par_dims(n, 1);
    let req = llt::solve::solve_in_place_scratch::<P::Storage>(n, 1, par);
    let mut scratch = MemBuffer::new(req);
    solve_llt_in_place(l, rhs.as_mut(), &mut scratch);
    Ok((0..n).map(|i| rhs[(i, 0)]).collect())
}