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
//! Save and load the sparse models ([`FittedSgpr`], [`OnlineSgpr`],
//! [`FittedSvgp`]) in the directory format of the Exact model.
//!
//! `config.json` holds the model kind, the settings, and the fitted
//! transforms; `model.safetensors` holds the original `X`, `y`, and `Z`, the
//! transformed `Z` (a [`crate::FreeInducing`] search moved it in those
//! coordinates, and mapping it back and forth is not exact), and for SVGP the
//! whitened `q(u)`. The factors are not stored: load factors the system
//! again at the saved `θ` and `Z`.

use std::path::Path;

use faer::Mat;

use crate::error::GprError;
use crate::error::PersistErrorKind;
use crate::kernel::{BlockAt, DistanceSlot, ModelKernel, SlotShape, SupplyViews};
use crate::optimizer::Fixed;
use crate::points::{IdRegistry, PointRegistry};
use crate::precision::GpScalar;
use crate::sgpr::{FittedSgpr, FixedInducing, InducingRegistry, OnlineSgpr};
use crate::sparse::{PersistedSparse, SparseCore, SparseSpec, SparseSupplied, SparseSupply};
use crate::svgp::FittedSvgp;
use crate::{PredictOptions, Prediction};

use super::config::{
    DistanceJson, JitterJson, LikelihoodJson, MathJson, ModelJson, PointsJson, PrecisionJson,
    ResidualJson, SparseConfig, SparseDistanceJson, d2_tensor, parse_sparse_config,
};
use super::kernel::KernelJson;
use super::tensors::{TensorFile, f64_tensor, read_f64, write_f64_tensors};
use super::transform::{
    encode_fitted_input, encode_fitted_target, encode_unfitted_input, encode_unfitted_target,
};
use super::{FORMAT_VERSION, PersistRegistry, decode_kernel, persist_err, widen};
use safetensors::SafeTensors;

const TENSOR_X: &str = "x";
const TENSOR_Y: &str = "y";
const TENSOR_Z: &str = "z";
const TENSOR_Z_TRAIN: &str = "z_train";
const TENSOR_Q_MEAN: &str = "q_mean";
const TENSOR_Q_L: &str = "q_l";

/// Identifiers of an online model, written only for [`ModelJson::OnlineSgpr`].
struct OnlineIds {
    points: Vec<u64>,
    next_point: u64,
    inducing: Vec<u64>,
    next_inducing: u64,
}

/// Each slot's `n × m` training blocks, as tensor `d2.<k>` for slot `k`:
/// `[n, m]` for a scalar slot, `[dims, n, m]` for an ARD slot, each block
/// column-major.
fn supply_tensors(
    supply: &SparseSupply,
    slots: &[DistanceSlot],
    (n, m): (usize, usize),
) -> Vec<(String, Vec<usize>, Vec<f64>)> {
    let xz = &supply.exact().xz;
    slots
        .iter()
        .enumerate()
        .map(|(k, slot)| {
            let blocks = slot.shape().blocks();
            let mut values = Vec::with_capacity(n.saturating_mul(m).saturating_mul(blocks));
            let at = crate::kernel::place_in_shape(slots, k);
            let shape = match slot.shape() {
                SlotShape::Scalar => {
                    xz.block_into(BlockAt::Scalar(at), &mut values);
                    vec![n, m]
                }
                SlotShape::Ard(dims) => {
                    for dim in 0..dims {
                        xz.block_into(BlockAt::Ard(at, dim), &mut values);
                    }
                    vec![dims, n, m]
                }
            };
            (d2_tensor(k), shape, values)
        })
        .collect()
}

fn write_sparse<P: GpScalar, K: ModelKernel>(
    dir: &Path,
    core: &SparseCore<K::Supply>,
    model: ModelJson,
    ids: Option<OnlineIds>,
    q: Option<(&[f64], faer::MatRef<'_, f64>)>,
) -> Result<(), GprError> {
    std::fs::create_dir_all(dir)
        .map_err(|err| persist_err(PersistErrorKind::Io, format!("create {dir:?}: {err}")))?;
    let kind = P::persist_kind();
    let (point_ids, next_point_id, inducing_ids, next_inducing_id) = match ids {
        Some(ids) => (
            Some(ids.points),
            Some(ids.next_point),
            Some(ids.inducing),
            Some(ids.next_inducing),
        ),
        None => (None, None, None, None),
    };
    let slots = core.slots();
    let config = SparseConfig {
        format_version: FORMAT_VERSION,
        model,
        n: core.n,
        m: core.m,
        d: core.d,
        precision: PrecisionJson::from_persist(kind),
        residual: ResidualJson::from_persist(kind),
        math: MathJson::encode(core.math),
        kernel: KernelJson::encode(&core.kernel, slots)?,
        likelihood: LikelihoodJson::encode(&core.likelihood),
        jitter: JitterJson::encode(core.jitter),
        x_unfitted: encode_unfitted_input(core.x_unfitted.as_ref())?,
        y_unfitted: encode_unfitted_target(core.y_unfitted.as_ref())?,
        x_transform: encode_fitted_input(core.x_transform.as_ref())?,
        y_transform: encode_fitted_target(core.y_transform.as_ref())?,
        point_ids,
        next_point_id,
        inducing_ids,
        next_inducing_id,
        // A model on supplied distances, even one with no slot, writes
        // its table and inducing indices; a coordinate model has none.
        distance: core.supply().map(|supply| SparseDistanceJson {
            table: DistanceJson::encode(PointsJson::of::<K>(), slots),
            inducing: supply.inducing.clone(),
        }),
    };
    let json = serde_json::to_vec_pretty(&config).map_err(|err| {
        persist_err(
            PersistErrorKind::Config,
            format!("serialize config.json: {err}"),
        )
    })?;
    let (n, m, d) = (core.n, core.m, core.d);
    let mut tensors: Vec<(&str, Vec<usize>, &[f64])> = vec![
        (TENSOR_X, vec![n, d], &core.x_obs),
        (TENSOR_Y, vec![n], &core.y_obs),
        (TENSOR_Z, vec![m, d], &core.z_obs),
        (TENSOR_Z_TRAIN, vec![m, d], &core.z_train),
    ];
    let q_l_values: Vec<f64>;
    if let Some((q_mean, q_l)) = q {
        q_l_values = (0..m)
            .flat_map(|col| (0..m).map(move |row| (row, col)))
            .map(|(row, col)| if row < col { 0.0 } else { q_l[(row, col)] })
            .collect();
        tensors.push((TENSOR_Q_MEAN, vec![m], q_mean));
        tensors.push((TENSOR_Q_L, vec![m, m], &q_l_values));
    }
    let d2 = core
        .supply()
        .map_or_else(Vec::new, |supply| supply_tensors(supply, slots, (n, m)));
    for (name, shape, values) in &d2 {
        tensors.push((name.as_str(), shape.clone(), values));
    }
    write_f64_tensors(dir, &tensors, Vec::new())?;
    super::write_config(dir, &json)
}

pub(crate) fn save_sgpr<O, I, P, K>(
    model: &FittedSgpr<O, I, P, K>,
    dir: &Path,
) -> Result<(), GprError>
where
    I: crate::sgpr::InducingLayout<K::Supply>,
    P: GpScalar,
    K: ModelKernel,
{
    write_sparse::<P, K>(dir, model.core(), ModelJson::Sgpr, None, None)
}

pub(crate) fn save_online_sgpr<O, P: GpScalar, K: ModelKernel>(
    model: &OnlineSgpr<O, P, K>,
    dir: &Path,
) -> Result<(), GprError> {
    let ids = OnlineIds {
        points: model.point_registry().raw_ids(),
        next_point: model.point_registry().next_id(),
        inducing: model.inducing_registry().raw_ids(),
        next_inducing: model.inducing_registry().next_id(),
    };
    write_sparse::<P, K>(dir, model.core(), ModelJson::OnlineSgpr, Some(ids), None)
}

pub(crate) fn save_svgp<P: GpScalar, K: ModelKernel>(
    model: &FittedSvgp<P, K>,
    dir: &Path,
) -> Result<(), GprError> {
    write_sparse::<P, K>(dir, model.core(), ModelJson::Svgp, None, Some(model.q()))
}

pub(super) fn read_config(
    dir: &Path,
    expected: &[ModelJson],
    points: Option<PointsJson>,
) -> Result<SparseConfig, GprError> {
    let bytes = super::read_model_bytes(dir, expected, points)?;
    parse_sparse_config(&bytes)
}

/// The core of a sparse persist directory, with the fitted transforms
/// read back from the config, and for a kernel on supplied distances its
/// training blocks bound to new slots, checked as a fit checks them and cast
/// for the storage scalar `S`.
fn read_core<S: crate::kernel::KernelScalar, K: ModelKernel>(
    tensors: &SafeTensors<'_>,
    config: &SparseConfig,
    registry: &PersistRegistry,
) -> Result<SparseCore<K::Supply>, GprError> {
    let (n, m, d) = (config.n, config.m, config.d);
    let table = config.distance.as_ref().map(|distance| &distance.table);
    let (kernel, slots) = decode_kernel::<K>(&config.kernel, table, registry)?;
    let spec = SparseSpec {
        kernel,
        likelihood: config.likelihood.decode()?,
        math: config.math.decode(),
        jitter: config.jitter.decode()?,
        x_transform: config.x_unfitted.clone().decode(registry)?,
        y_transform: config.y_unfitted.clone().decode(registry)?,
    };
    // `decode_kernel` makes slots only from the config's distance part.
    let supplied = <K::Supply as SupplyViews>::try_hold(|| {
        let distance = config.distance.as_ref().ok_or_else(|| {
            persist_err(
                PersistErrorKind::Config,
                "the config of a model on supplied distances has no `distance`",
            )
        })?;
        let supply = read_supply::<S>(tensors, config, &slots, &distance.inducing)?;
        Ok::<_, GprError>(SparseSupplied { supply, slots })
    })?;
    let core = SparseCore::from_persisted(PersistedSparse {
        spec,
        x_transform: config.x_transform.clone().decode(registry)?,
        y_transform: config.y_transform.clone().decode(registry)?,
        x_obs: read_f64(tensors, TENSOR_X, &[n, d])?,
        y_obs: read_f64(tensors, TENSOR_Y, &[n])?,
        z_obs: read_f64(tensors, TENSOR_Z, &[m, d])?,
        z_train: read_f64(tensors, TENSOR_Z_TRAIN, &[m, d])?,
        n,
        m,
        d,
        supplied,
    })?;
    // The coordinate leaves and the supplied blocks read the same points.
    if let Some(supply) = core.supply() {
        let inducing = &supply.inducing;
        same_rows(&core.z_obs, &core.x_obs, (n, d), inducing, TENSOR_Z)?;
        same_rows(
            &core.z_train,
            &core.x_train,
            (n, d),
            inducing,
            TENSOR_Z_TRAIN,
        )?;
    }
    Ok(core)
}

/// Checks that the `m × d` inducing points `z` of a model on supplied
/// distances are the rows `inducing` of the `n × d` training points `x`, to
/// the bit, as a fit makes them: the coordinate leaves and the supplied
/// blocks read the same points.
///
/// # Errors
///
/// Returns [`GprError::PersistFailed`] with
/// [`crate::PersistErrorKind::Config`] at the first value that differs.
fn same_rows(
    z: &[f64],
    x: &[f64],
    (n, d): (usize, usize),
    inducing: &[usize],
    name: &str,
) -> Result<(), GprError> {
    let m = inducing.len();
    for j in 0..d {
        for (a, &i) in inducing.iter().enumerate() {
            if z[j * m + a].to_bits() != x[j * n + i].to_bits() {
                return Err(persist_err(
                    PersistErrorKind::Config,
                    format!(
                        "{name} row {a} is not training point {i}, the inducing point the blocks name"
                    ),
                ));
            }
        }
    }
    Ok(())
}

/// The tensors of `dir`: mapped when the model holds supplied blocks, so
/// each block is copied once, from the map into its store; read otherwise.
fn open_tensors(dir: &Path, config: &SparseConfig) -> Result<TensorFile, GprError> {
    if config.distance.is_some() {
        TensorFile::map(dir)
    } else {
        TensorFile::read(dir)
    }
}

/// A slot's saved blocks, borrowed from the file's map.
enum SavedBlocks<'a> {
    Scalar(crate::kernel::ScalarDistance, &'a [f64]),
    Ard(crate::kernel::ArdDistance, Vec<&'a [f64]>),
}

/// The training blocks of `slots` (tensors `d2.<k>`) at the training
/// points `inducing`, bound as a fit binds its sources
/// ([`crate::kernel::bind_inducing`]): the same checks of the indices (`m`
/// of them, each below `n`, none twice) and of the values, and the squares
/// among the inducing points formed again from the blocks.
fn read_supply<S: crate::kernel::KernelScalar>(
    tensors: &SafeTensors<'_>,
    config: &SparseConfig,
    slots: &[DistanceSlot],
    inducing: &[usize],
) -> Result<SparseSupply, GprError> {
    let (n, m) = (config.n, config.m);
    if inducing.len() != m {
        return Err(persist_err(
            PersistErrorKind::Config,
            format!(
                "config has {} inducing indices, expected m = {m}",
                inducing.len()
            ),
        ));
    }
    let len = n.checked_mul(m).ok_or(GprError::SizeOverflow)?;
    // Each slot's tensor, borrowed from the map, an ARD one as its `dims`
    // blocks: the bind copies them into the store, the one copy a load makes.
    let tables = slots
        .iter()
        .enumerate()
        .map(|(k, slot)| {
            let name = d2_tensor(k);
            Ok(match slot {
                DistanceSlot::Ard(ard) => SavedBlocks::Ard(
                    *ard,
                    f64_tensor(tensors, &name, &[ard.dims(), n, m])?
                        .chunks_exact(len.max(1))
                        .collect(),
                ),
                DistanceSlot::Scalar(scalar) => {
                    SavedBlocks::Scalar(*scalar, f64_tensor(tensors, &name, &[n, m])?)
                }
            })
        })
        .collect::<Result<Vec<_>, GprError>>()?;
    let sources = tables.iter().map(|table| match table {
        SavedBlocks::Ard(ard, blocks) => ard.borrow(blocks),
        SavedBlocks::Scalar(scalar, block) => scalar.borrow(block),
    });
    SparseSupply::bind::<S>(slots, sources, n, inducing)
}

/// The saved online identifiers.
fn read_ids(config: &SparseConfig) -> Result<(PointRegistry, InducingRegistry), GprError> {
    let missing = |key: &str| {
        persist_err(
            PersistErrorKind::Config,
            format!("online_sgpr config missing {key}"),
        )
    };
    let points = IdRegistry::from_persisted(
        config
            .point_ids
            .as_deref()
            .ok_or_else(|| missing("point_ids"))?,
        config
            .next_point_id
            .ok_or_else(|| missing("next_point_id"))?,
    )?;
    let inducing = IdRegistry::from_persisted(
        config
            .inducing_ids
            .as_deref()
            .ok_or_else(|| missing("inducing_ids"))?,
        config
            .next_inducing_id
            .ok_or_else(|| missing("next_inducing_id"))?,
    )?;
    Ok((points, inducing))
}

/// The saved whitened `q(u)`: a finite mean and a lower `L` with a positive
/// diagonal.
fn read_q(tensors: &SafeTensors<'_>, m: usize) -> Result<(Vec<f64>, Mat<f64>), GprError> {
    let q_mean = read_f64(tensors, TENSOR_Q_MEAN, &[m])?;
    let values = read_f64(tensors, TENSOR_Q_L, &[m, m])?;
    let q_l = Mat::from_fn(m, m, |row, col| values[col * m + row]);
    let finite = q_mean.iter().chain(&values).all(|value| value.is_finite());
    let lower = (0..m).all(|col| (0..col).all(|row| q_l[(row, col)] == 0.0));
    let positive = (0..m).all(|i| q_l[(i, i)] > 0.0);
    if !(finite && lower && positive) {
        return Err(persist_err(
            PersistErrorKind::Tensor,
            "q_l must be lower triangular with a positive diagonal, and q finite",
        ));
    }
    Ok((q_mean, q_l))
}

/// Represents the prediction-only sparse GPR loaded from a persist directory written by the `save` of a coordinate [`FittedSgpr`] or [`OnlineSgpr`].
///
/// One variant per precision and model, as [`super::LoadedGpr`]. The kernel,
/// likelihood, kernel `exp`, `K_mm` jitter policy, and transforms are read
/// back; the VFE system is factored again at the saved `θ` and `Z`. The
/// optimizer is [`Fixed`] and the inducing points are [`FixedInducing`]:
/// the file does not store the search. [`Self::predict`],
/// [`Self::predict_with`], [`Self::n`], [`Self::m`], [`Self::d`], and
/// [`Self::is_online`] work on any variant.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{KernelSpec, RbfKernel};
/// use gprx::persist::{LoadedSgpr, PersistRegistry};
/// use gprx::{Fixed, GaussianLikelihood, PredictOptions, Sgpr, VarianceKind};
///
/// /// Names the precision (and factor kind) a load picked.
/// fn describe(model: &LoadedSgpr) -> &'static str {
///     match model {
///         LoadedSgpr::Double(_) => "f64",
///         LoadedSgpr::Single(_) => "f32",
///         LoadedSgpr::Mixed(_) => "mixed",
///         LoadedSgpr::Reevaluate(_) => "mixed, reevaluated",
///         LoadedSgpr::OnlineDouble(_) => "online f64",
///         LoadedSgpr::OnlineSingle(_) => "online f32",
///         LoadedSgpr::OnlineMixed(_) => "online mixed",
///         LoadedSgpr::OnlineReevaluate(_) => "online mixed, reevaluated",
///         _ => "a variant added later",
///     }
/// }
///
/// # 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 dir = std::env::temp_dir().join(format!("gprx-doctest-sgpr-{}", std::process::id()));
/// let _ = std::fs::remove_dir_all(&dir);
/// fitted.save(&dir)?;
/// let loaded = LoadedSgpr::load(&dir, &PersistRegistry::new())?;
/// // Three training points, two inducing points, one feature.
/// assert_eq!((loaded.n(), loaded.m(), loaded.d()), (3, 2, 1));
/// assert!(!loaded.is_online());
/// assert_eq!(describe(&loaded), "f64");
/// assert_eq!(loaded.predict(&[0.5], 1, 1)?, fitted.predict(&[0.5], 1, 1)?);
/// let latent = PredictOptions { variance_kind: VarianceKind::Latent };
/// assert_eq!(
///     loaded.predict_with(&[0.5], 1, 1, latent)?,
///     fitted.predict_with(&[0.5], 1, 1, latent)?,
/// );
/// let _ = std::fs::remove_dir_all(&dir);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum LoadedSgpr {
    /// Marks a [`crate::DoublePrecision`] model.
    ///
    /// See the example on [`LoadedSgpr`].
    Double(FittedSgpr<Fixed>),
    /// Marks a [`crate::SinglePrecision`] model.
    ///
    /// See the example on [`LoadedSgpr`].
    Single(FittedSgpr<Fixed, FixedInducing, crate::SinglePrecision>),
    /// Marks a promoted-storage [`crate::MixedPrecision`] model.
    ///
    /// See the example on [`LoadedSgpr`].
    Mixed(FittedSgpr<Fixed, FixedInducing, crate::MixedPrecision>),
    /// Marks a [`crate::MixedPrecision`]`<`[`crate::ReevaluateKernel`]`>` model.
    ///
    /// See the example on [`LoadedSgpr`].
    Reevaluate(FittedSgpr<Fixed, FixedInducing, crate::MixedPrecision<crate::ReevaluateKernel>>),
    /// Marks a [`crate::DoublePrecision`] online model.
    ///
    /// See the example on [`LoadedSgpr`].
    OnlineDouble(OnlineSgpr<Fixed>),
    /// Marks a [`crate::SinglePrecision`] online model.
    ///
    /// See the example on [`LoadedSgpr`].
    OnlineSingle(OnlineSgpr<Fixed, crate::SinglePrecision>),
    /// Marks a promoted-storage [`crate::MixedPrecision`] online model.
    ///
    /// See the example on [`LoadedSgpr`].
    OnlineMixed(OnlineSgpr<Fixed, crate::MixedPrecision>),
    /// Marks a [`crate::MixedPrecision`]`<`[`crate::ReevaluateKernel`]`>` online model.
    ///
    /// See the example on [`LoadedSgpr`].
    OnlineReevaluate(OnlineSgpr<Fixed, crate::MixedPrecision<crate::ReevaluateKernel>>),
}

/// The variants of a loaded SGPR enum `L` that hold precision `P` and
/// kernel `K`.
pub(super) struct SgprVariants<P: GpScalar, K: ModelKernel, L> {
    pub(super) fitted: fn(FittedSgpr<Fixed, FixedInducing, P, K>) -> L,
    pub(super) online: fn(OnlineSgpr<Fixed, P, K>) -> L,
}

pub(super) fn load_sgpr_as<P: GpScalar, K: ModelKernel, L>(
    dir: &Path,
    config: &SparseConfig,
    registry: &PersistRegistry,
    variants: SgprVariants<P, K, L>,
) -> Result<L, GprError> {
    let fitted =
        FittedSgpr::<Fixed, FixedInducing, P, K>::from_persisted(read_core::<P::Storage, K>(
            &open_tensors(dir, config)?.tensors()?,
            config,
            registry,
        )?)?;
    if config.model == ModelJson::OnlineSgpr {
        let (points, inducing) = read_ids(config)?;
        Ok((variants.online)(OnlineSgpr::from_persisted(
            fitted, points, inducing,
        )?))
    } else {
        Ok((variants.fitted)(fitted))
    }
}

impl LoadedSgpr {
    /// Reads `dir/config.json` and `dir/model.safetensors` written by the `save` of a coordinate [`FittedSgpr`] (loads a [`FittedSgpr`] variant) or [`OnlineSgpr`] (loads an [`OnlineSgpr`] variant with the saved identifiers).
    ///
    /// # Errors
    ///
    /// Returns [`GprError::UnsupportedPersistVersion`] when `format_version`
    /// is not [`FORMAT_VERSION`], or [`GprError::PersistFailed`] when the
    /// directory holds another model, or its JSON, tensors, or registry
    /// lookup is invalid, and [`GprError::NonFiniteInput`] when the saved
    /// maps send the training data past `f64`. Factorization errors use the
    /// same variants as the `factor` of a coordinate [`crate::Sgpr`] with
    /// [`Fixed`].
    ///
    /// See the example on [`LoadedSgpr`].
    pub fn load(dir: impl AsRef<Path>, registry: &PersistRegistry) -> Result<Self, GprError> {
        let dir = dir.as_ref();
        let config = read_config(dir, &[ModelJson::Sgpr, ModelJson::OnlineSgpr], None)?;
        by_precision!(config.persist_kind(), Self, |fitted, online| {
            load_sgpr_as(dir, &config, registry, SgprVariants { fitted, online })
        })
    }

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

    /// Returns the number of inducing points.
    ///
    /// See the example on [`LoadedSgpr`].
    pub fn m(&self) -> usize {
        self.view().core().m
    }

    /// Returns the number of input features.
    ///
    /// See the example on [`LoadedSgpr`].
    pub fn d(&self) -> usize {
        self.view().core().d
    }

    /// Returns `true` for an [`OnlineSgpr`] variant.
    ///
    /// See the example on [`LoadedSgpr`].
    pub fn is_online(&self) -> bool {
        matches!(
            self,
            Self::OnlineDouble(_)
                | Self::OnlineSingle(_)
                | Self::OnlineMixed(_)
                | Self::OnlineReevaluate(_)
        )
    }

    /// Returns the predictive mean and observation variance at `xs`, in `f64` whatever the stored precision.
    ///
    /// # Errors
    ///
    /// Same as the `predict` of a coordinate [`FittedSgpr`].
    ///
    /// See the example on [`LoadedSgpr`].
    pub fn predict(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
    ) -> Result<Prediction<f64>, GprError> {
        self.predict_with(xs, n_rows, n_cols, PredictOptions::default())
    }

    /// Returns the predictive mean and variance at `xs`, with the variance kind of `options`.
    ///
    /// # Errors
    ///
    /// Same as the `predict_with` of a coordinate [`FittedSgpr`].
    ///
    /// See the example on [`LoadedSgpr`].
    pub fn predict_with(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<Prediction<f64>, GprError> {
        self.view().predict_f64(xs, n_rows, n_cols, options)
    }

    /// The one place that tells the variants apart.
    fn view(&self) -> &dyn SparseView {
        match self {
            Self::Double(model) => model,
            Self::Single(model) => model,
            Self::Mixed(model) => model,
            Self::Reevaluate(model) => model,
            Self::OnlineDouble(model) => model,
            Self::OnlineSingle(model) => model,
            Self::OnlineMixed(model) => model,
            Self::OnlineReevaluate(model) => model,
        }
    }
}

/// Represents the prediction-only SVGP loaded from a persist directory written by the `save` of a coordinate [`FittedSvgp`].
///
/// One variant per precision, as [`super::LoadedGpr`]. `K_mm` and `A` are
/// factored again at the saved `θ` and `Z`, with the saved `q(u)`.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::{KernelSpec, RbfKernel};
/// use gprx::persist::{LoadedSvgp, PersistRegistry};
/// use gprx::{GaussianLikelihood, PredictOptions, Svgp, VarianceKind};
///
/// /// Names the precision (and factor kind) a load picked.
/// fn describe(model: &LoadedSvgp) -> &'static str {
///     match model {
///         LoadedSvgp::Double(_) => "f64",
///         LoadedSvgp::Single(_) => "f32",
///         LoadedSvgp::Mixed(_) => "mixed",
///         LoadedSvgp::Reevaluate(_) => "mixed, reevaluated",
///         _ => "a variant added later",
///     }
/// }
///
/// # 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 dir = std::env::temp_dir().join(format!("gprx-doctest-svgp-{}", std::process::id()));
/// let _ = std::fs::remove_dir_all(&dir);
/// fitted.save(&dir)?;
/// let loaded = LoadedSvgp::load(&dir, &PersistRegistry::new())?;
/// // Three training points, two inducing points, one feature.
/// assert_eq!((loaded.n(), loaded.m(), loaded.d()), (3, 2, 1));
/// assert_eq!(describe(&loaded), "f64");
/// assert_eq!(loaded.predict(&[0.5], 1, 1)?, fitted.predict(&[0.5], 1, 1)?);
/// let latent = PredictOptions { variance_kind: VarianceKind::Latent };
/// assert_eq!(
///     loaded.predict_with(&[0.5], 1, 1, latent)?,
///     fitted.predict_with(&[0.5], 1, 1, latent)?,
/// );
/// let _ = std::fs::remove_dir_all(&dir);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum LoadedSvgp {
    /// Marks a [`crate::DoublePrecision`] model.
    ///
    /// See the example on [`LoadedSvgp`].
    Double(FittedSvgp),
    /// Marks a [`crate::SinglePrecision`] model.
    ///
    /// See the example on [`LoadedSvgp`].
    Single(FittedSvgp<crate::SinglePrecision>),
    /// Marks a promoted-storage [`crate::MixedPrecision`] model.
    ///
    /// See the example on [`LoadedSvgp`].
    Mixed(FittedSvgp<crate::MixedPrecision>),
    /// Marks a [`crate::MixedPrecision`]`<`[`crate::ReevaluateKernel`]`>` model.
    ///
    /// See the example on [`LoadedSvgp`].
    Reevaluate(FittedSvgp<crate::MixedPrecision<crate::ReevaluateKernel>>),
}

pub(super) fn load_svgp_as<P: GpScalar, K: ModelKernel, L>(
    dir: &Path,
    config: &SparseConfig,
    registry: &PersistRegistry,
    variant: fn(FittedSvgp<P, K>) -> L,
) -> Result<L, GprError> {
    let file = open_tensors(dir, config)?;
    let tensors = file.tensors()?;
    let core = read_core::<P::Storage, K>(&tensors, config, registry)?;
    let (q_mean, q_l) = read_q(&tensors, config.m)?;
    Ok(variant(FittedSvgp::from_persisted(core, q_mean, q_l)?))
}

impl LoadedSvgp {
    /// Reads `dir/config.json` and `dir/model.safetensors` written by the `save` of a coordinate [`FittedSvgp`].
    ///
    /// # Errors
    ///
    /// Same as [`LoadedSgpr::load`], plus [`GprError::PersistFailed`] when the
    /// saved `q(u)` is not finite or its `L` is not lower triangular with a
    /// positive diagonal.
    ///
    /// See the example on [`LoadedSvgp`].
    pub fn load(dir: impl AsRef<Path>, registry: &PersistRegistry) -> Result<Self, GprError> {
        let dir = dir.as_ref();
        let config = read_config(dir, &[ModelJson::Svgp], None)?;
        by_precision!(config.persist_kind(), Self, |fitted| {
            load_svgp_as(dir, &config, registry, fitted)
        })
    }

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

    /// Returns the number of inducing points.
    ///
    /// See the example on [`LoadedSvgp`].
    pub fn m(&self) -> usize {
        self.view().core().m
    }

    /// Returns the number of input features.
    ///
    /// See the example on [`LoadedSvgp`].
    pub fn d(&self) -> usize {
        self.view().core().d
    }

    /// Returns the predictive mean and observation variance at `xs`, in `f64` whatever the stored precision.
    ///
    /// # Errors
    ///
    /// Same as the `predict` of a coordinate [`FittedSvgp`].
    ///
    /// See the example on [`LoadedSvgp`].
    pub fn predict(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
    ) -> Result<Prediction<f64>, GprError> {
        self.predict_with(xs, n_rows, n_cols, PredictOptions::default())
    }

    /// Returns the predictive mean and variance at `xs`, with the variance kind of `options`.
    ///
    /// # Errors
    ///
    /// Same as the `predict_with` of a coordinate [`FittedSvgp`].
    ///
    /// See the example on [`LoadedSvgp`].
    pub fn predict_with(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<Prediction<f64>, GprError> {
        self.view().predict_f64(xs, n_rows, n_cols, options)
    }

    fn view(&self) -> &dyn SparseView {
        match self {
            Self::Double(model) => model,
            Self::Single(model) => model,
            Self::Mixed(model) => model,
            Self::Reevaluate(model) => model,
        }
    }
}

/// Reads of a loaded sparse model that do not depend on its precision.
trait SparseView {
    fn core(&self) -> &SparseCore;
    fn predict_f64(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<Prediction<f64>, GprError>;
}

impl<P: GpScalar> SparseView for FittedSgpr<Fixed, FixedInducing, P> {
    fn core(&self) -> &SparseCore {
        FittedSgpr::core(self)
    }

    fn predict_f64(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<Prediction<f64>, GprError> {
        self.predict_with(xs, n_rows, n_cols, options).map(widen)
    }
}

impl<P: GpScalar> SparseView for OnlineSgpr<Fixed, P> {
    fn core(&self) -> &SparseCore {
        OnlineSgpr::core(self)
    }

    fn predict_f64(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<Prediction<f64>, GprError> {
        self.predict_with(xs, n_rows, n_cols, options).map(widen)
    }
}

impl<P: GpScalar> SparseView for FittedSvgp<P> {
    fn core(&self) -> &SparseCore {
        FittedSvgp::core(self)
    }

    fn predict_f64(
        &self,
        xs: &[f64],
        n_rows: usize,
        n_cols: usize,
        options: PredictOptions,
    ) -> Result<Prediction<f64>, GprError> {
        self.predict_with(xs, n_rows, n_cols, options).map(widen)
    }
}