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
//! Sparse VFE on supplied squared distances: the `fit`, `factor`, and
//! predict of [`Sgpr`] and [`FittedSgpr`] for a [`DistanceKernel`].
//!
//! The inducing points are training points, named by their indices. A
//! model takes, per slot, the `n × m` block from the `n` training points to
//! the `m` inducing points; `K_mm` reads the inducing points' rows of it.
//! A prediction takes the `m × q` block from the inducing points to the
//! `q` queries, and a covariance the `q × q` square among the queries. The
//! inducing points are not searched: [`crate::FreeInducing`] needs
//! coordinates to move.

use crate::error::GprError;
use crate::kernel::{
    DistanceKernel, DistanceOnly, DistanceSlot, DistanceSource, PointUse, SuppliedSpec, WithPoints,
};
use crate::optimizer::{Fixed, Optimizer};
use crate::policy::{JitterPolicy, with_kernel_exp};
use crate::precision::GpScalar;
use crate::prediction::{DistanceQuery, QueryPoints, distance_predict};
use crate::sparse::{PredictScratch, SparseCore};
use crate::{PredictOptions, Prediction, PredictiveCovariance};

use super::factor::{VfeSystem, assemble_fitted, predict_vfe_covariance, predict_vfe_into};
use super::{FittedSgpr, FixedInducing, InducingLayout, OnlineSgpr, Sgpr, SgprObjective};

/// A fitted SGPR on supplied distances, or the trainer `S` back with the
/// error.
type Fitted<O, P, C, S> = Result<FittedSgpr<O, FixedInducing, P, DistanceKernel<C>>, (S, GprError)>;

impl<O: Clone, P: GpScalar, C: PointUse> Sgpr<O, FixedInducing, P, DistanceKernel<C>> {
    /// The model factored at the current `θ`: the shared part of `fit` and
    /// `factor`.
    #[allow(clippy::result_large_err)] // failure returns the trainer so the caller can retry
    fn factor_supplied<'s>(
        self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        n: usize,
        points: (&[f64], usize),
        y: &[f64],
        inducing: &[usize],
    ) -> Fitted<O, P, C, Self> {
        let core = match SparseCore::prepare_supplied::<P::Storage>(
            &self.spec, sources, n, points, y, inducing,
        ) {
            Ok(core) => core,
            Err(err) => return Err((self, err)),
        };
        match with_kernel_exp!(self.spec.math, M => assemble_fitted::<_, _, M, _, DistanceKernel<C>>(
            core,
            self.optimizer.clone(),
        )) {
            Ok(fitted) => Ok(fitted),
            Err(err) => Err((self, err)),
        }
    }

    /// [`Self::factor_supplied`], then the search of `θ` with `O`.
    #[allow(clippy::result_large_err)] // failure returns the trainer so the caller can retry
    fn fit_supplied<'s>(
        self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        n: usize,
        points: (&[f64], usize),
        y: &[f64],
        inducing: &[usize],
    ) -> Fitted<O, P, C, Self>
    where
        O: for<'a> Optimizer<SgprObjective<'a, O, FixedInducing, P, DistanceKernel<C>>>,
    {
        let mut fitted = self.factor_supplied(sources, n, points, y, inducing)?;
        match fitted.optimize_hyperparameters() {
            Ok(()) => Ok(fitted),
            Err(err) => Err((fitted.into_trainer(), err)),
        }
    }
}

impl<O, P> Sgpr<O, FixedInducing, P, DistanceKernel<DistanceOnly>>
where
    P: GpScalar,
    O: Clone + for<'a> Optimizer<SgprObjective<'a, O, FixedInducing, P, DistanceKernel>>,
{
    /// Factors the VFE system on the supplied distances and searches kernel
    /// and likelihood `θ`.
    ///
    /// `sources` holds one source per slot of the kernel, in any order: the
    /// `n × m` squared distances from the `n` training samples to the `m`
    /// inducing points. The inducing points are the training samples
    /// `inducing`, in that order: column `a` of a block is the training
    /// sample `inducing[a]`, and `K_mm` reads their rows of it. The model
    /// keeps the blocks. `y` has `n` targets.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::EmptyInput`] if `n` or `inducing` is empty,
    /// [`GprError::IndexOutOfRange`] for an inducing index not below `n`,
    /// [`GprError::InvalidConfig`] for an inducing index listed twice,
    /// [`GprError::LengthMismatch`] if a table or `y` has the wrong length,
    /// [`GprError::DistanceSlot`] if a source names a slot the kernel does
    /// not read, two name one slot, or a slot has none,
    /// [`GprError::InvalidDistance`] for a value that is not
    /// finite or is negative, or for inducing rows that are not a square
    /// with a zero diagonal and equal mirror entries (see
    /// [`crate::kernel::DistanceSource::tidy`]), [`GprError::NonFiniteInput`]
    /// if a target is `NaN` or `Inf`, [`GprError::CholeskyFailed`] when
    /// `K_mm` or the VFE `B` matrix cannot be factored, or
    /// [`GprError::OptimizationNotConverged`] when the solver stops without
    /// a finite best vector.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{RbfKernel, ScalarDistance};
    /// use gprx::{GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// // Three samples on a line at 0, 1, 2; the inducing points are samples 0 and 2.
    /// // Column-major 3 × 2: the squared distances to sample 0, then to sample 2.
    /// let train = [0.0, 1.0, 4.0, 4.0, 1.0, 0.0];
    /// let fitted = Sgpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
    ///     .fit([image.borrow(&train)], 3, &[0.0, 1.0, 0.5], &[0, 2])
    ///     .map_err(|(_, e)| e)?;
    /// assert_eq!(fitted.inducing(), &[0, 2]);
    /// // One query at 1.5: its squared distances to the two inducing points (2 × 1).
    /// let pred = fitted.predict([image.borrow(&[2.25, 0.25])], 1)?;
    /// assert_eq!(pred.mean.len(), 1);
    /// # Ok(())
    /// # }
    /// ```
    #[allow(clippy::result_large_err)] // failure returns the trainer so the caller can retry
    pub fn fit<'s>(
        self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        n: usize,
        y: &[f64],
        inducing: &[usize],
    ) -> Result<FittedSgpr<O, FixedInducing, P, DistanceKernel>, (Self, GprError)> {
        self.fit_supplied(sources, n, (&[], 0), y, inducing)
    }
}

impl<P: GpScalar> Sgpr<Fixed, FixedInducing, P, DistanceKernel<DistanceOnly>> {
    /// Factors at the current `θ` without a search. Same data contract as
    /// `fit` of this kernel.
    ///
    /// # Errors
    ///
    /// Same as `fit` of this kernel, except
    /// [`GprError::OptimizationNotConverged`] does not apply.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{RbfKernel, ScalarDistance};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// let train = [0.0, 1.0, 4.0, 4.0, 1.0, 0.0];
    /// let fitted = Sgpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
    ///     .with_optimizer(Fixed)
    ///     .factor([image.borrow(&train)], 3, &[0.0, 1.0, 0.5], &[0, 2])
    ///     .map_err(|(_, e)| e)?;
    /// assert_eq!(fitted.m(), 2);
    /// # Ok(())
    /// # }
    /// ```
    #[allow(clippy::result_large_err)] // failure returns the trainer so the caller can retry
    pub fn factor<'s>(
        self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        n: usize,
        y: &[f64],
        inducing: &[usize],
    ) -> Result<FittedSgpr<Fixed, FixedInducing, P, DistanceKernel>, (Self, GprError)> {
        self.factor_supplied(sources, n, (&[], 0), y, inducing)
    }
}

impl<O, P> Sgpr<O, FixedInducing, P, DistanceKernel<WithPoints>>
where
    P: GpScalar,
    O: Clone
        + for<'a> Optimizer<SgprObjective<'a, O, FixedInducing, P, DistanceKernel<WithPoints>>>,
{
    /// Factors the VFE system on the supplied distances and the coordinates
    /// `x`, and searches kernel and likelihood `θ`.
    ///
    /// `x` is column-major, `n` points by `n_cols` features, and goes
    /// through the input transform; the distances do not. The inducing
    /// points' coordinates are their rows of `x`.
    ///
    /// # Errors
    ///
    /// Same as `fit` of a [`DistanceKernel<DistanceOnly>`] model, plus
    /// [`GprError::EmptyInput`] if `x` is empty, [`GprError::LengthMismatch`]
    /// if `x` is not `n × n_cols` (`n_cols` zero included), [`GprError::NonFiniteInput`] for a
    /// coordinate that is not finite, and the error of the input transform.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel, ScalarDistance};
    /// use gprx::{GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// let kernel = image.kernel(RbfKernel::new(1.0)?) * KernelSpec::from(RbfKernel::new(2.0)?);
    /// let train = [0.0, 1.0, 4.0, 4.0, 1.0, 0.0];
    /// let x = [0.0, 0.5, 1.0];
    /// let fitted = Sgpr::new(kernel, GaussianLikelihood::new(0.1)?)
    ///     .fit([image.borrow(&train)], 3, &x, 1, &[0.0, 1.0, 0.5], &[0, 2])
    ///     .map_err(|(_, e)| e)?;
    /// assert_eq!(fitted.z(), &[0.0, 1.0]);
    /// let pred = fitted.predict([image.borrow(&[2.25, 0.25])], &[0.75], 1, 1)?;
    /// assert_eq!(pred.mean.len(), 1);
    /// # Ok(())
    /// # }
    /// ```
    #[allow(clippy::result_large_err)] // failure returns the trainer so the caller can retry
    #[allow(clippy::too_many_arguments)]
    pub fn fit<'s>(
        self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        n: usize,
        x: &[f64],
        n_cols: usize,
        y: &[f64],
        inducing: &[usize],
    ) -> Fitted<O, P, WithPoints, Self> {
        self.fit_supplied(sources, n, (x, n_cols), y, inducing)
    }
}

impl<P: GpScalar> Sgpr<Fixed, FixedInducing, P, DistanceKernel<WithPoints>> {
    /// Factors at the current `θ` without a search. Same data contract as
    /// `fit` of this kernel.
    ///
    /// # Errors
    ///
    /// Same as `fit` of this kernel, except
    /// [`GprError::OptimizationNotConverged`] does not apply.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use gprx::kernel::{KernelSpec, RbfKernel, ScalarDistance};
    /// use gprx::{Fixed, GaussianLikelihood, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// let kernel = image.kernel(RbfKernel::new(1.0)?) + KernelSpec::from(RbfKernel::new(2.0)?);
    /// let train = [0.0, 1.0, 4.0, 4.0, 1.0, 0.0];
    /// let fitted = Sgpr::new(kernel, GaussianLikelihood::new(0.1)?)
    ///     .with_optimizer(Fixed)
    ///     .factor([image.borrow(&train)], 3, &[0.0, 0.5, 1.0], 1, &[0.0, 1.0, 0.5], &[0, 2])
    ///     .map_err(|(_, e)| e)?;
    /// assert_eq!(fitted.d(), 1);
    /// # Ok(())
    /// # }
    /// ```
    #[allow(clippy::result_large_err)] // failure returns the trainer so the caller can retry
    #[allow(clippy::too_many_arguments)]
    pub fn factor<'s>(
        self,
        sources: impl IntoIterator<Item = DistanceSource<'s>>,
        n: usize,
        x: &[f64],
        n_cols: usize,
        y: &[f64],
        inducing: &[usize],
    ) -> Fitted<Fixed, P, WithPoints, Self> {
        self.factor_supplied(sources, n, (x, n_cols), y, inducing)
    }
}

impl<O, I, P: GpScalar, C: PointUse> FittedSgpr<O, I, 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, Sgpr};
    ///
    /// # fn main() -> Result<(), gprx::GprError> {
    /// let image = ScalarDistance::new();
    /// // Three samples at 0, 1, 2; the inducing points are samples 0 and 2.
    /// let train = [0.0, 1.0, 4.0, 4.0, 1.0, 0.0];
    /// let fitted = Sgpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
    ///     .with_optimizer(Fixed)
    ///     .factor([image.borrow(&train)], 3, &[0.0, 1.0, 0.5], &[0, 2])
    ///     .map_err(|(_, e)| e)?;
    /// assert_eq!(fitted.to_kernel().num_params(), 1);
    /// assert_eq!(fitted.slots(), [DistanceSlot::Scalar(image)]);
    /// assert_eq!(fitted.inducing(), &[0, 2]);
    /// // The online model names the inducing points by their point identifiers.
    /// let online = fitted.into_online();
    /// let ids = online.point_ids();
    /// assert!(online.inducing_points().eq([ids[0], ids[2]]));
    /// # Ok(())
    /// # }
    /// ```
    pub fn to_kernel(&self) -> DistanceKernel<C> {
        <DistanceKernel<C> as crate::kernel::ModelKernelParts>::from_spec(self.core.kernel.clone())
    }

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

    /// Returns the training samples that are the inducing points, in the
    /// order of the columns of the training blocks and the rows of a
    /// prediction's blocks.
    ///
    /// See the example on [`Self::to_kernel`].
    pub fn inducing(&self) -> &[usize] {
        &self.core.supplied.supply.inducing
    }
}

impl<O, P: GpScalar, C: PointUse> FittedSgpr<O, FixedInducing, P, DistanceKernel<C>> {
    /// Writes this model to `dir` as `config.json` and `model.safetensors`.
    ///
    /// Stores what [`FittedSgpr::save`] of a coordinate kernel stores, with
    /// the kernel's slot table, each slot's `n × m` training blocks (in
    /// `f64` at every precision: the model keeps them at `f64`), and the
    /// inducing indices ([`Self::inducing`]). The factors are not stored;
    /// [`crate::persist::LoadedDistanceSgpr::load`] binds the blocks to new
    /// slots and factors the system again at the saved `θ`.
    ///
    /// # Errors
    ///
    /// Returns [`GprError::PersistFailed`] when the directory cannot be
    /// written or a kernel or transform has no persist form.
    ///
    /// See the example on [`crate::persist::LoadedDistanceSgpr`].
    pub fn save(&self, dir: impl AsRef<std::path::Path>) -> Result<(), GprError> {
        crate::persist::save_sgpr(self, dir.as_ref())
    }

    /// Converts this model to an online SGPR whose `insert`,
    /// `insert_inducing`, and deletes keep the training blocks.
    ///
    /// The point identifiers are `0..n` and the inducing identifiers
    /// `0..m`, in buffer order; nothing is copied. The inducing points keep
    /// the [`crate::PointId`]s of the training points they are
    /// ([`OnlineSgpr::inducing_points`]).
    ///
    /// See the example on [`Self::to_kernel`].
    pub fn into_online(self) -> OnlineSgpr<O, P, DistanceKernel<C>> {
        OnlineSgpr::from_fitted(self)
    }
}

/// The query of an SGPR on supplied distances.
impl<O, I: InducingLayout<SuppliedSpec>, P: GpScalar, C: PointUse> DistanceQuery
    for FittedSgpr<O, I, P, DistanceKernel<C>>
{
    type Refine = P::Refine;

    fn query_distances<'s>(
        &self,
        cross: impl IntoIterator<Item = DistanceSource<'s>>,
        points: QueryPoints<'_>,
        q: usize,
        options: PredictOptions,
    ) -> Result<Prediction<P::Refine>, GprError> {
        let mut out = Prediction::default();
        predict_vfe_into::<P, SuppliedSpec>(
            &self.core,
            &self.vfe_system(),
            points.xs,
            q,
            points.n_cols,
            cross,
            options,
            &mut PredictScratch::default(),
            &mut out,
        )?;
        Ok(out)
    }

    fn query_distances_into<'s>(
        &mut self,
        cross: impl IntoIterator<Item = DistanceSource<'s>>,
        points: QueryPoints<'_>,
        q: usize,
        options: PredictOptions,
        out: &mut Prediction<P::Refine>,
    ) -> Result<(), GprError> {
        let sys = VfeSystem::new(
            &self.core,
            self.k_mm_l.as_ref(),
            self.b_l.as_ref(),
            &self.predict_w,
        );
        predict_vfe_into::<P, SuppliedSpec>(
            &self.core,
            &sys,
            points.xs,
            q,
            points.n_cols,
            cross,
            options,
            &mut self.scratch.predict,
            out,
        )
    }

    fn query_distance_covariance<'s>(
        &self,
        cross: impl IntoIterator<Item = DistanceSource<'s>>,
        square: impl IntoIterator<Item = DistanceSource<'s>>,
        points: QueryPoints<'_>,
        q: usize,
        options: PredictOptions,
    ) -> Result<PredictiveCovariance<P::Refine>, GprError> {
        predict_vfe_covariance::<P, SuppliedSpec>(
            &self.core,
            &self.vfe_system(),
            points.xs,
            q,
            points.n_cols,
            cross,
            square,
            options,
        )
    }

    fn draw_jitter(&self) -> JitterPolicy {
        self.core.jitter
    }
}

impl<O, I, P: GpScalar, C: PointUse> FittedSgpr<O, I, P, DistanceKernel<C>> {
    /// The factors a prediction reads.
    fn vfe_system(&self) -> VfeSystem<'_, P, SuppliedSpec> {
        VfeSystem::new(
            &self.core,
            self.k_mm_l.as_ref(),
            self.b_l.as_ref(),
            &self.predict_w,
        )
    }
}

distance_predict!(
    impl [O, I: InducingLayout<SuppliedSpec>, P: GpScalar] FittedSgpr<O, I, P, DistanceKernel<DistanceOnly>>,
    refine = P::Refine,
    args = (),
    tail = (),
    points = QueryPoints::NONE,
    count = q,
    cross = {
        /// the `m × q` squared distances from the `m` inducing points (in
        /// [`Self::inducing`] order) to the `q` queries.
    },
    reads = {
        /// A table is read in place for this call (an `f32` model reads it
        /// in `f64`, as it predicts); a fill writes scratch once.
    },
    predict_doc = {
        /// # Examples
        ///
        /// ```rust
        /// use gprx::kernel::{RbfKernel, ScalarDistance};
        /// use gprx::{GaussianLikelihood, PredictOptions, Prediction, Sgpr};
        ///
        /// # fn main() -> Result<(), gprx::GprError> {
        /// let image = ScalarDistance::new();
        /// let train = [0.0, 1.0, 4.0, 4.0, 1.0, 0.0];
        /// let mut fitted = Sgpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
        ///     .fit([image.borrow(&train)], 3, &[0.0, 1.0, 0.5], &[0, 2])
        ///     .map_err(|(_, e)| e)?;
        /// // Two queries at 0.5 and 1.5: inducing × query (2 × 2), then query × query.
        /// let cross = [0.25, 2.25, 2.25, 0.25];
        /// let query = [0.0, 1.0, 1.0, 0.0];
        /// let options = PredictOptions::default();
        /// let pred = fitted.predict([image.borrow(&cross)], 2)?;
        /// assert_eq!(pred.mean.len(), 2);
        /// let mut out = Prediction::default();
        /// fitted.predict_into([image.borrow(&cross)], 2, &mut out)?;
        /// fitted.predict_with_into([image.borrow(&cross)], 2, options, &mut out)?;
        /// let _ = fitted.predict_with([image.borrow(&cross)], 2, options)?;
        /// let cov = fitted.predict_covariance([image.borrow(&cross)], [image.borrow(&query)], 2)?;
        /// assert_eq!(cov.covariance.len(), 4);
        /// let _ = fitted.predict_covariance_with([image.borrow(&cross)], [image.borrow(&query)], 2, options)?;
        /// let draws = fitted.sample([image.borrow(&cross)], [image.borrow(&query)], 2, 3, 7)?;
        /// assert_eq!(draws.len(), 6);
        /// let _ = fitted.sample_with([image.borrow(&cross)], [image.borrow(&query)], 2, options, 3, 7)?;
        /// # Ok(())
        /// # }
        /// ```
    },
    covariance_doc = {
        /// # Examples
        ///
        /// ```rust
        /// use gprx::kernel::{RbfKernel, ScalarDistance};
        /// use gprx::{GaussianLikelihood, PredictOptions, Prediction, Sgpr};
        ///
        /// # fn main() -> Result<(), gprx::GprError> {
        /// let image = ScalarDistance::new();
        /// let train = [0.0, 1.0, 4.0, 4.0, 1.0, 0.0];
        /// let mut fitted = Sgpr::new(image.kernel(RbfKernel::new(1.0)?), GaussianLikelihood::new(0.1)?)
        ///     .fit([image.borrow(&train)], 3, &[0.0, 1.0, 0.5], &[0, 2])
        ///     .map_err(|(_, e)| e)?;
        /// // Two queries at 0.5 and 1.5: inducing × query (2 × 2), then query × query.
        /// let cross = [0.25, 2.25, 2.25, 0.25];
        /// let query = [0.0, 1.0, 1.0, 0.0];
        /// let options = PredictOptions::default();
        /// let pred = fitted.predict([image.borrow(&cross)], 2)?;
        /// assert_eq!(pred.mean.len(), 2);
        /// let mut out = Prediction::default();
        /// fitted.predict_into([image.borrow(&cross)], 2, &mut out)?;
        /// fitted.predict_with_into([image.borrow(&cross)], 2, options, &mut out)?;
        /// let _ = fitted.predict_with([image.borrow(&cross)], 2, options)?;
        /// let cov = fitted.predict_covariance([image.borrow(&cross)], [image.borrow(&query)], 2)?;
        /// assert_eq!(cov.covariance.len(), 4);
        /// let _ = fitted.predict_covariance_with([image.borrow(&cross)], [image.borrow(&query)], 2, options)?;
        /// let draws = fitted.sample([image.borrow(&cross)], [image.borrow(&query)], 2, 3, 7)?;
        /// assert_eq!(draws.len(), 6);
        /// let _ = fitted.sample_with([image.borrow(&cross)], [image.borrow(&query)], 2, options, 3, 7)?;
        /// # Ok(())
        /// # }
        /// ```
    },
);

distance_predict!(
    impl [O, I: InducingLayout<SuppliedSpec>, P: GpScalar] FittedSgpr<O, I, P, DistanceKernel<WithPoints>>,
    refine = P::Refine,
    args = (xs: &[f64]),
    tail = (n_cols: usize),
    points = QueryPoints { xs, n_cols },
    count = q,
    cross = {
        /// the `m × q` squared distances from the `m` inducing points (in
        /// [`Self::inducing`] order) to the `q` queries.
    },
    reads = {
        /// A table is read in place for this call (an `f32` model reads it
        /// in `f64`, as it predicts); a fill writes scratch once.
    },
    predict_doc = {
        /// # Examples
        ///
        /// ```rust
        /// use gprx::kernel::{KernelSpec, RbfKernel, ScalarDistance};
        /// use gprx::{GaussianLikelihood, PredictOptions, Prediction, Sgpr};
        ///
        /// # fn main() -> Result<(), gprx::GprError> {
        /// let image = ScalarDistance::new();
        /// let kernel = image.kernel(RbfKernel::new(1.0)?) * KernelSpec::from(RbfKernel::new(2.0)?);
        /// let train = [0.0, 1.0, 4.0, 4.0, 1.0, 0.0];
        /// let mut fitted = Sgpr::new(kernel, GaussianLikelihood::new(0.1)?)
        ///     .fit([image.borrow(&train)], 3, &[0.0, 0.5, 1.0], 1, &[0.0, 1.0, 0.5], &[0, 2])
        ///     .map_err(|(_, e)| e)?;
        /// let (cross, query, xs) = ([0.25, 2.25, 2.25, 0.25], [0.0, 1.0, 1.0, 0.0], [0.25, 0.75]);
        /// let options = PredictOptions::default();
        /// let pred = fitted.predict([image.borrow(&cross)], &xs, 2, 1)?;
        /// assert_eq!(pred.mean.len(), 2);
        /// let mut out = Prediction::default();
        /// fitted.predict_into([image.borrow(&cross)], &xs, 2, 1, &mut out)?;
        /// fitted.predict_with_into([image.borrow(&cross)], &xs, 2, 1, options, &mut out)?;
        /// let _ = fitted.predict_with([image.borrow(&cross)], &xs, 2, 1, options)?;
        /// let cov = fitted.predict_covariance([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1)?;
        /// assert_eq!(cov.mean.len(), 2);
        /// let _ = fitted.predict_covariance_with([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1, options)?;
        /// let _ = fitted.sample([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1, 2, 0)?;
        /// let _ = fitted.sample_with([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1, options, 2, 0)?;
        /// # Ok(())
        /// # }
        /// ```
    },
    covariance_doc = {
        /// # Examples
        ///
        /// ```rust
        /// use gprx::kernel::{KernelSpec, RbfKernel, ScalarDistance};
        /// use gprx::{GaussianLikelihood, PredictOptions, Prediction, Sgpr};
        ///
        /// # fn main() -> Result<(), gprx::GprError> {
        /// let image = ScalarDistance::new();
        /// let kernel = image.kernel(RbfKernel::new(1.0)?) * KernelSpec::from(RbfKernel::new(2.0)?);
        /// let train = [0.0, 1.0, 4.0, 4.0, 1.0, 0.0];
        /// let mut fitted = Sgpr::new(kernel, GaussianLikelihood::new(0.1)?)
        ///     .fit([image.borrow(&train)], 3, &[0.0, 0.5, 1.0], 1, &[0.0, 1.0, 0.5], &[0, 2])
        ///     .map_err(|(_, e)| e)?;
        /// let (cross, query, xs) = ([0.25, 2.25, 2.25, 0.25], [0.0, 1.0, 1.0, 0.0], [0.25, 0.75]);
        /// let options = PredictOptions::default();
        /// let pred = fitted.predict([image.borrow(&cross)], &xs, 2, 1)?;
        /// assert_eq!(pred.mean.len(), 2);
        /// let mut out = Prediction::default();
        /// fitted.predict_into([image.borrow(&cross)], &xs, 2, 1, &mut out)?;
        /// fitted.predict_with_into([image.borrow(&cross)], &xs, 2, 1, options, &mut out)?;
        /// let _ = fitted.predict_with([image.borrow(&cross)], &xs, 2, 1, options)?;
        /// let cov = fitted.predict_covariance([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1)?;
        /// assert_eq!(cov.mean.len(), 2);
        /// let _ = fitted.predict_covariance_with([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1, options)?;
        /// let _ = fitted.sample([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1, 2, 0)?;
        /// let _ = fitted.sample_with([image.borrow(&cross)], [image.borrow(&query)], &xs, 2, 1, options, 2, 0)?;
        /// # Ok(())
        /// # }
        /// ```
    },
);