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
//! Compute scalar for [`super::CompiledKernel`] and the stored Gram factors.

use std::fmt;

use faer::{Mat, MatRef};

use crate::math::{self, ExpJet};

pub(crate) mod sealed {
    use dyn_stack::MemBuffer;
    use faer::{Mat, MatMut, MatRef};

    use crate::error::{CholeskyStage, GprError};
    use crate::kernel::KernelTerm;
    use crate::math::ExpJet;

    /// Crate-private operations whose algorithm differs between `f32` and `f64`.
    ///
    /// `f64` calls faer's blocked, parallel routines. `f32` accumulates in
    /// `f64` so a stored `f32` factor keeps the digits of an `f64` sum.
    pub trait ScalarOps: Sized {
        /// Scratch that holds `y` cast to this scalar. `f64` uses no buffer.
        type RowCast: Clone + Send + Sync + 'static;
        /// Scratch that holds `X` cast to this scalar. `f64` uses no buffer.
        type ColCast: Clone + Send + Sync + 'static;
        /// The `f64` Cholesky factor a sparse model keeps beside a stored
        /// factor of this scalar: the factor of `K_mm` its assembly formed
        /// before rounding, and the factor of `B` the rank-1 `X` steps of
        /// an online SGPR update. `f64` keeps none: its stored
        /// factor is that factor. `f32` keeps an `f64` matrix, so a new
        /// column of `A` is solved against the factor an assembly solves
        /// against, and a run of updates rounds the stored factor once per
        /// step instead of carrying each step's `f32` rounding into the
        /// next.
        type F64Factor: Clone + std::fmt::Debug + Send + Sync + 'static;
        /// What a model of this storage keeps in `f64` beside the values it
        /// rounds: `V` for `f32`, nothing (`()`) for `f64`, whose stored
        /// values are those values.
        type F64Held<V: Clone + std::fmt::Debug + Send + Sync + 'static>: Clone
            + std::fmt::Debug
            + Send
            + Sync
            + 'static;

        /// Sparse assembly and predict, the SVGP gradient, and Exact
        /// leave-one-out compute in `f64` and round into this storage, and
        /// an online SGPR inducing change assembles again instead of
        /// updating the stored factors in this scalar. `true` only for
        /// `f32`.
        const ROUNDS_FROM_F64: bool;

        /// safetensors dtype of this scalar.
        const DTYPE: safetensors::Dtype;

        /// Whether fit fills and reads the ARD `(Δx_d)²` cache at this scalar.
        const READS_ARD_CACHE: bool;

        /// Writes pairwise squared Euclidean distances of the rows of `x`.
        fn write_squared(x: MatRef<'_, Self>, dist: MatMut<'_, Self>, scratch: &mut [Mat<Self>]);

        /// Writes train × test squared Euclidean distances.
        fn write_cross(
            x_train: MatRef<'_, Self>,
            x_test: MatRef<'_, Self>,
            dist: MatMut<'_, Self>,
            scratch: &mut [Mat<Self>],
        );

        /// Writes the packed raw `(Δx_d)²` cache of
        /// [`crate::kernel::dist::ArdSqDiffBuf`].
        fn write_ard(x: MatRef<'_, Self>, cache: &mut [Self]);

        /// This slice as `f64` when the scalar is `f64`, for the SIMD paths.
        fn as_f64_slice(values: &[Self]) -> Option<&[f64]>;

        /// [`Self::as_f64_slice`] for a mutable slice.
        fn as_f64_slice_mut(values: &mut [Self]) -> Option<&mut [f64]>;

        /// `f64` values as this scalar when it is `f64`: a supplied table
        /// is read in place.
        fn from_f64_slice(values: &[f64]) -> Option<&[Self]>;

        /// [`Self::from_f64_slice`] for a list of borrowed tables.
        fn from_f64_slices<'a>(values: &'a [&'a [f64]]) -> Option<&'a [&'a [Self]]>;

        /// [`Self::from_f64_slice`] for a list of owned tables.
        fn from_f64_vecs(values: &[Vec<f64>]) -> Option<&[Vec<Self>]>;

        /// Owned `f64` tables as this scalar when it is `f64`, moved as
        /// they are; otherwise handed back.
        fn vecs_from_f64(values: Vec<Vec<f64>>) -> Result<Vec<Vec<Self>>, Vec<Vec<f64>>>;

        /// [`Self::as_f64_slice`] for a list of owned tables.
        fn as_f64_vecs(values: &[Vec<Self>]) -> Option<&[Vec<f64>]>;

        fn empty_rows() -> Self::RowCast;

        fn empty_cols() -> Self::ColCast;

        /// `values` as this scalar. `f64` takes the buffer as is.
        fn vec_from_f64(values: Vec<f64>) -> Vec<Self>;

        /// Views `y` as this scalar. `f64` returns `y`. `f32` fills `cast`.
        fn storage_rows<'a>(y: &'a [f64], cast: &'a mut Self::RowCast) -> &'a [Self];

        /// Views `x` as this scalar. `f64` returns `x`. `f32` fills `cast`.
        fn storage_cols<'a>(x: MatRef<'a, f64>, cast: &'a mut Self::ColCast) -> MatRef<'a, Self>;

        /// The [`Self::F64Factor`] of the stored factor `l`: nothing for
        /// `f64`, `l` promoted for `f32`.
        fn hold_f64_factor(l: MatRef<'_, Self>) -> Self::F64Factor;

        /// The [`Self::F64Factor`] of a stored factor that rounds `l`:
        /// nothing for `f64` (`l` is the stored factor), `l` for `f32`.
        fn f64_factor_from(l: Mat<f64>) -> Self::F64Factor;

        /// The `f64` factor of the stored `l` and its `held` copy: `l`
        /// itself for `f64`, `held` for `f32`.
        fn f64_factor<'a>(l: MatRef<'a, Self>, held: &'a Self::F64Factor) -> MatRef<'a, f64>;

        /// [`Self::f64_factor`] to update in place. Once it changes, call
        /// [`Self::store_f64_factor`].
        fn f64_factor_mut<'a>(
            l: &'a mut Mat<Self>,
            held: &'a mut Self::F64Factor,
        ) -> MatMut<'a, f64>;

        /// Writes the lower triangle of `held` into the stored `l`, rounded:
        /// nothing for `f64`.
        fn store_f64_factor(l: &mut Mat<Self>, held: &Self::F64Factor);

        /// A copy of [`Self::f64_factor`] to update on the side, for an
        /// update that can fail. [`Self::commit_f64_factor`] takes it.
        fn f64_factor_trial(l: MatRef<'_, Self>, held: &Self::F64Factor) -> Mat<f64>;

        /// Takes `trial` as the `f64` factor: as `l` for `f64`, as `held`
        /// and its lower triangle rounded into `l` for `f32`.
        fn commit_f64_factor(l: &mut Mat<Self>, held: &mut Self::F64Factor, trial: Mat<f64>);

        /// `make()` for `f32`; nothing (and `make` is not called) for `f64`.
        fn hold_f64<V: Clone + std::fmt::Debug + Send + Sync + 'static>(
            make: impl FnOnce() -> V,
        ) -> Self::F64Held<V>;

        /// The held value; `None` for `f64`.
        fn held_f64<V: Clone + std::fmt::Debug + Send + Sync + 'static>(
            held: Self::F64Held<V>,
        ) -> Option<V>;

        /// The held value, borrowed; `None` for `f64`.
        fn held_f64_ref<V: Clone + std::fmt::Debug + Send + Sync + 'static>(
            held: &Self::F64Held<V>,
        ) -> Option<&V>;

        /// This view as `f64` when the scalar is `f64`, for the SIMD paths.
        fn as_f64_ref(m: MatRef<'_, Self>) -> Option<MatRef<'_, f64>>;

        /// This view as `f64` when the scalar is `f64`, for the SIMD paths.
        fn as_f64_mut(m: MatMut<'_, Self>) -> Option<MatMut<'_, f64>>;

        /// Picks a [`crate::kernel::CustomKernel`] leaf's implementation at this scalar.
        fn pick_term<'a>(
            f64_term: &'a dyn KernelTerm<f64>,
            f32_term: &'a dyn KernelTerm<f32>,
        ) -> &'a dyn KernelTerm<Self>
        where
            Self: crate::kernel::KernelScalar;

        /// Degree-7 polynomial `exp` ([`crate::FastApprox`]).
        fn fast_exp(self) -> Self;

        /// Value and first two derivatives of [`Self::fast_exp`].
        fn fast_jet(self) -> ExpJet<Self>;

        /// Factors `A` in place as `L Lᵀ`. The strictly upper triangle is unspecified.
        fn cholesky_lower(
            a: &mut Mat<Self>,
            scratch: &mut MemBuffer,
            jitter: f64,
            stage: CholeskyStage,
        ) -> Result<(), GprError>;

        /// Overwrites `rhs` with `(L Lᵀ)⁻¹ rhs`. `scratch` sizes faer's solve.
        fn solve_llt_in_place(l: MatRef<'_, Self>, rhs: MatMut<'_, Self>, scratch: &mut MemBuffer);

        /// Overwrites `rhs` with `(L Lᵀ)⁻¹ rhs` with no caller scratch.
        fn solve_llt_owned_scratch(l: MatRef<'_, Self>, rhs: MatMut<'_, Self>);

        /// Writes `diag(A⁻¹)` from the lower Cholesky factor `L` of `A`.
        fn inv_diag_from_chol_l(l: MatRef<'_, Self>, q_diag: &mut [Self]);

        /// Writes `a · y` into column 0 of `ay`.
        fn matvec_columns(a: MatRef<'_, Self>, y: &[Self], ay: MatMut<'_, Self>);

        /// Writes `a aᵀ` into `b` (`b` is `m×m`, zero on entry).
        fn gram_aat(a: MatRef<'_, Self>, b: MatMut<'_, Self>);

        /// Solves `L w = v` in place for unit-lower `L` (`n = w.len()`), where
        /// row `i` of `L` is the head `lt[0..i, i]` of column `i` of `Lᵀ`.
        fn solve_unit_lower_rows(lt: &faer::Mat<Self>, w: &mut [Self]);

        /// Solves `L D Lᵀ x = b` for the leading `n` of the unit-lower `ld`
        /// (`D` on its diagonal), in place on every column of `rhs`.
        fn solve_ldlt_in_place(ld: MatRef<'_, Self>, rhs: MatMut<'_, Self>, n: usize);

        /// Deletes row and column `index` from the LDLT factor held in the
        /// leading `n×n` of `ld`.
        fn ldlt_delete_row_col(
            ld: MatMut<'_, Self>,
            index: usize,
            n: usize,
            scratch: &mut MemBuffer,
        );
    }
}

/// Represents the scalar used when a [`super::CompiledKernel`] evaluates a kernel.
///
/// Only `f32` and `f64` implement it. Parameters stay `f64`. The trait carries field
/// arithmetic plus the transcendental functions that kernel formulas need, so a leaf can be
/// written once over `T`.
///
/// # Examples
///
/// ```rust
/// use gprx::kernel::KernelScalar;
///
/// fn half_exp<T: KernelScalar>(x: T) -> T {
///     (x * T::from_f64(0.5)).exp()
/// }
///
/// assert!((half_exp(2.0_f64) - 1.0_f64.exp()).abs() < 1e-15);
/// assert!((half_exp(2.0_f32) - 1.0_f32.exp()).abs() < 1e-6);
///
/// /// Every operation once, on `x = 0.5`; returns how far each identity
/// /// is from exact, as `f64`.
/// fn identities<T: KernelScalar>() -> f64 {
///     let x = T::from_f64(0.5);
///     let two = T::from_f64(2.0);
///     let errors = [
///         x.exp().ln() - x,                          // ln(eˣ) = x
///         x.powf(two).sqrt() - x,                    // √(x²) = x
///         (T::from_f64(-0.5)).abs() - x,             // |−x| = x
///         x.sin() * x.sin() + x.cos() * x.cos() - T::from_f64(1.0),
///         x.max(two) - two,
///         x.min(two) - x,
///     ];
///     assert!(errors.iter().all(|e| e.is_finite()));
///     errors.iter().map(|e| e.abs().to_f64()).fold(0.0, f64::max)
/// }
///
/// assert!(identities::<f64>() < 1e-15);
/// assert!(identities::<f32>() < 1e-6);
/// ```
pub trait KernelScalar:
    sealed::ScalarOps + faer_traits::RealField + Copy + fmt::Debug + Default + Send + Sync + 'static
{
    /// Casts a stored `f64` parameter into this compute scalar.
    ///
    /// See the example on [`KernelScalar`].
    fn from_f64(value: f64) -> Self;

    /// Promotes a computed value back to `f64` for comparisons.
    ///
    /// See the example on [`KernelScalar`].
    fn to_f64(self) -> f64;

    /// Returns `eˣ`.
    ///
    /// See the example on [`KernelScalar`].
    fn exp(self) -> Self;

    /// Returns the natural logarithm.
    ///
    /// See the example on [`KernelScalar`].
    fn ln(self) -> Self;

    /// Returns the square root.
    ///
    /// See the example on [`KernelScalar`].
    fn sqrt(self) -> Self;

    /// Returns the absolute value.
    ///
    /// See the example on [`KernelScalar`].
    fn abs(self) -> Self;

    /// Returns whether the value is neither infinite nor `NaN`.
    ///
    /// See the example on [`KernelScalar`].
    fn is_finite(self) -> bool;

    /// Returns `self` raised to the real power `e`.
    ///
    /// See the example on [`KernelScalar`].
    fn powf(self, e: Self) -> Self;

    /// Returns the sine (radians).
    ///
    /// See the example on [`KernelScalar`].
    fn sin(self) -> Self;

    /// Returns the cosine (radians).
    ///
    /// See the example on [`KernelScalar`].
    fn cos(self) -> Self;

    /// Returns the larger of two values (`NaN` loses).
    ///
    /// See the example on [`KernelScalar`].
    fn max(self, other: Self) -> Self;

    /// Returns the smaller of two values (`NaN` loses).
    ///
    /// See the example on [`KernelScalar`].
    fn min(self, other: Self) -> Self;
}

/// `(src, dest)` as `f64` views when `T` is `f64`, for the SIMD paths.
#[inline(always)]
pub(crate) fn f64_pair<'a, T: KernelScalar>(
    src: MatRef<'a, T>,
    dest: faer::MatMut<'a, T>,
) -> Option<(MatRef<'a, f64>, faer::MatMut<'a, f64>)> {
    Some((T::as_f64_ref(src)?, T::as_f64_mut(dest)?))
}

macro_rules! impl_kernel_scalar {
    ($t:ty) => {
        impl KernelScalar for $t {
            #[inline(always)]
            fn from_f64(value: f64) -> Self {
                value as $t
            }

            #[inline(always)]
            fn to_f64(self) -> f64 {
                f64::from(self)
            }

            #[inline(always)]
            fn exp(self) -> Self {
                <$t>::exp(self)
            }

            #[inline(always)]
            fn ln(self) -> Self {
                <$t>::ln(self)
            }

            #[inline(always)]
            fn sqrt(self) -> Self {
                <$t>::sqrt(self)
            }

            #[inline(always)]
            fn abs(self) -> Self {
                <$t>::abs(self)
            }

            #[inline(always)]
            fn is_finite(self) -> bool {
                <$t>::is_finite(self)
            }

            #[inline(always)]
            fn powf(self, e: Self) -> Self {
                <$t>::powf(self, e)
            }

            #[inline(always)]
            fn sin(self) -> Self {
                <$t>::sin(self)
            }

            #[inline(always)]
            fn cos(self) -> Self {
                <$t>::cos(self)
            }

            #[inline(always)]
            fn max(self, other: Self) -> Self {
                <$t>::max(self, other)
            }

            #[inline(always)]
            fn min(self, other: Self) -> Self {
                <$t>::min(self, other)
            }
        }
    };
}

impl_kernel_scalar!(f32);
impl_kernel_scalar!(f64);

impl sealed::ScalarOps for f64 {
    type RowCast = ();
    type ColCast = ();
    type F64Factor = ();
    type F64Held<V: Clone + std::fmt::Debug + Send + Sync + 'static> = ();

    const ROUNDS_FROM_F64: bool = false;
    const DTYPE: safetensors::Dtype = safetensors::Dtype::F64;
    const READS_ARD_CACHE: bool = true;

    fn write_squared(x: MatRef<'_, Self>, dist: faer::MatMut<'_, Self>, scratch: &mut [Mat<Self>]) {
        super::dist::fill_squared_euclidean(x, dist, scratch);
    }

    fn write_cross(
        x_train: MatRef<'_, Self>,
        x_test: MatRef<'_, Self>,
        dist: faer::MatMut<'_, Self>,
        scratch: &mut [Mat<Self>],
    ) {
        super::dist::fill_squared_euclidean_cross(x_train, x_test, dist, scratch);
    }

    fn write_ard(x: MatRef<'_, Self>, cache: &mut [Self]) {
        super::dist::fill_ard_squared_diff(x, cache);
    }

    fn as_f64_slice(values: &[Self]) -> Option<&[f64]> {
        Some(values)
    }

    fn from_f64_slice(values: &[f64]) -> Option<&[Self]> {
        Some(values)
    }

    fn from_f64_slices<'a>(values: &'a [&'a [f64]]) -> Option<&'a [&'a [Self]]> {
        Some(values)
    }

    fn from_f64_vecs(values: &[Vec<f64>]) -> Option<&[Vec<Self>]> {
        Some(values)
    }

    fn vecs_from_f64(values: Vec<Vec<f64>>) -> Result<Vec<Vec<Self>>, Vec<Vec<f64>>> {
        Ok(values)
    }

    fn as_f64_vecs(values: &[Vec<Self>]) -> Option<&[Vec<f64>]> {
        Some(values)
    }

    fn as_f64_slice_mut(values: &mut [Self]) -> Option<&mut [f64]> {
        Some(values)
    }

    fn empty_rows() -> Self::RowCast {}

    fn empty_cols() -> Self::ColCast {}

    fn vec_from_f64(values: Vec<f64>) -> Vec<Self> {
        values
    }

    fn storage_rows<'a>(y: &'a [f64], _cast: &'a mut Self::RowCast) -> &'a [Self] {
        y
    }

    fn storage_cols<'a>(x: MatRef<'a, f64>, _cast: &'a mut Self::ColCast) -> MatRef<'a, Self> {
        x
    }

    fn pick_term<'a>(
        f64_term: &'a dyn crate::kernel::KernelTerm<f64>,
        _f32_term: &'a dyn crate::kernel::KernelTerm<f32>,
    ) -> &'a dyn crate::kernel::KernelTerm<Self> {
        f64_term
    }

    fn hold_f64_factor(_l: MatRef<'_, Self>) -> Self::F64Factor {}

    fn f64_factor_from(_l: Mat<f64>) -> Self::F64Factor {}

    fn f64_factor<'a>(l: MatRef<'a, Self>, _held: &'a Self::F64Factor) -> MatRef<'a, f64> {
        l
    }

    fn f64_factor_mut<'a>(
        l: &'a mut Mat<Self>,
        _held: &'a mut Self::F64Factor,
    ) -> faer::MatMut<'a, f64> {
        l.as_mut()
    }

    fn store_f64_factor(_l: &mut Mat<Self>, _held: &Self::F64Factor) {}

    fn f64_factor_trial(l: MatRef<'_, Self>, _held: &Self::F64Factor) -> Mat<f64> {
        l.to_owned()
    }

    fn commit_f64_factor(l: &mut Mat<Self>, _held: &mut Self::F64Factor, trial: Mat<f64>) {
        *l = trial;
    }

    fn hold_f64<V: Clone + std::fmt::Debug + Send + Sync + 'static>(_make: impl FnOnce() -> V) {}

    fn held_f64<V: Clone + std::fmt::Debug + Send + Sync + 'static>((): ()) -> Option<V> {
        None
    }

    fn held_f64_ref<V: Clone + std::fmt::Debug + Send + Sync + 'static>((): &()) -> Option<&V> {
        None
    }

    #[inline(always)]
    fn as_f64_ref(m: MatRef<'_, Self>) -> Option<MatRef<'_, f64>> {
        Some(m)
    }

    #[inline(always)]
    fn as_f64_mut(m: faer::MatMut<'_, Self>) -> Option<faer::MatMut<'_, f64>> {
        Some(m)
    }

    #[inline(always)]
    fn fast_exp(self) -> Self {
        math::fast_exp_f64(self)
    }

    #[inline(always)]
    fn fast_jet(self) -> ExpJet<Self> {
        math::fast_jet_f64(self)
    }

    fn cholesky_lower(
        a: &mut Mat<Self>,
        scratch: &mut dyn_stack::MemBuffer,
        jitter: f64,
        stage: crate::error::CholeskyStage,
    ) -> Result<(), crate::error::GprError> {
        crate::linalg::cholesky_lower_faer(a, scratch, jitter, stage)
    }

    fn solve_llt_in_place(
        l: MatRef<'_, Self>,
        rhs: faer::MatMut<'_, Self>,
        scratch: &mut dyn_stack::MemBuffer,
    ) {
        crate::linalg::solve_llt_faer(l, rhs, scratch);
    }

    fn solve_llt_owned_scratch(l: MatRef<'_, Self>, rhs: faer::MatMut<'_, Self>) {
        crate::linalg::solve_llt_faer_owned(l, rhs);
    }

    fn inv_diag_from_chol_l(l: MatRef<'_, Self>, q_diag: &mut [Self]) {
        crate::linalg::inv_diag_from_chol_l_faer(l, q_diag);
    }

    fn matvec_columns(a: MatRef<'_, Self>, y: &[Self], ay: faer::MatMut<'_, Self>) {
        crate::linalg::matvec_columns_native(a, y, ay);
    }

    fn gram_aat(a: MatRef<'_, Self>, b: faer::MatMut<'_, Self>) {
        crate::linalg::gram_aat_faer(a, b);
    }

    fn solve_unit_lower_rows(lt: &faer::Mat<Self>, w: &mut [Self]) {
        crate::linalg::solve_unit_lower_rows_f64(lt, w);
    }

    fn solve_ldlt_in_place(ld: MatRef<'_, Self>, rhs: faer::MatMut<'_, Self>, n: usize) {
        crate::linalg::solve_ldlt_faer(ld, rhs, n);
    }

    fn ldlt_delete_row_col(
        ld: faer::MatMut<'_, Self>,
        index: usize,
        n: usize,
        scratch: &mut dyn_stack::MemBuffer,
    ) {
        crate::linalg::ldlt_delete_faer(ld, index, n, scratch);
    }
}

impl sealed::ScalarOps for f32 {
    type RowCast = Vec<f32>;
    type ColCast = Mat<f32>;
    type F64Factor = Mat<f64>;
    type F64Held<V: Clone + std::fmt::Debug + Send + Sync + 'static> = V;

    const ROUNDS_FROM_F64: bool = true;
    const DTYPE: safetensors::Dtype = safetensors::Dtype::F32;
    const READS_ARD_CACHE: bool = false;

    fn write_squared(
        x: MatRef<'_, Self>,
        dist: faer::MatMut<'_, Self>,
        _scratch: &mut [Mat<Self>],
    ) {
        super::dist::fill_squared_scalar(x, dist);
    }

    fn write_cross(
        x_train: MatRef<'_, Self>,
        x_test: MatRef<'_, Self>,
        dist: faer::MatMut<'_, Self>,
        _scratch: &mut [Mat<Self>],
    ) {
        super::dist::fill_cross_scalar(x_train, x_test, dist);
    }

    fn write_ard(x: MatRef<'_, Self>, cache: &mut [Self]) {
        super::dist::fill_ard_scalar(x, cache);
    }

    fn as_f64_slice(_values: &[Self]) -> Option<&[f64]> {
        None
    }

    fn from_f64_slice(_values: &[f64]) -> Option<&[Self]> {
        None
    }

    fn from_f64_slices<'a>(_values: &'a [&'a [f64]]) -> Option<&'a [&'a [Self]]> {
        None
    }

    fn from_f64_vecs(_values: &[Vec<f64>]) -> Option<&[Vec<Self>]> {
        None
    }

    fn vecs_from_f64(values: Vec<Vec<f64>>) -> Result<Vec<Vec<Self>>, Vec<Vec<f64>>> {
        Err(values)
    }

    fn as_f64_vecs(_values: &[Vec<Self>]) -> Option<&[Vec<f64>]> {
        None
    }

    fn as_f64_slice_mut(_values: &mut [Self]) -> Option<&mut [f64]> {
        None
    }

    fn empty_rows() -> Self::RowCast {
        Vec::new()
    }

    fn empty_cols() -> Self::ColCast {
        Mat::zeros(0, 0)
    }

    fn vec_from_f64(values: Vec<f64>) -> Vec<Self> {
        values.into_iter().map(|v| v as f32).collect()
    }

    fn storage_rows<'a>(y: &'a [f64], cast: &'a mut Self::RowCast) -> &'a [Self] {
        if cast.len() != y.len() {
            cast.resize(y.len(), 0.0);
        }
        for (slot, &value) in cast.iter_mut().zip(y.iter()) {
            *slot = value as f32;
        }
        cast.as_slice()
    }

    fn storage_cols<'a>(x: MatRef<'a, f64>, cast: &'a mut Self::ColCast) -> MatRef<'a, Self> {
        if cast.nrows() != x.nrows() || cast.ncols() != x.ncols() {
            *cast = Mat::zeros(x.nrows(), x.ncols());
        }
        for col in 0..x.ncols() {
            for row in 0..x.nrows() {
                cast[(row, col)] = x[(row, col)] as f32;
            }
        }
        cast.as_ref()
    }

    fn pick_term<'a>(
        _f64_term: &'a dyn crate::kernel::KernelTerm<f64>,
        f32_term: &'a dyn crate::kernel::KernelTerm<f32>,
    ) -> &'a dyn crate::kernel::KernelTerm<Self> {
        f32_term
    }

    fn hold_f64_factor(l: MatRef<'_, Self>) -> Self::F64Factor {
        Mat::from_fn(l.nrows(), l.ncols(), |row, col| f64::from(l[(row, col)]))
    }

    fn f64_factor_from(l: Mat<f64>) -> Self::F64Factor {
        l
    }

    fn f64_factor<'a>(_l: MatRef<'a, Self>, held: &'a Self::F64Factor) -> MatRef<'a, f64> {
        held.as_ref()
    }

    fn f64_factor_mut<'a>(
        _l: &'a mut Mat<Self>,
        held: &'a mut Self::F64Factor,
    ) -> faer::MatMut<'a, f64> {
        held.as_mut()
    }

    fn store_f64_factor(l: &mut Mat<Self>, held: &Self::F64Factor) {
        for col in 0..l.ncols() {
            let from = &held.col_as_slice(col)[col..];
            for (slot, &value) in l.col_as_slice_mut(col)[col..].iter_mut().zip(from) {
                *slot = value as f32;
            }
        }
    }

    fn f64_factor_trial(_l: MatRef<'_, Self>, held: &Self::F64Factor) -> Mat<f64> {
        held.clone()
    }

    fn commit_f64_factor(l: &mut Mat<Self>, held: &mut Self::F64Factor, trial: Mat<f64>) {
        *held = trial;
        Self::store_f64_factor(l, held);
    }

    fn hold_f64<V: Clone + std::fmt::Debug + Send + Sync + 'static>(make: impl FnOnce() -> V) -> V {
        make()
    }

    fn held_f64<V: Clone + std::fmt::Debug + Send + Sync + 'static>(held: V) -> Option<V> {
        Some(held)
    }

    fn held_f64_ref<V: Clone + std::fmt::Debug + Send + Sync + 'static>(held: &V) -> Option<&V> {
        Some(held)
    }

    #[inline(always)]
    fn as_f64_ref(_m: MatRef<'_, Self>) -> Option<MatRef<'_, f64>> {
        None
    }

    #[inline(always)]
    fn as_f64_mut(_m: faer::MatMut<'_, Self>) -> Option<faer::MatMut<'_, f64>> {
        None
    }

    #[inline(always)]
    fn fast_exp(self) -> Self {
        math::fast_exp_f32(self)
    }

    #[inline(always)]
    fn fast_jet(self) -> ExpJet<Self> {
        math::fast_jet_f32(self)
    }

    fn cholesky_lower(
        a: &mut Mat<Self>,
        _scratch: &mut dyn_stack::MemBuffer,
        jitter: f64,
        stage: crate::error::CholeskyStage,
    ) -> Result<(), crate::error::GprError> {
        crate::linalg::cholesky_lower_f64_accum(a, jitter, stage)
    }

    fn solve_llt_in_place(
        l: MatRef<'_, Self>,
        rhs: faer::MatMut<'_, Self>,
        _scratch: &mut dyn_stack::MemBuffer,
    ) {
        crate::linalg::solve_llt_f64_accum(l, rhs);
    }

    fn solve_llt_owned_scratch(l: MatRef<'_, Self>, rhs: faer::MatMut<'_, Self>) {
        crate::linalg::solve_llt_f64_accum(l, rhs);
    }

    fn inv_diag_from_chol_l(l: MatRef<'_, Self>, q_diag: &mut [Self]) {
        crate::linalg::inv_diag_from_chol_l_f64_accum(l, q_diag);
    }

    fn matvec_columns(a: MatRef<'_, Self>, y: &[Self], ay: faer::MatMut<'_, Self>) {
        crate::linalg::matvec_columns_f64_accum(a, y, ay);
    }

    fn gram_aat(a: MatRef<'_, Self>, b: faer::MatMut<'_, Self>) {
        crate::linalg::gram_aat_f64_accum(a, b);
    }

    fn solve_unit_lower_rows(lt: &faer::Mat<Self>, w: &mut [Self]) {
        crate::linalg::solve_unit_lower_rows_f32(lt, w);
    }

    fn solve_ldlt_in_place(ld: MatRef<'_, Self>, rhs: faer::MatMut<'_, Self>, n: usize) {
        crate::linalg::solve_ldlt_f64_accum(ld, rhs, n);
    }

    fn ldlt_delete_row_col(
        ld: faer::MatMut<'_, Self>,
        index: usize,
        n: usize,
        _scratch: &mut dyn_stack::MemBuffer,
    ) {
        crate::linalg::ldlt_delete_via_f64(ld, index, n);
    }
}