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
//! [`ExactFit`]: every hyperparameter write, gradient, and Hessian of an Exact GPR.

use faer::{Mat, MatMut, MatRef};

use crate::error::{CholeskyStage, GprError};
use crate::gpr::GprObjective;
use crate::kernel::ScalarOps;
use crate::kernel::{
    CompiledKernel, KernelScalar, ModelKernel, SpecOf, Supply, Triangle, WeightedWalk,
};
use crate::likelihood::GaussianLikelihood;
use crate::linalg::{frobenius_lower, gemv_sym_lower, solve_lower};
use crate::optimizer::{OptResult, Optimizer};
use crate::param::Interval;
use crate::precision::{GpScalar, StoredFactor};
use crate::workspace::{FitWorkspace, HessianScratch, WorkspaceCore};

use super::factor::{
    FactorPolicy, apply_compiled_to, factor_train_keeping_with_policy, factor_train_with_policy,
    factor_written_k_with_policy, fill_cached_inputs, neg_mll_from_factor,
};
use super::shared::train_points;
use super::{FitBuffers, GprCore, LltStore, Policies};
use crate::policy::{DistanceCachePolicy, with_kernel_exp};

/// [`Optimizer::USES_CHANGE_INDICES`] of `O` for the objective `obj`.
fn uses_change_indices<Obj, O: Optimizer<Obj>>(_obj: &Obj) -> bool {
    O::USES_CHANGE_INDICES
}

/// Allocates fit buffers for `n` points under `policies`.
///
/// A kernel that reads neither pairwise distances nor the ARD `(Δx_d)²`
/// tensor gets no distance cache, whatever the policy says.
pub(crate) fn fit_buffers<P: GpScalar, S: Supply>(
    n: usize,
    policies: Policies,
    compiled: &CompiledKernel<P::Storage, S>,
) -> Result<FitBuffers<P>, GprError> {
    let cache = if compiled.reads_distances()? || compiled.needs_ard_sq_diff() {
        policies.distance_cache
    } else {
        DistanceCachePolicy::Uncached
    };
    FitBuffers::<P>::new(n, cache, policies.cholesky_buffer)
}

/// Borrowed fit state: the shared core plus the LLT buffers.
///
/// Every hyperparameter write (`set_params`, gradient, Hessian, `fit`,
/// `refit`) runs here. [`crate::FittedGpr`] lends its own buffers.
/// [`crate::OnlineGpr`] lends temporary ones filled from its LDLT.
pub(crate) struct ExactFit<'a, P: GpScalar, K: ModelKernel> {
    pub(crate) core: &'a mut GprCore<P, K>,
    pub(crate) store: &'a mut LltStore<P>,
}

/// Per-leaf Gram matrices an incremental objective keeps during `fit` /
/// `refit` (`L · n²`, outside the fit buffers), plus the reused bookkeeping
/// for one coordinate step.
pub(crate) struct LeafCache<S> {
    grams: Vec<Mat<S>>,
    dirty: Vec<bool>,
    /// `params` of the last evaluation that factored.
    last: Vec<f64>,
    /// `grams` match `last`.
    primed: bool,
}

impl<S: KernelScalar> LeafCache<S> {
    pub(crate) fn new() -> Self {
        Self {
            grams: Vec::new(),
            dirty: Vec::new(),
            last: Vec::new(),
            primed: false,
        }
    }

    /// Sizes the Grams for `n_leaves` leaves of order `n`. A resize drops them.
    fn fit(&mut self, n_leaves: usize, n: usize) {
        if self.grams.len() != n_leaves || self.grams.first().is_some_and(|m| m.nrows() != n) {
            self.grams = (0..n_leaves).map(|_| Mat::<S>::zeros(n, n)).collect();
            self.primed = false;
        }
        self.dirty.resize(n_leaves, true);
    }

    /// Rejects a step that changed a coordinate `changed` does not list.
    fn require_listed(&self, params: &[f64], changed: &[usize]) -> Result<(), GprError> {
        for (j, (prev, next)) in self.last.iter().zip(params).enumerate() {
            if prev.to_bits() != next.to_bits() && !changed.contains(&j) {
                return Err(GprError::IndexOutOfRange {
                    reason: format!(
                        "coordinate {j} changed since the previous evaluation but is not in the change indices"
                    ),
                });
            }
        }
        Ok(())
    }

    fn record(&mut self, params: &[f64]) {
        self.last.clear();
        self.last.extend_from_slice(params);
        self.primed = true;
    }
}

impl<P: GpScalar, K: ModelKernel> ExactFit<'_, P, K> {
    pub(crate) fn reborrow(&mut self) -> ExactFit<'_, P, K> {
        ExactFit {
            core: &mut *self.core,
            store: &mut *self.store,
        }
    }

    pub(crate) fn num_params(&self) -> usize {
        self.core.num_params()
    }

    fn get_params(&self, out: &mut [f64]) -> Result<(), GprError> {
        self.core.get_params(out)
    }

    /// Runs `optimizer` from the current `θ`, then leaves `L` / `α` at the result.
    pub(crate) fn optimize<O>(&mut self, optimizer: &O) -> Result<(), GprError>
    where
        O: for<'b> Optimizer<GprObjective<'b, P, K>>,
    {
        let mut init = vec![0.0; self.num_params()];
        self.get_params(&mut init)?;
        let kernel_before = self.core.kernel.clone();
        let likelihood_before = self.core.likelihood;
        let result = {
            let obj = GprObjective::new(self.reborrow());
            let uses_change_indices = uses_change_indices::<_, O>(&obj);
            let mut obj = obj.with_change_indices(uses_change_indices);
            optimizer.minimize(&mut obj, &init)
        };
        self.commit_or_revert_optimize(kernel_before, likelihood_before, result)?;
        self.finish()
    }

    /// Rebuilds `L` at the current `θ` and publishes the predict `α`.
    pub(crate) fn refactor(&mut self) -> Result<(), GprError> {
        self.factorize_current()?;
        self.finish()
    }

    /// Ends every public write: `L` back in place of a reuse `W`, then the
    /// predict `α` for that `L`. Between public calls the predict `α`
    /// always matches the stored factor.
    fn finish(&mut self) -> Result<(), GprError> {
        self.restore_cholesky_if_overwritten()?;
        self.publish_predict_alpha()
    }

    pub(crate) fn publish_predict_alpha(&mut self) -> Result<(), GprError> {
        let jitter = self.store.buffers.core().factor_jitter;
        self.core.publish_predict_alpha(
            StoredFactor::Llt(self.store.l()),
            jitter,
            CholeskyStage::Fit,
        )
    }

    pub(crate) fn set_params(&mut self, params: &[f64]) -> Result<(), GprError> {
        crate::data::require_count(params.len(), self.num_params(), "parameters")?;
        self.factor_at(params, Keep::Nothing)?;
        if let Err(err) = self.finish() {
            self.restore_theta();
            let _ = self.factorize_current();
            let _ = self.publish_predict_alpha();
            return Err(err);
        }
        Ok(())
    }

    pub(crate) fn value_and_gradient_into(
        &mut self,
        params: &[f64],
        out: &mut [f64],
    ) -> Result<f64, GprError> {
        let nlml = self.value_and_gradient_into_fit(params, out)?;
        self.finish()?;
        Ok(nlml)
    }

    /// Writes `θ = params` and factors `A` at it.
    ///
    /// The one rollback rule for hyperparameter writes: `θ` is written in
    /// place (no clone of the kernel trees), with the previous `θ` kept in a
    /// reused buffer. When `A` does not factor, that `θ` is written back and
    /// `L` / `α` are rebuilt at it, so nothing is copied up front.
    fn factor_at(&mut self, params: &[f64], keep: Keep) -> Result<KeptGrams, GprError> {
        self.write_theta(params)?;
        match self.factor_with(keep) {
            Ok(kept) => Ok(kept),
            Err(err) => {
                self.restore_theta();
                let _ = self.factorize_current();
                Err(err)
            }
        }
    }

    /// Writes `params` into the stored kernel, compiled kernel, and likelihood.
    ///
    /// The previous `θ` goes to the fit buffers' `θ` scratch for
    /// [`Self::restore_theta`]. A rejected slice changes nothing.
    fn write_theta(&mut self, params: &[f64]) -> Result<(), GprError> {
        let n_kernel = self.core.kernel.num_params();
        let mut likelihood = self.core.likelihood;
        likelihood.set_params(&params[n_kernel..])?;
        let prev = &mut self.store.buffers.core_mut().theta;
        prev.resize(params.len(), 0.0);
        self.core.get_params(prev)?;
        let (kernel_prev, _) = prev.split_at(n_kernel);
        self.core
            .kernel
            .set_params_in_place(&params[..n_kernel], kernel_prev)?;
        if let Err(err) = self
            .core
            .compiled
            .set_params_in_place(&params[..n_kernel], kernel_prev)
        {
            let _ = self
                .core
                .kernel
                .set_params_in_place(kernel_prev, kernel_prev);
            return Err(err);
        }
        self.core.likelihood = likelihood;
        Ok(())
    }

    /// Writes back the `θ` the last [`Self::write_theta`] replaced.
    fn restore_theta(&mut self) {
        let n_kernel = self.core.kernel.num_params();
        let prev = &self.store.buffers.core().theta;
        let (kernel_prev, likelihood_prev) = prev.split_at(n_kernel);
        let _ = self
            .core
            .kernel
            .set_params_in_place(kernel_prev, kernel_prev);
        let _ = self
            .core
            .compiled
            .set_params_in_place(kernel_prev, kernel_prev);
        let _ = self.core.likelihood.set_params(likelihood_prev);
    }

    /// Factors `A` at the stored `θ` into the buffers.
    fn factor(&mut self) -> Result<(), GprError> {
        self.factor_with(Keep::Nothing).map(|_| ())
    }

    /// Factors `A` at the stored `θ` into the buffers. With
    /// [`Keep::FactorGrams`], the product factor Grams the joint gradient
    /// reads ([`CompiledKernel::eval_gram_keeping`]) stay in the leading
    /// `weighted` buffers, and the returned [`KeptGrams`] says how many
    /// products kept them at this `θ`.
    fn factor_with(&mut self, keep: Keep) -> Result<KeptGrams, GprError> {
        let products = match keep {
            Keep::Nothing => 0,
            Keep::FactorGrams => self.core.compiled.kept_products(),
        };
        self.store.release_mapped();
        let n = self.core.n;
        if products > 0 {
            self.ensure_weighted(n, products)?;
        }
        let x = train_points::<P, _>(
            &self.core.x,
            (self.core.n, self.core.d),
            &mut self.core.x_cast,
            &self.core.supplied,
        );
        let policy = FactorPolicy {
            jitter: self.core.policies.jitter,
            stage: CholeskyStage::Fit,
        };
        let compiled = &self.core.compiled;
        let noise = self.core.likelihood.noise_variance();
        let buffers = &mut self.store.buffers;
        let y = &self.core.y_train;
        if products == 0 {
            with_kernel_exp!(self.core.policies.math, M => factor_train_with_policy::<_, _, M, _>(
                compiled, x, buffers, y, noise, policy,
            ))?;
        } else {
            with_kernel_exp!(self.core.policies.math, M => factor_train_keeping_with_policy::<_, _, M, _>(
                compiled, x, buffers, y, noise, policy, products,
            ))?;
        }
        self.commit_factor();
        Ok(KeptGrams { products })
    }

    /// Sizes the gradient walk's `n×n` buffers when `products` products keep
    /// their Grams ([`CompiledKernel::weighted_buffers`]) and, for a tree
    /// that needs it, `kernel_scratch`.
    fn ensure_weighted(&mut self, n: usize, products: usize) -> Result<(), GprError> {
        let compiled = &self.core.compiled;
        let core = self.store.buffers.core_mut();
        if compiled.needs_grad_scratch() {
            core.ensure_kernel_scratch(n)?;
        }
        core.weighted.retain(|m| m.nrows() == n && m.ncols() == n);
        while core.weighted.len() < compiled.weighted_buffers(products) {
            core.weighted.push(Mat::zeros(n, n));
        }
        Ok(())
    }

    /// Joint MLL+grad used during `fit`. Does not restore `L` when the buffer
    /// overwrites the factor; the optimizer's next step rebuilds `A`.
    pub(crate) fn value_and_gradient_into_fit(
        &mut self,
        params: &[f64],
        out: &mut [f64],
    ) -> Result<f64, GprError> {
        let n_kernel = self.core.kernel.num_params();
        let n_params = self.num_params();
        crate::data::require_count(params.len(), n_params, "parameters")?;
        crate::data::require_count(out.len(), n_params, "parameters")?;
        let kept = self.factor_at(params, Keep::FactorGrams)?;
        let n = self.core.n;
        let mut rows = P::Storage::empty_rows();
        let y = P::Storage::storage_rows(&self.core.y_train, &mut rows);
        let nlml = neg_mll_from_factor(
            self.store.buffers.core().k_matrix.as_ref(),
            y,
            &self.core.factor_alpha,
            n,
        )
        .to_f64();
        self.fill_gradient_from_factor(n_kernel, n, out, kept)?;
        Ok(nlml)
    }

    /// Rebuilds dirty compiled leaves, recombines the tree, and factors.
    ///
    /// `indices` lists every coordinate that differs from the previous
    /// evaluation through `cache`; only the leaves they touch are rebuilt.
    /// `None`, or a cache that holds nothing yet, rebuilds every leaf.
    pub(crate) fn value_from_leaf_grams(
        &mut self,
        params: &[f64],
        indices: Option<&[usize]>,
        cache: &mut LeafCache<P::Storage>,
    ) -> Result<f64, GprError> {
        let n_kernel = self.core.kernel.num_params();
        let n_params = self.num_params();
        crate::data::require_count(params.len(), n_params, "parameters")?;
        if let Some(changed) = indices {
            require_change_indices(changed, n_params)?;
        }
        let n = self.core.n;
        let n_leaves = self.core.compiled.leaf_count();
        cache.fit(n_leaves, n);
        match (cache.primed, indices) {
            (true, Some(changed)) => {
                cache.require_listed(params, changed)?;
                cache.dirty.fill(false);
                for &j in changed {
                    if j < n_kernel {
                        cache.dirty[self.core.compiled.leaf_index_for_param(j)?] = true;
                    }
                }
            }
            _ => cache.dirty.fill(true),
        }
        self.write_theta(params)?;
        // Grams are only trusted again once this evaluation factors.
        cache.primed = false;
        if let Err(err) = self.rebuild_dirty_leaves(cache) {
            self.restore_theta();
            return Err(err);
        }
        self.store.release_mapped();
        let compiled = &self.core.compiled;
        let grams = &cache.grams;
        if let Err(err) = factor_written_k_with_policy(
            &mut self.store.buffers,
            &self.core.y_train,
            self.core.likelihood.noise_variance(),
            FactorPolicy {
                jitter: self.core.policies.jitter,
                stage: CholeskyStage::Fit,
            },
            |ws| {
                let core = ws.core_mut();
                compiled.combine_from_leaf_grams(
                    grams,
                    core.k_matrix.as_mut(),
                    core.exp_buf.as_mut(),
                    &mut core.nested,
                    Triangle::Lower,
                )
            },
        ) {
            self.restore_theta();
            let _ = self.factorize_current();
            return Err(err);
        }
        cache.record(params);
        self.commit_factor();
        let mut rows = P::Storage::empty_rows();
        let y = P::Storage::storage_rows(&self.core.y_train, &mut rows);
        Ok(neg_mll_from_factor(
            self.store.buffers.core().k_matrix.as_ref(),
            y,
            &self.core.factor_alpha,
            n,
        )
        .to_f64())
    }

    /// Re-evaluates the leaves `cache.dirty` marks at the stored `θ`.
    fn rebuild_dirty_leaves(&mut self, cache: &mut LeafCache<P::Storage>) -> Result<(), GprError> {
        let LeafCache { grams, dirty, .. } = cache;
        for (i, slot) in grams.iter_mut().enumerate() {
            if dirty[i] {
                let x = train_points::<P, _>(
                    &self.core.x,
                    (self.core.n, self.core.d),
                    &mut self.core.x_cast,
                    &self.core.supplied,
                );
                with_kernel_exp!(self.core.policies.math, M => apply_compiled_to::<_, _, M, _>(
                    self.core.compiled.leaf_at(i)?,
                    x,
                    &mut self.store.buffers,
                    slot.as_mut(),
                ))?;
            }
        }
        Ok(())
    }

    pub(crate) fn hessian_into(&mut self, params: &[f64], out: &mut [f64]) -> Result<(), GprError> {
        self.hessian_into_fit(params, out)?;
        self.finish()
    }

    pub(crate) fn hessian_into_fit(
        &mut self,
        params: &[f64],
        out: &mut [f64],
    ) -> Result<(), GprError> {
        let n_kernel = self.core.kernel.num_params();
        let n_params = self.num_params();
        crate::data::require_count(params.len(), n_params, "parameters")?;
        crate::data::require_count(out.len(), n_params * n_params, "parameters")?;
        self.factor_at(params, Keep::Nothing)?;
        let n = self.core.n;
        self.fill_hessian_from_factor(n_kernel, n, out)
    }

    /// Joint value, gradient, and Hessian during `fit` from one
    /// factorization of `A`.
    ///
    /// The gradient forms `W` from that factor. A dedicated `W` keeps `L`, so
    /// the Hessian reads the same factor; [`crate::CholeskyBuffer::Reuse`]
    /// wrote `W` over `L`, so `L` is rebuilt at the same `θ` first.
    pub(crate) fn value_gradient_hessian_into_fit(
        &mut self,
        params: &[f64],
        grad: &mut [f64],
        hess: &mut [f64],
    ) -> Result<f64, GprError> {
        let n_params = self.num_params();
        crate::data::require_count(hess.len(), n_params * n_params, "parameters")?;
        let nlml = self.value_and_gradient_into_fit(params, grad)?;
        self.restore_cholesky_if_overwritten()?;
        let n_kernel = self.core.kernel.num_params();
        let n = self.core.n;
        self.fill_hessian_from_factor(n_kernel, n, hess)?;
        Ok(nlml)
    }

    fn fill_hessian_from_factor(
        &mut self,
        n_kernel: usize,
        n: usize,
        out: &mut [f64],
    ) -> Result<(), GprError> {
        self.store.buffers.core_mut().ensure_kernel_scratch(n)?;
        self.store
            .buffers
            .form_gradient_w(&self.core.factor_alpha, n);
        out.fill(0.0);
        let n_params = n_kernel + 1;
        let noise = self.core.likelihood.noise_variance();
        let thread_scratch = std::mem::take(&mut self.store.buffers.core_mut().thread_scratch);
        let second = (|| {
            for i in 0..n_params {
                for j in i..n_params {
                    self.write_second_deriv(n_kernel, i, j, n)?;
                    let inner = frobenius_lower(
                        self.store.buffers.gradient_w(),
                        self.store.buffers.core().exp_buf.as_ref(),
                        n,
                    );
                    let hij = -0.5 * inner.to_f64();
                    out[i * n_params + j] = hij;
                    out[j * n_params + i] = hij;
                }
            }
            Ok::<(), GprError>(())
        })();
        self.store.buffers.core_mut().thread_scratch = thread_scratch;
        second?;
        let mut hess = std::mem::take(&mut self.store.buffers.core_mut().hessian);
        hess.ensure(n, n_params);
        let first = self.add_first_order(n_kernel, n, noise, out, &mut hess);
        self.store.buffers.core_mut().hessian = hess;
        first
    }

    /// Adds the first-order part of the Hessian of every pair:
    /// `−½ tr(A⁻¹ A_i A⁻¹ A_j) + αᵀ A_i A⁻¹ A_j α`, with `A_i = ∂A/∂θ_i`
    /// (the kernel's `∂K/∂θ_i`, or `σn² I` for the noise).
    ///
    /// With `A = L Lᵀ`, `S_i = L⁻¹ A_i L⁻ᵀ` and `v_i = L⁻¹ A_i α` give
    /// `tr(A⁻¹ A_i A⁻¹ A_j) = ⟨S_i, S_j⟩_F` and `αᵀ A_i A⁻¹ A_j α = v_iᵀ v_j`.
    /// Each `S_i` takes two triangular solves, so the pairs cost
    /// `O(p n³ + p² n²)` and `hess` keeps `p` matrices of `n × n`.
    fn add_first_order(
        &mut self,
        n_kernel: usize,
        n: usize,
        noise: f64,
        out: &mut [f64],
        hess: &mut HessianScratch<P::Storage>,
    ) -> Result<(), GprError> {
        if !self.store.buffers.has_dedicated_w() {
            // `W` was written over `L` for the second-order part.
            self.factorize_current()?;
        }
        let n_params = n_kernel + 1;
        let thread_scratch = std::mem::take(&mut self.store.buffers.core_mut().thread_scratch);
        let halves = (|| {
            for i in 0..n_params {
                if i < n_kernel {
                    self.write_first_deriv(i)?;
                } else {
                    zero_and_maybe_noise(
                        self.store.buffers.core_mut().exp_buf.as_mut(),
                        n,
                        true,
                        noise,
                    );
                }
                let l = self.store.buffers.core().k_matrix.as_ref();
                let d_a = self.store.buffers.core().exp_buf.as_ref();
                gemv_sym_lower(d_a, &self.core.factor_alpha, &mut hess.u, n);
                let mut v_i = hess.v.as_mut().col_mut(i);
                for (row, value) in hess.u.iter().enumerate() {
                    v_i[row] = *value;
                }
                solve_lower(l, hess.v.as_mut().subcols_mut(i, 1));
                let s_i = &mut hess.s[i];
                for col in 0..n {
                    for row in col..n {
                        s_i[(row, col)] = d_a[(row, col)];
                        s_i[(col, row)] = d_a[(row, col)];
                    }
                }
                // `L⁻¹ A_i`, then `L⁻¹ (L⁻¹ A_i)ᵀ = L⁻¹ A_i L⁻ᵀ`.
                solve_lower(l, s_i.as_mut());
                transpose_square_in_place(s_i.as_mut(), n);
                solve_lower(l, s_i.as_mut());
            }
            Ok::<(), GprError>(())
        })();
        self.store.buffers.core_mut().thread_scratch = thread_scratch;
        halves?;
        for i in 0..n_params {
            for j in 0..=i {
                let tr = frobenius_full(hess.s[i].as_ref(), hess.s[j].as_ref(), n);
                let mut v_dot = 0.0;
                for row in 0..n {
                    v_dot += hess.v[(row, i)].to_f64() * hess.v[(row, j)].to_f64();
                }
                let add = -0.5 * tr + v_dot;
                out[i * n_params + j] += add;
                if i != j {
                    out[j * n_params + i] += add;
                }
            }
        }
        Ok(())
    }

    fn write_second_deriv(
        &mut self,
        n_kernel: usize,
        i: usize,
        j: usize,
        n: usize,
    ) -> Result<(), GprError> {
        if i >= n_kernel || j >= n_kernel {
            zero_and_maybe_noise(
                self.store.buffers.core_mut().exp_buf.as_mut(),
                n,
                i == n_kernel && j == n_kernel,
                self.core.likelihood.noise_variance(),
            );
            return Ok(());
        }
        let x = train_points::<P, _>(
            &self.core.x,
            (self.core.n, self.core.d),
            &mut self.core.x_cast,
            &self.core.supplied,
        );
        let (core, dist) = self.store.buffers.split_fit();
        let WorkspaceCore {
            exp_buf,
            kernel_scratch,
            nested,
            thread_scratch,
            ..
        } = core;
        let inputs = fill_cached_inputs(&self.core.compiled, x, dist, thread_scratch)?;
        with_kernel_exp!(self.core.policies.math, M => self.core.compiled.hess_gram::<M>(
            inputs,
            exp_buf.as_mut(),
            (i, j),
            Triangle::Lower,
            kernel_scratch.as_mut(),
            nested,
        ))
    }

    fn write_first_deriv(&mut self, idx: usize) -> Result<(), GprError> {
        let x = train_points::<P, _>(
            &self.core.x,
            (self.core.n, self.core.d),
            &mut self.core.x_cast,
            &self.core.supplied,
        );
        let (core, dist) = self.store.buffers.split_fit();
        let WorkspaceCore {
            exp_buf,
            kernel_scratch,
            nested,
            thread_scratch,
            ..
        } = core;
        let inputs = fill_cached_inputs(&self.core.compiled, x, dist, thread_scratch)?;
        with_kernel_exp!(self.core.policies.math, M => self.core.compiled.grad_gram::<M>(
            inputs,
            exp_buf.as_mut(),
            idx,
            Triangle::Lower,
            kernel_scratch.as_mut(),
            nested,
        ))
    }

    fn fill_gradient_from_factor(
        &mut self,
        n_kernel: usize,
        n: usize,
        out: &mut [f64],
        kept: KeptGrams,
    ) -> Result<(), GprError> {
        self.store
            .buffers
            .form_gradient_w(&self.core.factor_alpha, n);
        self.kernel_gradient_into(n, &mut out[..n_kernel], kept)?;
        let mut noise_inner = 0.0;
        let d_noise = self.core.likelihood.noise_variance();
        let w = self.store.buffers.gradient_w();
        for i in 0..n {
            noise_inner += w[(i, i)].to_f64() * d_noise;
        }
        out[n_kernel] = -0.5 * noise_inner;
        Ok(())
    }

    /// Writes `-½ ⟨W, ∂K/∂θ_i⟩_F` for every kernel parameter into `out`, in
    /// one walk of the kernel tree (`CompiledKernel::weighted_grads`). The
    /// walk reads the product factor Grams `kept` says the factor of this
    /// `θ` left ([`Self::factor_with`]).
    fn kernel_gradient_into(
        &mut self,
        n: usize,
        out: &mut [f64],
        kept: KeptGrams,
    ) -> Result<(), GprError> {
        if out.is_empty() {
            return Ok(());
        }
        let KeptGrams { products } = kept;
        self.ensure_weighted(n, products)?;
        let x = train_points::<P, _>(
            &self.core.x,
            (self.core.n, self.core.d),
            &mut self.core.x_cast,
            &self.core.supplied,
        );
        let compiled = &self.core.compiled;
        let views = self.store.buffers.split_gradient();
        let (kept, bufs) = views.weighted.split_at_mut(compiled.kept_buffers(products));
        let inputs = fill_cached_inputs(compiled, x, views.dist, views.thread_scratch)?;
        let mut walk = WeightedWalk {
            inputs,
            scratch: views.kernel_scratch.as_mut(),
            nested: views.nested,
            kept,
            kept_products: products,
            fold: views.ard_fold,
        };
        with_kernel_exp!(self.core.policies.math, M => compiled.weighted_grads::<M>(
            &mut walk,
            views.w,
            out,
            bufs,
        ))?;
        for value in out.iter_mut() {
            *value *= -0.5;
        }
        Ok(())
    }

    /// Whether a gradient writes `W` over `L` ([`crate::CholeskyBuffer::Reuse`]).
    pub(crate) fn overwrites_cholesky(&self) -> bool {
        self.store.buffers.overwrites_cholesky()
    }

    pub(crate) fn restore_cholesky_if_overwritten(&mut self) -> Result<(), GprError> {
        if self.overwrites_cholesky() {
            self.factorize_current()?;
        }
        Ok(())
    }

    pub(crate) fn commit_or_revert_optimize(
        &mut self,
        kernel_before: SpecOf<K>,
        likelihood_before: GaussianLikelihood,
        result: Result<OptResult, GprError>,
    ) -> Result<(), GprError> {
        match result {
            Ok(opt) => {
                if opt.params.len() != self.num_params() || !opt.value.is_finite() {
                    self.revert_theta(kernel_before, likelihood_before);
                    return Err(GprError::OptimizationNotConverged {
                        iterations: opt.iterations as usize,
                    });
                }
                // The model holds the last θ the optimizer evaluated, which is
                // not the result after restarts, a rejected annealing step, or
                // a caller optimizer that searched past its best point.
                if !self.holds_params(&opt.params)?
                    && let Err(err) = self.factor_at(&opt.params, Keep::Nothing)
                {
                    self.revert_theta(kernel_before, likelihood_before);
                    return Err(err);
                }
                Ok(())
            }
            Err(err) => {
                self.revert_theta(kernel_before, likelihood_before);
                Err(err)
            }
        }
    }

    /// Whether the stored `θ` is bit-for-bit `params`.
    fn holds_params(&mut self, params: &[f64]) -> Result<bool, GprError> {
        let current = &mut self.store.buffers.core_mut().theta;
        current.resize(params.len(), 0.0);
        self.core.get_params(current)?;
        Ok(current
            .iter()
            .zip(params)
            .all(|(a, b)| a.to_bits() == b.to_bits()))
    }

    fn revert_theta(&mut self, kernel: SpecOf<K>, likelihood: GaussianLikelihood) {
        self.core.kernel = kernel;
        self.core.likelihood = likelihood;
        self.core.compiled = self.core.kernel.compile_as::<P::Storage>();
        let _ = self.factorize_current();
    }

    pub(crate) fn factorize_current(&mut self) -> Result<(), GprError> {
        self.factor()
    }

    /// The one writer of the factor `α`: `A⁻¹ y` from the solve that just ran.
    fn commit_factor(&mut self) {
        let n = self.core.n;
        if self.core.factor_alpha.len() != n {
            self.core.factor_alpha.resize(n, P::Storage::from_f64(0.0));
        }
        for (i, slot) in self.core.factor_alpha.iter_mut().enumerate() {
            *slot = self.store.buffers.core().rhs[(i, 0)];
        }
    }

    pub(crate) fn fill_intervals(&self, out: &mut [Interval]) -> Result<(), GprError> {
        let n = self.num_params();
        if out.len() != n {
            return Err(GprError::LengthMismatch {
                reason: format!("expected {n} intervals, got {}", out.len()),
            });
        }
        let n_kernel = self.core.kernel.num_params();
        let mut offset = 0;
        self.core
            .kernel
            .write_intervals(&mut out[..n_kernel], &mut offset)?;
        out[n_kernel] = self.core.likelihood.bounds();
        Ok(())
    }
}

/// Whether a factor keeps the product factor Grams for the joint gradient.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Keep {
    Nothing,
    FactorGrams,
}

/// What the last factor left in the leading `weighted` buffers: the factor
/// Grams of the first `products` products that keep them, at the `θ` of that
/// factor. Only [`ExactFit::factor_with`] makes one, and the joint gradient
/// takes it by value, so the walk reads kept Grams only right after the
/// factor that wrote them.
struct KeptGrams {
    products: usize,
}

fn require_change_indices(indices: &[usize], n_params: usize) -> Result<(), GprError> {
    if indices.is_empty() {
        return Err(GprError::IndexOutOfRange {
            reason: "change indices must not be empty".to_owned(),
        });
    }
    for (k, &i) in indices.iter().enumerate() {
        if i >= n_params {
            return Err(GprError::IndexOutOfRange {
                reason: format!("change index {i} is out of range (n_params={n_params})"),
            });
        }
        if indices[..k].contains(&i) {
            return Err(GprError::IndexOutOfRange {
                reason: format!("change index {i} is duplicated"),
            });
        }
    }
    Ok(())
}

fn zero_and_maybe_noise<T: KernelScalar>(
    mut out: MatMut<'_, T>,
    n: usize,
    noise_diag: bool,
    noise: f64,
) {
    let noise_s = T::from_f64(noise);
    let zero = T::from_f64(0.0);
    for col in 0..n {
        for row in col..n {
            out[(row, col)] = if noise_diag && row == col {
                noise_s
            } else {
                zero
            };
        }
    }
}

/// `⟨a, b⟩_F` over the full `n × n` matrices, accumulated in `f64`.
fn frobenius_full<T: KernelScalar>(a: MatRef<'_, T>, b: MatRef<'_, T>, n: usize) -> f64 {
    let mut sum = 0.0;
    for col in 0..n {
        for row in 0..n {
            sum += a[(row, col)].to_f64() * b[(row, col)].to_f64();
        }
    }
    sum
}

fn transpose_square_in_place<T: KernelScalar>(mut a: MatMut<'_, T>, n: usize) {
    for col in 0..n {
        for row in col + 1..n {
            let upper = a[(col, row)];
            a[(col, row)] = a[(row, col)];
            a[(row, col)] = upper;
        }
    }
}