gprx 0.1.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
//! Allocation ratchet after Workspace setup (P1A-19 / P2-4).
//!
//! Counts heap allocations on the Exact GPR hot path once `fit` has already
//! sized the workspace. Caps may fall, never rise without an Issue. P2-4
//! requires zero on isotropic RBF (`value_and_gradient_into` and
//! `predict_into` after warmup). User kernels are excluded. P2B-22 (#143)
//! pins `RAYON_NUM_THREADS=1` in this binary so faer `Par::rayon(1)` does
//! not allocate worker scratch that a multi-thread pool would.

mod common;
use common::rng::{open_unit, seeded_rng};
use gprx::Adam;
use gprx::kernel::{ConstantKernel, KernelSpec, RbfArdKernel, RbfKernel};
use gprx::{
    DoublePrecision, FittedGpr, Fixed, GaussianLikelihood, GpScalar, Gpr, GprError, KernelExp,
    MixedPrecision, Prediction, ReevaluateKernel, Sgpr, SinglePrecision, Svgp,
};
use stats_alloc::{INSTRUMENTED_SYSTEM, Region, StatsAlloc};
use std::alloc::System;
use std::num::{NonZeroU64, NonZeroUsize};
use std::sync::{Mutex, OnceLock};

#[global_allocator]
static GLOBAL: &StatsAlloc<System> = &INSTRUMENTED_SYSTEM;

const N: usize = 256;
const D: usize = 8;
const M: usize = 100;
const SEED: u64 = 0;
const ELL: f64 = 1.0;
const NOISE: f64 = 0.1;

/// One `value_and_gradient_into` after a warmup call. Do not raise without an Issue.
const MAX_MLL_AND_GRAD_ALLOCS: usize = 0;

/// One coordinate step (`value_at_changes`) of an incremental fit on a sum
/// of two leaves, after a warmup step (R4-5 / #243, #270, #272). Do not
/// raise without an Issue.
const MAX_LEAF_STEP_ALLOCS: usize = 0;

/// One `value_and_gradient_into` on composite kernels after a warmup call,
/// by kernel (#270, #272). Do not raise without an Issue.
const MAX_COMPOSITE_MLL_AND_GRAD_ALLOCS: [(&str, usize); 6] = [
    ("sum_with_ard", 0),
    ("product", 0),
    ("ard", 0),
    ("sum", 0),
    ("nested", 0),
    ("nested_mixed", 0),
];

/// One `hessian_into` after a warmup call, by kernel: the isotropic RBF leaf,
/// then the composite kernels (#272). Do not raise without an Issue.
const MAX_HESSIAN_ALLOCS: [(&str, usize); 7] = [
    ("rbf", 0),
    ("sum_with_ard", 0),
    ("product", 0),
    ("ard", 0),
    ("sum", 0),
    ("nested", 0),
    ("nested_mixed", 0),
];

/// Training points of the Hessian ratchet: it solves `n×n` systems per
/// parameter pair, and its allocations do not depend on `n`.
const N_HESSIAN: usize = 32;

/// One `predict_into` of 100 points on composite kernels after a warmup call,
/// by kernel (#272). Do not raise without an Issue.
const MAX_COMPOSITE_PREDICT_100_ALLOCS: [(&str, usize); 6] = [
    ("sum_with_ard", 0),
    ("product", 0),
    ("ard", 0),
    ("sum", 0),
    ("nested", 0),
    ("nested_mixed", 0),
];

/// One `predict_into` of 100 points after a warmup call. Do not raise without an Issue.
const MAX_PREDICT_100_ALLOCS: usize = 0;

/// Bytes one [`MixedPrecision`] `predict_into` of 100 points may allocate after
/// a warmup call: below one `n×n` `f32` matrix, so predict never rebuilds or
/// refines the training system (R3-1 / #236). Do not raise without an Issue.
const MAX_MIXED_PREDICT_100_BYTES: usize = N * N * std::mem::size_of::<f32>();

/// Inducing points of the sparse ratchets.
const M_SPARSE: usize = 32;

/// Allocations of one call on the sparse models after a warmup call, by
/// path (R5-1d / #246). The sparse fits return new matrices for their
/// factors, so these are not zero; the kernel scratch of the `&mut self`
/// paths is kept on the model between calls. Do not raise without an Issue.
const MAX_SPARSE_ALLOCS: [(&str, usize); 5] = [
    ("sgpr_mll_and_grad", 12),
    ("sgpr_hessian", 109),
    ("online_sgpr_insert", 8),
    ("online_sgpr_insert_nested", 16),
    ("svgp_mll_and_grad", 16),
];

/// One sparse `predict_into` of 100 points after a warmup call, by model,
/// kernel, and precision (R5-5 / #283). Do not raise without an Issue.
const MAX_SPARSE_PREDICT_100_ALLOCS: usize = 0;

/// Bytes one [`MixedPrecision`] SVGP `predict_into` of 100 points may
/// allocate after a warmup call: the mixed mean refines `L_mm⁻¹ k_*` in
/// `f64` for each query (#39), and the refinement loop keeps three `f64`
/// vectors of length `m` per query. The `f64` reference (`L_mm`, `K(Z, X*)`)
/// is built once per call into buffers the model keeps. The other sparse
/// paths allocate nothing. Do not raise without an Issue.
const MAX_SVGP_MIXED_PREDICT_100_BYTES: usize = M * 3 * M_SPARSE * std::mem::size_of::<f64>();

fn ensure_one_rayon_worker() {
    static INIT: OnceLock<()> = OnceLock::new();
    INIT.get_or_init(|| {
        // SAFETY: this integration test has not started the Rayon pool yet.
        // One worker keeps faer at `Par::rayon(1)` so the 0-alloc ratchet
        // still applies after P2B-22 (#143).
        unsafe {
            std::env::set_var("RAYON_NUM_THREADS", "1");
        }
    });
}

fn fill_column_major(n: usize, d: usize, seed: u64) -> Vec<f64> {
    let mut rng = seeded_rng(seed);
    let mut x = vec![0.0; n * d];
    for col in 0..d {
        for row in 0..n {
            x[col * n + row] = open_unit(&mut rng);
        }
    }
    x
}

fn fitted_model() -> Result<(FittedGpr<Fixed>, Vec<f64>), GprError> {
    ensure_one_rayon_worker();
    let kernel = KernelSpec::from(RbfKernel::new(ELL)?);
    let likelihood = GaussianLikelihood::new(NOISE)?;
    let x = fill_column_major(N, D, SEED);
    let mut rng = seeded_rng(SEED ^ 0xA5A5_A5A5_A5A5_A5A5);
    let y: Vec<f64> = (0..N).map(|_| open_unit(&mut rng)).collect();
    let gpr = Gpr::new(kernel, likelihood)
        .with_optimizer(Fixed)
        .factor(&x, N, D, &y)?;
    let xs = fill_column_major(M, D, SEED.wrapping_add(1));
    Ok((gpr, xs))
}

fn alloc_lock() -> std::sync::MutexGuard<'static, ()> {
    // `stats_alloc` counts the process, not the calling thread.
    static LOCK: Mutex<()> = Mutex::new(());
    LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}

fn allocs_in(f: impl FnOnce()) -> usize {
    let region = Region::new(GLOBAL);
    f();
    let stats = region.change();
    stats.allocations + stats.reallocations
}

fn assert_alloc_cap(label: &str, count: usize, cap: usize) {
    eprintln!("{label}: allocations={count} cap={cap}");
    assert!(
        count <= cap,
        "{label}: allocations={count}, cap={cap}; lower the cap when allocs drop, do not raise it without an Issue"
    );
}

#[test]
fn mll_and_grad_allocs_after_workspace() {
    let _guard = alloc_lock();
    let (mut gpr, _) = fitted_model().expect("spd");
    let mut params = vec![0.0; gpr.num_params()];
    gpr.get_params(&mut params).expect("len");
    let mut grad = vec![0.0; params.len()];
    gpr.value_and_gradient_into(&params, &mut grad)
        .expect("warmup");
    let count = allocs_in(|| {
        gpr.value_and_gradient_into(&params, &mut grad)
            .expect("counted");
    });
    assert_alloc_cap("mll_and_grad", count, MAX_MLL_AND_GRAD_ALLOCS);
}

#[test]
fn fast_approx_mll_and_grad_allocs_after_workspace() {
    let _guard = alloc_lock();
    ensure_one_rayon_worker();
    let kernel = KernelSpec::from(RbfKernel::new(ELL).expect("ell"));
    let likelihood = GaussianLikelihood::new(NOISE).expect("noise");
    let x = fill_column_major(N, D, SEED);
    let mut rng = seeded_rng(SEED ^ 0xA5A5_A5A5_A5A5_A5A5);
    let y: Vec<f64> = (0..N).map(|_| open_unit(&mut rng)).collect();
    let mut gpr = Gpr::new(kernel, likelihood)
        .with_math(KernelExp::FastApprox)
        .with_optimizer(Fixed)
        .factor(&x, N, D, &y)
        .expect("spd");
    let mut params = vec![0.0; gpr.num_params()];
    gpr.get_params(&mut params).expect("len");
    let mut grad = vec![0.0; params.len()];
    gpr.value_and_gradient_into(&params, &mut grad)
        .expect("warmup");
    let count = allocs_in(|| {
        gpr.value_and_gradient_into(&params, &mut grad)
            .expect("counted");
    });
    assert_alloc_cap("fast_mll_and_grad", count, MAX_MLL_AND_GRAD_ALLOCS);
    let _typed: FittedGpr<Fixed> = gpr;
}

#[test]
fn predict_100_allocs_after_workspace() {
    let _guard = alloc_lock();
    let (mut gpr, xs) = fitted_model().expect("spd");
    let mut pred = Prediction::default();
    gpr.predict_into(&xs, M, D, &mut pred).expect("warmup");
    let count = allocs_in(|| {
        gpr.predict_into(&xs, M, D, &mut pred).expect("counted");
    });
    assert_alloc_cap("predict_100", count, MAX_PREDICT_100_ALLOCS);
}

type MixedFitted<R> = FittedGpr<Fixed, MixedPrecision<R>>;

fn fitted_mixed<R>() -> Result<(MixedFitted<R>, Vec<f64>), GprError>
where
    MixedPrecision<R>: gprx::GpScalar,
    R: gprx::ResidualFormula,
{
    ensure_one_rayon_worker();
    let kernel = KernelSpec::from(RbfKernel::new(ELL)?);
    let likelihood = GaussianLikelihood::new(NOISE)?;
    let x = fill_column_major(N, D, SEED);
    let mut rng = seeded_rng(SEED ^ 0xA5A5_A5A5_A5A5_A5A5);
    let y: Vec<f64> = (0..N).map(|_| open_unit(&mut rng)).collect();
    let gpr = Gpr::new(kernel, likelihood)
        .with_optimizer(Fixed)
        .with_precision::<MixedPrecision<R>>()
        .factor(&x, N, D, &y)
        .map_err(|(_, e)| e)?;
    let xs = fill_column_major(M, D, SEED.wrapping_add(1));
    Ok((gpr, xs))
}

fn bytes_in(f: impl FnOnce()) -> usize {
    let region = Region::new(GLOBAL);
    f();
    let stats = region.change();
    stats.bytes_allocated + stats.bytes_reallocated.max(0) as usize
}

#[allow(clippy::expect_used)] // helper is outside `#[test]`; clippy.toml allows only the test body
fn assert_mixed_predict_bytes<R>(label: &str)
where
    MixedPrecision<R>: gprx::GpScalar,
    R: gprx::ResidualFormula,
{
    let _guard = alloc_lock();
    let (mut gpr, xs) = fitted_mixed::<R>().expect("spd");
    let mut pred = Prediction::default();
    gpr.predict_into(&xs, M, D, &mut pred).expect("warmup");
    let bytes = bytes_in(|| {
        gpr.predict_into(&xs, M, D, &mut pred).expect("counted");
    });
    eprintln!("{label}: bytes={bytes} cap={MAX_MIXED_PREDICT_100_BYTES}");
    assert!(
        bytes < MAX_MIXED_PREDICT_100_BYTES,
        "{label}: bytes={bytes}, cap={MAX_MIXED_PREDICT_100_BYTES}; predict must not rebuild the n×n system"
    );
}

#[test]
fn mixed_promote_predict_100_bytes_after_workspace() {
    assert_mixed_predict_bytes::<gprx::PromoteStorage>("mixed_promote_predict_100");
}

#[test]
fn mixed_reevaluate_predict_100_bytes_after_workspace() {
    assert_mixed_predict_bytes::<ReevaluateKernel>("mixed_reevaluate_predict_100");
}

/// Optimizer that measures one incremental coordinate step inside `minimize`.
#[derive(Clone, Copy, Debug)]
struct LeafStepProbe;

static LEAF_STEP_ALLOCS: Mutex<Option<usize>> = Mutex::new(None);

impl<P: gprx::Objective> gprx::Optimizer<P> for LeafStepProbe {
    const USES_CHANGE_INDICES: bool = true;

    fn minimize(&self, objective: &mut P, init: &[f64]) -> Result<gprx::OptResult, GprError> {
        let mut step = init.to_vec();
        let value = objective.value(&step)?;
        step[0] += 0.01;
        objective.value_at_changes(&step, &[0])?;
        step[0] += 0.01;
        let mut result = Ok(0.0);
        let count = allocs_in(|| {
            result = objective.value_at_changes(&step, &[0]);
        });
        result?;
        if let Ok(mut slot) = LEAF_STEP_ALLOCS.lock() {
            *slot = Some(count);
        }
        Ok(gprx::OptResult {
            params: init.to_vec(),
            value,
            iterations: 0,
        })
    }
}

#[test]
fn incremental_leaf_step_allocs_after_warmup() {
    let _guard = alloc_lock();
    ensure_one_rayon_worker();
    let kernel = KernelSpec::from(RbfKernel::new(ELL).expect("ell"))
        + KernelSpec::from(RbfKernel::new(2.0 * ELL).expect("ell"));
    let likelihood = GaussianLikelihood::new(NOISE).expect("noise");
    let x = fill_column_major(N, D, SEED);
    let mut rng = seeded_rng(SEED ^ 0xA5A5_A5A5_A5A5_A5A5);
    let y: Vec<f64> = (0..N).map(|_| open_unit(&mut rng)).collect();
    Gpr::new(kernel, likelihood)
        .with_optimizer(LeafStepProbe)
        .fit(&x, N, D, &y)
        .map_err(|(_, e)| e)
        .expect("fit");
    let count = LEAF_STEP_ALLOCS.lock().expect("lock").expect("probe ran");
    assert_alloc_cap("leaf_step", count, MAX_LEAF_STEP_ALLOCS);
}

/// Flat sums and products, one ARD leaf, and a sum / product nested in
/// another in distance mode and in mixed coordinate mode.
#[allow(clippy::expect_used)] // helper is outside `#[test]`; clippy.toml allows only the test body
fn composite_kernels() -> [(&'static str, KernelSpec); 6] {
    let rbf = |ell: f64| KernelSpec::from(RbfKernel::new(ell).expect("ell"));
    let ard = || KernelSpec::from(RbfArdKernel::new(&[ELL; D]).expect("ell"));
    let constant = |value: f64| KernelSpec::from(ConstantKernel::new(value).expect("constant"));
    [
        ("sum_with_ard", rbf(ELL) + ard()),
        ("product", constant(1.5) * rbf(ELL)),
        ("ard", ard()),
        ("sum", rbf(ELL) + rbf(2.0 * ELL)),
        (
            "nested",
            (rbf(ELL) + rbf(2.0 * ELL)) * (constant(1.5) * rbf(3.0 * ELL) + constant(0.5)),
        ),
        (
            "nested_mixed",
            (rbf(ELL) + ard()) * (constant(1.5) * rbf(3.0 * ELL) + constant(0.5)),
        ),
    ]
}

#[allow(clippy::expect_used)] // helper is outside `#[test]`; clippy.toml allows only the test body
fn fitted_with(kernel: KernelSpec, n: usize) -> FittedGpr<Fixed> {
    ensure_one_rayon_worker();
    let likelihood = GaussianLikelihood::new(NOISE).expect("noise");
    let x = fill_column_major(n, D, SEED);
    let mut rng = seeded_rng(SEED ^ 0xA5A5_A5A5_A5A5_A5A5);
    let y: Vec<f64> = (0..n).map(|_| open_unit(&mut rng)).collect();
    Gpr::new(kernel, likelihood)
        .with_optimizer(Fixed)
        .factor(&x, n, D, &y)
        .map_err(|(_, e)| e)
        .expect("spd")
}

/// `value_and_gradient_into` on composite kernels after a warmup call.
#[test]
fn composite_mll_and_grad_allocs_after_workspace() {
    let _guard = alloc_lock();
    for ((label, cap), (name, kernel)) in MAX_COMPOSITE_MLL_AND_GRAD_ALLOCS
        .into_iter()
        .zip(composite_kernels())
    {
        assert_eq!(label, name);
        let mut gpr = fitted_with(kernel, N);
        let mut params = vec![0.0; gpr.num_params()];
        gpr.get_params(&mut params).expect("len");
        let mut grad = vec![0.0; params.len()];
        gpr.value_and_gradient_into(&params, &mut grad)
            .expect("warmup");
        let count = allocs_in(|| {
            gpr.value_and_gradient_into(&params, &mut grad)
                .expect("counted");
        });
        assert_alloc_cap(label, count, cap);
    }
}

/// `hessian_into` on the RBF leaf and the composite kernels after a warmup call.
#[test]
fn hessian_allocs_after_warmup() {
    let _guard = alloc_lock();
    let kernels = std::iter::once(("rbf", KernelSpec::from(RbfKernel::new(ELL).expect("ell"))))
        .chain(composite_kernels());
    for ((label, cap), (name, kernel)) in MAX_HESSIAN_ALLOCS.into_iter().zip(kernels) {
        assert_eq!(label, name);
        let mut gpr = fitted_with(kernel, N_HESSIAN);
        let mut params = vec![0.0; gpr.num_params()];
        gpr.get_params(&mut params).expect("len");
        let mut hess = vec![0.0; params.len() * params.len()];
        gpr.hessian_into(&params, &mut hess).expect("warmup");
        let count = allocs_in(|| {
            gpr.hessian_into(&params, &mut hess).expect("counted");
        });
        assert_alloc_cap(&format!("hessian_{label}"), count, cap);
    }
}

/// `predict_into` of 100 points on the composite kernels after a warmup call.
#[test]
fn composite_predict_100_allocs_after_workspace() {
    let _guard = alloc_lock();
    let xs = fill_column_major(M, D, SEED.wrapping_add(1));
    for ((label, cap), (name, kernel)) in MAX_COMPOSITE_PREDICT_100_ALLOCS
        .into_iter()
        .zip(composite_kernels())
    {
        assert_eq!(label, name);
        let mut gpr = fitted_with(kernel, N);
        let mut pred = Prediction::default();
        gpr.predict_into(&xs, M, D, &mut pred).expect("warmup");
        let count = allocs_in(|| {
            gpr.predict_into(&xs, M, D, &mut pred).expect("counted");
        });
        assert_alloc_cap(&format!("predict_100_{label}"), count, cap);
    }
}

#[allow(clippy::expect_used)] // helper is outside `#[test]`; clippy.toml allows only the test body
fn sparse_allocs(label: &str, kernel: KernelSpec) -> Vec<(String, usize)> {
    ensure_one_rayon_worker();
    let x = fill_column_major(N, D, SEED);
    let z = fill_column_major(M_SPARSE, D, SEED.wrapping_add(2));
    let mut rng = seeded_rng(SEED ^ 0xA5A5_A5A5_A5A5_A5A5);
    let y: Vec<f64> = (0..N).map(|_| open_unit(&mut rng)).collect();
    let x_new: Vec<f64> = (0..D).map(|dim| 0.1 * dim as f64).collect();
    let likelihood = GaussianLikelihood::new(NOISE).expect("noise");
    let mut fitted = Sgpr::new(kernel.clone(), likelihood)
        .with_optimizer(Fixed)
        .factor(&x, N, D, &y, &z, M_SPARSE)
        .map_err(|(_, e)| e)
        .expect("spd");
    let mut out = Vec::new();
    if label == "rbf" {
        let mut params = vec![0.0; fitted.num_params()];
        fitted.get_params(&mut params).expect("len");
        let mut grad = vec![0.0; params.len()];
        let mut hess = vec![0.0; params.len() * params.len()];
        fitted
            .value_and_gradient_into(&params, &mut grad)
            .expect("warmup");
        let count = allocs_in(|| {
            fitted
                .value_and_gradient_into(&params, &mut grad)
                .expect("counted");
        });
        out.push(("sgpr_mll_and_grad".to_owned(), count));
        fitted.hessian_into(&params, &mut hess).expect("warmup");
        let count = allocs_in(|| {
            fitted.hessian_into(&params, &mut hess).expect("counted");
        });
        out.push(("sgpr_hessian".to_owned(), count));
    }
    let mut online = fitted.into_online();
    online.insert(&x_new, 0.5).expect("warmup");
    let count = allocs_in(|| {
        online.insert(&x_new, 0.25).expect("counted");
    });
    let insert_label = if label == "rbf" {
        "online_sgpr_insert"
    } else {
        "online_sgpr_insert_nested"
    };
    out.push((insert_label.to_owned(), count));
    if label == "rbf" {
        let mut svgp = Svgp::new(kernel, likelihood)
            .factor(&x, N, D, &y, &z, M_SPARSE)
            .map_err(|(_, e)| e)
            .expect("spd");
        let mut params = vec![0.0; svgp.num_params()];
        svgp.get_params(&mut params).expect("len");
        let mut grad = vec![0.0; params.len()];
        svgp.value_and_gradient_into(&params, &mut grad)
            .expect("warmup");
        let count = allocs_in(|| {
            svgp.value_and_gradient_into(&params, &mut grad)
                .expect("counted");
        });
        out.push(("svgp_mll_and_grad".to_owned(), count));
    }
    out
}

/// One call on each sparse path after a warmup call. The nested kernel (a
/// product of sums) covers the nested scratch levels on the insert path.
#[test]
fn sparse_allocs_after_warmup() {
    let _guard = alloc_lock();
    let rbf = || KernelSpec::from(RbfKernel::new(ELL).expect("ell"));
    let constant = |v: f64| KernelSpec::from(ConstantKernel::new(v).expect("constant"));
    let nested = (rbf() + KernelSpec::from(RbfKernel::new(2.0 * ELL).expect("ell")))
        * (constant(1.5) * rbf() + constant(0.5));
    let mut counts = sparse_allocs("rbf", rbf());
    counts.extend(sparse_allocs("nested", nested));
    for (label, cap) in MAX_SPARSE_ALLOCS {
        let count = counts
            .iter()
            .find(|(name, _)| name == label)
            .map(|(_, count)| *count)
            .expect("measured");
        assert_alloc_cap(label, count, cap);
    }
}

/// Allocations (or, with `count = bytes_in`, bytes) of one `predict_into` of
/// `M` points after a warmup call on a [`gprx::FittedSgpr`], the
/// [`gprx::OnlineSgpr`] after one insert, and a [`gprx::FittedSvgp`], at
/// precision `P`.
#[allow(clippy::expect_used)] // helper is outside `#[test]`; clippy.toml allows only the test body
fn sparse_predict_counts<P: GpScalar>(
    kernel: KernelSpec,
    count: fn(&mut dyn FnMut()) -> usize,
) -> [(&'static str, usize); 3] {
    ensure_one_rayon_worker();
    let x = fill_column_major(N, D, SEED);
    let z = fill_column_major(M_SPARSE, D, SEED.wrapping_add(2));
    let xs = fill_column_major(M, D, SEED.wrapping_add(1));
    let mut rng = seeded_rng(SEED ^ 0xA5A5_A5A5_A5A5_A5A5);
    let y: Vec<f64> = (0..N).map(|_| open_unit(&mut rng)).collect();
    let likelihood = GaussianLikelihood::new(NOISE).expect("noise");
    let mut pred = Prediction::default();
    let mut fitted = Sgpr::new(kernel.clone(), likelihood)
        .with_optimizer(Fixed)
        .with_precision::<P>()
        .factor(&x, N, D, &y, &z, M_SPARSE)
        .map_err(|(_, e)| e)
        .expect("spd");
    fitted.predict_into(&xs, M, D, &mut pred).expect("warmup");
    let sgpr = count(&mut || fitted.predict_into(&xs, M, D, &mut pred).expect("counted"));
    let mut online = fitted.into_online();
    let x_new: Vec<f64> = (0..D).map(|dim| 0.1 * dim as f64).collect();
    online.insert(&x_new, 0.5).expect("insert");
    online.predict_into(&xs, M, D, &mut pred).expect("warmup");
    let online = count(&mut || online.predict_into(&xs, M, D, &mut pred).expect("counted"));
    let mut svgp = Svgp::new(kernel, likelihood)
        .with_precision::<P>()
        .factor(&x, N, D, &y, &z, M_SPARSE)
        .map_err(|(_, e)| e)
        .expect("spd");
    svgp.predict_into(&xs, M, D, &mut pred).expect("warmup");
    let svgp = count(&mut || svgp.predict_into(&xs, M, D, &mut pred).expect("counted"));
    [("sgpr", sgpr), ("online_sgpr", online), ("svgp", svgp)]
}

fn allocs_in_dyn(f: &mut dyn FnMut()) -> usize {
    allocs_in(f)
}

fn bytes_in_dyn(f: &mut dyn FnMut()) -> usize {
    bytes_in(f)
}

/// Sparse `predict_into` after a warmup call: every model, a leaf and a
/// nested kernel, `f64` and `f32` storage, and mixed precision.
#[test]
fn sparse_predict_into_allocs_after_warmup() {
    let _guard = alloc_lock();
    let rbf = || KernelSpec::from(RbfKernel::new(ELL).expect("ell"));
    let constant = |v: f64| KernelSpec::from(ConstantKernel::new(v).expect("constant"));
    let nested = || {
        (rbf() + KernelSpec::from(RbfKernel::new(2.0 * ELL).expect("ell")))
            * (constant(1.5) * rbf() + constant(0.5))
    };
    let cases = [
        (
            "f64",
            sparse_predict_counts::<DoublePrecision>(rbf(), allocs_in_dyn),
        ),
        (
            "f64_nested",
            sparse_predict_counts::<DoublePrecision>(nested(), allocs_in_dyn),
        ),
        (
            "f32",
            sparse_predict_counts::<SinglePrecision>(rbf(), allocs_in_dyn),
        ),
        (
            "f32_nested",
            sparse_predict_counts::<SinglePrecision>(nested(), allocs_in_dyn),
        ),
    ];
    for (precision, counts) in cases {
        for (model, count) in counts {
            assert_alloc_cap(
                &format!("{model}_predict_100_{precision}"),
                count,
                MAX_SPARSE_PREDICT_100_ALLOCS,
            );
        }
    }
    for (label, counts) in [
        (
            "promote",
            sparse_predict_counts::<MixedPrecision<gprx::PromoteStorage>>(rbf(), allocs_in_dyn),
        ),
        (
            "reevaluate",
            sparse_predict_counts::<MixedPrecision<ReevaluateKernel>>(rbf(), allocs_in_dyn),
        ),
    ] {
        for (model, count) in counts {
            if model != "svgp" {
                assert_alloc_cap(
                    &format!("{model}_predict_100_mixed_{label}"),
                    count,
                    MAX_SPARSE_PREDICT_100_ALLOCS,
                );
            }
        }
    }
    for (label, counts) in [
        (
            "promote",
            sparse_predict_counts::<MixedPrecision<gprx::PromoteStorage>>(rbf(), bytes_in_dyn),
        ),
        (
            "reevaluate",
            sparse_predict_counts::<MixedPrecision<ReevaluateKernel>>(rbf(), bytes_in_dyn),
        ),
    ] {
        let bytes = counts[2].1;
        eprintln!(
            "svgp_predict_100_mixed_{label}: bytes={bytes} cap={MAX_SVGP_MIXED_PREDICT_100_BYTES}"
        );
        assert!(
            bytes <= MAX_SVGP_MIXED_PREDICT_100_BYTES,
            "svgp_predict_100_mixed_{label}: bytes={bytes}, cap={MAX_SVGP_MIXED_PREDICT_100_BYTES}"
        );
    }
}

/// Bytes one Adam step of `Svgp::fit` may allocate at `n = 4096`, relative to
/// `n = 512` at the same batch size: a step costs `O(batch · m²)`, so its
/// allocations do not grow with `n` (#300). It grew with `n` (8×) while a step
/// rebuilt `A` and the tangents of every point.
const MAX_SVGP_STEP_BYTES_GROWTH: f64 = 1.25;

/// Bytes per step the growth check tolerates on top of the ratio. A step now
/// allocates nothing (#353), so the ratio alone would fail on one stray
/// allocation from the thread pool spread over the steps.
const SVGP_STEP_BYTES_SLACK: f64 = 1024.0;

/// Bytes of one `Svgp::fit` with `epochs` epochs of mini-batches of 32.
#[allow(clippy::expect_used)] // helper is outside `#[test]`; clippy.toml allows only the test body
fn svgp_fit_bytes(n: usize, epochs: u64) -> usize {
    ensure_one_rayon_worker();
    let x = fill_column_major(n, D, SEED);
    let z = fill_column_major(M_SPARSE, D, SEED.wrapping_add(2));
    let mut rng = seeded_rng(SEED ^ 0xA5A5_A5A5_A5A5_A5A5);
    let y: Vec<f64> = (0..n).map(|_| open_unit(&mut rng)).collect();
    let kernel = KernelSpec::from(RbfKernel::new(ELL).expect("ell"));
    let adam = Adam::new()
        .with_batch_size(NonZeroUsize::new(32).expect("batch"))
        .with_epochs(NonZeroU64::new(epochs).expect("epochs"));
    let trainer =
        Svgp::new(kernel, GaussianLikelihood::new(NOISE).expect("noise")).with_optimizer(adam);
    let mut fitted = None;
    let bytes = bytes_in(|| {
        fitted = Some(
            trainer
                .fit(&x, n, D, &y, &z, M_SPARSE)
                .map_err(|(_, e)| e)
                .expect("fit"),
        );
    });
    drop(fitted);
    bytes
}

/// The bytes of one step: one more epoch is `n / 32` more steps, and the
/// setup and the final rebuild of `A` cancel in the difference.
fn svgp_step_bytes(n: usize) -> f64 {
    let extra = svgp_fit_bytes(n, 2) as f64 - svgp_fit_bytes(n, 1) as f64;
    extra / (n / 32) as f64
}

#[test]
fn svgp_adam_step_bytes_do_not_grow_with_n() {
    let _guard = alloc_lock();
    let _ = svgp_fit_bytes(64, 1); // one-time allocations (thread pool, statics)
    let small = svgp_step_bytes(512);
    let large = svgp_step_bytes(4096);
    eprintln!("svgp step bytes: n=512 {small:.0}, n=4096 {large:.0}");
    assert!(
        large <= MAX_SVGP_STEP_BYTES_GROWTH * small + SVGP_STEP_BYTES_SLACK,
        "an Adam step allocates {large:.0} bytes at n=4096 and {small:.0} at n=512: it scales with n"
    );
}

/// Allocations one more Adam epoch adds to `Svgp::fit` (64 points, batches
/// of 8: eight steps per epoch), by kernel. Do not raise without an Issue.
const MAX_SVGP_ADAM_EPOCH_ALLOCS: [(&str, usize); 3] =
    [("rbf", 0), ("rbf_ard", 0), ("constant_times_rbf", 0)];

#[test]
fn svgp_adam_epoch_allocs() {
    let _guard = alloc_lock();
    let n = 64;
    let x: Vec<f64> = (0..n * 2)
        .map(|i| (i % n) as f64 / 8.0 + (i / n) as f64)
        .collect();
    let y: Vec<f64> = (0..n).map(|i| (i as f64 / 8.0).sin()).collect();
    let z: Vec<f64> = (0..16).map(|i| (i % 8) as f64 + (i / 8) as f64).collect();
    let kernels = [
        KernelSpec::from(RbfKernel::new(ELL).expect("ell")),
        KernelSpec::from(RbfArdKernel::new(&[ELL, 2.0 * ELL]).expect("ell")),
        KernelSpec::from(ConstantKernel::new(1.5).expect("c"))
            * KernelSpec::from(RbfKernel::new(ELL).expect("ell")),
    ];
    for ((label, cap), kernel) in MAX_SVGP_ADAM_EPOCH_ALLOCS.iter().zip(kernels) {
        let fit = |epochs: u64| {
            allocs_in(|| {
                let fitted =
                    Svgp::new(kernel.clone(), GaussianLikelihood::new(0.1).expect("noise"))
                        .with_optimizer(
                            Adam::new()
                                .with_batch_size(NonZeroUsize::new(8).expect("8"))
                                .with_epochs(NonZeroU64::new(epochs).expect("epochs")),
                        )
                        .fit(&x, n, 2, &y, &z, 8)
                        .map_err(|(_, e)| e)
                        .expect("fit");
                std::hint::black_box(fitted);
            })
        };
        // Warm the thread pool, then take the least of a few differences: the
        // counter sees the whole process, not only this fit.
        fit(1);
        let per_epoch = (0..3)
            .map(|_| fit(3).saturating_sub(fit(1)) / 2)
            .min()
            .unwrap_or(usize::MAX);
        assert_alloc_cap(&format!("svgp_adam_epoch_{label}"), per_epoch, *cap);
    }
}