Skip to main content

gam_gpu/
encode_throughput.rs

1//! Measured device-resident throughput of the SAE/LLM batched-solve COMPONENT —
2//! the resident penalized normal-equations inner solve, NOT the full exact SAE
3//! encode (see the SCOPE section below) (#1412, #988, #1017 Phase-3).
4//!
5//! ## Why this module exists
6//!
7//! The historical throughput "decision gate" (#1412) asserted a `100_000`
8//! rows/sec/GPU deployment target **without ever measuring a device**. Its
9//! successor still keyed the deployment decision on a *CPU* measurement scaled
10//! by a hardcoded `CPU_TO_GPU_SCALING = 100.0` fudge factor — so passing the
11//! gate established nothing about real GPU throughput. #988 closed
12//! `COMPLETED` while the maintainer's own follow-up confirmed the GPU
13//! steady-state encode rate had never been measured.
14//!
15//! This module makes the measurement real and *testable as a library function*
16//! (the prior real benchmark lived only in `examples/throughput_1412.rs`, which
17//! nothing in CI ran or asserted). [`measure_resident_solve_throughput`] runs
18//! the production IRLS inner step — upload `X` once, then repeatedly solve the
19//! penalized normal equations `(XᵀWX + ridge·I)β = rhs` with the `p×p` Gram and
20//! its Cholesky factor kept DEVICE-RESIDENT, downloading only the `p`-vector
21//! `β` — on the real device, and reports the measured design-rows/sec.
22//!
23//! ## SCOPE — this is a COMPONENT benchmark, not the full exact SAE encode
24//!
25//! What is timed here is the resident penalized normal-equations *inner solve*
26//! `(XᵀWX + ridge·I)β = rhs` ONLY. That is one component of the SAE encode, NOT
27//! the full exact per-row SAE encode, and the measured rate is therefore NOT
28//! evidence for a "batched exact per-row GPU encode" title claim. The full exact
29//! encode would additionally require, per row: active-set routing (which atoms
30//! are live), the per-row latent-coordinate Newton refinement on the manifold,
31//! the assignment/gate (softmax/IBP) solve, and the certificate/fallback +
32//! reconstruction-validation path. None of those are exercised or timed by this
33//! function. Establishing the end-to-end encode-throughput claim requires a
34//! separate benchmark that times the *production encode path itself* (routing +
35//! latent-coordinate Newton + assignment/gate solve + fallback/certificate), not
36//! this inner-solve cell. Treat the number below strictly as the resident
37//! normal-equations inner-solve throughput.
38//!
39//! ## Fail-loud, never false-route
40//!
41//! The single recurring failure mode this guards against is *false GPU
42//! routing*: claiming a device measurement while the work silently ran on the
43//! CPU. [`ResidentSolveThroughput::engaged`] is `true` only when
44//! [`ResidentDesignGram::try_new`] actually staged `X` on the device AND every
45//! timed solve returned a device result. If the device path declines or fails
46//! mid-measurement, `engaged` is `false` and `measured_rows_per_sec` is left at
47//! `0.0` — a non-measurement that [`GpuThroughputVerdict`] can never report as
48//! meeting the target. There is no CPU fallback inside the measurement: a
49//! caller that wants the CPU oracle runs it separately for parity.
50
51use std::hint::black_box;
52use std::time::{Duration, Instant};
53
54use ndarray::{Array1, Array2, ArrayView1, ArrayView2};
55
56use super::linalg_dispatch::ResidentDesignGram;
57use super::policy::{GpuThroughputVerdict, GPU_THROUGHPUT_TARGET_ROWS_PER_SEC};
58
59/// A representative LLM/SAE batched-solve work cell: `n` design rows, `p` wide
60/// decoder border. (`d`, the per-atom reduced-Schur block size, is fixed by the
61/// term and does not enter the resident-solve throughput.)
62#[derive(Clone, Copy, Debug)]
63pub struct EncodeShape {
64    /// Human-readable label for reporting.
65    pub label: &'static str,
66    /// Design rows pushed through the device per fit.
67    pub n: usize,
68    /// Decoder-border width (the resident Gram is `p×p`).
69    pub p: usize,
70}
71
72/// The canonical qwen/olmo-scale SAE residual-block shapes (matches the
73/// `examples/throughput_1412.rs` workload so the library measurement and the
74/// example agree).
75pub const CANONICAL_ENCODE_SHAPES: &[EncodeShape] = &[
76    EncodeShape {
77        label: "sae-2k-2048",
78        n: 2_000,
79        p: 2_048,
80    },
81    EncodeShape {
82        label: "sae-4k-4096",
83        n: 4_000,
84        p: 4_096,
85    },
86    EncodeShape {
87        label: "sae-8k-1024",
88        n: 8_000,
89        p: 1_024,
90    },
91];
92
93/// Outcome of measuring the device-resident penalized-solve throughput for one
94/// [`EncodeShape`].
95#[derive(Clone, Copy, Debug)]
96pub struct ResidentSolveThroughput {
97    /// The shape that was measured.
98    pub shape: EncodeShape,
99    /// `true` iff `X` was staged on the device AND every timed solve returned a
100    /// device result. `false` means the device path declined or failed — the
101    /// number below is **not** a device measurement.
102    pub engaged: bool,
103    /// Measured design-rows/sec for the resident solve, or `0.0` when the
104    /// device path did not engage (a non-measurement).
105    pub measured_rows_per_sec: f64,
106    /// The verdict comparing `measured_rows_per_sec` against
107    /// [`GPU_THROUGHPUT_TARGET_ROWS_PER_SEC`].
108    pub verdict: GpuThroughputVerdict,
109}
110
111/// Deterministic LCG in `[-1, 1)` — no `rand` dependency, fully reproducible
112/// across runs so the measured fixture is stable.
113fn lcg(state: &mut u64) -> f64 {
114    *state = state
115        .wrapping_mul(6364136223846793005)
116        .wrapping_add(1442695040888963407);
117    (*state >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0
118}
119
120/// Build a deterministic `n×p` design fixture for the throughput measurement.
121fn planted_design(n: usize, p: usize, seed: u64) -> Array2<f64> {
122    let mut s = seed;
123    Array2::from_shape_fn((n, p), |_| lcg(&mut s) * 0.05)
124}
125
126/// Measure the device-resident penalized-normal-equations solve throughput for
127/// one shape: upload `X` once, then time `reps` solves that cross only `w`
128/// (H2D), `rhs` (H2D, fixed), and `β` (D2H) — the production IRLS inner step.
129///
130/// `reps` is the number of timed solves; `w` is perturbed per rep so each solve
131/// is genuine work, mirroring an IRLS weight update. Returns a
132/// [`ResidentSolveThroughput`] whose `engaged` flag is the false-routing guard:
133/// on a CPU-only host (or if the device declines) it is `false` and the rate is
134/// `0.0`.
135#[must_use]
136pub fn measure_resident_solve_throughput(shape: EncodeShape, reps: usize) -> ResidentSolveThroughput {
137    let EncodeShape { n, p, .. } = shape;
138    let not_engaged = |shape| ResidentSolveThroughput {
139        shape,
140        engaged: false,
141        measured_rows_per_sec: 0.0,
142        verdict: GpuThroughputVerdict::from_measurement(0.0),
143    };
144    if n == 0 || p == 0 || reps == 0 {
145        return not_engaged(shape);
146    }
147
148    let x = planted_design(n, p, 0x1412_a100_dead_beef);
149    let w = {
150        let mut s = 0x988_5ae_e0c0_de01u64;
151        Array1::from_shape_fn(n, |_| lcg(&mut s).abs() + 1e-3)
152    };
153    let rhs = Array1::from_shape_fn(p, |j| ((j as f64 + 1.0) * 0.03).cos());
154    let ridge = 1e-3_f64;
155
156    // Stage X once. `None` => no device / shape below the Gram threshold => not
157    // a device measurement.
158    let handle = match ResidentDesignGram::try_new(x.view()) {
159        Some(h) => h,
160        None => return not_engaged(shape),
161    };
162
163    // Warm the resident solve (allocations, kernel handles) outside the timer;
164    // if even the warm solve declines, the device path is not usable here.
165    if handle.solve_normal_equations(w.view(), rhs.view(), ridge).is_none() {
166        return not_engaged(shape);
167    }
168
169    let mut total = Duration::ZERO;
170    for r in 0..reps {
171        let wr = Array1::from_shape_fn(n, |i| (w[i] + 1e-3 * (r as f64)).abs());
172        let start = Instant::now();
173        match handle.solve_normal_equations(wr.view(), rhs.view(), ridge) {
174            Some(beta) => {
175                black_box(beta);
176            }
177            // A mid-measurement decline means the timed region is no longer a
178            // pure device measurement — refuse to report it as one.
179            None => return not_engaged(shape),
180        }
181        total += start.elapsed();
182    }
183
184    let secs = total.as_secs_f64() / reps as f64;
185    let measured_rows_per_sec = if secs > 0.0 { n as f64 / secs } else { 0.0 };
186    ResidentSolveThroughput {
187        shape,
188        engaged: measured_rows_per_sec > 0.0,
189        measured_rows_per_sec,
190        verdict: GpuThroughputVerdict::from_measurement(measured_rows_per_sec),
191    }
192}
193
194/// CPU oracle for the same penalized normal-equations solve, used for parity:
195/// `(XᵀWX + ridge·I)β = rhs` solved by a host Cholesky. This is the definition
196/// of truth the device solve must match (up to IEEE-754 reduction order).
197#[must_use]
198pub fn cpu_oracle_normal_equations_solve(
199    x: ArrayView2<'_, f64>,
200    w: ArrayView1<'_, f64>,
201    rhs: ArrayView1<'_, f64>,
202    ridge: f64,
203) -> Array1<f64> {
204    let (n, p) = x.dim();
205    assert_eq!(w.len(), n, "w must have one entry per design row");
206    assert_eq!(rhs.len(), p, "rhs must have one entry per border column");
207
208    // Gram = Xᵀ diag(w) X + ridge·I, formed in f64 as (√w⊙X)ᵀ(√w⊙X) via the
209    // BLAS-backed `dot` (the scalar triple loop is O(n·p²) and dominates the
210    // oracle at p in the thousands). Folding √w into both factors keeps the
211    // weighting exact: row i contributes wᵢ·xᵢₐ·xᵢᵦ as (√wᵢxᵢₐ)(√wᵢxᵢᵦ).
212    let mut xw = x.to_owned();
213    for i in 0..n {
214        let sw = w[i].sqrt();
215        for a in 0..p {
216            xw[[i, a]] *= sw;
217        }
218    }
219    let mut gram = xw.t().dot(&xw);
220    for j in 0..p {
221        gram[[j, j]] += ridge;
222    }
223
224    // Cholesky: gram = L Lᵀ (lower), then solve L y = rhs, Lᵀ β = y.
225    let mut l = Array2::<f64>::zeros((p, p));
226    for j in 0..p {
227        let mut diag = gram[[j, j]];
228        for s in 0..j {
229            diag -= l[[j, s]] * l[[j, s]];
230        }
231        // The oracle exists to be the truth the device is checked against, so a
232        // non-PD pivot must fail loudly here rather than clamp to 0 and launder
233        // a divide-by-zero into a silent NaN in the back-substitution. For the
234        // ridge·I + XᵀWX systems this is called on (ridge > 0, w > 0) the pivot
235        // is always strictly positive; a non-positive pivot means the caller
236        // passed a degenerate system and parity would be meaningless.
237        assert!(
238            diag > 0.0,
239            "cpu_oracle: non-positive Cholesky pivot {diag:.3e} at index {j} — \
240             the Gram is not positive-definite (need ridge>0 and w>0)"
241        );
242        let ljj = diag.sqrt();
243        l[[j, j]] = ljj;
244        for i in (j + 1)..p {
245            let mut off = gram[[i, j]];
246            for s in 0..j {
247                off -= l[[i, s]] * l[[j, s]];
248            }
249            l[[i, j]] = off / ljj;
250        }
251    }
252    let mut y = rhs.to_owned();
253    for i in 0..p {
254        let mut acc = y[i];
255        for s in 0..i {
256            acc -= l[[i, s]] * y[s];
257        }
258        y[i] = acc / l[[i, i]];
259    }
260    let mut beta = y;
261    for i in (0..p).rev() {
262        let mut acc = beta[i];
263        for s in (i + 1)..p {
264            acc -= l[[s, i]] * beta[s];
265        }
266        beta[i] = acc / l[[i, i]];
267    }
268    beta
269}
270
271/// The deployment target, re-exported so callers measuring throughput do not
272/// have to import the policy module directly.
273pub const DEPLOYMENT_TARGET_ROWS_PER_SEC: f64 = GPU_THROUGHPUT_TARGET_ROWS_PER_SEC;
274
275// ===========================================================================
276// FULL exact per-row encode throughput + correctness (#1412 follow-up).
277//
278// The component benchmark above times ONLY the resident normal-equations inner
279// solve `(XᵀWX+ridge·I)β=rhs` and is explicit (see the SCOPE section) that this
280// is NOT the full exact per-row SAE encode. The pieces below are the reusable,
281// gam-sae-free instrument for benchmarking the *full* production encode path
282// end-to-end — active-set/chart routing + per-row latent-coordinate Newton +
283// gate/assignment (amplitude) + Kantorovich certificate/fallback +
284// reconstruction. They live here (CPU-linkable, no `gam-sae` dependency: this
285// crate is *below* `gam-sae`) so the timing harness and the correctness gate
286// are shared, while the driver that actually calls the production
287// `EncodeAtlas::certified_encode_batch` lives in
288// `crates/gam-gpu/tests/encode_full_path_throughput.rs` (a dev-dependency cycle
289// onto `gam-sae`, allowed by cargo for test-only edges).
290//
291// HONEST DEVICE STATUS. This helper is still backend-agnostic instrumentation:
292// callers must set `device_encode_engaged` to `true` only when their encode was
293// produced by a real device-resident exact-encode kernel. The current SAE device
294// driver that can make that assertion lives in
295// `gam_sae::gpu_kernels::sae_encode_resident::measure_device_encode_throughput`;
296// older host-only full-path harnesses pass `false`. This benchmark therefore
297// never fabricates a device "batched exact per-row GPU encode" number from a
298// host encode — it reports the full-path timing and a correctness contract
299// (support agreement, coordinate error, reconstruction explained-variance, and
300// fallback rate), while the caller-owned engagement flag decides whether the
301// #988 deployment/surrogate gate may consume the rate as a device measurement.
302// ===========================================================================
303
304/// End-to-end throughput of the FULL exact per-row encode for one batch.
305///
306/// Distinct from [`ResidentSolveThroughput`] (which times only the inner solve):
307/// `rows_per_sec` here is `n_rows / encode_secs` for the *entire* production
308/// `certified_encode_batch` — routing, per-row Newton, certificate, fallback,
309/// and the per-row reconstruction selection included.
310#[derive(Clone, Copy, Debug)]
311pub struct FullEncodeThroughput {
312    /// Rows encoded in the timed batch.
313    pub n_rows: usize,
314    /// Wall-clock seconds for the full encode of the batch.
315    pub encode_secs: f64,
316    /// `n_rows / encode_secs` (`0.0` for a degenerate / non-positive time).
317    pub rows_per_sec: f64,
318    /// `true` ONLY if a device-resident exact-encode kernel actually ran the
319    /// encode. No such kernel exists yet, so this is `false` even on a GPU host
320    /// — the flag is the false-routing guard that keeps the CPU encode rate from
321    /// ever being reported as a device measurement.
322    pub device_encode_engaged: bool,
323}
324
325impl FullEncodeThroughput {
326    /// Build a throughput record from a measured elapsed time. `engaged` is the
327    /// caller's honest assertion that a device-resident encode kernel produced
328    /// the result; pass `false` for the host encode path.
329    #[must_use]
330    pub fn from_elapsed(n_rows: usize, elapsed: Duration, device_encode_engaged: bool) -> Self {
331        let encode_secs = elapsed.as_secs_f64();
332        let rows_per_sec = if n_rows > 0 && encode_secs > 0.0 {
333            n_rows as f64 / encode_secs
334        } else {
335            0.0
336        };
337        Self {
338            n_rows,
339            encode_secs,
340            rows_per_sec,
341            device_encode_engaged,
342        }
343    }
344}
345
346/// Correctness of an encode result, measured against the production CPU encode
347/// (a per-row reference) and the reconstruction it implies.
348///
349/// Every field is a quantity a "batched exact per-row encode" claim has to
350/// stand on: it must AGREE with the production per-row encode (support +
351/// coordinates), it must RECONSTRUCT the targets (explained variance), and it
352/// must be honest about how many rows it could not certify (fallback rate).
353#[derive(Clone, Copy, Debug)]
354pub struct EncodeQualityMetrics {
355    /// Rows compared.
356    pub n_rows: usize,
357    /// Rows the encode-under-test certified (`h ≤ ½`, exact-into-the-ball).
358    pub certified_rows: usize,
359    /// Fraction of rows the encode-under-test could NOT certify and flagged for
360    /// the multi-start fallback (`1 - certified_rows/n_rows`). This is the
361    /// "fallback rate".
362    pub fallback_rate: f64,
363    /// Fraction of rows whose certificate flag AGREES with the per-row reference
364    /// encode. For a correct batched encode this is `1.0` (the batch is just the
365    /// per-row encode fanned out).
366    pub support_agreement: f64,
367    /// Largest absolute latent-coordinate difference between the encode-under-test
368    /// and the per-row reference encode, over all rows and coordinate dims. A
369    /// correct batched encode matches the per-row encode to round-off (≈ `0`).
370    pub max_coord_abs_err: f64,
371    /// Largest absolute element-wise reconstruction residual `|x̂ − x|` over the
372    /// whole batch (the "amplitude"/reconstruction error in raw output units).
373    pub max_reconstruction_abs_err: f64,
374    /// Reconstruction explained variance `1 − ‖X − X̂‖²_F / ‖X − X̄‖²_F`, with each
375    /// output column centered by its own mean `X̄`. `1.0` is a perfect on-manifold
376    /// reconstruction; `0.0` is no better than the per-column mean.
377    pub reconstruction_ev: f64,
378}
379
380/// Compute [`EncodeQualityMetrics`] for an encode result.
381///
382/// * `coords` / `certified` — the encode UNDER TEST (`n×d` coords, `n` flags).
383/// * `coords_ref` / `certified_ref` — the production per-row reference encode
384///   (the definition of truth the batched/accelerated encode must match).
385/// * `reconstruction` — the decoded reconstruction `x̂` implied by `coords`
386///   (`n×p`, i.e. `amplitudeᵢ · Φ(coordsᵢ) · B`).
387/// * `targets` — the encode inputs `x` (`n×p`).
388///
389/// Panics on a shape mismatch: this is a benchmark/correctness helper and a
390/// mismatched comparison would silently launder a wrong number.
391#[must_use]
392pub fn encode_quality_metrics(
393    coords: ArrayView2<'_, f64>,
394    certified: &[bool],
395    coords_ref: ArrayView2<'_, f64>,
396    certified_ref: &[bool],
397    reconstruction: ArrayView2<'_, f64>,
398    targets: ArrayView2<'_, f64>,
399) -> EncodeQualityMetrics {
400    let (n, d) = coords.dim();
401    assert_eq!(
402        coords_ref.dim(),
403        (n, d),
404        "encode_quality_metrics: reference coords shape {:?} != under-test {:?}",
405        coords_ref.dim(),
406        (n, d)
407    );
408    assert_eq!(certified.len(), n, "certified flags must have one entry per row");
409    assert_eq!(
410        certified_ref.len(),
411        n,
412        "reference certified flags must have one entry per row"
413    );
414    let (nt, p) = targets.dim();
415    assert_eq!(nt, n, "targets must have one row per encoded row");
416    assert_eq!(
417        reconstruction.dim(),
418        (n, p),
419        "reconstruction shape {:?} != targets {:?}",
420        reconstruction.dim(),
421        (n, p)
422    );
423
424    let certified_rows = certified.iter().filter(|c| **c).count();
425    let fallback_rate = if n > 0 {
426        1.0 - certified_rows as f64 / n as f64
427    } else {
428        0.0
429    };
430
431    let agree = certified
432        .iter()
433        .zip(certified_ref.iter())
434        .filter(|(a, b)| a == b)
435        .count();
436    let support_agreement = if n > 0 { agree as f64 / n as f64 } else { 1.0 };
437
438    let mut max_coord_abs_err = 0.0_f64;
439    for i in 0..n {
440        for j in 0..d {
441            max_coord_abs_err = max_coord_abs_err.max((coords[[i, j]] - coords_ref[[i, j]]).abs());
442        }
443    }
444
445    // Reconstruction error + explained variance (per-column centering).
446    let mut max_reconstruction_abs_err = 0.0_f64;
447    let mut ss_res = 0.0_f64;
448    let mut ss_tot = 0.0_f64;
449    for c in 0..p {
450        let mut mean = 0.0_f64;
451        for i in 0..n {
452            mean += targets[[i, c]];
453        }
454        if n > 0 {
455            mean /= n as f64;
456        }
457        for i in 0..n {
458            let resid = reconstruction[[i, c]] - targets[[i, c]];
459            max_reconstruction_abs_err = max_reconstruction_abs_err.max(resid.abs());
460            ss_res += resid * resid;
461            let centered = targets[[i, c]] - mean;
462            ss_tot += centered * centered;
463        }
464    }
465    let reconstruction_ev = if ss_tot > 0.0 {
466        1.0 - ss_res / ss_tot
467    } else {
468        // Degenerate (all targets equal their column mean): a perfect
469        // reconstruction is EV 1, anything else is 0 rather than a NaN.
470        if ss_res == 0.0 { 1.0 } else { 0.0 }
471    };
472
473    EncodeQualityMetrics {
474        n_rows: n,
475        certified_rows,
476        fallback_rate,
477        support_agreement,
478        max_coord_abs_err,
479        max_reconstruction_abs_err,
480        reconstruction_ev,
481    }
482}
483
484#[cfg(test)]
485mod full_encode_metric_tests {
486    use super::*;
487    use ndarray::array;
488
489    #[test]
490    fn throughput_is_rows_over_seconds_and_guards_degenerate_time() {
491        let t = FullEncodeThroughput::from_elapsed(8_000, Duration::from_millis(100), false);
492        assert_eq!(t.n_rows, 8_000);
493        assert!(!t.device_encode_engaged);
494        // 8000 rows / 0.1 s = 80_000 rows/sec.
495        assert!((t.rows_per_sec - 80_000.0).abs() < 1.0, "got {}", t.rows_per_sec);
496        // Zero elapsed is a non-measurement, not an infinite rate.
497        let z = FullEncodeThroughput::from_elapsed(8_000, Duration::ZERO, false);
498        assert_eq!(z.rows_per_sec, 0.0);
499    }
500
501    #[test]
502    fn perfect_match_scores_full_agreement_and_unit_ev() {
503        // Two rows, 1 latent dim, 2 output dims. Reconstruction == targets.
504        let coords = array![[0.10], [0.40]];
505        let targets = array![[1.0, 0.0], [0.0, 1.0]];
506        let m = encode_quality_metrics(
507            coords.view(),
508            &[true, true],
509            coords.view(),
510            &[true, true],
511            targets.view(),
512            targets.view(),
513        );
514        assert_eq!(m.n_rows, 2);
515        assert_eq!(m.certified_rows, 2);
516        assert_eq!(m.fallback_rate, 0.0);
517        assert_eq!(m.support_agreement, 1.0);
518        assert_eq!(m.max_coord_abs_err, 0.0);
519        assert_eq!(m.max_reconstruction_abs_err, 0.0);
520        assert!((m.reconstruction_ev - 1.0).abs() < 1e-12);
521    }
522
523    #[test]
524    fn divergence_is_surfaced_in_every_axis() {
525        let coords = array![[0.10], [0.40]];
526        let coords_ref = array![[0.10], [0.50]]; // row 1 differs by 0.10
527        let targets = array![[1.0, 0.0], [0.0, 1.0]];
528        // Reconstruction misses target by 0.25 on one element.
529        let recon = array![[1.0, 0.0], [0.0, 0.75]];
530        let m = encode_quality_metrics(
531            coords.view(),
532            &[true, false], // row 1 uncertified under test
533            coords_ref.view(),
534            &[true, true], // reference certified both
535            recon.view(),
536            targets.view(),
537        );
538        assert_eq!(m.certified_rows, 1);
539        assert!((m.fallback_rate - 0.5).abs() < 1e-12);
540        assert!((m.support_agreement - 0.5).abs() < 1e-12); // row 1 flags disagree
541        assert!((m.max_coord_abs_err - 0.10).abs() < 1e-12);
542        assert!((m.max_reconstruction_abs_err - 0.25).abs() < 1e-12);
543        assert!(m.reconstruction_ev < 1.0);
544    }
545}