Skip to main content

gam_models/bms/gpu/
row.rs

1//! Stage 2 of the BMS FLEX row kernel — per-row math that turns per-cell
2//! derivative moments (built by Stage 1 in `src/gpu/cubic_cell/mod.rs`) into a
3//! row gradient and row-primary `r × r` Hessian.
4//!
5//! Math (mirrors the CPU reference
6//! `BernoulliMarginalSlope::lower_bms_flex_row_order2_from_parts` in
7//! `src/families/bernoulli_marginal_slope.rs`):
8//!
9//! For each row `i`, with per-cell cubic predictor coefficients
10//! `C_c = (C0, C1, C2, C3)` and derivative moments `m_0..m_9`, build
11//!
12//! ```text
13//!     κ        = 1 / (2π)
14//!     T_n      = κ · Σ_{e=0..3} C_e · m_{e+n}     (n = 0..6)
15//!     D(R)     = κ · Σ_{k=0..3} R_k · m_k
16//!     Q(R, S)  = Σ_{p,q=0..3} R_p · S_q · T_{p+q}
17//!     H(R, S, U) = D(U) − Q(R, S)
18//! ```
19//!
20//! Per cell `c`, accumulate into row scratch:
21//!
22//! ```text
23//!     F_a   += D(A_c)
24//!     F_aa  += H(A_c, A_c, AA_c)
25//!     F_u   += D(R_{c,u})                         u > 0
26//!     F_au  += H(A_c, R_{c,u}, AR_{c,u})          u > 0
27//!     F_uv  += H(R_{c,u}, R_{c,v}, S_{c,uv})      0 < u ≤ v
28//! ```
29//!
30//! After the cell sum, the `q`-row is overridden:
31//!
32//! ```text
33//!     F_q  = −mu_1
34//!     F_qq = −mu_2
35//!     F_qv = 0   (v > 0)
36//!     F_aq = 0
37//! ```
38//!
39//! Implicit function theorem (single `1/F_a`):
40//!
41//! ```text
42//!     inv_Fa = 1 / F_a
43//!     a_u    = −F_u · inv_Fa                       (q-row override: mu_1 · inv_Fa)
44//!     a_uv   = −(F_uv + F_au·a_v + F_av·a_u + F_aa·a_u·a_v) · inv_Fa
45//! ```
46//!
47//! Observed predictor at `z_obs` (host supplies pre-evaluated chi, xi, rho, tau,
48//! r_uv per row and coordinate):
49//!
50//! ```text
51//!     bar_e_u  = chi_obs · a_u + rho_u
52//!     bar_e_uv = chi_obs · a_uv + xi_obs · a_u · a_v + tau_u · a_v
53//!                + a_u · tau_v + r_uv
54//! ```
55//!
56//! Probit Mills (stable; uses the shared curvature primitive from
57//! `numerics_device::PROBIT_NUMERICS_CU`):
58//!
59//! ```text
60//!     s = 2y − 1 ;  m = s · e_obs
61//!     [log_cdf, λ, C] = log_ndtr_mills_curvature(m),  C = −d²logΦ(m)/dm²
62//!     A = −w · s · λ
63//!     B =  w · C
64//! ```
65//!
66//! Final outputs:
67//!
68//! ```text
69//!     neglog   = −w · log_cdf
70//!     g_u      = A · bar_e_u
71//!     H_{uv}   = B · bar_e_u · bar_e_v + A · bar_e_uv     (symmetric)
72//! ```
73//!
74//! Implementation choice (Stage 2): **one CUDA block per row**, with
75//! `blockDim.x = 32` threads. The already-required output buffers are the
76//! width-general scratch authority: `out_grad[row]` evolves `F_u → a_u → g`,
77//! and `out_hess[row]` evolves `F_uv → a_uv → H`. One additional checked
78//! `[n, r]` buffer holds `F_au`. Only the fixed 32-thread scalar reduction is
79//! shared, so primary width has no shared-memory or thread-stack ceiling.
80
81#[cfg(target_os = "linux")]
82use std::sync::OnceLock;
83
84use gam_gpu::gpu_error::GpuError;
85
86#[cfg(target_os = "linux")]
87use std::sync::Arc;
88
89#[cfg(target_os = "linux")]
90use cudarc::driver::{CudaModule, CudaSlice, CudaStream, LaunchConfig, PushKernelArg};
91
92#[cfg(target_os = "linux")]
93use super::super::flex_row_program::{
94    BmsFlexCalibrationOrder2Phase, BmsFlexRowOrder2FinalizerPhase, BmsFlexRowProgram,
95};
96
97/// `blockDim.x` for the row kernel. Threads of a row-block parallelise the
98/// per-cell loop; thread 0 of the block finalises the IFT solve. Linux-only
99/// because the kernel launcher that consumes it is Linux-only.
100#[cfg(target_os = "linux")]
101pub(crate) const ROW_KERNEL_THREADS: u32 = 32;
102
103/// Number of cubic predictor coefficients per cell (`C0..C3`) and the matching
104/// support length of `A_c`, `R_{c,u}`, `AA_c`, `AR_{c,u}`, `S_{c,uv}`.
105pub(crate) const COEFF4: usize = 4;
106
107/// Highest moment index touched per cell: `T_n` uses `m_{n+e}` for `e = 0..3`
108/// and `n = 0..6`, so the maximum index is `9`. `MOMENT_STRIDE = 10`.
109pub(crate) const MOMENT_STRIDE: usize = 10;
110
111/// Source of the per-cell derivative moments fed into the row kernel.
112/// Phase-4 wiring: the substrate at `src/gpu/cubic_cell/mod.rs` can produce
113/// these on the GPU; this enum lets the launcher consume them directly
114/// without a DtoH+HtoD round-trip.
115pub(crate) enum CellMomentsSource<'a> {
116    /// Host-resident `[total_cells, MOMENT_STRIDE = 10]` row-major buffer.
117    /// The launcher will HtoD-upload this on every launch.
118    Host(&'a [f64]),
119    /// Device-resident moments already living on the row-kernel backend's
120    /// default stream (which is the same `cuda_context_for(ordinal).default_stream()`
121    /// the cubic-cell substrate uses, so no cross-context copy is needed).
122    /// Length on the device must be `total_cells * MOMENT_STRIDE`. Linux-only.
123    #[cfg(target_os = "linux")]
124    Device(&'a CudaSlice<f64>),
125}
126
127impl<'a> CellMomentsSource<'a> {
128    /// Logical element count of the moments source, used by [`BmsFlexRowKernelInputs::validate`].
129    pub(crate) fn len(&self) -> usize {
130        match self {
131            CellMomentsSource::Host(slice) => slice.len(),
132            #[cfg(target_os = "linux")]
133            CellMomentsSource::Device(d) => d.len(),
134        }
135    }
136}
137
138/// Per-row input bundle for [`launch_bms_flex_row_kernel`].
139///
140/// Coordinate ordering convention: `u = 0` is `a` (the latent intercept and
141/// the variable IFT eliminates); `u = 1` is `b` (slope); `u = 2..2+p_h` is the
142/// score-warp `β_h` block; `u = 2+p_h..2+p_h+p_w` is the link-wiggle `β_w`
143/// block. So `r = 2 + p_h + p_w` and `u = 1` is the `b` (slope) index used by
144/// the sparse `S_{b·h}` / `S_{b·w}` payloads.
145macro_rules! define_bms_flex_row_kernel_input_types {
146    (
147        f64_fields: [$($f64_field:ident),+ $(,)?],
148        u32_fields: [$($u32_field:ident),+ $(,)?],
149        moments_field: $moments_field:ident $(,)?
150    ) => {
151        pub(crate) struct BmsFlexRowKernelInputs<'a> {
152            /// Number of observation rows.
153            pub n_rows: usize,
154            /// Total primary local dimension. `r = 2 + p_h + p_w`.
155            pub r: usize,
156            /// Number of score-warp basis coordinates.
157            pub p_h: usize,
158            /// Number of link-wiggle basis coordinates.
159            pub p_w: usize,
160            /// Probit frailty scale `S_f` (scalar shared across rows; matches
161            /// `BernoulliMarginalSlope::probit_frailty_scale`).
162            pub s_f: f64,
163            $(pub $f64_field: &'a [f64],)+
164            $(pub $u32_field: &'a [u32],)+
165            pub $moments_field: CellMomentsSource<'a>,
166        }
167
168        /// Owned twin of [`BmsFlexRowKernelInputs`] — every borrowed slice is
169        /// replaced by an owned `Vec`. The buffer fields are declared from the
170        /// same schema as the borrowed launch ABI and converted by
171        /// [`BmsFlexRowKernelInputsOwned::as_borrowed`].
172        pub(crate) struct BmsFlexRowKernelInputsOwned {
173            pub n_rows: usize,
174            pub r: usize,
175            pub p_h: usize,
176            pub p_w: usize,
177            pub s_f: f64,
178            $(pub $f64_field: Vec<f64>,)+
179            $(pub $u32_field: Vec<u32>,)+
180            pub $moments_field: Vec<f64>,
181            /// Phase-4 device-resident moments. When `Some(_)`, the launcher
182            /// skips the host upload and consumes the buffer directly.
183            /// Linux-only field.
184            #[cfg(target_os = "linux")]
185            pub cell_moments_device: Option<CudaSlice<f64>>,
186        }
187
188        impl BmsFlexRowKernelInputsOwned {
189            /// Borrowed view over `self` suitable for
190            /// [`launch_bms_flex_row_kernel`]. The returned struct holds
191            /// references into `self` so the owned bundle must outlive the
192            /// launch.
193            pub(crate) fn as_borrowed(&self) -> BmsFlexRowKernelInputs<'_> {
194                #[cfg(target_os = "linux")]
195                let cell_moments = match self.cell_moments_device.as_ref() {
196                    Some(d) => CellMomentsSource::Device(d),
197                    None => CellMomentsSource::Host(&self.cell_moments),
198                };
199                #[cfg(not(target_os = "linux"))]
200                let cell_moments = CellMomentsSource::Host(&self.cell_moments);
201                BmsFlexRowKernelInputs {
202                    n_rows: self.n_rows,
203                    r: self.r,
204                    p_h: self.p_h,
205                    p_w: self.p_w,
206                    s_f: self.s_f,
207                    $($f64_field: &self.$f64_field,)+
208                    $($u32_field: &self.$u32_field,)+
209                    $moments_field: cell_moments,
210                }
211            }
212        }
213    };
214}
215
216define_bms_flex_row_kernel_input_types! {
217    f64_fields: [
218        q,
219        b,
220        mu_1,
221        mu_2,
222        z_obs,
223        y,
224        w,
225        e_obs,
226        cell_c0,
227        cell_c1,
228        cell_c2,
229        cell_c3,
230        cell_a,
231        cell_aa,
232        cell_r,
233        cell_ar,
234        cell_sbb,
235        cell_sbh,
236        cell_sbw,
237        chi_obs,
238        xi_obs,
239        rho_u,
240        tau_u,
241        r_uv,
242    ],
243    u32_fields: [cell_offsets],
244    moments_field: cell_moments,
245}
246
247/// Per-row outputs produced by [`launch_bms_flex_row_kernel`].
248#[derive(Debug)]
249pub(crate) struct BmsFlexRowKernelOutputs {
250    /// Per-row negative log-likelihood. Length `n_rows`.
251    pub neglog: Vec<f64>,
252    /// Per-row gradient, row-major `[n_rows, r]`.
253    pub grad: Vec<f64>,
254    /// Per-row Hessian, row-major `[n_rows, r*r]`. The kernel writes the full
255    /// symmetric matrix.
256    pub hess: Vec<f64>,
257}
258
259fn checked_shape_len(context: &str, dimensions: &[usize]) -> Result<usize, GpuError> {
260    dimensions
261        .iter()
262        .copied()
263        .try_fold(1_usize, |product, dimension| {
264            product
265                .checked_mul(dimension)
266                .ok_or_else(|| GpuError::DriverCallFailed {
267                    reason: format!(
268                        "bms_flex_row {context}: shape product overflow for dimensions {dimensions:?}"
269                    ),
270                })
271        })
272}
273
274impl<'a> BmsFlexRowKernelInputs<'a> {
275    /// Sanity-check every shape the kernel relies on. This is the only place
276    /// length errors are surfaced — the device kernel assumes valid layout.
277    pub(crate) fn validate(&self) -> Result<(), GpuError> {
278        if self.n_rows == 0 {
279            return Err(GpuError::DriverCallFailed {
280                reason: "bms_flex_row inputs: n_rows must be > 0".to_string(),
281            });
282        }
283        if self.r == 0 {
284            return Err(GpuError::DriverCallFailed {
285                reason: "bms_flex_row inputs: r must be > 0".to_string(),
286            });
287        }
288        let decomposed_r = 2_usize
289            .checked_add(self.p_h)
290            .and_then(|value| value.checked_add(self.p_w))
291            .ok_or_else(|| GpuError::DriverCallFailed {
292                reason: format!(
293                    "bms_flex_row inputs: primary decomposition overflow for p_h={} p_w={}",
294                    self.p_h, self.p_w
295                ),
296            })?;
297        if self.r != decomposed_r {
298            return Err(GpuError::DriverCallFailed {
299                reason: format!(
300                    "bms_flex_row inputs: r={} must equal 2 + p_h({}) + p_w({}) = {}",
301                    self.r, self.p_h, self.p_w, decomposed_r
302                ),
303            });
304        }
305        let n = self.n_rows;
306        let check_len = |name: &str, have: usize, want: usize| -> Result<(), GpuError> {
307            if have != want {
308                return Err(GpuError::DriverCallFailed {
309                    reason: format!("bms_flex_row inputs: {name}.len()={have} != {want}"),
310                });
311            }
312            Ok(())
313        };
314        check_len("q", self.q.len(), n)?;
315        check_len("b", self.b.len(), n)?;
316        check_len("mu_1", self.mu_1.len(), n)?;
317        check_len("mu_2", self.mu_2.len(), n)?;
318        check_len("z_obs", self.z_obs.len(), n)?;
319        check_len("y", self.y.len(), n)?;
320        check_len("w", self.w.len(), n)?;
321        check_len("e_obs", self.e_obs.len(), n)?;
322        check_len("chi_obs", self.chi_obs.len(), n)?;
323        check_len("xi_obs", self.xi_obs.len(), n)?;
324        let nr = checked_shape_len("validate [n,r]", &[n, self.r])?;
325        let nrr = checked_shape_len("validate [n,r,r]", &[n, self.r, self.r])?;
326        check_len("rho_u", self.rho_u.len(), nr)?;
327        check_len("tau_u", self.tau_u.len(), nr)?;
328        check_len("r_uv", self.r_uv.len(), nrr)?;
329        let offsets_len = n.checked_add(1).ok_or_else(|| GpuError::DriverCallFailed {
330            reason: format!("bms_flex_row inputs: n_rows={n} cannot form n+1 offsets"),
331        })?;
332        check_len("cell_offsets", self.cell_offsets.len(), offsets_len)?;
333        let total_cells_u32 = self.cell_offsets[n];
334        let total_cells = total_cells_u32 as usize;
335        check_len("cell_c0", self.cell_c0.len(), total_cells)?;
336        check_len("cell_c1", self.cell_c1.len(), total_cells)?;
337        check_len("cell_c2", self.cell_c2.len(), total_cells)?;
338        check_len("cell_c3", self.cell_c3.len(), total_cells)?;
339        let cells_coeff4 = checked_shape_len("validate cell coeff4", &[total_cells, COEFF4])?;
340        check_len("cell_a", self.cell_a.len(), cells_coeff4)?;
341        check_len("cell_aa", self.cell_aa.len(), cells_coeff4)?;
342        check_len(
343            "cell_r",
344            self.cell_r.len(),
345            checked_shape_len(
346                "validate cell_r",
347                &[total_cells, self.r.saturating_sub(1), COEFF4],
348            )?,
349        )?;
350        check_len(
351            "cell_ar",
352            self.cell_ar.len(),
353            checked_shape_len(
354                "validate cell_ar",
355                &[total_cells, self.r.saturating_sub(1), COEFF4],
356            )?,
357        )?;
358        check_len("cell_sbb", self.cell_sbb.len(), cells_coeff4)?;
359        check_len(
360            "cell_sbh",
361            self.cell_sbh.len(),
362            checked_shape_len("validate cell_sbh", &[total_cells, self.p_h, COEFF4])?,
363        )?;
364        check_len(
365            "cell_sbw",
366            self.cell_sbw.len(),
367            checked_shape_len("validate cell_sbw", &[total_cells, self.p_w, COEFF4])?,
368        )?;
369        check_len(
370            "cell_moments",
371            self.cell_moments.len(),
372            checked_shape_len("validate cell_moments", &[total_cells, MOMENT_STRIDE])?,
373        )?;
374        // Bonus: when the moments came from `CellMomentsSource::Device`, the
375        // launcher needs to know the source is from a device buffer; nothing
376        // to validate beyond length above. The Host variant length check is
377        // also already covered above.
378        // Monotone cell_offsets check.
379        for i in 0..n {
380            if self.cell_offsets[i] > self.cell_offsets[i + 1] {
381                return Err(GpuError::DriverCallFailed {
382                    reason: format!(
383                        "bms_flex_row inputs: cell_offsets must be monotone (offset[{}]={} > offset[{}]={})",
384                        i,
385                        self.cell_offsets[i],
386                        i + 1,
387                        self.cell_offsets[i + 1]
388                    ),
389                });
390            }
391        }
392        Ok(())
393    }
394}
395
396/// Non-semantic CUDA scaffolding for the generated row kernel. One CUDA block
397/// per row; the generated launch width parallelises the per-cell sums into
398/// shared-memory scratch. The calibration and finalizer markers are replaced
399/// by interpreting [`BmsFlexRowProgram`]'s typed node streams.
400///
401/// Shared probit numerics (`erfcx_nonnegative`, `log_ndtr`,
402/// `log_ndtr_and_mills`) are provided by
403/// `numerics_device::PROBIT_NUMERICS_CU`, which is prepended before
404/// passing to `cudarc::nvrtc::compile_ptx`.
405///
406#[cfg(target_os = "linux")]
407const CUDA_ROW_KERNEL_TEMPLATE: &str = r#"
408// One block per row. threadIdx.x parallelises per-cell sums.
409// Semantic calibration/finalization visits are generated from BmsFlexRowProgram.
410
411#define INV_TWO_PI     0.15915494309189535
412#define BMS_FLEX_ROW_THREADS /*__BMS_FLEX_ROW_THREADS__*/
413
414extern "C" __device__ __forceinline__ double atomic_add_f64(double *addr, double value) {
415    unsigned long long int *addr_as_ull = (unsigned long long int *)addr;
416    unsigned long long int old = *addr_as_ull;
417    unsigned long long int assumed;
418    do {
419        assumed = old;
420        double next = __longlong_as_double((long long int)assumed) + value;
421        old = atomicCAS(addr_as_ull, assumed, (unsigned long long int)__double_as_longlong(next));
422    } while (assumed != old);
423    return __longlong_as_double((long long int)old);
424}
425
426// `nan_fill_outputs`: thread-0-only path used when row inputs are degenerate
427// (`F_a` non-finite or non-positive). The status channel makes the host reject
428// the entire selected-GPU execution before any output can enter a cache.
429extern "C" __device__ __forceinline__ void
430nan_fill_outputs(int r,
431                 int row,
432                 double *out_neglog,
433                 double *out_grad,
434                 double *out_hess,
435                 unsigned int *out_status) {
436    double nan_value = __longlong_as_double(0x7ff8000000000000ULL);
437    out_status[row] = 1U;
438    out_neglog[row] = nan_value;
439    size_t row_r = (size_t)row * (size_t)r;
440    for (int u = 0; u < r; ++u) {
441        out_grad[row_r + (size_t)u] = nan_value;
442    }
443    size_t rr = (size_t)r * (size_t)r;
444    size_t row_rr = (size_t)row * rr;
445    for (size_t idx = 0; idx < rr; ++idx) {
446        out_hess[row_rr + idx] = nan_value;
447    }
448}
449
450extern "C" __global__ void bms_flex_row_kernel(
451    int                  n_rows,
452    int                  r,
453    int                  p_h,
454    int                  p_w,
455    double               s_f,                // currently unused on device:
456                                             // host has already baked S_f
457                                             // into the cubic coefficients.
458                                             // Kept for diagnostic parity.
459    const double * __restrict__ row_q,
460    const double * __restrict__ row_b,
461    const double * __restrict__ row_mu1,
462    const double * __restrict__ row_mu2,
463    const double * __restrict__ row_zobs,
464    const double * __restrict__ row_y,
465    const double * __restrict__ row_w,
466    const unsigned int * __restrict__ cell_offsets,
467    const double * __restrict__ cell_c0,
468    const double * __restrict__ cell_c1,
469    const double * __restrict__ cell_c2,
470    const double * __restrict__ cell_c3,
471    const double * __restrict__ cell_a,       // [n_cells, 4]
472    const double * __restrict__ cell_aa,      // [n_cells, 4]
473    const double * __restrict__ cell_r,       // [n_cells, r-1, 4]
474    const double * __restrict__ cell_ar,      // [n_cells, r-1, 4]
475    const double * __restrict__ cell_sbb,     // [n_cells, 4]
476    const double * __restrict__ cell_sbh,     // [n_cells, p_h, 4]
477    const double * __restrict__ cell_sbw,     // [n_cells, p_w, 4]
478    const double * __restrict__ cell_moments, // [n_cells, 10]
479    const double * __restrict__ row_chi,
480    const double * __restrict__ row_xi,
481    const double * __restrict__ row_rho,      // [n_rows, r]
482    const double * __restrict__ row_tau,      // [n_rows, r]
483    const double * __restrict__ row_ruv,      // [n_rows, r*r]
484    const double * __restrict__ row_e_obs,    // [n_rows] observed predictor VALUE
485    double       * __restrict__ row_f_au,      // [n_rows, r] general-width scratch
486    double       * __restrict__ out_neglog,
487    double       * __restrict__ out_grad,
488    double       * __restrict__ out_hess,
489    unsigned int * __restrict__ out_status)
490{
491    int row = blockIdx.x;
492    if (row >= n_rows) return;
493    int tid = threadIdx.x;
494
495    // Width-general row scratch. Reuse the final output allocations in-place:
496    // F_u → a_u → gradient and F_uv → a_uv → Hessian. Only F_au needs one
497    // additional checked [n,r] device allocation.
498    size_t row_r_base = (size_t)row * (size_t)r;
499    size_t rr = (size_t)r * (size_t)r;
500    size_t row_rr_base = (size_t)row * rr;
501    double *F_u = out_grad + row_r_base;
502    double *F_au = row_f_au + row_r_base;
503    double *F_uv = out_hess + row_rr_base;
504    __shared__ double reduce_a[BMS_FLEX_ROW_THREADS];
505    __shared__ double reduce_b[BMS_FLEX_ROW_THREADS];
506    __shared__ double F_a_shared;
507    __shared__ double F_aa_shared;
508
509    // Zero scratch.
510    if (tid == 0) { F_a_shared = 0.0; F_aa_shared = 0.0; }
511    for (int u = tid; u < r; u += blockDim.x) {
512        F_u[u]  = 0.0;
513        F_au[u] = 0.0;
514    }
515    for (size_t uv = (size_t)tid; uv < rr; uv += (size_t)blockDim.x) {
516        F_uv[uv] = 0.0;
517    }
518    __syncthreads();
519
520    // ── per-cell sweep ───────────────────────────────────────────────────
521    unsigned int cell_lo = cell_offsets[row];
522    unsigned int cell_hi = cell_offsets[row + 1];
523    unsigned int n_cells = cell_hi - cell_lo;
524
525    double local_Fa  = 0.0;
526    double local_Faa = 0.0;
527
528    for (unsigned int local_c = (unsigned int)tid;
529         local_c < n_cells;
530         local_c += (unsigned int)blockDim.x) {
531        unsigned int c = cell_lo + local_c;
532
533        // Load cubic predictor coeffs C0..C3.
534        double C[4];
535        C[0] = cell_c0[c]; C[1] = cell_c1[c];
536        C[2] = cell_c2[c]; C[3] = cell_c3[c];
537
538        // Load m_0..m_9.
539        const double *m = cell_moments + (size_t)c * 10;
540
541        // T_n = κ · Σ_e C_e · m_{e+n}, n = 0..6.
542        // CPU parity: equivalent to the `eta_rs ⊗ moments` contraction in
543        //             `cell_second_derivative_from_moments` after folding the
544        //             cubic predictor.
545        double T[7];
546        #pragma unroll
547        for (int n = 0; n < 7; ++n) {
548            double acc = 0.0;
549            #pragma unroll
550            for (int e = 0; e < 4; ++e) {
551                acc = fma(C[e], m[e + n], acc);
552            }
553            T[n] = acc * INV_TWO_PI;
554        }
555
556        // D(R) = κ · Σ_k R_k · m_k.
557        // CPU parity: `cell_first_derivative_from_moments`.
558        // The argument is parenthesized because callers pass pointer
559        // ARITHMETIC (`D_OF(base + offset)`): without it the expansion binds
560        // as `base + offset[0]`, which NVRTC rejects ("pointer-to-object
561        // type" on the integer term) — the calibration-phase emitter was the
562        // first caller to hit this.
563        #define D_OF(R) (INV_TWO_PI * ((R)[0]*m[0] + (R)[1]*m[1] + (R)[2]*m[2] + (R)[3]*m[3]))
564
565        // Q(R, S) = Σ_{p,q} R_p · S_q · T_{p+q}.
566        // CPU parity: the `eta_rs` folded dot in
567        // `cell_second_derivative_from_moments`.
568        #define Q_OF(R, S)                                                                 \
569            (((R)[0]*(S)[0])*T[0] + ((R)[0]*(S)[1] + (R)[1]*(S)[0])*T[1]                   \
570             + ((R)[0]*(S)[2] + (R)[1]*(S)[1] + (R)[2]*(S)[0])*T[2]                        \
571             + ((R)[0]*(S)[3] + (R)[1]*(S)[2] + (R)[2]*(S)[1] + (R)[3]*(S)[0])*T[3]        \
572             + ((R)[1]*(S)[3] + (R)[2]*(S)[2] + (R)[3]*(S)[1])*T[4]                        \
573             + ((R)[2]*(S)[3] + (R)[3]*(S)[2])*T[5]                                        \
574             + ((R)[3]*(S)[3])*T[6])
575
576        // The typed calibration schedule below consumes these primitive
577        // coefficient views through D_OF/Q_OF.
578        const double *A_c  = cell_a  + (size_t)c * 4;
579        const double *AA_c = cell_aa + (size_t)c * 4;
580        /*__BMS_FLEX_CALIBRATION_ORDER2__*/
581
582        #undef D_OF
583        #undef Q_OF
584    }
585
586    // Block reduction of local_Fa, local_Faa into shared.
587    reduce_a[tid] = local_Fa;
588    reduce_b[tid] = local_Faa;
589    __syncthreads();
590    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
591        if (tid < stride) {
592            reduce_a[tid] += reduce_a[tid + stride];
593            reduce_b[tid] += reduce_b[tid + stride];
594        }
595        __syncthreads();
596    }
597    if (tid == 0) {
598        F_a_shared  = reduce_a[0];
599        F_aa_shared = reduce_b[0];
600    }
601    __syncthreads();
602
603    // ── thread-0 finalisation: IFT + observed-point + Mills + writes ──────
604    if (tid != 0) return;
605
606    double F_a  = F_a_shared;
607    double F_aa = F_aa_shared;
608    double mu_1 = row_mu1[row];
609    double mu_2 = row_mu2[row];
610
611    // q-row overrides.
612    //   F_q  = -mu_1 ; F_qq = -mu_2 ; F_qv = 0 (v > 0) ; F_aq = 0.
613    F_u[0]  = -mu_1;
614    F_au[0] = 0.0;
615    // Zero the q-cross row/column of F_uv (u == 0 or v == 0), then plant -mu_2 at (0,0).
616    for (int v = 0; v < r; ++v) {
617        F_uv[(size_t)v] = 0.0;
618        F_uv[(size_t)v * (size_t)r] = 0.0;
619    }
620    F_uv[0] = -mu_2;
621
622    // Guard: degenerate F_a ⇒ NaN-fill this row's outputs.
623    if (!isfinite(F_a) || F_a <= 0.0) {
624        nan_fill_outputs(r, row, out_neglog, out_grad, out_hess, out_status);
625        return;
626    }
627    double inv_Fa = 1.0 / F_a;
628
629    // Storage consumed by the generated dependency-ordered finalizer. Both
630    // aliases overwrite their no-longer-needed calibration predecessors.
631    double *a_u = F_u;
632    double *a_uv = F_uv;
633    double chi = row_chi[row];
634    double xi  = row_xi[row];
635    const double *rho = row_rho + (size_t)row * r;
636    const double *tau = row_tau + (size_t)row * r;
637    const double *ruv = row_ruv + row_rr_base;
638
639    // Probit Mills.
640    double y    = row_y[row];
641    double w    = row_w[row];
642    double s    = 2.0 * y - 1.0;
643    // The "observed predictor" e_obs is the VALUE (degree-0 term) of the
644    // observed jet η(a(θ), θ; z_obs) — NOT `bar_e_u[0]`, which is the u=0
645    // FIRST-derivative jet (`chi·a_0 + rho_0 = dη_obs/dq`). The host packs
646    // the observed value directly in `row_e_obs[row]` (see
647    // `pack_bms_flex_row_kernel_inputs`, `eta_val = eval_coeff4_at(obs.coeff,
648    // z_obs)`), matching the CPU family `lower_bms_flex_row_order2_from_parts`
649    // which forms `signed_margin = s_y · eta_val`. #415 parity lock.
650    double e_obs = row_e_obs[row];
651    double m_arg = s * e_obs;
652    double log_cdf, lambda, probit_curvature;
653    log_ndtr_mills_curvature(m_arg, &log_cdf, &lambda, &probit_curvature);
654    double A_i = -w * s * lambda;
655    double B_i =  w * probit_curvature;
656
657    out_neglog[row] = -w * log_cdf;
658    /*__BMS_FLEX_ORDER2_FINALIZER__*/
659    if (!isfinite(out_neglog[row])) {
660        out_status[row] = 2U;
661    }
662    for (int u = 0; u < r; ++u) {
663        if (!isfinite(out_grad[row_r_base + (size_t)u])) {
664            out_status[row] = 2U;
665        }
666    }
667    for (size_t uv = 0; uv < rr; ++uv) {
668        if (!isfinite(out_hess[row_rr_base + uv])) {
669            out_status[row] = 2U;
670        }
671    }
672}
673"#;
674
675#[cfg(target_os = "linux")]
676fn build_generated_row_kernel_source() -> String {
677    const CALIBRATION_MARKER: &str = "        /*__BMS_FLEX_CALIBRATION_ORDER2__*/";
678    const FINALIZER_MARKER: &str = "    /*__BMS_FLEX_ORDER2_FINALIZER__*/";
679
680    let (prefix, remainder) = CUDA_ROW_KERNEL_TEMPLATE
681        .split_once(CALIBRATION_MARKER)
682        .expect("CUDA row template must contain the calibration marker");
683    let (between, suffix) = remainder
684        .split_once(FINALIZER_MARKER)
685        .expect("CUDA row template must contain the finalizer marker");
686    let mut source = String::with_capacity(CUDA_ROW_KERNEL_TEMPLATE.len() + 16_000);
687    source.push_str(prefix);
688
689    BmsFlexRowProgram::try_for_each_calibration_order2_phase(
690        true,
691        |phase| -> Result<(), std::convert::Infallible> {
692            source.push_str(&format!(
693                "        // canonical calibration phase: {phase:?}\n"
694            ));
695            match phase {
696                BmsFlexCalibrationOrder2Phase::InterceptFirst => {
697                    source.push_str("        local_Fa += D_OF(A_c);\n");
698                }
699                BmsFlexCalibrationOrder2Phase::InterceptSecond => {
700                    source.push_str("        local_Faa += D_OF(AA_c) - Q_OF(A_c, A_c);\n");
701                }
702                BmsFlexCalibrationOrder2Phase::PrimaryFirstAndInterceptSecond => {
703                    source.push_str(
704                        r#"        for (int u = 1; u < r; ++u) {
705            const double *R_u = cell_r + ((size_t)c * (size_t)(r - 1) + (size_t)(u - 1)) * 4;
706            const double *AR_u = cell_ar + ((size_t)c * (size_t)(r - 1) + (size_t)(u - 1)) * 4;
707            atomic_add_f64(&F_u[u], D_OF(R_u));
708            atomic_add_f64(&F_au[u], D_OF(AR_u) - Q_OF(A_c, R_u));
709        }
710"#,
711                    );
712                }
713                BmsFlexCalibrationOrder2Phase::PrimaryPairSecond => {
714                    source.push_str(
715                        r#"        for (int u = 1; u < r; ++u) {
716            const double *R_u = cell_r + ((size_t)c * (size_t)(r - 1) + (size_t)(u - 1)) * 4;
717            for (int v = u; v < r; ++v) {
718                const double *R_v = cell_r + ((size_t)c * (size_t)(r - 1) + (size_t)(v - 1)) * 4;
719                double explicit_second = 0.0;
720                if (u == 1 && v == 1) {
721                    explicit_second = D_OF(cell_sbb + (size_t)c * 4);
722                } else if (u == 1 && v < 2 + p_h) {
723                    int j = v - 2;
724                    explicit_second = D_OF(cell_sbh + ((size_t)c * (size_t)p_h + (size_t)j) * 4);
725                } else if (u == 1) {
726                    int l = v - (2 + p_h);
727                    explicit_second = D_OF(cell_sbw + ((size_t)c * (size_t)p_w + (size_t)l) * 4);
728                }
729                atomic_add_f64(&F_uv[(size_t)u * (size_t)r + (size_t)v], explicit_second - Q_OF(R_u, R_v));
730            }
731        }
732"#,
733                    );
734                }
735            }
736            Ok(())
737        },
738    )
739    .expect("the infallible calibration phase emitter cannot fail");
740
741    source.push_str(between);
742    BmsFlexRowProgram::try_for_each_order2_finalizer_phase(
743        true,
744        |phase| -> Result<(), std::convert::Infallible> {
745            source.push_str(&format!("    // canonical finalizer phase: {phase:?}\n"));
746            match phase {
747                BmsFlexRowOrder2FinalizerPhase::ImplicitFirst => {
748                    source.push_str(
749                        r#"    for (int u = 0; u < r; ++u) {
750        a_u[u] = -F_u[u] * inv_Fa;
751    }
752"#,
753                    );
754                }
755                BmsFlexRowOrder2FinalizerPhase::ImplicitFirstComplete => {
756                    source.push_str("    // Canonical implicit-first stage complete.\n");
757                }
758                BmsFlexRowOrder2FinalizerPhase::ImplicitSecond => {
759                    source.push_str(
760                        r#"    for (int u = 0; u < r; ++u) {
761        for (int v = u; v < r; ++v) {
762            size_t uv = (size_t)u * (size_t)r + (size_t)v;
763            size_t vu = (size_t)v * (size_t)r + (size_t)u;
764            double term = F_uv[uv]
765                        + F_au[v] * a_u[u]
766                        + F_au[u] * a_u[v]
767                        + F_aa * a_u[u] * a_u[v];
768            double value = -term * inv_Fa;
769            a_uv[uv] = value;
770            a_uv[vu] = value;
771        }
772    }
773"#,
774                    );
775                }
776                BmsFlexRowOrder2FinalizerPhase::ObservedFirst => {
777                    source.push_str("    // Observed first derivatives are derived on demand.\n");
778                }
779                BmsFlexRowOrder2FinalizerPhase::ObservedScoreSensitivity => {
780                    source.push_str(
781                        "    // Score sensitivity has no Stage-2 device output channel.\n",
782                    );
783                }
784                BmsFlexRowOrder2FinalizerPhase::ObservedSecond => {
785                    source.push_str(
786                        r#"    for (int u = 0; u < r; ++u) {
787        for (int v = u; v < r; ++v) {
788            size_t uv = (size_t)u * (size_t)r + (size_t)v;
789            size_t vu = (size_t)v * (size_t)r + (size_t)u;
790            double bar_e_u = chi * a_u[u] + rho[u];
791            double bar_e_v = chi * a_u[v] + rho[v];
792            double observed_second = chi * a_uv[uv]
793                                   + xi * a_u[u] * a_u[v]
794                                   + tau[u] * a_u[v]
795                                   + a_u[u] * tau[v]
796                                   + ruv[uv];
797            double hessian_value =
798                B_i * bar_e_u * bar_e_v + A_i * observed_second;
799            out_hess[row_rr_base + uv] = hessian_value;
800            out_hess[row_rr_base + vu] = hessian_value;
801        }
802    }
803"#,
804                    );
805                }
806                BmsFlexRowOrder2FinalizerPhase::NegLogFirst => {
807                    source.push_str(
808                        r#"    for (int u = 0; u < r; ++u) {
809        double bar_e_u = chi * a_u[u] + rho[u];
810        out_grad[row_r_base + (size_t)u] = A_i * bar_e_u;
811    }
812"#,
813                    );
814                }
815            }
816            Ok(())
817        },
818    )
819    .expect("the infallible finalizer phase emitter cannot fail");
820    source.push_str(suffix);
821    source.replace(
822        "/*__BMS_FLEX_ROW_THREADS__*/",
823        &ROW_KERNEL_THREADS.to_string(),
824    )
825}
826
827#[cfg(target_os = "linux")]
828pub(crate) fn generated_row_kernel_source() -> &'static str {
829    static SOURCE: OnceLock<String> = OnceLock::new();
830    SOURCE.get_or_init(build_generated_row_kernel_source)
831}
832
833// Force `s_f` to be considered used at the Rust level even though Stage 2 of
834// the kernel doesn't consume it on-device (the host has already baked the
835// probit frailty scale into the per-cell cubic coefficients). The dispatcher
836// validates that the host-baked cubic coefficients came from a finite,
837// positive frailty scale; reading it here also avoids a `let _` silencer.
838#[inline]
839pub(crate) fn s_f_diagnostic_finite(inputs: &BmsFlexRowKernelInputs<'_>) -> bool {
840    inputs.s_f.is_finite() && inputs.s_f > 0.0
841}
842
843#[cfg(target_os = "linux")]
844pub(crate) struct RowKernelBackend {
845    pub(crate) stream: Arc<CudaStream>,
846    pub(crate) module: Arc<CudaModule>,
847}
848
849#[cfg(target_os = "linux")]
850impl RowKernelBackend {
851    pub(crate) fn probe() -> Result<&'static Self, GpuError> {
852        static BACKEND: OnceLock<Result<RowKernelBackend, GpuError>> = OnceLock::new();
853        BACKEND
854            .get_or_init(|| {
855                gam_gpu::backend_probe::probe_backend_with_compile("bms_flex_row", |parts| {
856                    let row_kernel_source = [
857                        gam_gpu::numerics_device::PROBIT_NUMERICS_CU,
858                        generated_row_kernel_source(),
859                    ]
860                    .concat();
861                    // #1551: route through the project's single arch-aware NVRTC
862                    // entry point instead of bare `cudarc::nvrtc::compile_ptx`.
863                    // `compile_ptx_arch` pins `--gpu-architecture` to the selected
864                    // device's compute capability and supplies the standard CUDA
865                    // include paths; bare `compile_ptx` uses NVRTC's default
866                    // virtual arch with no includes. The row kernel's 64-bit
867                    // `atomic_add_f64` (atomicCAS emulation) compiles best against
868                    // the real device arch, and this keeps every BMS-flex compile
869                    // site consistent with the SAE arrow/Schur kernels that do
870                    // require the sm_60 pin for native `atomicAdd(double*,double)`.
871                    let ptx = gam_gpu::device_cache::compile_ptx_arch(&row_kernel_source).map_err(
872                        |err| GpuError::DriverCallFailed {
873                            reason: format!("bms_flex_row NVRTC compile failed: {err}"),
874                        },
875                    )?;
876                    let module =
877                        parts
878                            .ctx
879                            .load_module(ptx)
880                            .map_err(|err| GpuError::DriverCallFailed {
881                                reason: format!("bms_flex_row module load failed: {err}"),
882                            })?;
883                    Ok(RowKernelBackend {
884                        stream: parts.stream.clone(),
885                        module,
886                    })
887                })
888            })
889            .as_ref()
890            .map_err(GpuError::clone)
891    }
892}
893
894/// Launch Stage-2 BMS FLEX row kernel. On non-Linux returns
895/// [`GpuError::DriverLibraryUnavailable`]; on Linux NVRTC-compiles the kernel
896/// (cached for the process lifetime), uploads the per-row + per-cell buffers,
897/// and dispatches one block per row.
898pub(crate) fn launch_bms_flex_row_kernel(
899    inputs: BmsFlexRowKernelInputs<'_>,
900) -> Result<BmsFlexRowKernelOutputs, GpuError> {
901    inputs.validate()?;
902    if !s_f_diagnostic_finite(&inputs) {
903        return Err(GpuError::DriverCallFailed {
904            reason: format!(
905                "bms_flex_row inputs: s_f must be positive and finite, got {}",
906                inputs.s_f
907            ),
908        });
909    }
910
911    #[cfg(target_os = "linux")]
912    {
913        launch_linux(inputs)
914    }
915    #[cfg(not(target_os = "linux"))]
916    {
917        Err(GpuError::DriverLibraryUnavailable {
918            reason: "bms_flex_row GPU kernel is Linux-only".to_string(),
919        })
920    }
921}
922
923#[cfg(target_os = "linux")]
924pub(crate) fn launch_linux(
925    inputs: BmsFlexRowKernelInputs<'_>,
926) -> Result<BmsFlexRowKernelOutputs, GpuError> {
927    let backend = RowKernelBackend::probe()?;
928    let stream = &backend.stream;
929
930    let upload_f64 = |slice: &[f64], label: &str| {
931        stream
932            .clone_htod(slice)
933            .map_err(|err| GpuError::DriverCallFailed {
934                reason: format!("bms_flex_row upload {label}: {err}"),
935            })
936    };
937    let upload_u32 = |slice: &[u32], label: &str| {
938        stream
939            .clone_htod(slice)
940            .map_err(|err| GpuError::DriverCallFailed {
941                reason: format!("bms_flex_row upload {label}: {err}"),
942            })
943    };
944
945    let d_q = upload_f64(inputs.q, "q")?;
946    let d_b = upload_f64(inputs.b, "b")?;
947    let d_mu1 = upload_f64(inputs.mu_1, "mu_1")?;
948    let d_mu2 = upload_f64(inputs.mu_2, "mu_2")?;
949    let d_zobs = upload_f64(inputs.z_obs, "z_obs")?;
950    let d_y = upload_f64(inputs.y, "y")?;
951    let d_w = upload_f64(inputs.w, "w")?;
952    let d_offsets = upload_u32(inputs.cell_offsets, "cell_offsets")?;
953    let d_c0 = upload_f64(inputs.cell_c0, "cell_c0")?;
954    let d_c1 = upload_f64(inputs.cell_c1, "cell_c1")?;
955    let d_c2 = upload_f64(inputs.cell_c2, "cell_c2")?;
956    let d_c3 = upload_f64(inputs.cell_c3, "cell_c3")?;
957    let d_a = upload_f64(inputs.cell_a, "cell_a")?;
958    let d_aa = upload_f64(inputs.cell_aa, "cell_aa")?;
959    let d_r = upload_f64(inputs.cell_r, "cell_r")?;
960    let d_ar = upload_f64(inputs.cell_ar, "cell_ar")?;
961    let d_sbb = upload_f64(inputs.cell_sbb, "cell_sbb")?;
962    let d_sbh = upload_f64(inputs.cell_sbh, "cell_sbh")?;
963    let d_sbw = upload_f64(inputs.cell_sbw, "cell_sbw")?;
964    // Phase-4: optionally consume device-resident moments (no host upload).
965    // Both branches end up holding a `&CudaSlice<f64>` named `d_moments_ref`
966    // we can pass to the launch builder uniformly.
967    let owned_host_moments: CudaSlice<f64>;
968    let d_moments_ref: &CudaSlice<f64> = match &inputs.cell_moments {
969        CellMomentsSource::Host(slice) => {
970            owned_host_moments = upload_f64(slice, "cell_moments")?;
971            &owned_host_moments
972        }
973        CellMomentsSource::Device(d) => *d,
974    };
975    let d_chi = upload_f64(inputs.chi_obs, "chi_obs")?;
976    let d_xi = upload_f64(inputs.xi_obs, "xi_obs")?;
977    let d_rho = upload_f64(inputs.rho_u, "rho_u")?;
978    let d_tau = upload_f64(inputs.tau_u, "tau_u")?;
979    let d_ruv = upload_f64(inputs.r_uv, "r_uv")?;
980    let d_e_obs = upload_f64(inputs.e_obs, "e_obs")?;
981
982    let n = inputs.n_rows;
983    let r = inputs.r;
984    let nr = checked_shape_len("launch [n,r]", &[n, r])?;
985    let nrr = checked_shape_len("launch [n,r,r]", &[n, r, r])?;
986    let mut d_neglog = stream
987        .alloc_zeros::<f64>(n)
988        .map_err(|err| GpuError::DriverCallFailed {
989            reason: format!("bms_flex_row alloc neglog: {err}"),
990        })?;
991    let mut d_grad = stream
992        .alloc_zeros::<f64>(nr)
993        .map_err(|err| GpuError::DriverCallFailed {
994            reason: format!("bms_flex_row alloc grad: {err}"),
995        })?;
996    let mut d_hess = stream
997        .alloc_zeros::<f64>(nrr)
998        .map_err(|err| GpuError::DriverCallFailed {
999            reason: format!("bms_flex_row alloc hess: {err}"),
1000        })?;
1001    let mut d_f_au = stream
1002        .alloc_zeros::<f64>(nr)
1003        .map_err(|err| GpuError::DriverCallFailed {
1004            reason: format!("bms_flex_row alloc F_au scratch: {err}"),
1005        })?;
1006    let mut d_status = stream
1007        .alloc_zeros::<u32>(n)
1008        .map_err(|err| GpuError::DriverCallFailed {
1009            reason: format!("bms_flex_row alloc status: {err}"),
1010        })?;
1011
1012    let func = backend
1013        .module
1014        .load_function("bms_flex_row_kernel")
1015        .map_err(|err| GpuError::DriverCallFailed {
1016            reason: format!("bms_flex_row load_function: {err}"),
1017        })?;
1018
1019    let n_u32 = u32::try_from(n).map_err(|_| GpuError::DriverCallFailed {
1020        reason: format!("bms_flex_row: n_rows={n} exceeds CUDA grid range"),
1021    })?;
1022    let cfg = LaunchConfig {
1023        grid_dim: (n_u32, 1, 1),
1024        block_dim: (ROW_KERNEL_THREADS, 1, 1),
1025        shared_mem_bytes: 0,
1026    };
1027    let n_i32 = i32::try_from(n).map_err(|_| GpuError::DriverCallFailed {
1028        reason: format!("bms_flex_row: n_rows={n} exceeds i32 range"),
1029    })?;
1030    let r_i32 = i32::try_from(r).map_err(|_| GpuError::DriverCallFailed {
1031        reason: format!("bms_flex_row: r={r} exceeds i32 range"),
1032    })?;
1033    let p_h_i32 = i32::try_from(inputs.p_h).map_err(|_| GpuError::DriverCallFailed {
1034        reason: format!("bms_flex_row: p_h={} exceeds i32 range", inputs.p_h),
1035    })?;
1036    let p_w_i32 = i32::try_from(inputs.p_w).map_err(|_| GpuError::DriverCallFailed {
1037        reason: format!("bms_flex_row: p_w={} exceeds i32 range", inputs.p_w),
1038    })?;
1039    let s_f = inputs.s_f;
1040
1041    let mut builder = stream.launch_builder(&func);
1042    builder
1043        .arg(&n_i32)
1044        .arg(&r_i32)
1045        .arg(&p_h_i32)
1046        .arg(&p_w_i32)
1047        .arg(&s_f)
1048        .arg(&d_q)
1049        .arg(&d_b)
1050        .arg(&d_mu1)
1051        .arg(&d_mu2)
1052        .arg(&d_zobs)
1053        .arg(&d_y)
1054        .arg(&d_w)
1055        .arg(&d_offsets)
1056        .arg(&d_c0)
1057        .arg(&d_c1)
1058        .arg(&d_c2)
1059        .arg(&d_c3)
1060        .arg(&d_a)
1061        .arg(&d_aa)
1062        .arg(&d_r)
1063        .arg(&d_ar)
1064        .arg(&d_sbb)
1065        .arg(&d_sbh)
1066        .arg(&d_sbw)
1067        .arg(d_moments_ref)
1068        .arg(&d_chi)
1069        .arg(&d_xi)
1070        .arg(&d_rho)
1071        .arg(&d_tau)
1072        .arg(&d_ruv)
1073        .arg(&d_e_obs)
1074        .arg(&mut d_f_au)
1075        .arg(&mut d_neglog)
1076        .arg(&mut d_grad)
1077        .arg(&mut d_hess)
1078        .arg(&mut d_status);
1079
1080    // SAFETY: every kernel parameter above is either a primitive `i32` /
1081    // `f64` (passed by value), a const device pointer to a buffer whose
1082    // length the host validated against the input struct, or an output
1083    // buffers pre-allocated to checked `n_rows`, `n_rows*r`, and
1084    // `n_rows*r*r` lengths. Primary-width scratch aliases those outputs plus
1085    // the checked `d_f_au` allocation; no fixed-width device array exists.
1086    unsafe { builder.launch(cfg) }.map_err(|err| GpuError::DriverCallFailed {
1087        reason: format!("bms_flex_row launch: {err}"),
1088    })?;
1089    stream
1090        .synchronize()
1091        .map_err(|err| GpuError::DriverCallFailed {
1092            reason: format!("bms_flex_row synchronize: {err}"),
1093        })?;
1094
1095    let status = stream
1096        .clone_dtoh(&d_status)
1097        .map_err(|err| GpuError::DriverCallFailed {
1098            reason: format!("bms_flex_row download status: {err}"),
1099        })?;
1100    if let Some((row, code)) = status
1101        .iter()
1102        .copied()
1103        .enumerate()
1104        .find(|(_, code)| *code != 0)
1105    {
1106        return Err(GpuError::DriverCallFailed {
1107            reason: format!("bms_flex_row rejected non-finite row {row} with status {code}"),
1108        });
1109    }
1110
1111    let neglog = stream
1112        .clone_dtoh(&d_neglog)
1113        .map_err(|err| GpuError::DriverCallFailed {
1114            reason: format!("bms_flex_row download neglog: {err}"),
1115        })?;
1116    let grad = stream
1117        .clone_dtoh(&d_grad)
1118        .map_err(|err| GpuError::DriverCallFailed {
1119            reason: format!("bms_flex_row download grad: {err}"),
1120        })?;
1121    let hess = stream
1122        .clone_dtoh(&d_hess)
1123        .map_err(|err| GpuError::DriverCallFailed {
1124            reason: format!("bms_flex_row download hess: {err}"),
1125        })?;
1126
1127    Ok(BmsFlexRowKernelOutputs { neglog, grad, hess })
1128}
1129
1130// ─────────────────────────────────────────────────────────────────────────────
1131// Phase 3: device-resident row Hessian + HVP / diagonal kernels.
1132//
1133// Math (mirrors the CPU oracle in
1134// `src/families/bernoulli_marginal_slope.rs::exact_newton_joint_hessian_*_from_cache`):
1135//
1136//   Block layout (joint β):
1137//     marginal = [0..p_m), logslope = [p_m..p_m+p_g),
1138//     h        = [h_start..h_end), w = [w_start..w_end), total = p_total.
1139//
1140//   Primary layout (per-row r-vector):
1141//     q = 0, logslope = 1,
1142//     h = [h_primary_start..h_primary_end),
1143//     w = [w_primary_start..w_primary_end), total = r.
1144//
1145//   row_dir[u] for u in primary layout:
1146//     row_dir[0]   = Σ_j marginal_design[row, j] · v[j]
1147//     row_dir[1]   = Σ_j logslope_design[row, j] · v[p_m + j]
1148//     row_dir[h_k] = v[h_block_start + (h_k - h_primary_start)]
1149//     row_dir[w_k] = v[w_block_start + (w_k - w_primary_start)]
1150//
1151//   action[u]    = Σ_v row_hessians[row, u*r + v] · row_dir[v]
1152//
1153//   block_partial[marginal_j] += action[0] · marginal_design[row, j]
1154//   block_partial[logslope_j] += action[1] · logslope_design[row, j]
1155//   block_partial[h_block_start + (h_k - h_primary_start)] += action[h_k]
1156//   block_partial[w_block_start + (w_k - w_primary_start)] += action[w_k]
1157//
1158// Diagonal:
1159//   diag[marginal_j] += row_hess[row, 0*r + 0] · marginal_design[row, j]²
1160//   diag[logslope_j] += row_hess[row, 1*r + 1] · logslope_design[row, j]²
1161//   diag[h_block_start + k] += row_hess[row, ii*r + ii]   (ii = h_primary_start + k)
1162//   diag[w_block_start + k] += row_hess[row, ii*r + ii]   (ii = w_primary_start + k)
1163//
1164// Determinism: each CTA owns a contiguous slice of `[chunk_start..chunk_end)`
1165// rows and writes its full per-chunk `p_total` partial into a non-overlapping
1166// region of the global partial buffer. The reduce kernel then sums those
1167// partials in fixed chunk-major order. No atomics.
1168
1169/// Joint-β block layout shared with the host (mirrors `BlockSlices` in
1170/// `bernoulli_marginal_slope.rs`).
1171///
1172/// Gating: Linux-only. The lone production constructor lives in
1173/// `bernoulli_marginal_slope.rs:9189` behind `#[cfg(target_os = "linux")]`
1174/// — the device-resident row-Hessian path is the only producer (see
1175/// `launch_bms_flex_row_kernel_device_resident`), and the joint-β
1176/// consumers `launch_bms_flex_row_hvp` / `_diagonal` / `_dense_block`
1177/// are also Linux-only. Any non-Linux test referencing this type must
1178/// guard itself with `#[cfg(target_os = "linux")]` too — the build.rs
1179/// ban scanner explicitly rejects `#[cfg(any(..., test))]` on items as
1180/// a dead-code escape hatch.
1181#[cfg(target_os = "linux")]
1182#[derive(Clone, Debug)]
1183pub(crate) struct BmsFlexBlockLayout {
1184    pub p_m: usize,
1185    pub p_g: usize,
1186    pub h: Option<std::ops::Range<usize>>,
1187    pub w: Option<std::ops::Range<usize>>,
1188    pub p_total: usize,
1189}
1190
1191/// Primary-r layout shared with the host (mirrors `PrimarySlices`).
1192/// Gating rationale identical to [`BmsFlexBlockLayout`].
1193#[cfg(target_os = "linux")]
1194#[derive(Clone, Debug)]
1195pub(crate) struct BmsFlexPrimaryLayout {
1196    pub h: Option<std::ops::Range<usize>>,
1197    pub w: Option<std::ops::Range<usize>>,
1198    pub r: usize,
1199}
1200
1201// ── Linux-only: device-resident row-Hessian state + kernels ─────────────────
1202
1203/// Number of rows each HVP / diagonal CTA processes. Each CTA writes a single
1204/// `[1, p_total]` partial row into the global partial buffer (no atomics);
1205/// the reduce kernel then sums partials in chunk-major fixed order.
1206#[cfg(target_os = "linux")]
1207pub(crate) const HVP_ROWS_PER_CTA: u32 = 256;
1208
1209/// `blockDim.x` for the HVP / diagonal partial kernels.
1210#[cfg(target_os = "linux")]
1211pub(crate) const HVP_THREADS: u32 = 128;
1212
1213/// `blockDim.x` for the partial-sum reduction kernels (one element per thread,
1214/// grid-strided over the `p_total`/`rhs_elems` partial buffer). A full warp
1215/// multiple that keeps the reduce launch occupancy-bound rather than tail-bound
1216/// for the typical large-scale `p_total`.
1217#[cfg(target_os = "linux")]
1218pub(crate) const REDUCTION_THREADS: u32 = 256;
1219
1220/// Maximum RHS columns fused into one row-primary HVP launch. This is an
1221/// internal batching width, not a matrix-width limit: wider dense matrices are
1222/// materialised in consecutive batches. The CUDA source has four scalar
1223/// shared arrays of this length; primary directions are derived on demand.
1224#[cfg(target_os = "linux")]
1225pub(crate) const BMS_FLEX_ROW_HVP_MAX_RHS: usize = 8;
1226
1227/// Device-resident state produced by
1228/// [`launch_bms_flex_row_kernel_device_resident`] and consumed by
1229/// [`launch_bms_flex_row_hvp`] / [`launch_bms_flex_row_diagonal`].
1230///
1231/// Owns the canonical row value, gradient, Hessian, and design slices on-device
1232/// so every downstream value/score/Hessian consumer shares one row evaluation
1233/// without round-tripping the large cache through host RAM. Drop releases the
1234/// device memory back to the CUDA runtime.
1235#[cfg(target_os = "linux")]
1236pub struct DeviceResidentRowHess {
1237    /// Per-row negative log likelihood emitted by the same canonical row
1238    /// program that emits `grad` and `hess`.
1239    pub(crate) neglog: CudaSlice<f64>,
1240    /// Per-row objective gradient `[n, r]`, row-major. Joint-score consumers
1241    /// negate and pull this buffer back through the two designs/direct blocks.
1242    pub(crate) grad: CudaSlice<f64>,
1243    /// Per-row dense `[n, r, r]` row-major Hessian. Element `(u, v)` of row
1244    /// `i` is `hess[i*r*r + u*r + v]`. This is the only on-device storage
1245    /// layout supported by the current HVP / diag kernels.
1246    pub(crate) hess: CudaSlice<f64>,
1247    pub(crate) marginal_design: CudaSlice<f64>,
1248    pub(crate) logslope_design: CudaSlice<f64>,
1249    pub(crate) n: usize,
1250    pub(crate) r: usize,
1251    pub(crate) block: BmsFlexBlockLayout,
1252    pub(crate) primary: BmsFlexPrimaryLayout,
1253    /// Estimated bytes resident on device (for accounting).
1254    pub(crate) bytes: u64,
1255}
1256
1257/// Host image of the deterministic device reduction over the canonical row
1258/// value/gradient buffers. The gradient uses log-likelihood/score sign.
1259#[cfg(target_os = "linux")]
1260pub(crate) struct BmsFlexDeviceJointGradient {
1261    pub(crate) log_likelihood: f64,
1262    pub(crate) gradient: Vec<f64>,
1263}
1264
1265#[cfg(target_os = "linux")]
1266impl std::fmt::Debug for DeviceResidentRowHess {
1267    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1268        f.debug_struct("DeviceResidentRowHess")
1269            .field("n", &self.n)
1270            .field("r", &self.r)
1271            .field("p_total", &self.block.p_total)
1272            .field("bytes", &self.bytes)
1273            .finish()
1274    }
1275}
1276
1277/// Sized-to-fit-once CTA mapping. Rows `[c * HVP_ROWS_PER_CTA, (c+1) * HVP_ROWS_PER_CTA)`
1278/// belong to chunk `c`.
1279#[cfg(target_os = "linux")]
1280pub(crate) fn num_hvp_chunks(n: usize) -> usize {
1281    n.div_ceil(HVP_ROWS_PER_CTA as usize)
1282}
1283
1284/// NVRTC source: deterministic joint-gradient, HVP, diagonal, and dense
1285/// partial+reduce kernels. All kernels mirror CPU oracles in this file.
1286#[cfg(target_os = "linux")]
1287pub(crate) const HVP_KERNEL_SOURCE: &str = r#"
1288// CPU parity reference: cpu_oracle_bms_flex_row_hvp / cpu_oracle_bms_flex_row_diagonal
1289// in this module.
1290
1291#define MAX_MULTI_RHS 8
1292
1293__device__ __forceinline__ double bms_flex_primary_direction(
1294    int primary_idx,
1295    int h_block_start,
1296    int h_block_len,
1297    int w_block_start,
1298    int w_block_len,
1299    int h_primary_start,
1300    int w_primary_start,
1301    double direction_q,
1302    double direction_g,
1303    const double * __restrict__ v)
1304{
1305    if (primary_idx == 0) return direction_q;
1306    if (primary_idx == 1) return direction_g;
1307    if (primary_idx >= h_primary_start && primary_idx < h_primary_start + h_block_len) {
1308        return v[h_block_start + primary_idx - h_primary_start];
1309    }
1310    if (primary_idx >= w_primary_start && primary_idx < w_primary_start + w_block_len) {
1311        return v[w_block_start + primary_idx - w_primary_start];
1312    }
1313    return 0.0;
1314}
1315
1316extern "C" __global__ void bms_flex_row_hvp_partial(
1317    int                  n_rows,
1318    int                  r,
1319    int                  p_m,
1320    int                  p_g,
1321    int                  p_total,
1322    int                  h_block_start,
1323    int                  h_block_len,
1324    int                  w_block_start,
1325    int                  w_block_len,
1326    int                  h_primary_start,
1327    int                  w_primary_start,
1328    int                  rows_per_cta,
1329    const double * __restrict__ row_hessians,    // [n, r*r]
1330    const double * __restrict__ marginal_design, // [n, p_m] row-major
1331    const double * __restrict__ logslope_design, // [n, p_g] row-major
1332    const double * __restrict__ v,               // [p_total]
1333    double       * __restrict__ partial)         // [num_chunks, p_total]
1334{
1335    int chunk = blockIdx.x;
1336    int tid   = threadIdx.x;
1337    int row_lo = chunk * rows_per_cta;
1338    int remaining_rows = n_rows - row_lo;
1339    int row_hi = row_lo + (remaining_rows < rows_per_cta ? remaining_rows : rows_per_cta);
1340
1341    // Zero this chunk's partial slice cooperatively.
1342    double *out = partial + (size_t)chunk * (size_t)p_total;
1343    for (int j = tid; j < p_total; j += blockDim.x) {
1344        out[j] = 0.0;
1345    }
1346    __syncthreads();
1347
1348    // Width-general scratch: only the two design directions/actions are
1349    // shared. Every h/w direction is read directly from v, and the thread
1350    // owning primary coordinate u accumulates that coordinate's action.
1351    __shared__ double direction_q;
1352    __shared__ double direction_g;
1353    __shared__ double action_q;
1354    __shared__ double action_g;
1355    __shared__ double dot_reduce[128];
1356
1357    for (int row = row_lo; row < row_hi; ++row) {
1358        const double *mrow = marginal_design + (size_t)row * (size_t)p_m;
1359        const double *grow = logslope_design + (size_t)row * (size_t)p_g;
1360        const double *Hrow = row_hessians + (size_t)row * (size_t)r * (size_t)r;
1361
1362        // row_dir[0] = mrow · v[0..p_m]
1363        double local = 0.0;
1364        for (int j = tid; j < p_m; j += blockDim.x) {
1365            local += mrow[j] * v[j];
1366        }
1367        dot_reduce[tid] = local;
1368        __syncthreads();
1369        for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
1370            if (tid < stride) dot_reduce[tid] += dot_reduce[tid + stride];
1371            __syncthreads();
1372        }
1373        if (tid == 0) direction_q = dot_reduce[0];
1374
1375        // row_dir[1] = grow · v[p_m..p_m+p_g]
1376        local = 0.0;
1377        for (int j = tid; j < p_g; j += blockDim.x) {
1378            local += grow[j] * v[p_m + j];
1379        }
1380        dot_reduce[tid] = local;
1381        __syncthreads();
1382        for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
1383            if (tid < stride) dot_reduce[tid] += dot_reduce[tid + stride];
1384            __syncthreads();
1385        }
1386        if (tid == 0) direction_g = dot_reduce[0];
1387        __syncthreads();
1388
1389        for (int u = tid; u < r; u += blockDim.x) {
1390            double acc = 0.0;
1391            for (int vv = 0; vv < r; ++vv) {
1392                double row_direction = bms_flex_primary_direction(
1393                    vv,
1394                    h_block_start, h_block_len,
1395                    w_block_start, w_block_len,
1396                    h_primary_start, w_primary_start,
1397                    direction_q, direction_g, v);
1398                acc += Hrow[(size_t)u * (size_t)r + (size_t)vv] * row_direction;
1399            }
1400            if (u == 0) {
1401                action_q = acc;
1402            } else if (u == 1) {
1403                action_g = acc;
1404            } else if (u >= h_primary_start && u < h_primary_start + h_block_len) {
1405                out[h_block_start + u - h_primary_start] += acc;
1406            } else if (u >= w_primary_start && u < w_primary_start + w_block_len) {
1407                out[w_block_start + u - w_primary_start] += acc;
1408            }
1409        }
1410        __syncthreads();
1411
1412        // Pull back into joint β slot.
1413        double a0 = action_q;
1414        for (int j = tid; j < p_m; j += blockDim.x) {
1415            out[j] += a0 * mrow[j];
1416        }
1417        double a1 = action_g;
1418        for (int j = tid; j < p_g; j += blockDim.x) {
1419            out[p_m + j] += a1 * grow[j];
1420        }
1421        __syncthreads();
1422    }
1423}
1424
1425extern "C" __global__ void bms_flex_row_hvp_reduce(
1426    int                  num_chunks,
1427    int                  p_total,
1428    const double * __restrict__ partial,   // [num_chunks, p_total]
1429    double       * __restrict__ out)        // [p_total]
1430{
1431    int j = blockIdx.x * blockDim.x + threadIdx.x;
1432    if (j >= p_total) return;
1433    double acc = 0.0;
1434    for (int c = 0; c < num_chunks; ++c) {
1435        acc += partial[(size_t)c * (size_t)p_total + (size_t)j];
1436    }
1437    out[j] = acc;
1438}
1439
1440extern "C" __global__ void bms_flex_row_joint_gradient_partial(
1441    int                  n_rows,
1442    int                  r,
1443    int                  p_m,
1444    int                  p_g,
1445    int                  p_total,
1446    int                  h_block_start,
1447    int                  h_block_len,
1448    int                  w_block_start,
1449    int                  w_block_len,
1450    int                  h_primary_start,
1451    int                  w_primary_start,
1452    int                  rows_per_cta,
1453    const double * __restrict__ row_neglog,       // [n]
1454    const double * __restrict__ row_grad,         // [n, r]
1455    const double * __restrict__ marginal_design,  // [n, p_m]
1456    const double * __restrict__ logslope_design,  // [n, p_g]
1457    double       * __restrict__ partial)          // [num_chunks, 1+p_total]
1458{
1459    int chunk = blockIdx.x;
1460    int tid = threadIdx.x;
1461    int row_lo = chunk * rows_per_cta;
1462    int remaining_rows = n_rows - row_lo;
1463    int row_hi = row_lo + (remaining_rows < rows_per_cta ? remaining_rows : rows_per_cta);
1464    int output_width = p_total + 1;
1465    double *out = partial + (size_t)chunk * (size_t)output_width;
1466
1467    // One thread owns each output coordinate for the whole row chunk. The
1468    // inner row loop therefore has a fixed order and needs no atomics.
1469    for (int output_idx = tid; output_idx < output_width; output_idx += blockDim.x) {
1470        double acc = 0.0;
1471        if (output_idx == 0) {
1472            for (int row = row_lo; row < row_hi; ++row) {
1473                acc -= row_neglog[row];
1474            }
1475        } else {
1476            int beta_idx = output_idx - 1;
1477            if (beta_idx < p_m) {
1478                for (int row = row_lo; row < row_hi; ++row) {
1479                    acc -= row_grad[(size_t)row * (size_t)r]
1480                         * marginal_design[(size_t)row * (size_t)p_m + (size_t)beta_idx];
1481                }
1482            } else if (beta_idx < p_m + p_g) {
1483                int j = beta_idx - p_m;
1484                for (int row = row_lo; row < row_hi; ++row) {
1485                    acc -= row_grad[(size_t)row * (size_t)r + 1]
1486                         * logslope_design[(size_t)row * (size_t)p_g + (size_t)j];
1487                }
1488            } else if (beta_idx >= h_block_start && beta_idx < h_block_start + h_block_len) {
1489                int primary_idx = h_primary_start + beta_idx - h_block_start;
1490                for (int row = row_lo; row < row_hi; ++row) {
1491                    acc -= row_grad[(size_t)row * (size_t)r + (size_t)primary_idx];
1492                }
1493            } else if (beta_idx >= w_block_start && beta_idx < w_block_start + w_block_len) {
1494                int primary_idx = w_primary_start + beta_idx - w_block_start;
1495                for (int row = row_lo; row < row_hi; ++row) {
1496                    acc -= row_grad[(size_t)row * (size_t)r + (size_t)primary_idx];
1497                }
1498            }
1499        }
1500        out[output_idx] = acc;
1501    }
1502}
1503
1504extern "C" __global__ void bms_flex_row_joint_gradient_reduce(
1505    int                  num_chunks,
1506    int                  output_width,
1507    const double * __restrict__ partial,   // [num_chunks, output_width]
1508    double       * __restrict__ out)        // [output_width]
1509{
1510    int j = blockIdx.x * blockDim.x + threadIdx.x;
1511    if (j >= output_width) return;
1512    double acc = 0.0;
1513    for (int c = 0; c < num_chunks; ++c) {
1514        acc += partial[(size_t)c * (size_t)output_width + (size_t)j];
1515    }
1516    out[j] = acc;
1517}
1518
1519extern "C" __global__ void bms_flex_row_hvp_multi_partial(
1520    int                  n_rows,
1521    int                  r,
1522    int                  p_m,
1523    int                  p_g,
1524    int                  p_total,
1525    int                  h_block_start,
1526    int                  h_block_len,
1527    int                  w_block_start,
1528    int                  w_block_len,
1529    int                  h_primary_start,
1530    int                  w_primary_start,
1531    int                  rows_per_cta,
1532    int                  rhs_count,
1533    const double * __restrict__ row_hessians,    // [n, r*r]
1534    const double * __restrict__ marginal_design, // [n, p_m]
1535    const double * __restrict__ logslope_design, // [n, p_g]
1536    const double * __restrict__ v_rhs,           // [rhs_count, p_total]
1537    double       * __restrict__ partial)         // [rhs_count, num_chunks, p_total]
1538{
1539    int chunk = blockIdx.x;
1540    int tid   = threadIdx.x;
1541    int row_lo = chunk * rows_per_cta;
1542    int remaining_rows = n_rows - row_lo;
1543    int row_hi = row_lo + (remaining_rows < rows_per_cta ? remaining_rows : rows_per_cta);
1544
1545    int num_chunks = 1 + (n_rows - 1) / rows_per_cta;
1546    for (int idx = tid; idx < rhs_count * p_total; idx += blockDim.x) {
1547        int rhs = idx / p_total;
1548        int j = idx - rhs * p_total;
1549        partial[((size_t)rhs * (size_t)num_chunks + (size_t)chunk) * (size_t)p_total + (size_t)j] = 0.0;
1550    }
1551    __syncthreads();
1552
1553    __shared__ double direction_q[MAX_MULTI_RHS];
1554    __shared__ double direction_g[MAX_MULTI_RHS];
1555    __shared__ double action_q[MAX_MULTI_RHS];
1556    __shared__ double action_g[MAX_MULTI_RHS];
1557    __shared__ double dot_reduce[128];
1558
1559    for (int row = row_lo; row < row_hi; ++row) {
1560        const double *mrow = marginal_design + (size_t)row * (size_t)p_m;
1561        const double *grow = logslope_design + (size_t)row * (size_t)p_g;
1562        const double *Hrow = row_hessians + (size_t)row * (size_t)r * (size_t)r;
1563
1564        for (int rhs = 0; rhs < rhs_count; ++rhs) {
1565            const double *v = v_rhs + (size_t)rhs * (size_t)p_total;
1566
1567            double local = 0.0;
1568            for (int j = tid; j < p_m; j += blockDim.x) {
1569                local += mrow[j] * v[j];
1570            }
1571            dot_reduce[tid] = local;
1572            __syncthreads();
1573            for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
1574                if (tid < stride) dot_reduce[tid] += dot_reduce[tid + stride];
1575                __syncthreads();
1576            }
1577            if (tid == 0) direction_q[rhs] = dot_reduce[0];
1578
1579            local = 0.0;
1580            for (int j = tid; j < p_g; j += blockDim.x) {
1581                local += grow[j] * v[p_m + j];
1582            }
1583            dot_reduce[tid] = local;
1584            __syncthreads();
1585            for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
1586                if (tid < stride) dot_reduce[tid] += dot_reduce[tid + stride];
1587                __syncthreads();
1588            }
1589            if (tid == 0) direction_g[rhs] = dot_reduce[0];
1590            __syncthreads();
1591        }
1592
1593        size_t total_actions = (size_t)rhs_count * (size_t)r;
1594        for (size_t idx = (size_t)tid; idx < total_actions; idx += (size_t)blockDim.x) {
1595            int rhs = (int)(idx / (size_t)r);
1596            int u = (int)(idx - (size_t)rhs * (size_t)r);
1597            const double *v = v_rhs + (size_t)rhs * (size_t)p_total;
1598            double *out = partial + ((size_t)rhs * (size_t)num_chunks + (size_t)chunk) * (size_t)p_total;
1599            double acc = 0.0;
1600            for (int vv = 0; vv < r; ++vv) {
1601                double row_direction = bms_flex_primary_direction(
1602                    vv,
1603                    h_block_start, h_block_len,
1604                    w_block_start, w_block_len,
1605                    h_primary_start, w_primary_start,
1606                    direction_q[rhs], direction_g[rhs], v);
1607                acc += Hrow[(size_t)u * (size_t)r + (size_t)vv] * row_direction;
1608            }
1609            if (u == 0) {
1610                action_q[rhs] = acc;
1611            } else if (u == 1) {
1612                action_g[rhs] = acc;
1613            } else if (u >= h_primary_start && u < h_primary_start + h_block_len) {
1614                out[h_block_start + u - h_primary_start] += acc;
1615            } else if (u >= w_primary_start && u < w_primary_start + w_block_len) {
1616                out[w_block_start + u - w_primary_start] += acc;
1617            }
1618        }
1619        __syncthreads();
1620
1621        for (int rhs = 0; rhs < rhs_count; ++rhs) {
1622            double *out = partial + ((size_t)rhs * (size_t)num_chunks + (size_t)chunk) * (size_t)p_total;
1623            double a0 = action_q[rhs];
1624            for (int j = tid; j < p_m; j += blockDim.x) {
1625                out[j] += a0 * mrow[j];
1626            }
1627            double a1 = action_g[rhs];
1628            for (int j = tid; j < p_g; j += blockDim.x) {
1629                out[p_m + j] += a1 * grow[j];
1630            }
1631            __syncthreads();
1632        }
1633    }
1634}
1635
1636extern "C" __global__ void bms_flex_row_hvp_multi_reduce(
1637    int                  num_chunks,
1638    int                  p_total,
1639    int                  rhs_count,
1640    const double * __restrict__ partial,   // [rhs_count, num_chunks, p_total]
1641    double       * __restrict__ out)        // [rhs_count, p_total]
1642{
1643    int idx = blockIdx.x * blockDim.x + threadIdx.x;
1644    int total = rhs_count * p_total;
1645    if (idx >= total) return;
1646    int rhs = idx / p_total;
1647    int j = idx - rhs * p_total;
1648    double acc = 0.0;
1649    for (int c = 0; c < num_chunks; ++c) {
1650        acc += partial[((size_t)rhs * (size_t)num_chunks + (size_t)c) * (size_t)p_total + (size_t)j];
1651    }
1652    out[(size_t)rhs * (size_t)p_total + (size_t)j] = acc;
1653}
1654
1655extern "C" __global__ void bms_flex_row_diag_partial(
1656    int                  n_rows,
1657    int                  r,
1658    int                  p_m,
1659    int                  p_g,
1660    int                  p_total,
1661    int                  h_block_start,
1662    int                  h_block_len,
1663    int                  w_block_start,
1664    int                  w_block_len,
1665    int                  h_primary_start,
1666    int                  w_primary_start,
1667    int                  rows_per_cta,
1668    const double * __restrict__ row_hessians,
1669    const double * __restrict__ marginal_design,
1670    const double * __restrict__ logslope_design,
1671    double       * __restrict__ partial)
1672{
1673    int chunk = blockIdx.x;
1674    int tid   = threadIdx.x;
1675    int row_lo = chunk * rows_per_cta;
1676    int remaining_rows = n_rows - row_lo;
1677    int row_hi = row_lo + (remaining_rows < rows_per_cta ? remaining_rows : rows_per_cta);
1678
1679    double *out = partial + (size_t)chunk * (size_t)p_total;
1680    for (int j = tid; j < p_total; j += blockDim.x) {
1681        out[j] = 0.0;
1682    }
1683    __syncthreads();
1684
1685    for (int row = row_lo; row < row_hi; ++row) {
1686        const double *mrow = marginal_design + (size_t)row * (size_t)p_m;
1687        const double *grow = logslope_design + (size_t)row * (size_t)p_g;
1688        const double *Hrow = row_hessians + (size_t)row * (size_t)r * (size_t)r;
1689        double h00 = Hrow[0];
1690        double h11 = Hrow[(size_t)r + 1U];
1691        for (int j = tid; j < p_m; j += blockDim.x) {
1692            double v = mrow[j];
1693            out[j] += h00 * v * v;
1694        }
1695        for (int j = tid; j < p_g; j += blockDim.x) {
1696            double v = grow[j];
1697            out[p_m + j] += h11 * v * v;
1698        }
1699        if (tid == 0) {
1700            for (int k = 0; k < h_block_len; ++k) {
1701                int ii = h_primary_start + k;
1702                out[h_block_start + k] +=
1703                    Hrow[(size_t)ii * (size_t)r + (size_t)ii];
1704            }
1705            for (int k = 0; k < w_block_len; ++k) {
1706                int ii = w_primary_start + k;
1707                out[w_block_start + k] +=
1708                    Hrow[(size_t)ii * (size_t)r + (size_t)ii];
1709            }
1710        }
1711        __syncthreads();
1712    }
1713}
1714
1715// ────────────────────────────────────────────────────────────────────────
1716// Phase 6 — dense joint-Hessian block kernel for the debug / exact-REML
1717// route. Materialises the full `[p_total, p_total]` row-major joint H
1718// from the per-row r×r Hessian via the P_i pullback. NOT the default
1719// Newton path: production Newton uses HVP (Phase 2/3); this kernel exists
1720// for exact-REML logdet / dense-H comparisons / diagnostic dumps where the
1721// caller genuinely needs the dense matrix on the device.
1722//
1723// Per-CTA partial: each CTA owns a contiguous chunk of rows
1724// `[chunk*rows_per_cta, (chunk+1)*rows_per_cta)`. Inside the CTA the
1725// per-row pullback computes `(P_i^T H_i P_i)[m, n]` and adds it to the
1726// CTA's shared-mem `[p_total, p_total]` partial. The reduce kernel sums
1727// chunk-major-fixed-order into a single `[p_total, p_total]` output.
1728//
1729// Math: for primary index u ∈ [0, r):
1730//   * u = 0:        phi_u = (X_i in slot 0..p_m, 0 elsewhere)
1731//   * u = 1:        phi_u = (0, G_i in slot p_m..p_m+p_g, 0 elsewhere)
1732//   * u = 2+j:      phi_u = e_{h_block_start + j}  (j ∈ 0..h_block_len)
1733//   * u = 2+h+l:    phi_u = e_{w_block_start + l}  (l ∈ 0..w_block_len)
1734// Then `H_full[m, n] += sum_{u,v} H_i[u,v] * phi_u[m] * phi_v[n]`.
1735//
1736// Shared-memory budget: at large-scale shape p_total = 44, a [44, 44] f64
1737// partial is 44*44*8 = 15.5 KiB — well below the V100 48 KiB/SM cap.
1738// At p_total ≤ 80 the kernel still fits (80*80*8 = 50 KiB → just over
1739// V100 cap; caller must enforce p_total ≤ DENSE_BLOCK_MAX_P). The
1740// launcher rejects oversize p_total cleanly.
1741
1742extern "C" __global__ void bms_flex_row_dense_block_partial(
1743    int                  n_rows,
1744    int                  r,
1745    int                  p_m,
1746    int                  p_g,
1747    int                  p_total,
1748    int                  h_block_start,
1749    int                  h_block_len,
1750    int                  w_block_start,
1751    int                  w_block_len,
1752    int                  h_primary_start,
1753    int                  w_primary_start,
1754    int                  rows_per_cta,
1755    const double * __restrict__ row_hessians,    // [n, r*r]
1756    const double * __restrict__ marginal_design, // [n, p_m]
1757    const double * __restrict__ logslope_design, // [n, p_g]
1758    double       * __restrict__ partial)         // [num_chunks, p_total, p_total]
1759{
1760    extern __shared__ double shmem[];
1761    int chunk = blockIdx.x;
1762    int tid   = threadIdx.x;
1763    int row_lo = chunk * rows_per_cta;
1764    int remaining_rows = n_rows - row_lo;
1765    int row_hi = row_lo + (remaining_rows < rows_per_cta ? remaining_rows : rows_per_cta);
1766
1767    int pp = p_total * p_total;
1768    double *acc = shmem; // CTA-private accumulator [p_total, p_total]
1769    for (int j = tid; j < pp; j += blockDim.x) acc[j] = 0.0;
1770    __syncthreads();
1771
1772    // Per-row work performed by thread 0 to avoid cross-thread RW
1773    // contention on `acc[]`. Per-row complexity is O(r² + p_total²); the host
1774    // selects this direct algorithm only for small p_total, while r remains a
1775    // checked runtime width with no semantic ceiling.
1776    // Tighter parallel implementations are possible (warp-stripe the
1777    // 4-way nested u-v-m-n loop) but Phase 6 is a debug-only path and
1778    // the simple version is easier to audit for correctness against
1779    // the host-side P_i pullback oracle.
1780    if (tid == 0) {
1781        for (int row = row_lo; row < row_hi; ++row) {
1782            const double *mrow = marginal_design + (size_t)row * (size_t)p_m;
1783            const double *grow = logslope_design + (size_t)row * (size_t)p_g;
1784            const double *Hrow = row_hessians + (size_t)row * (size_t)r * (size_t)r;
1785            for (int u = 0; u < r; ++u) {
1786                for (int v = 0; v < r; ++v) {
1787                    double huv = Hrow[(size_t)u * (size_t)r + (size_t)v];
1788                    if (huv == 0.0) continue;
1789                    // For each (u, v), iterate (m, n) over the non-zero
1790                    // outer-product support of phi_u and phi_v.
1791                    // Build a small (offset, len, src_ptr) descriptor for
1792                    // each operand block as we go.
1793                    int m_off, m_len; const double *m_src; bool m_indicator;
1794                    int n_off, n_len; const double *n_src; bool n_indicator;
1795                    if (u == 0)      { m_off = 0;   m_len = p_m; m_src = mrow; m_indicator = false; }
1796                    else if (u == 1) { m_off = p_m; m_len = p_g; m_src = grow; m_indicator = false; }
1797                    else if (u - 2 < h_block_len) {
1798                                       m_off = h_block_start + (u - 2);
1799                                       m_len = 1;   m_src = NULL; m_indicator = true;
1800                    } else {
1801                                       m_off = w_block_start + (u - 2 - h_block_len);
1802                                       m_len = 1;   m_src = NULL; m_indicator = true;
1803                    }
1804                    if (v == 0)      { n_off = 0;   n_len = p_m; n_src = mrow; n_indicator = false; }
1805                    else if (v == 1) { n_off = p_m; n_len = p_g; n_src = grow; n_indicator = false; }
1806                    else if (v - 2 < h_block_len) {
1807                                       n_off = h_block_start + (v - 2);
1808                                       n_len = 1;   n_src = NULL; n_indicator = true;
1809                    } else {
1810                                       n_off = w_block_start + (v - 2 - h_block_len);
1811                                       n_len = 1;   n_src = NULL; n_indicator = true;
1812                    }
1813                    // accumulate huv * phi_u[m] * phi_v[n] into acc[m, n]
1814                    for (int mi = 0; mi < m_len; ++mi) {
1815                        double pm = m_indicator ? 1.0 : m_src[mi];
1816                        if (pm == 0.0) continue;
1817                        double scaled = huv * pm;
1818                        int m_idx = m_off + mi;
1819                        for (int ni = 0; ni < n_len; ++ni) {
1820                            double pn = n_indicator ? 1.0 : n_src[ni];
1821                            int n_idx = n_off + ni;
1822                            acc[m_idx * p_total + n_idx] += scaled * pn;
1823                        }
1824                    }
1825                }
1826            }
1827        }
1828    }
1829    __syncthreads();
1830
1831    // Write CTA accumulator out to global memory at its chunk slot.
1832    double *out_chunk = partial + (size_t)chunk * (size_t)pp;
1833    for (int j = tid; j < pp; j += blockDim.x) {
1834        out_chunk[j] = acc[j];
1835    }
1836}
1837
1838extern "C" __global__ void bms_flex_row_dense_block_reduce(
1839    int                  num_chunks,
1840    int                  p_total,
1841    const double * __restrict__ partial,
1842    double       * __restrict__ out)
1843{
1844    int j = blockIdx.x * blockDim.x + threadIdx.x;
1845    int pp = p_total * p_total;
1846    if (j >= pp) return;
1847    double acc = 0.0;
1848    for (int c = 0; c < num_chunks; ++c) {
1849        acc += partial[(size_t)c * (size_t)pp + (size_t)j];
1850    }
1851    out[j] = acc;
1852}
1853
1854"#;
1855
1856#[cfg(target_os = "linux")]
1857pub(crate) struct HvpKernelBackend {
1858    pub(crate) stream: Arc<CudaStream>,
1859    pub(crate) module: Arc<CudaModule>,
1860}
1861
1862#[cfg(target_os = "linux")]
1863impl HvpKernelBackend {
1864    pub(crate) fn probe() -> Result<&'static Self, GpuError> {
1865        static BACKEND: OnceLock<Result<HvpKernelBackend, GpuError>> = OnceLock::new();
1866        BACKEND
1867            .get_or_init(|| {
1868                gam_gpu::backend_probe::probe_backend_with_compile("bms_flex_row hvp", |parts| {
1869                    // #1551: arch-aware compile (see launch_bms_flex_row_kernel) —
1870                    // pin `--gpu-architecture` to the device capability and supply
1871                    // the standard include paths via the shared NVRTC entry point.
1872                    let ptx = gam_gpu::device_cache::compile_ptx_arch(HVP_KERNEL_SOURCE).map_err(
1873                        |err| GpuError::DriverCallFailed {
1874                            reason: format!("bms_flex_row hvp NVRTC compile failed: {err}"),
1875                        },
1876                    )?;
1877                    let module =
1878                        parts
1879                            .ctx
1880                            .load_module(ptx)
1881                            .map_err(|err| GpuError::DriverCallFailed {
1882                                reason: format!("bms_flex_row hvp module load failed: {err}"),
1883                            })?;
1884                    Ok(HvpKernelBackend {
1885                        stream: parts.stream.clone(),
1886                        module,
1887                    })
1888                })
1889            })
1890            .as_ref()
1891            .map_err(GpuError::clone)
1892    }
1893}
1894
1895/// Build a device-resident row-Hessian cache by launching the row kernel and
1896/// keeping the resulting `n × r²` slice resident on the device. Also uploads
1897/// the dense marginal + logslope design matrices so subsequent HVPs do not
1898/// re-upload them at every direction.
1899///
1900/// `marginal_design_row_major` and `logslope_design_row_major` must be
1901/// row-major `[n, p_m]` and `[n, p_g]` contiguous slices.
1902///
1903/// #461 absorber (additive Stage-1 influence block): the orthogonalization is
1904/// realized as **A2 — the marginal design widened to `[M | Z̃_infl]`** (see
1905/// `src/families/bms/block_specs.rs::widen_marginal_dense_with_influence`), NOT
1906/// a dedicated 5th primary coordinate. The absorber `+Z̃_infl·γ` is plain
1907/// additive into the marginal index `α(x)`, so γ lives inside `β_m` of the
1908/// widened block and `p_m` already counts the `p₁` influence columns. The row
1909/// kernel reads the marginal index from `block_states[0].eta` (which carries
1910/// `Z̃_infl·γ`) and pulls back through this same widened `marginal_design`, so
1911/// the absorber rides the existing primary-coordinate `u = 0` chain with **no
1912/// kernel-source change**: η, gradient, and Hessian match the CPU kernel
1913/// bit-for-bit precisely because `marginal_design` and `β_m` are the matched
1914/// (design, coefficient) pair the CPU path uses. The validation below pins
1915/// `marginal_design.len() == n·p_m` (with `p_m` widened), so a stale narrow
1916/// design against a widened `block.p_m` is rejected cleanly rather than
1917/// silently computing the wrong η. The absorber is dropped at
1918/// predict, where the marginal design is rebuilt without the influence columns,
1919/// so the predict-time `p_m` is narrow and this path is correct there too.
1920#[cfg(target_os = "linux")]
1921pub(crate) fn launch_bms_flex_row_kernel_device_resident(
1922    inputs: BmsFlexRowKernelInputs<'_>,
1923    marginal_design_row_major: &[f64],
1924    logslope_design_row_major: &[f64],
1925    block: BmsFlexBlockLayout,
1926    primary: BmsFlexPrimaryLayout,
1927) -> Result<DeviceResidentRowHess, GpuError> {
1928    inputs.validate()?;
1929    if !s_f_diagnostic_finite(&inputs) {
1930        return Err(GpuError::DriverCallFailed {
1931            reason: format!(
1932                "bms_flex_row device-resident: s_f must be positive and finite, got {}",
1933                inputs.s_f
1934            ),
1935        });
1936    }
1937    let n = inputs.n_rows;
1938    let r = inputs.r;
1939    let nr = checked_shape_len("device-resident [n,r]", &[n, r])?;
1940    let nrr = checked_shape_len("device-resident [n,r,r]", &[n, r, r])?;
1941    let marginal_len = checked_shape_len("device-resident marginal design", &[n, block.p_m])?;
1942    let logslope_len = checked_shape_len("device-resident logslope design", &[n, block.p_g])?;
1943    if marginal_design_row_major.len() != marginal_len {
1944        return Err(GpuError::DriverCallFailed {
1945            reason: format!(
1946                "bms_flex_row device-resident: marginal_design len={} != n*p_m={}",
1947                marginal_design_row_major.len(),
1948                marginal_len
1949            ),
1950        });
1951    }
1952    if logslope_design_row_major.len() != logslope_len {
1953        return Err(GpuError::DriverCallFailed {
1954            reason: format!(
1955                "bms_flex_row device-resident: logslope_design len={} != n*p_g={}",
1956                logslope_design_row_major.len(),
1957                logslope_len
1958            ),
1959        });
1960    }
1961    if primary.r != r {
1962        return Err(GpuError::DriverCallFailed {
1963            reason: format!(
1964                "bms_flex_row device-resident: primary.r={} != inputs.r={}",
1965                primary.r, r
1966            ),
1967        });
1968    }
1969
1970    // Ensure the row kernel backend is compiled & loaded (this also compiles
1971    // the HVP backend on first use so the caller surfaces failures here).
1972    let backend = RowKernelBackend::probe()?;
1973    HvpKernelBackend::probe()?;
1974    let stream = backend.stream.clone();
1975
1976    let upload_f64 = |slice: &[f64], label: &str| {
1977        stream
1978            .clone_htod(slice)
1979            .map_err(|err| GpuError::DriverCallFailed {
1980                reason: format!("bms_flex_row device-resident upload {label}: {err}"),
1981            })
1982    };
1983    let upload_u32 = |slice: &[u32], label: &str| {
1984        stream
1985            .clone_htod(slice)
1986            .map_err(|err| GpuError::DriverCallFailed {
1987                reason: format!("bms_flex_row device-resident upload {label}: {err}"),
1988            })
1989    };
1990
1991    let d_q = upload_f64(inputs.q, "q")?;
1992    let d_b = upload_f64(inputs.b, "b")?;
1993    let d_mu1 = upload_f64(inputs.mu_1, "mu_1")?;
1994    let d_mu2 = upload_f64(inputs.mu_2, "mu_2")?;
1995    let d_zobs = upload_f64(inputs.z_obs, "z_obs")?;
1996    let d_y = upload_f64(inputs.y, "y")?;
1997    let d_w = upload_f64(inputs.w, "w")?;
1998    let d_offsets = upload_u32(inputs.cell_offsets, "cell_offsets")?;
1999    let d_c0 = upload_f64(inputs.cell_c0, "cell_c0")?;
2000    let d_c1 = upload_f64(inputs.cell_c1, "cell_c1")?;
2001    let d_c2 = upload_f64(inputs.cell_c2, "cell_c2")?;
2002    let d_c3 = upload_f64(inputs.cell_c3, "cell_c3")?;
2003    let d_a = upload_f64(inputs.cell_a, "cell_a")?;
2004    let d_aa = upload_f64(inputs.cell_aa, "cell_aa")?;
2005    let d_r = upload_f64(inputs.cell_r, "cell_r")?;
2006    let d_ar = upload_f64(inputs.cell_ar, "cell_ar")?;
2007    let d_sbb = upload_f64(inputs.cell_sbb, "cell_sbb")?;
2008    let d_sbh = upload_f64(inputs.cell_sbh, "cell_sbh")?;
2009    let d_sbw = upload_f64(inputs.cell_sbw, "cell_sbw")?;
2010    // Phase-4: optionally consume device-resident moments (no host upload).
2011    let owned_host_moments: CudaSlice<f64>;
2012    let d_moments_ref: &CudaSlice<f64> = match &inputs.cell_moments {
2013        CellMomentsSource::Host(slice) => {
2014            owned_host_moments = upload_f64(slice, "cell_moments")?;
2015            &owned_host_moments
2016        }
2017        CellMomentsSource::Device(d) => *d,
2018    };
2019    let d_chi = upload_f64(inputs.chi_obs, "chi_obs")?;
2020    let d_xi = upload_f64(inputs.xi_obs, "xi_obs")?;
2021    let d_rho = upload_f64(inputs.rho_u, "rho_u")?;
2022    let d_tau = upload_f64(inputs.tau_u, "tau_u")?;
2023    let d_ruv = upload_f64(inputs.r_uv, "r_uv")?;
2024    let d_e_obs = upload_f64(inputs.e_obs, "e_obs")?;
2025
2026    let d_marginal = upload_f64(marginal_design_row_major, "marginal_design")?;
2027    let d_logslope = upload_f64(logslope_design_row_major, "logslope_design")?;
2028
2029    let mut d_neglog = stream
2030        .alloc_zeros::<f64>(n)
2031        .map_err(|err| GpuError::DriverCallFailed {
2032            reason: format!("bms_flex_row device-resident alloc neglog: {err}"),
2033        })?;
2034    let mut d_grad = stream
2035        .alloc_zeros::<f64>(nr)
2036        .map_err(|err| GpuError::DriverCallFailed {
2037            reason: format!("bms_flex_row device-resident alloc grad: {err}"),
2038        })?;
2039    let mut d_hess = stream
2040        .alloc_zeros::<f64>(nrr)
2041        .map_err(|err| GpuError::DriverCallFailed {
2042            reason: format!("bms_flex_row device-resident alloc hess: {err}"),
2043        })?;
2044    let mut d_f_au = stream
2045        .alloc_zeros::<f64>(nr)
2046        .map_err(|err| GpuError::DriverCallFailed {
2047            reason: format!("bms_flex_row device-resident alloc F_au scratch: {err}"),
2048        })?;
2049    let mut d_status = stream
2050        .alloc_zeros::<u32>(n)
2051        .map_err(|err| GpuError::DriverCallFailed {
2052            reason: format!("bms_flex_row device-resident alloc status: {err}"),
2053        })?;
2054
2055    let func = backend
2056        .module
2057        .load_function("bms_flex_row_kernel")
2058        .map_err(|err| GpuError::DriverCallFailed {
2059            reason: format!("bms_flex_row device-resident load_function: {err}"),
2060        })?;
2061
2062    let n_u32 = u32::try_from(n).map_err(|_| GpuError::DriverCallFailed {
2063        reason: format!("bms_flex_row device-resident: n_rows={n} exceeds CUDA grid range"),
2064    })?;
2065    let cfg = LaunchConfig {
2066        grid_dim: (n_u32, 1, 1),
2067        block_dim: (ROW_KERNEL_THREADS, 1, 1),
2068        shared_mem_bytes: 0,
2069    };
2070    let n_i32 = i32::try_from(n).map_err(|_| GpuError::DriverCallFailed {
2071        reason: format!("bms_flex_row device-resident: n_rows={n} exceeds i32 range"),
2072    })?;
2073    let r_i32 = i32::try_from(r).map_err(|_| GpuError::DriverCallFailed {
2074        reason: format!("bms_flex_row device-resident: r={r} exceeds i32 range"),
2075    })?;
2076    let p_h_i32 = i32::try_from(inputs.p_h).map_err(|_| GpuError::DriverCallFailed {
2077        reason: format!(
2078            "bms_flex_row device-resident: p_h={} exceeds i32 range",
2079            inputs.p_h
2080        ),
2081    })?;
2082    let p_w_i32 = i32::try_from(inputs.p_w).map_err(|_| GpuError::DriverCallFailed {
2083        reason: format!(
2084            "bms_flex_row device-resident: p_w={} exceeds i32 range",
2085            inputs.p_w
2086        ),
2087    })?;
2088    let s_f_val = inputs.s_f;
2089
2090    let mut builder = stream.launch_builder(&func);
2091    builder
2092        .arg(&n_i32)
2093        .arg(&r_i32)
2094        .arg(&p_h_i32)
2095        .arg(&p_w_i32)
2096        .arg(&s_f_val)
2097        .arg(&d_q)
2098        .arg(&d_b)
2099        .arg(&d_mu1)
2100        .arg(&d_mu2)
2101        .arg(&d_zobs)
2102        .arg(&d_y)
2103        .arg(&d_w)
2104        .arg(&d_offsets)
2105        .arg(&d_c0)
2106        .arg(&d_c1)
2107        .arg(&d_c2)
2108        .arg(&d_c3)
2109        .arg(&d_a)
2110        .arg(&d_aa)
2111        .arg(&d_r)
2112        .arg(&d_ar)
2113        .arg(&d_sbb)
2114        .arg(&d_sbh)
2115        .arg(&d_sbw)
2116        .arg(d_moments_ref)
2117        .arg(&d_chi)
2118        .arg(&d_xi)
2119        .arg(&d_rho)
2120        .arg(&d_tau)
2121        .arg(&d_ruv)
2122        .arg(&d_e_obs)
2123        .arg(&mut d_f_au)
2124        .arg(&mut d_neglog)
2125        .arg(&mut d_grad)
2126        .arg(&mut d_hess)
2127        .arg(&mut d_status);
2128    // SAFETY: same shape contract as `launch_linux`: every kernel parameter is
2129    // either a primitive scalar by-value, a const device pointer whose
2130    // capacity was validated by `inputs.validate()`, or one of the three
2131    // output buffers we just allocated with the expected element count.
2132    unsafe { builder.launch(cfg) }.map_err(|err| GpuError::DriverCallFailed {
2133        reason: format!("bms_flex_row device-resident launch: {err}"),
2134    })?;
2135    stream
2136        .synchronize()
2137        .map_err(|err| GpuError::DriverCallFailed {
2138            reason: format!("bms_flex_row device-resident synchronize: {err}"),
2139        })?;
2140
2141    let status = stream
2142        .clone_dtoh(&d_status)
2143        .map_err(|err| GpuError::DriverCallFailed {
2144            reason: format!("bms_flex_row device-resident download status: {err}"),
2145        })?;
2146    if let Some((row, code)) = status
2147        .iter()
2148        .copied()
2149        .enumerate()
2150        .find(|(_, code)| *code != 0)
2151    {
2152        return Err(GpuError::DriverCallFailed {
2153            reason: format!(
2154                "bms_flex_row device-resident rejected non-finite row {row} with status {code}"
2155            ),
2156        });
2157    }
2158    drop(d_status);
2159    drop(d_f_au);
2160
2161    // Drop the per-cell uploads; keep the canonical row value, gradient,
2162    // Hessian, and both pullback designs in one device-resident authority.
2163    drop(d_q);
2164    drop(d_b);
2165    drop(d_mu1);
2166    drop(d_mu2);
2167    drop(d_zobs);
2168    drop(d_y);
2169    drop(d_w);
2170    drop(d_offsets);
2171    drop(d_c0);
2172    drop(d_c1);
2173    drop(d_c2);
2174    drop(d_c3);
2175    drop(d_a);
2176    drop(d_aa);
2177    drop(d_r);
2178    drop(d_ar);
2179    drop(d_sbb);
2180    drop(d_sbh);
2181    drop(d_sbw);
2182    // `owned_host_moments` (if any) and the borrowed `d_moments_ref` both
2183    // go out of scope at the end of the function; the device-resident
2184    // moments owned by the caller stay alive.
2185    drop(d_chi);
2186    drop(d_xi);
2187    drop(d_rho);
2188    drop(d_tau);
2189    drop(d_ruv);
2190
2191    let resident_elements = n
2192        .checked_add(nr)
2193        .and_then(|value| value.checked_add(nrr))
2194        .and_then(|value| value.checked_add(marginal_len))
2195        .and_then(|value| value.checked_add(logslope_len))
2196        .ok_or_else(|| GpuError::DriverCallFailed {
2197            reason: "bms_flex_row device-resident: resident element count overflow".to_string(),
2198        })?;
2199    let resident_bytes = resident_elements
2200        .checked_mul(std::mem::size_of::<f64>())
2201        .ok_or_else(|| GpuError::DriverCallFailed {
2202            reason: "bms_flex_row device-resident: resident byte count overflow".to_string(),
2203        })?;
2204    let bytes = u64::try_from(resident_bytes).map_err(|_| GpuError::DriverCallFailed {
2205        reason: format!(
2206            "bms_flex_row device-resident: resident bytes={resident_bytes} exceed u64 range"
2207        ),
2208    })?;
2209    Ok(DeviceResidentRowHess {
2210        neglog: d_neglog,
2211        grad: d_grad,
2212        hess: d_hess,
2213        marginal_design: d_marginal,
2214        logslope_design: d_logslope,
2215        n,
2216        r,
2217        block,
2218        primary,
2219        bytes,
2220    })
2221}
2222
2223/// Reduce the canonical per-row value and objective gradient into the joint
2224/// log-likelihood and score gradient without re-running row calculus on CPU.
2225/// Both stages use fixed row/chunk order and no atomics.
2226#[cfg(target_os = "linux")]
2227pub(crate) fn launch_bms_flex_row_joint_gradient(
2228    storage: &DeviceResidentRowHess,
2229) -> Result<BmsFlexDeviceJointGradient, GpuError> {
2230    let p_total = storage.block.p_total;
2231    let output_width = p_total
2232        .checked_add(1)
2233        .ok_or_else(|| GpuError::DriverCallFailed {
2234            reason: "bms_flex_row joint gradient: output width overflow".to_string(),
2235        })?;
2236    if storage.n == 0 {
2237        return Ok(BmsFlexDeviceJointGradient {
2238            log_likelihood: 0.0,
2239            gradient: vec![0.0; p_total],
2240        });
2241    }
2242
2243    let backend = HvpKernelBackend::probe()?;
2244    let stream = backend.stream.clone();
2245    let args = PreparedBmsFlexRowLaunchArgs::from_storage(storage)?;
2246    let partial_len = args
2247        .num_chunks
2248        .checked_mul(output_width)
2249        .ok_or_else(|| GpuError::DriverCallFailed {
2250            reason: format!(
2251                "bms_flex_row joint gradient: partial length overflow for chunks={} width={output_width}",
2252                args.num_chunks
2253            ),
2254        })?;
2255    let mut d_partial =
2256        stream
2257            .alloc_zeros::<f64>(partial_len)
2258            .map_err(|err| GpuError::DriverCallFailed {
2259                reason: format!("bms_flex_row joint gradient alloc partial: {err}"),
2260            })?;
2261    let mut d_out =
2262        stream
2263            .alloc_zeros::<f64>(output_width)
2264            .map_err(|err| GpuError::DriverCallFailed {
2265                reason: format!("bms_flex_row joint gradient alloc output: {err}"),
2266            })?;
2267    let partial_func = backend
2268        .module
2269        .load_function("bms_flex_row_joint_gradient_partial")
2270        .map_err(|err| GpuError::DriverCallFailed {
2271            reason: format!("bms_flex_row joint gradient load partial: {err}"),
2272        })?;
2273    let reduce_func = backend
2274        .module
2275        .load_function("bms_flex_row_joint_gradient_reduce")
2276        .map_err(|err| GpuError::DriverCallFailed {
2277            reason: format!("bms_flex_row joint gradient load reduce: {err}"),
2278        })?;
2279
2280    let num_chunks_u32 =
2281        u32::try_from(args.num_chunks).map_err(|_| GpuError::DriverCallFailed {
2282            reason: format!(
2283                "bms_flex_row joint gradient: num_chunks={} exceeds u32 range",
2284                args.num_chunks
2285            ),
2286        })?;
2287    let cfg_partial = LaunchConfig {
2288        grid_dim: (num_chunks_u32, 1, 1),
2289        block_dim: (HVP_THREADS, 1, 1),
2290        shared_mem_bytes: 0,
2291    };
2292    let mut builder = stream.launch_builder(&partial_func);
2293    builder
2294        .arg(&args.n_i32)
2295        .arg(&args.r_i32)
2296        .arg(&args.p_m_i32)
2297        .arg(&args.p_g_i32)
2298        .arg(&args.p_total_i32)
2299        .arg(&args.h_block_start)
2300        .arg(&args.h_block_len)
2301        .arg(&args.w_block_start)
2302        .arg(&args.w_block_len)
2303        .arg(&args.h_primary_start)
2304        .arg(&args.w_primary_start)
2305        .arg(&args.rows_per_cta)
2306        .arg(&storage.neglog)
2307        .arg(&storage.grad)
2308        .arg(&storage.marginal_design)
2309        .arg(&storage.logslope_design)
2310        .arg(&mut d_partial);
2311    // SAFETY: all resident buffers were allocated and shape-validated by the
2312    // row-kernel producer; `d_partial` has `num_chunks * (1+p_total)` entries.
2313    unsafe { builder.launch(cfg_partial) }.map_err(|err| GpuError::DriverCallFailed {
2314        reason: format!("bms_flex_row joint gradient partial launch: {err}"),
2315    })?;
2316
2317    let output_width_i32 = i32::try_from(output_width).map_err(|_| GpuError::DriverCallFailed {
2318        reason: format!(
2319            "bms_flex_row joint gradient: output_width={output_width} exceeds i32 range"
2320        ),
2321    })?;
2322    let num_chunks_i32 =
2323        i32::try_from(args.num_chunks).map_err(|_| GpuError::DriverCallFailed {
2324            reason: format!(
2325                "bms_flex_row joint gradient: num_chunks={} exceeds i32 range",
2326                args.num_chunks
2327            ),
2328        })?;
2329    let output_width_u32 = u32::try_from(output_width).map_err(|_| GpuError::DriverCallFailed {
2330        reason: format!(
2331            "bms_flex_row joint gradient: output_width={output_width} exceeds u32 range"
2332        ),
2333    })?;
2334    let reduce_blocks = output_width_u32.div_ceil(REDUCTION_THREADS);
2335    let cfg_reduce = LaunchConfig {
2336        grid_dim: (reduce_blocks, 1, 1),
2337        block_dim: (REDUCTION_THREADS, 1, 1),
2338        shared_mem_bytes: 0,
2339    };
2340    let mut builder = stream.launch_builder(&reduce_func);
2341    builder
2342        .arg(&num_chunks_i32)
2343        .arg(&output_width_i32)
2344        .arg(&d_partial)
2345        .arg(&mut d_out);
2346    // SAFETY: the partial launch above populated the exact partial shape and
2347    // `d_out` owns `output_width` entries.
2348    unsafe { builder.launch(cfg_reduce) }.map_err(|err| GpuError::DriverCallFailed {
2349        reason: format!("bms_flex_row joint gradient reduce launch: {err}"),
2350    })?;
2351    stream
2352        .synchronize()
2353        .map_err(|err| GpuError::DriverCallFailed {
2354            reason: format!("bms_flex_row joint gradient synchronize: {err}"),
2355        })?;
2356    let host = stream
2357        .clone_dtoh(&d_out)
2358        .map_err(|err| GpuError::DriverCallFailed {
2359            reason: format!("bms_flex_row joint gradient download: {err}"),
2360        })?;
2361    if let Some((index, value)) = host
2362        .iter()
2363        .copied()
2364        .enumerate()
2365        .find(|(_, value)| !value.is_finite())
2366    {
2367        return Err(GpuError::DriverCallFailed {
2368            reason: format!(
2369                "bms_flex_row joint gradient produced non-finite output[{index}]={value}"
2370            ),
2371        });
2372    }
2373    Ok(BmsFlexDeviceJointGradient {
2374        log_likelihood: host[0],
2375        gradient: host[1..].to_vec(),
2376    })
2377}
2378
2379/// Which partial kernel the joint-β engine drives, whether it consumes a
2380/// direction vector `d_v`, and where the reduced `[1, p_total]` image lands.
2381/// All three points of variation are encoded here so the public entry points
2382/// stay thin wrappers over one launch helper.
2383#[cfg(target_os = "linux")]
2384#[derive(Clone, Copy)]
2385pub(crate) enum BmsFlexRowLaunchMode {
2386    /// `bms_flex_row_hvp_partial`, `H · v` per row, result left on-stream.
2387    HvpDeviceOut,
2388    /// `bms_flex_row_diag_partial`, `diag(H)` per row, downloaded to host.
2389    DiagonalHostOut,
2390}
2391
2392#[cfg(target_os = "linux")]
2393impl BmsFlexRowLaunchMode {
2394    /// Name of the partial kernel this mode loads from the HVP module.
2395    pub(crate) fn partial_kernel_name(self) -> &'static str {
2396        match self {
2397            BmsFlexRowLaunchMode::HvpDeviceOut => "bms_flex_row_hvp_partial",
2398            BmsFlexRowLaunchMode::DiagonalHostOut => "bms_flex_row_diag_partial",
2399        }
2400    }
2401}
2402
2403/// All scalar launch arguments for the joint-β partial kernel, derived once
2404/// from a [`DeviceResidentRowHess`]. The HVP and diagonal partial kernels take
2405/// the identical leading block-layout argument list (only the trailing
2406/// `d_v` / output pointers differ), so this captures the long, easy-to-
2407/// desynchronize prefix in a single place.
2408#[cfg(target_os = "linux")]
2409pub(crate) struct PreparedBmsFlexRowLaunchArgs {
2410    pub(crate) n_i32: i32,
2411    pub(crate) r_i32: i32,
2412    pub(crate) p_m_i32: i32,
2413    pub(crate) p_g_i32: i32,
2414    pub(crate) p_total_i32: i32,
2415    pub(crate) h_block_start: i32,
2416    pub(crate) h_block_len: i32,
2417    pub(crate) w_block_start: i32,
2418    pub(crate) w_block_len: i32,
2419    pub(crate) h_primary_start: i32,
2420    pub(crate) w_primary_start: i32,
2421    pub(crate) rows_per_cta: i32,
2422    pub(crate) num_chunks: usize,
2423    pub(crate) num_chunks_i32: i32,
2424    pub(crate) num_chunks_u32: u32,
2425    pub(crate) p_total_u32: u32,
2426}
2427
2428#[cfg(target_os = "linux")]
2429impl PreparedBmsFlexRowLaunchArgs {
2430    pub(crate) fn from_storage(storage: &DeviceResidentRowHess) -> Result<Self, GpuError> {
2431        if storage.n == 0 {
2432            return Err(GpuError::DriverCallFailed {
2433                reason: "bms_flex_row launch: n_rows must be > 0".to_string(),
2434            });
2435        }
2436        if storage.r < 2 {
2437            return Err(GpuError::DriverCallFailed {
2438                reason: format!("bms_flex_row launch: r={} must be >= 2", storage.r),
2439            });
2440        }
2441        let p_total = storage.block.p_total;
2442        if p_total == 0 {
2443            return Err(GpuError::DriverCallFailed {
2444                reason: "bms_flex_row launch: p_total must be > 0".to_string(),
2445            });
2446        }
2447        if storage.primary.r != storage.r {
2448            return Err(GpuError::DriverCallFailed {
2449                reason: format!(
2450                    "bms_flex_row launch: primary.r={} != storage.r={}",
2451                    storage.primary.r, storage.r
2452                ),
2453            });
2454        }
2455        let h_block_len = storage.block.h.as_ref().map_or(0, |range| range.len());
2456        let w_block_len = storage.block.w.as_ref().map_or(0, |range| range.len());
2457        let h_primary_len = storage.primary.h.as_ref().map_or(0, |range| range.len());
2458        let w_primary_len = storage.primary.w.as_ref().map_or(0, |range| range.len());
2459        if h_block_len != h_primary_len || w_block_len != w_primary_len {
2460            return Err(GpuError::DriverCallFailed {
2461                reason: format!(
2462                    "bms_flex_row launch: block/primary direct lengths disagree: h={h_block_len}/{h_primary_len}, w={w_block_len}/{w_primary_len}"
2463                ),
2464            });
2465        }
2466        let h_block_start = storage
2467            .block
2468            .p_m
2469            .checked_add(storage.block.p_g)
2470            .ok_or_else(|| GpuError::DriverCallFailed {
2471                reason: "bms_flex_row launch: p_m+p_g overflow".to_string(),
2472            })?;
2473        let w_block_start =
2474            h_block_start
2475                .checked_add(h_block_len)
2476                .ok_or_else(|| GpuError::DriverCallFailed {
2477                    reason: "bms_flex_row launch: h block end overflow".to_string(),
2478                })?;
2479        let expected_p_total =
2480            w_block_start
2481                .checked_add(w_block_len)
2482                .ok_or_else(|| GpuError::DriverCallFailed {
2483                    reason: "bms_flex_row launch: w block end overflow".to_string(),
2484                })?;
2485        let w_primary_start =
2486            2_usize
2487                .checked_add(h_primary_len)
2488                .ok_or_else(|| GpuError::DriverCallFailed {
2489                    reason: "bms_flex_row launch: h primary end overflow".to_string(),
2490                })?;
2491        let expected_r = w_primary_start.checked_add(w_primary_len).ok_or_else(|| {
2492            GpuError::DriverCallFailed {
2493                reason: "bms_flex_row launch: w primary end overflow".to_string(),
2494            }
2495        })?;
2496        let check_range = |name: &str,
2497                           range: Option<&std::ops::Range<usize>>,
2498                           expected_start: usize,
2499                           expected_len: usize|
2500         -> Result<(), GpuError> {
2501            match (range, expected_len) {
2502                (None, 0) => Ok(()),
2503                (Some(range), len)
2504                    if len > 0
2505                        && range.start == expected_start
2506                        && range.end == expected_start + len =>
2507                {
2508                    Ok(())
2509                }
2510                _ => Err(GpuError::DriverCallFailed {
2511                    reason: format!(
2512                        "bms_flex_row launch: {name}={range:?} must be {expected_start}..{}",
2513                        expected_start + expected_len
2514                    ),
2515                }),
2516            }
2517        };
2518        check_range(
2519            "block.h",
2520            storage.block.h.as_ref(),
2521            h_block_start,
2522            h_block_len,
2523        )?;
2524        check_range(
2525            "block.w",
2526            storage.block.w.as_ref(),
2527            w_block_start,
2528            w_block_len,
2529        )?;
2530        check_range("primary.h", storage.primary.h.as_ref(), 2, h_primary_len)?;
2531        check_range(
2532            "primary.w",
2533            storage.primary.w.as_ref(),
2534            w_primary_start,
2535            w_primary_len,
2536        )?;
2537        if p_total != expected_p_total || storage.r != expected_r {
2538            return Err(GpuError::DriverCallFailed {
2539                reason: format!(
2540                    "bms_flex_row launch: inconsistent layout p_total={p_total}/{expected_p_total}, r={}/{}",
2541                    storage.r, expected_r
2542                ),
2543            });
2544        }
2545        let expected_nr = checked_shape_len("launch storage [n,r]", &[storage.n, storage.r])?;
2546        let expected_nrr =
2547            checked_shape_len("launch storage [n,r,r]", &[storage.n, storage.r, storage.r])?;
2548        let expected_marginal = checked_shape_len(
2549            "launch storage marginal design",
2550            &[storage.n, storage.block.p_m],
2551        )?;
2552        let expected_logslope = checked_shape_len(
2553            "launch storage logslope design",
2554            &[storage.n, storage.block.p_g],
2555        )?;
2556        for (name, have, want) in [
2557            ("neglog", storage.neglog.len(), storage.n),
2558            ("grad", storage.grad.len(), expected_nr),
2559            ("hess", storage.hess.len(), expected_nrr),
2560            (
2561                "marginal_design",
2562                storage.marginal_design.len(),
2563                expected_marginal,
2564            ),
2565            (
2566                "logslope_design",
2567                storage.logslope_design.len(),
2568                expected_logslope,
2569            ),
2570        ] {
2571            if have != want {
2572                return Err(GpuError::DriverCallFailed {
2573                    reason: format!("bms_flex_row launch: storage {name}.len()={have} != {want}"),
2574                });
2575            }
2576        }
2577        let num_chunks = num_hvp_chunks(storage.n);
2578        let to_i32 = |name: &str, value: usize| {
2579            i32::try_from(value).map_err(|_| GpuError::DriverCallFailed {
2580                reason: format!("bms_flex_row launch: {name}={value} exceeds i32 range"),
2581            })
2582        };
2583        let to_u32 = |name: &str, value: usize| {
2584            u32::try_from(value).map_err(|_| GpuError::DriverCallFailed {
2585                reason: format!("bms_flex_row launch: {name}={value} exceeds u32 range"),
2586            })
2587        };
2588        Ok(PreparedBmsFlexRowLaunchArgs {
2589            n_i32: to_i32("n_rows", storage.n)?,
2590            r_i32: to_i32("r", storage.r)?,
2591            p_m_i32: to_i32("p_m", storage.block.p_m)?,
2592            p_g_i32: to_i32("p_g", storage.block.p_g)?,
2593            p_total_i32: to_i32("p_total", p_total)?,
2594            h_block_start: storage
2595                .block
2596                .h
2597                .as_ref()
2598                .map(|range| to_i32("h_block_start", range.start))
2599                .transpose()?
2600                .unwrap_or(0),
2601            h_block_len: storage
2602                .block
2603                .h
2604                .as_ref()
2605                .map(|range| to_i32("h_block_len", range.len()))
2606                .transpose()?
2607                .unwrap_or(0),
2608            w_block_start: storage
2609                .block
2610                .w
2611                .as_ref()
2612                .map(|range| to_i32("w_block_start", range.start))
2613                .transpose()?
2614                .unwrap_or(0),
2615            w_block_len: storage
2616                .block
2617                .w
2618                .as_ref()
2619                .map(|range| to_i32("w_block_len", range.len()))
2620                .transpose()?
2621                .unwrap_or(0),
2622            h_primary_start: storage
2623                .primary
2624                .h
2625                .as_ref()
2626                .map(|range| to_i32("h_primary_start", range.start))
2627                .transpose()?
2628                .unwrap_or(0),
2629            w_primary_start: storage
2630                .primary
2631                .w
2632                .as_ref()
2633                .map(|range| to_i32("w_primary_start", range.start))
2634                .transpose()?
2635                .unwrap_or(0),
2636            rows_per_cta: i32::try_from(HVP_ROWS_PER_CTA).map_err(|_| {
2637                GpuError::DriverCallFailed {
2638                    reason: format!(
2639                        "bms_flex_row launch: rows_per_cta={HVP_ROWS_PER_CTA} exceeds i32 range"
2640                    ),
2641                }
2642            })?,
2643            num_chunks,
2644            num_chunks_i32: to_i32("num_chunks", num_chunks)?,
2645            num_chunks_u32: to_u32("num_chunks", num_chunks)?,
2646            p_total_u32: to_u32("p_total", p_total)?,
2647        })
2648    }
2649}
2650
2651/// Shared partial+reduce engine behind every joint-β launcher.
2652///
2653/// Allocates the `[num_chunks, p_total]` partial buffer, loads the mode's
2654/// partial kernel plus the common `bms_flex_row_hvp_reduce`, builds both
2655/// launch configs from a single [`PreparedBmsFlexRowLaunchArgs`], launches the
2656/// partial kernel (binding `d_v` only for the HVP modes), and launches the
2657/// reduction into caller-supplied `d_out`.
2658///
2659/// **No** `synchronize()` or DtoH is performed here — the surrounding helper
2660/// decides whether to keep the result on-stream (device-resident PCG hot path)
2661/// or sync + download it to the host. `ctx` is a short error-context tag woven
2662/// into every `DriverCallFailed` reason so failures stay attributable to the
2663/// originating entry point.
2664#[cfg(target_os = "linux")]
2665pub(crate) fn run_bms_flex_row_partial_reduce(
2666    storage: &DeviceResidentRowHess,
2667    mode: BmsFlexRowLaunchMode,
2668    d_v: Option<&CudaSlice<f64>>,
2669    d_out: &mut CudaSlice<f64>,
2670    ctx: &str,
2671) -> Result<(), GpuError> {
2672    let backend = HvpKernelBackend::probe()?;
2673    let stream = backend.stream.clone();
2674    let args = PreparedBmsFlexRowLaunchArgs::from_storage(storage)?;
2675    let p_total = storage.block.p_total;
2676
2677    let partial_len = checked_shape_len(
2678        &format!("{ctx} partial [num_chunks,p_total]"),
2679        &[args.num_chunks, p_total],
2680    )?;
2681    let mut d_partial =
2682        stream
2683            .alloc_zeros::<f64>(partial_len)
2684            .map_err(|err| GpuError::DriverCallFailed {
2685                reason: format!("bms_flex_row {ctx} alloc partial: {err}"),
2686            })?;
2687
2688    let partial_kernel_name = mode.partial_kernel_name();
2689    let part_func = backend
2690        .module
2691        .load_function(partial_kernel_name)
2692        .map_err(|err| GpuError::DriverCallFailed {
2693            reason: format!("bms_flex_row {ctx} load {partial_kernel_name}: {err}"),
2694        })?;
2695    let red_func = backend
2696        .module
2697        .load_function("bms_flex_row_hvp_reduce")
2698        .map_err(|err| GpuError::DriverCallFailed {
2699            reason: format!("bms_flex_row {ctx} load reduce: {err}"),
2700        })?;
2701
2702    let cfg_part = LaunchConfig {
2703        grid_dim: (args.num_chunks_u32, 1, 1),
2704        block_dim: (HVP_THREADS, 1, 1),
2705        shared_mem_bytes: 0,
2706    };
2707    let mut builder = stream.launch_builder(&part_func);
2708    builder
2709        .arg(&args.n_i32)
2710        .arg(&args.r_i32)
2711        .arg(&args.p_m_i32)
2712        .arg(&args.p_g_i32)
2713        .arg(&args.p_total_i32)
2714        .arg(&args.h_block_start)
2715        .arg(&args.h_block_len)
2716        .arg(&args.w_block_start)
2717        .arg(&args.w_block_len)
2718        .arg(&args.h_primary_start)
2719        .arg(&args.w_primary_start)
2720        .arg(&args.rows_per_cta)
2721        .arg(&storage.hess)
2722        .arg(&storage.marginal_design)
2723        .arg(&storage.logslope_design);
2724    if let Some(d_v) = d_v {
2725        builder.arg(d_v);
2726    }
2727    builder.arg(&mut d_partial);
2728    // SAFETY: every device pointer above either comes from `storage` (whose
2729    // capacities were established by
2730    // `launch_bms_flex_row_kernel_device_resident`) or was just allocated here
2731    // (`d_partial` = num_chunks * p_total). `d_v`, when bound, is length-checked
2732    // by the calling adapter against `p_total`. The diagonal partial kernel
2733    // takes no direction argument, matching `d_v == None`. Scalar args are i32
2734    // by-value.
2735    unsafe { builder.launch(cfg_part) }.map_err(|err| GpuError::DriverCallFailed {
2736        reason: format!("bms_flex_row {ctx} partial launch: {err}"),
2737    })?;
2738
2739    let red_threads: u32 = REDUCTION_THREADS;
2740    let red_blocks = args.p_total_u32.div_ceil(red_threads);
2741    let cfg_red = LaunchConfig {
2742        grid_dim: (red_blocks, 1, 1),
2743        block_dim: (red_threads, 1, 1),
2744        shared_mem_bytes: 0,
2745    };
2746    let mut builder = stream.launch_builder(&red_func);
2747    builder
2748        .arg(&args.num_chunks_i32)
2749        .arg(&args.p_total_i32)
2750        .arg(&d_partial)
2751        .arg(d_out);
2752    // SAFETY: `d_partial` was just populated by the partial kernel above;
2753    // `d_out` is `p_total` doubles (length-checked / allocated by the calling
2754    // adapter); both scalar args fit i32.
2755    unsafe { builder.launch(cfg_red) }.map_err(|err| GpuError::DriverCallFailed {
2756        reason: format!("bms_flex_row {ctx} reduce launch: {err}"),
2757    })?;
2758    // `d_partial` drops at end of fn; cudarc keeps the alloc alive until the
2759    // stream is done with it, so the reduce kernel completes safely.
2760    drop(d_partial);
2761    Ok(())
2762}
2763
2764/// Host-returning diagonal adapter. HVP host output uses the multi-RHS engine,
2765/// so this function exposes only the one live no-direction mode.
2766#[cfg(target_os = "linux")]
2767pub(crate) fn launch_bms_flex_row_diagonal_host(
2768    storage: &DeviceResidentRowHess,
2769) -> Result<Vec<f64>, GpuError> {
2770    let p_total = storage.block.p_total;
2771    let backend = HvpKernelBackend::probe()?;
2772    let stream = backend.stream.clone();
2773    let mut d_out =
2774        stream
2775            .alloc_zeros::<f64>(p_total)
2776            .map_err(|err| GpuError::DriverCallFailed {
2777                reason: format!("bms_flex_row diag alloc out: {err}"),
2778            })?;
2779
2780    run_bms_flex_row_partial_reduce(
2781        storage,
2782        BmsFlexRowLaunchMode::DiagonalHostOut,
2783        None,
2784        &mut d_out,
2785        "diag",
2786    )?;
2787
2788    stream
2789        .synchronize()
2790        .map_err(|err| GpuError::DriverCallFailed {
2791            reason: format!("bms_flex_row diag synchronize: {err}"),
2792        })?;
2793    stream
2794        .clone_dtoh(&d_out)
2795        .map_err(|err| GpuError::DriverCallFailed {
2796            reason: format!("bms_flex_row diag download out: {err}"),
2797        })
2798}
2799
2800#[cfg(target_os = "linux")]
2801pub(crate) fn validate_bms_flex_row_hvp_multi_shape(
2802    storage: &DeviceResidentRowHess,
2803    rhs_count: usize,
2804    v_rhs_len: usize,
2805    out_len: Option<usize>,
2806    ctx: &str,
2807) -> Result<usize, GpuError> {
2808    if rhs_count == 0 || rhs_count > BMS_FLEX_ROW_HVP_MAX_RHS {
2809        return Err(GpuError::DriverCallFailed {
2810            reason: format!(
2811                "bms_flex_row {ctx}: rhs_count={rhs_count} outside 1..={BMS_FLEX_ROW_HVP_MAX_RHS}"
2812            ),
2813        });
2814    }
2815    let p_total = storage.block.p_total;
2816    let rhs_elems = rhs_count
2817        .checked_mul(p_total)
2818        .ok_or_else(|| GpuError::DriverCallFailed {
2819            reason: format!(
2820                "bms_flex_row {ctx}: rhs_count({rhs_count})*p_total({p_total}) overflow"
2821            ),
2822        })?;
2823    i32::try_from(rhs_elems).map_err(|_| GpuError::DriverCallFailed {
2824        reason: format!(
2825            "bms_flex_row {ctx}: rhs_count({rhs_count})*p_total({p_total})={rhs_elems} exceeds CUDA int indexing range"
2826        ),
2827    })?;
2828    if v_rhs_len != rhs_elems {
2829        return Err(GpuError::DriverCallFailed {
2830            reason: format!(
2831                "bms_flex_row {ctx}: v_rhs.len()={v_rhs_len} != rhs_count({rhs_count})*p_total({p_total})={rhs_elems}"
2832            ),
2833        });
2834    }
2835    if let Some(out_len) = out_len
2836        && out_len != rhs_elems
2837    {
2838        return Err(GpuError::DriverCallFailed {
2839            reason: format!(
2840                "bms_flex_row {ctx}: out.len()={out_len} != rhs_count({rhs_count})*p_total({p_total})={rhs_elems}"
2841            ),
2842        });
2843    }
2844    Ok(rhs_elems)
2845}
2846
2847/// Transient device bytes for a multi-RHS HVP launch, excluding persistent
2848/// row-Hessian/design storage. Scratch scales with
2849/// `rhs_count * num_chunks * p_total`, not `rhs_count * n * r * r`.
2850#[cfg(target_os = "linux")]
2851pub fn bms_flex_row_hvp_multi_scratch_bytes_for_shape(
2852    n: usize,
2853    p_total: usize,
2854    rhs_count: usize,
2855) -> Result<u64, GpuError> {
2856    if rhs_count == 0 || rhs_count > BMS_FLEX_ROW_HVP_MAX_RHS {
2857        return Err(GpuError::DriverCallFailed {
2858            reason: format!(
2859                "bms_flex_row hvp_multi_scratch_bytes: rhs_count={rhs_count} outside 1..={BMS_FLEX_ROW_HVP_MAX_RHS}"
2860            ),
2861        });
2862    }
2863    let num_chunks = num_hvp_chunks(n);
2864    let partial = rhs_count
2865        .checked_mul(num_chunks)
2866        .and_then(|v| v.checked_mul(p_total))
2867        .ok_or_else(|| GpuError::DriverCallFailed {
2868            reason: format!(
2869                "bms_flex_row hvp_multi_scratch_bytes: rhs_count({rhs_count})*num_chunks({num_chunks})*p_total({p_total}) overflow"
2870            ),
2871        })?;
2872    let rhs_vectors = rhs_count
2873        .checked_mul(p_total)
2874        .and_then(|v| v.checked_mul(2))
2875        .ok_or_else(|| GpuError::DriverCallFailed {
2876            reason: format!(
2877                "bms_flex_row hvp_multi_scratch_bytes: 2*rhs_count({rhs_count})*p_total({p_total}) overflow"
2878            ),
2879        })?;
2880    let elems = partial
2881        .checked_add(rhs_vectors)
2882        .ok_or_else(|| GpuError::DriverCallFailed {
2883            reason: "bms_flex_row hvp_multi_scratch_bytes: element count overflow".to_string(),
2884        })?;
2885    let bytes = elems
2886        .checked_mul(std::mem::size_of::<f64>())
2887        .ok_or_else(|| GpuError::DriverCallFailed {
2888            reason: "bms_flex_row hvp_multi_scratch_bytes: byte count overflow".to_string(),
2889        })?;
2890    u64::try_from(bytes).map_err(|_| GpuError::DriverCallFailed {
2891        reason: format!(
2892            "bms_flex_row hvp_multi_scratch_bytes: byte count={bytes} exceeds u64 range"
2893        ),
2894    })
2895}
2896
2897#[cfg(target_os = "linux")]
2898pub(crate) fn run_bms_flex_row_multi_partial_reduce(
2899    storage: &DeviceResidentRowHess,
2900    rhs_count: usize,
2901    d_v_rhs: &CudaSlice<f64>,
2902    d_out: &mut CudaSlice<f64>,
2903    ctx: &str,
2904) -> Result<(), GpuError> {
2905    let rhs_elems = validate_bms_flex_row_hvp_multi_shape(
2906        storage,
2907        rhs_count,
2908        d_v_rhs.len(),
2909        Some(d_out.len()),
2910        ctx,
2911    )?;
2912    let backend = HvpKernelBackend::probe()?;
2913    let stream = backend.stream.clone();
2914    let args = PreparedBmsFlexRowLaunchArgs::from_storage(storage)?;
2915    let p_total = storage.block.p_total;
2916    let partial_len = rhs_count
2917        .checked_mul(args.num_chunks)
2918        .and_then(|v| v.checked_mul(p_total))
2919        .ok_or_else(|| GpuError::DriverCallFailed {
2920            reason: format!(
2921                "bms_flex_row {ctx}: partial length overflow for rhs_count={rhs_count}, num_chunks={}, p_total={p_total}",
2922                args.num_chunks
2923            ),
2924        })?;
2925
2926    let mut d_partial =
2927        stream
2928            .alloc_zeros::<f64>(partial_len)
2929            .map_err(|err| GpuError::DriverCallFailed {
2930                reason: format!("bms_flex_row {ctx} alloc multi partial: {err}"),
2931            })?;
2932    let part_func = backend
2933        .module
2934        .load_function("bms_flex_row_hvp_multi_partial")
2935        .map_err(|err| GpuError::DriverCallFailed {
2936            reason: format!("bms_flex_row {ctx} load multi partial: {err}"),
2937        })?;
2938    let red_func = backend
2939        .module
2940        .load_function("bms_flex_row_hvp_multi_reduce")
2941        .map_err(|err| GpuError::DriverCallFailed {
2942            reason: format!("bms_flex_row {ctx} load multi reduce: {err}"),
2943        })?;
2944
2945    let rhs_count_i32 = i32::try_from(rhs_count).map_err(|_| GpuError::DriverCallFailed {
2946        reason: format!("bms_flex_row {ctx}: rhs_count={rhs_count} exceeds i32 range"),
2947    })?;
2948    let cfg_part = LaunchConfig {
2949        grid_dim: (args.num_chunks_u32, 1, 1),
2950        block_dim: (HVP_THREADS, 1, 1),
2951        shared_mem_bytes: 0,
2952    };
2953    let mut builder = stream.launch_builder(&part_func);
2954    builder
2955        .arg(&args.n_i32)
2956        .arg(&args.r_i32)
2957        .arg(&args.p_m_i32)
2958        .arg(&args.p_g_i32)
2959        .arg(&args.p_total_i32)
2960        .arg(&args.h_block_start)
2961        .arg(&args.h_block_len)
2962        .arg(&args.w_block_start)
2963        .arg(&args.w_block_len)
2964        .arg(&args.h_primary_start)
2965        .arg(&args.w_primary_start)
2966        .arg(&args.rows_per_cta)
2967        .arg(&rhs_count_i32)
2968        .arg(&storage.hess)
2969        .arg(&storage.marginal_design)
2970        .arg(&storage.logslope_design)
2971        .arg(d_v_rhs)
2972        .arg(&mut d_partial);
2973    // SAFETY: storage buffers were validated at construction; `d_v_rhs` and
2974    // `d_out` have rhs_count*p_total elements, `d_partial` has
2975    // rhs_count*num_chunks*p_total, and rhs_count is bounded by fixed shared
2976    // array sizes in the CUDA source.
2977    unsafe { builder.launch(cfg_part) }.map_err(|err| GpuError::DriverCallFailed {
2978        reason: format!("bms_flex_row {ctx} multi partial launch: {err}"),
2979    })?;
2980
2981    let red_threads: u32 = REDUCTION_THREADS;
2982    let rhs_elems_u32 = u32::try_from(rhs_elems).map_err(|_| GpuError::DriverCallFailed {
2983        reason: format!("bms_flex_row {ctx}: rhs elements={rhs_elems} exceed u32 range"),
2984    })?;
2985    let red_blocks = rhs_elems_u32.div_ceil(red_threads);
2986    let cfg_red = LaunchConfig {
2987        grid_dim: (red_blocks, 1, 1),
2988        block_dim: (red_threads, 1, 1),
2989        shared_mem_bytes: 0,
2990    };
2991    let mut builder = stream.launch_builder(&red_func);
2992    builder
2993        .arg(&args.num_chunks_i32)
2994        .arg(&args.p_total_i32)
2995        .arg(&rhs_count_i32)
2996        .arg(&d_partial)
2997        .arg(d_out);
2998    // SAFETY: the reduce kernel reads the just-populated partial buffer and
2999    // writes exactly rhs_count*p_total output entries.
3000    unsafe { builder.launch(cfg_red) }.map_err(|err| GpuError::DriverCallFailed {
3001        reason: format!("bms_flex_row {ctx} multi reduce launch: {err}"),
3002    })?;
3003    drop(d_partial);
3004    Ok(())
3005}
3006
3007/// Device-resident multi-RHS HVP. `v_rhs` is row-major
3008/// `[rhs_count, p_total]`; the returned vector has the same layout.
3009#[cfg(target_os = "linux")]
3010pub(crate) fn launch_bms_flex_row_hvp_multi(
3011    storage: &DeviceResidentRowHess,
3012    v_rhs: &[f64],
3013    rhs_count: usize,
3014) -> Result<Vec<f64>, GpuError> {
3015    let rhs_elems =
3016        validate_bms_flex_row_hvp_multi_shape(storage, rhs_count, v_rhs.len(), None, "hvp_multi")?;
3017    let backend = HvpKernelBackend::probe()?;
3018    let stream = backend.stream.clone();
3019    let d_v_rhs = stream
3020        .clone_htod(v_rhs)
3021        .map_err(|err| GpuError::DriverCallFailed {
3022            reason: format!("bms_flex_row hvp_multi upload v_rhs: {err}"),
3023        })?;
3024    let mut d_out =
3025        stream
3026            .alloc_zeros::<f64>(rhs_elems)
3027            .map_err(|err| GpuError::DriverCallFailed {
3028                reason: format!("bms_flex_row hvp_multi alloc out: {err}"),
3029            })?;
3030    run_bms_flex_row_multi_partial_reduce(storage, rhs_count, &d_v_rhs, &mut d_out, "hvp_multi")?;
3031    stream
3032        .synchronize()
3033        .map_err(|err| GpuError::DriverCallFailed {
3034            reason: format!("bms_flex_row hvp_multi synchronize: {err}"),
3035        })?;
3036    stream
3037        .clone_dtoh(&d_out)
3038        .map_err(|err| GpuError::DriverCallFailed {
3039            reason: format!("bms_flex_row hvp_multi download out: {err}"),
3040        })
3041}
3042
3043/// Materialize a row-major dense matrix from batched column images `H * I`.
3044/// Each launcher input/output is row-major `[rhs_count, p_total]`; the output
3045/// vectors are columns of `H`, so this routine performs the one required
3046/// transpose while copying them into `[row, column]` storage.
3047#[cfg(target_os = "linux")]
3048fn materialize_dense_from_hvp_batches(
3049    p_total: usize,
3050    mut launch: impl FnMut(&[f64], usize) -> Result<Vec<f64>, GpuError>,
3051) -> Result<Vec<f64>, GpuError> {
3052    if p_total == 0 {
3053        return Err(GpuError::DriverCallFailed {
3054            reason: "bms_flex_row dense HVP materialization: p_total must be > 0".to_string(),
3055        });
3056    }
3057    let dense_len = p_total
3058        .checked_mul(p_total)
3059        .ok_or_else(|| GpuError::DriverCallFailed {
3060            reason: format!(
3061                "bms_flex_row dense HVP materialization: p_total={p_total} square overflow"
3062            ),
3063        })?;
3064    let mut dense = vec![0.0_f64; dense_len];
3065    for column_start in (0..p_total).step_by(BMS_FLEX_ROW_HVP_MAX_RHS) {
3066        let rhs_count = (p_total - column_start).min(BMS_FLEX_ROW_HVP_MAX_RHS);
3067        let batch_len = checked_shape_len(
3068            "dense HVP materialization [rhs_count,p_total]",
3069            &[rhs_count, p_total],
3070        )?;
3071        let mut basis = vec![0.0_f64; batch_len];
3072        for local_column in 0..rhs_count {
3073            basis[local_column * p_total + column_start + local_column] = 1.0;
3074        }
3075        let images = launch(&basis, rhs_count)?;
3076        if images.len() != basis.len() {
3077            return Err(GpuError::DriverCallFailed {
3078                reason: format!(
3079                    "bms_flex_row dense HVP materialization: batch at column {column_start} returned {} values, expected {}",
3080                    images.len(),
3081                    basis.len()
3082                ),
3083            });
3084        }
3085        for local_column in 0..rhs_count {
3086            let column = column_start + local_column;
3087            let image = &images[local_column * p_total..(local_column + 1) * p_total];
3088            for (row, &value) in image.iter().enumerate() {
3089                dense[row * p_total + column] = value;
3090            }
3091        }
3092    }
3093    Ok(dense)
3094}
3095
3096/// Device-output HVP. Runs `bms_flex_row_hvp_partial` +
3097/// `bms_flex_row_hvp_reduce` on the storage's stream against caller-supplied
3098/// device-resident `d_v` (length `p_total` doubles), writing the result into
3099/// caller-supplied `d_out` (also `p_total` doubles). **No** `synchronize()`
3100/// or DtoH is performed — the caller is responsible for stream ordering
3101/// against any consumer that reads `d_out`.
3102///
3103/// This is the device-resident PCG hot path (Block 9 Phase 5): keeping the
3104/// HVP output on the stream lets the outer PCG loop chain axpy / dot /
3105/// preconditioner kernels back-to-back without a per-iter device sync.
3106#[cfg(target_os = "linux")]
3107pub(crate) fn launch_bms_flex_row_hvp_into_device(
3108    storage: &DeviceResidentRowHess,
3109    d_v: &CudaSlice<f64>,
3110    d_out: &mut CudaSlice<f64>,
3111) -> Result<(), GpuError> {
3112    let p_total = storage.block.p_total;
3113    if d_v.len() != p_total {
3114        return Err(GpuError::DriverCallFailed {
3115            reason: format!(
3116                "bms_flex_row hvp_into_device: d_v.len()={} != p_total={}",
3117                d_v.len(),
3118                p_total
3119            ),
3120        });
3121    }
3122    if d_out.len() != p_total {
3123        return Err(GpuError::DriverCallFailed {
3124            reason: format!(
3125                "bms_flex_row hvp_into_device: d_out.len()={} != p_total={}",
3126                d_out.len(),
3127                p_total
3128            ),
3129        });
3130    }
3131    // On-stream output: the shared engine launches partial+reduce into the
3132    // caller's `d_out` and returns without sync/DtoH, so the outer PCG loop can
3133    // chain device kernels against the result.
3134    run_bms_flex_row_partial_reduce(
3135        storage,
3136        BmsFlexRowLaunchMode::HvpDeviceOut,
3137        Some(d_v),
3138        d_out,
3139        "hvp_into_device",
3140    )
3141}
3142
3143/// Launch the device-resident HVP kernel. Returns the host-side joint β image
3144/// of length `block.p_total`.
3145#[cfg(target_os = "linux")]
3146pub(crate) fn launch_bms_flex_row_hvp(
3147    storage: &DeviceResidentRowHess,
3148    v: &[f64],
3149) -> Result<Vec<f64>, GpuError> {
3150    launch_bms_flex_row_hvp_multi(storage, v, 1)
3151}
3152
3153/// Launch the device-resident diagonal kernel. Returns the host-side joint
3154/// β diagonal of length `block.p_total`.
3155#[cfg(target_os = "linux")]
3156pub(crate) fn launch_bms_flex_row_diagonal(
3157    storage: &DeviceResidentRowHess,
3158) -> Result<Vec<f64>, GpuError> {
3159    launch_bms_flex_row_diagonal_host(storage)
3160}
3161
3162/// Block 9 Phase 6 — hard cap on `p_total` for the dense joint-Hessian
3163/// device kernel. Per-CTA shared-memory accumulator is `p_total² * 8`
3164/// bytes. V100 default per-block shared cap is 48 KiB, so the largest
3165/// safe `p_total` here is `sqrt(48 KiB / 8) = 78`. We round down to a
3166/// power-of-two-ish multiple of 8 for predictable launch geometry.
3167#[cfg(target_os = "linux")]
3168pub(crate) const DENSE_BLOCK_MAX_P: usize = 72;
3169
3170/// Number of rows each dense-block CTA processes. Smaller than the HVP
3171/// `HVP_ROWS_PER_CTA = 256` because the per-row inner loop is `O(r² *
3172/// (p_m + p_g + h_block_len + w_block_len))` rather than `O(r²)` — fewer
3173/// rows per CTA keeps the per-CTA wall time short and lets us scale grid
3174/// occupancy with `num_chunks = ceil(n / DENSE_BLOCK_ROWS_PER_CTA)`.
3175#[cfg(target_os = "linux")]
3176pub(crate) const DENSE_BLOCK_ROWS_PER_CTA: u32 = 32;
3177
3178/// Materialize the selected device-resident joint Hessian using the fastest
3179/// CUDA algorithm supported by its width. The direct shared-memory kernel is
3180/// used through [`DENSE_BLOCK_MAX_P`]; wider matrices are formed as batched
3181/// `H * I` column images through the existing bounded multi-RHS HVP kernel.
3182/// This is an up-front device algorithm choice, not a CUDA-to-CPU fallback.
3183#[cfg(target_os = "linux")]
3184pub(crate) fn launch_bms_flex_row_dense(
3185    storage: &DeviceResidentRowHess,
3186) -> Result<Vec<f64>, GpuError> {
3187    let p_total = storage.block.p_total;
3188    if p_total <= DENSE_BLOCK_MAX_P {
3189        return launch_bms_flex_row_dense_block(storage);
3190    }
3191    materialize_dense_from_hvp_batches(p_total, |basis, rhs_count| {
3192        launch_bms_flex_row_hvp_multi(storage, basis, rhs_count)
3193    })
3194}
3195
3196/// Launch the Phase-6 dense joint-Hessian block kernel. Returns the
3197/// host-side `[p_total, p_total]` row-major joint H as a `Vec<f64>`
3198/// (length `p_total²`).
3199///
3200/// **Not the default Newton path.** Production Newton uses HVP (Phase 2)
3201/// and never materialises the full dense Hessian. This entry exists for:
3202///   * exact-REML logdet (`log|H|`) when the unified evaluator wants to
3203///     factor H directly instead of going through the matrix-free path;
3204///   * diagnostic dumps that compare the GPU dense build against the CPU
3205///     `BernoulliMarginalSlopeFamily::fused_gradient_dense` reference;
3206///   * small-`p` debug routes where it is cheaper to factor + solve dense
3207///     than to run a PCG.
3208///
3209/// The kernel rejects `p_total > DENSE_BLOCK_MAX_P` cleanly because the
3210/// per-CTA shared-memory accumulator (`p_total² * 8` bytes) would exceed
3211/// the V100 48 KiB/block cap above that threshold.
3212#[cfg(target_os = "linux")]
3213pub fn launch_bms_flex_row_dense_block(
3214    storage: &DeviceResidentRowHess,
3215) -> Result<Vec<f64>, GpuError> {
3216    let p_total = storage.block.p_total;
3217    if p_total == 0 {
3218        return Err(GpuError::DriverCallFailed {
3219            reason: "bms_flex_row dense_block: p_total must be > 0".to_string(),
3220        });
3221    }
3222    if p_total > DENSE_BLOCK_MAX_P {
3223        return Err(GpuError::DriverCallFailed {
3224            reason: format!(
3225                "bms_flex_row dense_block: p_total={p_total} exceeds DENSE_BLOCK_MAX_P={DENSE_BLOCK_MAX_P} \
3226                 (per-CTA shmem accumulator p²*8 bytes would exceed V100's 48 KiB/block)"
3227            ),
3228        });
3229    }
3230    let backend = HvpKernelBackend::probe()?;
3231    let stream = backend.stream.clone();
3232    let args = PreparedBmsFlexRowLaunchArgs::from_storage(storage)?;
3233    let n = storage.n;
3234    let rows_per_cta = DENSE_BLOCK_ROWS_PER_CTA as usize;
3235    let num_chunks = n.div_ceil(rows_per_cta);
3236    let pp = checked_shape_len("dense_block [p_total,p_total]", &[p_total, p_total])?;
3237    let partial_len = checked_shape_len("dense_block partial", &[num_chunks, pp])?;
3238
3239    let mut d_partial =
3240        stream
3241            .alloc_zeros::<f64>(partial_len)
3242            .map_err(|err| GpuError::DriverCallFailed {
3243                reason: format!("bms_flex_row dense_block alloc partial: {err}"),
3244            })?;
3245    let mut d_out = stream
3246        .alloc_zeros::<f64>(pp)
3247        .map_err(|err| GpuError::DriverCallFailed {
3248            reason: format!("bms_flex_row dense_block alloc out: {err}"),
3249        })?;
3250
3251    let part_func = backend
3252        .module
3253        .load_function("bms_flex_row_dense_block_partial")
3254        .map_err(|err| GpuError::DriverCallFailed {
3255            reason: format!("bms_flex_row dense_block load partial: {err}"),
3256        })?;
3257    let red_func = backend
3258        .module
3259        .load_function("bms_flex_row_dense_block_reduce")
3260        .map_err(|err| GpuError::DriverCallFailed {
3261            reason: format!("bms_flex_row dense_block load reduce: {err}"),
3262        })?;
3263
3264    let rows_per_cta_i32 = i32::try_from(DENSE_BLOCK_ROWS_PER_CTA).map_err(|_| {
3265        GpuError::DriverCallFailed {
3266            reason: format!(
3267                "bms_flex_row dense_block: rows_per_cta={DENSE_BLOCK_ROWS_PER_CTA} exceeds i32 range"
3268            ),
3269        }
3270    })?;
3271    let num_chunks_u32 = u32::try_from(num_chunks).map_err(|_| GpuError::DriverCallFailed {
3272        reason: format!("bms_flex_row dense_block: num_chunks={num_chunks} exceeds u32 range"),
3273    })?;
3274    let num_chunks_i32 = i32::try_from(num_chunks).map_err(|_| GpuError::DriverCallFailed {
3275        reason: format!("bms_flex_row dense_block: num_chunks={num_chunks} exceeds i32 range"),
3276    })?;
3277    let pp_u32 = u32::try_from(pp).map_err(|_| GpuError::DriverCallFailed {
3278        reason: format!("bms_flex_row dense_block: p_total²={pp} exceeds u32 range"),
3279    })?;
3280
3281    // Per-CTA shmem accumulator: p_total² doubles.
3282    let shmem_bytes_usize =
3283        pp.checked_mul(std::mem::size_of::<f64>())
3284            .ok_or_else(|| GpuError::DriverCallFailed {
3285                reason: format!("dense_block shmem bytes overflow for p_total={p_total}"),
3286            })?;
3287    let shmem_bytes: u32 =
3288        u32::try_from(shmem_bytes_usize).map_err(|_| GpuError::DriverCallFailed {
3289            reason: format!("dense_block shmem bytes overflow u32 for p_total={p_total}"),
3290        })?;
3291
3292    let cfg_part = LaunchConfig {
3293        grid_dim: (num_chunks_u32, 1, 1),
3294        block_dim: (HVP_THREADS, 1, 1),
3295        shared_mem_bytes: shmem_bytes,
3296    };
3297    let mut builder = stream.launch_builder(&part_func);
3298    builder
3299        .arg(&args.n_i32)
3300        .arg(&args.r_i32)
3301        .arg(&args.p_m_i32)
3302        .arg(&args.p_g_i32)
3303        .arg(&args.p_total_i32)
3304        .arg(&args.h_block_start)
3305        .arg(&args.h_block_len)
3306        .arg(&args.w_block_start)
3307        .arg(&args.w_block_len)
3308        .arg(&args.h_primary_start)
3309        .arg(&args.w_primary_start)
3310        .arg(&rows_per_cta_i32)
3311        .arg(&storage.hess)
3312        .arg(&storage.marginal_design)
3313        .arg(&storage.logslope_design)
3314        .arg(&mut d_partial);
3315    // SAFETY: storage pointers have validated capacities; d_partial sized
3316    // num_chunks * pp doubles; dynamic shmem matches the kernel's `extern
3317    // __shared__` accumulator length.
3318    unsafe { builder.launch(cfg_part) }.map_err(|err| GpuError::DriverCallFailed {
3319        reason: format!("bms_flex_row dense_block partial launch: {err}"),
3320    })?;
3321
3322    let red_threads: u32 = REDUCTION_THREADS;
3323    let red_blocks = pp_u32.div_ceil(red_threads);
3324    let cfg_red = LaunchConfig {
3325        grid_dim: (red_blocks, 1, 1),
3326        block_dim: (red_threads, 1, 1),
3327        shared_mem_bytes: 0,
3328    };
3329    let mut builder = stream.launch_builder(&red_func);
3330    builder
3331        .arg(&num_chunks_i32)
3332        .arg(&args.p_total_i32)
3333        .arg(&d_partial)
3334        .arg(&mut d_out);
3335    // SAFETY: d_partial just populated, d_out is pp doubles.
3336    unsafe { builder.launch(cfg_red) }.map_err(|err| GpuError::DriverCallFailed {
3337        reason: format!("bms_flex_row dense_block reduce launch: {err}"),
3338    })?;
3339    stream
3340        .synchronize()
3341        .map_err(|err| GpuError::DriverCallFailed {
3342            reason: format!("bms_flex_row dense_block sync: {err}"),
3343        })?;
3344    stream
3345        .clone_dtoh(&d_out)
3346        .map_err(|err| GpuError::DriverCallFailed {
3347            reason: format!("bms_flex_row dense_block download: {err}"),
3348        })
3349}
3350
3351// Host numerical primitives and the production CPU↔generated-CUDA parity lock.
3352#[cfg(test)]
3353mod row_kernel_tests {
3354    pub(crate) fn host_log_ndtr_and_mills(x: f64) -> (f64, f64) {
3355        gam_gpu::numerics_host::log_ndtr_and_mills(x)
3356    }
3357
3358    // Sole consumer is the `cfg(all(test, target_os = "linux"))` device-test
3359    // module below; off-Linux this would be dead code under `-D warnings`.
3360    #[cfg(target_os = "linux")]
3361    pub(crate) fn host_log_ndtr_mills_curvature(x: f64) -> (f64, f64, f64) {
3362        gam_gpu::numerics_host::log_ndtr_mills_curvature(x)
3363    }
3364
3365    // #415 parity lock: one fitted StandardNormal FLEX family supplies both
3366    // the production CPU lowering and the generated CUDA launch.
3367    pub(crate) mod parity_415 {
3368        use crate::bms::family::*;
3369        use crate::bms::hessian_paths::*;
3370        use crate::bms::{DeviationBlockConfig, LatentMeasureKind, exact_kernel};
3371        use gam_linalg::matrix::{DenseDesignMatrix, DesignMatrix};
3372        use gam_problem::{InverseLink, ParameterBlockState, StandardLink};
3373        use ndarray::{Array1, Array2};
3374        use std::sync::{Arc, Mutex};
3375
3376        /// Build a small but REAL flex BMS family in the `StandardNormal`
3377        /// latent-measure branch with BOTH a score-warp (`p_h > 0`) and a
3378        /// link-deviation (`p_w > 0`) block active, plus mixed labels y ∈ {0,1}.
3379        /// Ported from the `gradient_paths` flex oracle fixture so the cache is
3380        /// populated by the production cell-moment assembly (never hand-faked).
3381        pub(crate) fn make_flex_parity_family(
3382            n: usize,
3383            score_internal_knots: usize,
3384            link_internal_knots: usize,
3385        ) -> (BernoulliMarginalSlopeFamily, Vec<ParameterBlockState>) {
3386            let score_seed = Array1::linspace(-2.0, 2.0, n.max(6));
3387            let link_seed = Array1::linspace(-1.8, 1.8, n.max(6));
3388            let score_cfg = DeviationBlockConfig {
3389                num_internal_knots: score_internal_knots,
3390                ..DeviationBlockConfig::default()
3391            };
3392            let link_cfg = DeviationBlockConfig {
3393                num_internal_knots: link_internal_knots,
3394                ..DeviationBlockConfig::default()
3395            };
3396            let score_prepared =
3397                build_score_warp_deviation_block_from_seed(&score_seed, &score_cfg)
3398                    .expect("build score warp block");
3399            let link_prepared = build_link_deviation_block_from_knots_design_seed_and_weights(
3400                &link_seed, &link_seed, &link_cfg,
3401            )
3402            .expect("build link deviation block");
3403
3404            // Mixed labels y ∈ {0,1} so both s_y = ±1 Mills branches are exercised.
3405            let y: Array1<f64> =
3406                Array1::from_iter((0..n).map(|i| if (i * 17 + 3) % 7 >= 4 { 1.0 } else { 0.0 }));
3407            let weights: Array1<f64> =
3408                Array1::from_iter((0..n).map(|i| 0.75 + ((i * 11 + 5) % 5) as f64 * 0.05));
3409            let z: Array1<f64> =
3410                Array1::from_iter((0..n).map(|i| -1.7 + 3.4 * (i as f64 + 0.5) / n as f64));
3411            let marginal_x = Array2::from_shape_fn((n, 2), |(i, j)| {
3412                if j == 0 {
3413                    1.0
3414                } else {
3415                    -0.4 + 0.8 * ((i * 19 + 7) % n) as f64 / n as f64
3416                }
3417            });
3418            let logslope_x = Array2::from_shape_fn((n, 2), |(i, j)| {
3419                if j == 0 {
3420                    1.0
3421                } else {
3422                    0.3 - 0.6 * ((i * 23 + 11) % n) as f64 / n as f64
3423                }
3424            });
3425
3426            let family = BernoulliMarginalSlopeFamily {
3427                y: Arc::new(y),
3428                weights: Arc::new(weights),
3429                z: Arc::new(z.clone()),
3430                latent_measure: LatentMeasureKind::StandardNormal,
3431                gaussian_frailty_sd: Some(0.15),
3432                base_link: InverseLink::Standard(StandardLink::Probit),
3433                marginal_design: DesignMatrix::Dense(DenseDesignMatrix::from(marginal_x.clone())),
3434                logslope_design: DesignMatrix::Dense(DenseDesignMatrix::from(logslope_x.clone())),
3435                score_warp: Some(score_prepared.runtime.clone()),
3436                link_dev: Some(link_prepared.runtime.clone()),
3437                policy: gam_runtime::resource::ResourcePolicy::default_library(),
3438                cell_moment_lru: Arc::new(exact_kernel::CellMomentLruCache::new(1024)),
3439                cell_moment_cache_stats: Arc::new(exact_kernel::CellMomentCacheStats::default()),
3440                intercept_warm_starts: None,
3441                auto_subsample_phase_counter: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
3442                auto_subsample_last_rho: Arc::new(Mutex::new(None)),
3443            };
3444
3445            let beta_m = Array1::from_vec(vec![0.12, -0.04]);
3446            let beta_g = Array1::from_vec(vec![0.35, 0.03]);
3447            let beta_h = Array1::from_iter(
3448                (0..score_prepared.runtime.basis_dim()).map(|idx| 0.0015 * (idx as f64 + 1.0)),
3449            );
3450            let beta_w = Array1::from_iter(
3451                (0..link_prepared.runtime.basis_dim()).map(|idx| -0.001 * (idx as f64 + 1.0)),
3452            );
3453            let states = vec![
3454                ParameterBlockState {
3455                    eta: marginal_x.dot(&beta_m),
3456                    beta: beta_m,
3457                },
3458                ParameterBlockState {
3459                    eta: logslope_x.dot(&beta_g),
3460                    beta: beta_g,
3461                },
3462                ParameterBlockState {
3463                    beta: beta_h,
3464                    eta: Array1::zeros(z.len()),
3465                },
3466                ParameterBlockState {
3467                    beta: beta_w,
3468                    eta: Array1::zeros(z.len()),
3469                },
3470            ];
3471            (family, states)
3472        }
3473
3474        /// One real StandardNormal full-FLEX fit drives both the production CPU
3475        /// lowering and the generated CUDA kernel. No mirrored host algebra is
3476        /// involved.
3477        fn assert_generated_cuda_row_kernel_matches_canonical_cpu_lowering(
3478            n: usize,
3479            score_internal_knots: usize,
3480            link_internal_knots: usize,
3481            expected_r: Option<usize>,
3482        ) {
3483            let (family, states) =
3484                make_flex_parity_family(n, score_internal_knots, link_internal_knots);
3485            let cache = family
3486                .build_exact_eval_cache(&states)
3487                .expect("flex exact eval cache");
3488            assert!(
3489                cache.row_cell_moments.is_some(),
3490                "#415 fixture must materialise production row-cell moments"
3491            );
3492            let primary = &cache.primary;
3493            let r = primary.total;
3494            let p_h = primary.h.as_ref().map(|range| range.len()).unwrap_or(0);
3495            let p_w = primary.w.as_ref().map(|range| range.len()).unwrap_or(0);
3496            assert!(
3497                p_h > 0 && p_w > 0,
3498                "fixture must activate both deviation blocks"
3499            );
3500            assert_eq!(r, 2 + p_h + p_w);
3501            if let Some(expected_r) = expected_r {
3502                assert_eq!(
3503                    r, expected_r,
3504                    "fixture knot counts must exercise the requested primary width"
3505                );
3506            }
3507
3508            let owned = family
3509                .pack_bms_flex_row_kernel_inputs(&states, &cache)
3510                .expect("packing production CUDA inputs must not error")
3511                .expect("StandardNormal full-FLEX fixture must admit the CUDA row kernel");
3512            let inputs = owned.as_borrowed();
3513            let mut canonical_neglog = vec![0.0; n];
3514            let mut canonical_grad = vec![0.0; n * r];
3515            let mut canonical_hess = vec![0.0; n * r * r];
3516            let mut scratch = BernoulliMarginalSlopeFlexRowScratch::new(r);
3517            let mut checked_labels = [false, false];
3518
3519            for row in 0..n {
3520                let row_ctx = BernoulliMarginalSlopeFamily::row_ctx(&cache, row);
3521                let row_moments = cache
3522                    .row_cell_moments
3523                    .as_ref()
3524                    .and_then(|bundle| bundle.row(row, 9));
3525                assert!(
3526                    row_moments.is_some(),
3527                    "row {row} must carry degree-9 moments"
3528                );
3529                canonical_neglog[row] = family
3530                    .lower_bms_flex_row_order2_with_moments(
3531                        row,
3532                        &states,
3533                        primary,
3534                        row_ctx,
3535                        row_moments,
3536                        cache.cell_family_forest.as_ref(),
3537                        true,
3538                        &mut scratch,
3539                    )
3540                    .expect("canonical production CPU row lowering");
3541                for u in 0..r {
3542                    canonical_grad[row * r + u] = scratch.grad[u];
3543                    for v in 0..r {
3544                        let value = scratch.hess[[u, v]];
3545                        assert!(value.is_finite(), "row {row}: H[{u},{v}] is non-finite");
3546                        assert_eq!(
3547                            value.to_bits(),
3548                            scratch.hess[[v, u]].to_bits(),
3549                            "row {row}: canonical Hessian lost exact symmetry"
3550                        );
3551                        canonical_hess[row * r * r + u * r + v] = value;
3552                    }
3553                }
3554                checked_labels[family.y[row] as usize] = true;
3555            }
3556            assert!(checked_labels[0] && checked_labels[1]);
3557
3558            let mut separates_value_from_q_derivative = false;
3559            for row in 0..n {
3560                let sign = 2.0 * inputs.y[row] - 1.0;
3561                let (_, lambda) = super::host_log_ndtr_and_mills(sign * inputs.e_obs[row]);
3562                let scale = -inputs.w[row] * sign * lambda;
3563                if scale.abs() > 1e-12 {
3564                    let observed_q_derivative = canonical_grad[row * r] / scale;
3565                    if (observed_q_derivative - inputs.e_obs[row]).abs() > 1e-8 {
3566                        separates_value_from_q_derivative = true;
3567                        break;
3568                    }
3569                }
3570            }
3571            assert!(
3572                separates_value_from_q_derivative,
3573                "fixture must distinguish the observed value from its q derivative"
3574            );
3575
3576            #[cfg(not(target_os = "linux"))]
3577            {
3578                eprintln!("[bms_flex_row parity] generated CUDA check requires Linux");
3579                return;
3580            }
3581            #[cfg(target_os = "linux")]
3582            {
3583                match gam_gpu::device_runtime::GpuRuntime::resolve(gam_gpu::GpuPolicy::Auto) {
3584                    Ok(Some(_)) => {}
3585                    Ok(None) => {
3586                        eprintln!("[bms_flex_row parity] no CUDA device");
3587                        return;
3588                    }
3589                    Err(error) => panic!("[bms_flex_row parity] CUDA probe failed: {error}"),
3590                }
3591                let gpu = super::super::launch_bms_flex_row_kernel(owned.as_borrowed())
3592                    .expect("CUDA-selected canonical parity launch must succeed");
3593                let check = |channel: &str, index: usize, cpu: f64, device: f64| {
3594                    let difference = (cpu - device).abs();
3595                    let tolerance = 1e-8 + 1e-8 * cpu.abs();
3596                    assert!(
3597                        difference <= tolerance,
3598                        "{channel}[{index}] CPU={cpu:.17e} CUDA={device:.17e} \
3599                         difference={difference:.3e} tolerance={tolerance:.3e}"
3600                    );
3601                };
3602                for (index, (&cpu, &device)) in
3603                    canonical_neglog.iter().zip(gpu.neglog.iter()).enumerate()
3604                {
3605                    check("neglog", index, cpu, device);
3606                }
3607                for (index, (&cpu, &device)) in
3608                    canonical_grad.iter().zip(gpu.grad.iter()).enumerate()
3609                {
3610                    check("gradient", index, cpu, device);
3611                }
3612                for (index, (&cpu, &device)) in
3613                    canonical_hess.iter().zip(gpu.hess.iter()).enumerate()
3614                {
3615                    check("hessian", index, cpu, device);
3616                }
3617            }
3618        }
3619
3620        #[test]
3621        fn generated_cuda_row_kernel_matches_canonical_cpu_lowering_415() {
3622            assert_generated_cuda_row_kernel_matches_canonical_cpu_lowering(12, 3, 3, None);
3623        }
3624
3625        #[test]
3626        fn full_flex_canonical_exact_cache_admits_material_finite_cell_curvature_2321() {
3627            let (family, states) = make_flex_parity_family(256, 8, 6);
3628            let cache = family
3629                .build_exact_eval_cache(&states)
3630                .expect("the full-FLEX host cache must preserve non-affine finite cells");
3631
3632            let score_width = cache
3633                .primary
3634                .h
3635                .as_ref()
3636                .expect("the full-FLEX fixture must retain its score-warp block")
3637                .len();
3638            let deviation_width = cache
3639                .primary
3640                .w
3641                .as_ref()
3642                .expect("the full-FLEX fixture must retain its link-deviation block")
3643                .len();
3644            assert!(score_width > 0 && deviation_width > 0);
3645            assert_eq!(
3646                cache.primary.total,
3647                2 + score_width + deviation_width,
3648                "the canonical primary layout must contain exactly q, logslope, score-warp, and link-deviation coordinates"
3649            );
3650            assert!(
3651                cache.row_cell_moments.is_some(),
3652                "the production full-FLEX fixture must materialize its exact row-cell cache"
3653            );
3654        }
3655
3656        #[test]
3657        fn generated_cuda_row_kernel_r33_matches_canonical_cpu_lowering_932() {
3658            gam_gpu::configure_global_policy(gam_gpu::GpuPolicy::Required);
3659            assert_eq!(
3660                gam_gpu::global_policy(),
3661                gam_gpu::GpuPolicy::Required,
3662                "fresh-process r=33 parity must claim Required before runtime discovery"
3663            );
3664            gam_gpu::device_runtime::GpuRuntime::require()
3665                .expect("#932 mandatory r=33 CUDA runtime");
3666            // Cubic deviation runtimes expose `num_internal_knots + 1` live
3667            // controls since the #2319 knot-selection orbit canonicalization
3668            // (one control fewer per block than the pre-orbit layout this
3669            // fixture was written against). These unequal blocks therefore
3670            // give p_h=16, p_w=15, r=33 — the width just past the 32-lane
3671            // warp boundary this regression exists to exercise.
3672            assert_generated_cuda_row_kernel_matches_canonical_cpu_lowering(40, 15, 14, Some(33));
3673        }
3674    }
3675}
3676
3677#[cfg(all(test, target_os = "linux"))]
3678mod tests {
3679    use super::row_kernel_tests::*;
3680    use super::*;
3681    use crate::bms::exact_eval_cache::RowPrimaryEvalCache;
3682    use crate::bms::row_kernel::BernoulliMarginalSlopeExactNewtonJointHessianWorkspace;
3683    use crate::custom_family::{BlockwiseFitOptions, ExactNewtonJointHessianWorkspace};
3684    use gam_gpu::{GpuPolicy, configure_global_policy};
3685    use ndarray::{Array1, Array2};
3686    use std::hint::black_box;
3687    use std::sync::atomic::AtomicUsize;
3688    use std::time::{Duration, Instant};
3689
3690    /// Assert the dispatch-worthiness claim and record the timings without
3691    /// asserting on them (#2487, SPEC rule 19).
3692    ///
3693    /// These gates asserted `cpu_median / gpu_median >= 2.0` (walked down from
3694    /// 5× and 10× calibration-box ratios). A ratio of two wall-clock medians is
3695    /// a property of whoever else is on the box, not of the kernel: under
3696    /// co-tenancy the device arm degrades harder than the host arm, so the
3697    /// ratio collapses toward 1 exactly when the fleet is busiest, and the red
3698    /// gets read as a code regression. The claim these gates exist to make —
3699    /// "this shape belongs on the device" — is decided instead by the
3700    /// calibrated policy, whose row crossover is a per-device *measurement*.
3701    ///
3702    /// The medians stay in the log as the hill-climbing perf record, which is
3703    /// what a timing is good for.
3704    #[cfg(target_os = "linux")]
3705    fn assert_row_batch_dispatch_worthy(
3706        label: &str,
3707        policy: &gam_gpu::policy::GpuDispatchPolicy,
3708        n: usize,
3709    ) {
3710        assert!(
3711            policy.row_batch_target_is_gpu(n),
3712            "{label}: n={n} rows is below this device's calibrated row-kernel \
3713             crossover ({}), so the fixture no longer exercises a shape the \
3714             dispatch policy would send to the device — grow the fixture rather \
3715             than lowering the crossover",
3716            policy.row_kernel_min_n
3717        );
3718        assert!(
3719            !policy.row_batch_target_is_gpu(0),
3720            "{label}: the dispatch predicate admitted an empty batch, so the \
3721             assertion above proves nothing about n={n}"
3722        );
3723    }
3724
3725    fn cuda_runtime_for_test(
3726        test_name: &str,
3727    ) -> Option<&'static gam_gpu::device_runtime::GpuRuntime> {
3728        match gam_gpu::device_runtime::GpuRuntime::resolve(GpuPolicy::Auto) {
3729            Ok(Some(runtime)) => Some(runtime),
3730            Ok(None) => {
3731                eprintln!("[{test_name}] no CUDA device — skipping");
3732                None
3733            }
3734            Err(error) => panic!("[{test_name}] CUDA probe failed: {error}"),
3735        }
3736    }
3737
3738    fn assert_array1_close_932(label: &str, expected: &Array1<f64>, actual: &Array1<f64>) {
3739        assert_eq!(expected.len(), actual.len(), "{label}: length mismatch");
3740        for (index, (&want, &got)) in expected.iter().zip(actual).enumerate() {
3741            let tolerance = 2.0e-8 * (1.0 + want.abs());
3742            assert!(
3743                want.is_finite() && got.is_finite() && (want - got).abs() <= tolerance,
3744                "{label}[{index}]: expected={want:.17e} actual={got:.17e} tolerance={tolerance:.3e}"
3745            );
3746        }
3747    }
3748
3749    /// Mandatory A100 acceptance hook. Run this exact test in a fresh process:
3750    /// configuring `Required` is deliberately the first GPU action, and every
3751    /// missing-runtime, probe, upload, launch, synchronization, status, or
3752    /// download failure aborts the test instead of turning into a skip.
3753    #[test]
3754    fn mandatory_required_gpu_workspace_consumes_device_cache_end_to_end_932() {
3755        configure_global_policy(GpuPolicy::Required);
3756        assert_eq!(
3757            gam_gpu::global_policy(),
3758            GpuPolicy::Required,
3759            "fresh-process acceptance test must claim Required before any competing policy"
3760        );
3761        gam_gpu::device_runtime::GpuRuntime::require().expect("#932 mandatory CUDA runtime");
3762
3763        let (family, states) = row_kernel_tests::parity_415::make_flex_parity_family(256, 8, 6);
3764        let mut workspace = BernoulliMarginalSlopeExactNewtonJointHessianWorkspace::new(
3765            family,
3766            states,
3767            BlockwiseFitOptions::default(),
3768        )
3769        .expect("#932 Required workspace must build its device row cache");
3770
3771        assert!(
3772            matches!(
3773                &workspace.cache.row_primary_hessians,
3774                RowPrimaryEvalCache::Device(_)
3775            ),
3776            "Required full-FLEX workspace must retain RowPrimaryEvalCache::Device"
3777        );
3778        {
3779            let device = workspace
3780                .cache
3781                .row_primary_hessians
3782                .device()
3783                .expect("device cache variant");
3784            assert!(
3785                device
3786                    .primary
3787                    .h
3788                    .as_ref()
3789                    .is_some_and(|range| !range.is_empty())
3790                    && device
3791                        .primary
3792                        .w
3793                        .as_ref()
3794                        .is_some_and(|range| !range.is_empty()),
3795                "mandatory fixture must carry active h and w primary blocks"
3796            );
3797            assert!(
3798                device
3799                    .block
3800                    .h
3801                    .as_ref()
3802                    .is_some_and(|range| !range.is_empty())
3803                    && device
3804                        .block
3805                        .w
3806                        .as_ref()
3807                        .is_some_and(|range| !range.is_empty()),
3808                "mandatory fixture must carry active h and w coefficient blocks"
3809            );
3810        }
3811        for operation in ["host HVP replay", "host diagonal replay"] {
3812            let error = workspace
3813                .cache
3814                .row_primary_hessians
3815                .reject_device_cpu_recompute(operation)
3816                .expect_err("a selected device cache must reject host row recomputation");
3817            assert!(
3818                error.contains("device-resident row evaluation selected")
3819                    && error.contains("CPU row recomputation is forbidden"),
3820                "unexpected fail-closed diagnostic: {error}"
3821            );
3822        }
3823
3824        let total = workspace.cache.slices.total;
3825        let direction = Array1::from_shape_fn(total, |index| {
3826            let sign = if index % 2 == 0 { 1.0 } else { -1.0 };
3827            sign * (0.025 + 0.0075 * index as f64)
3828        });
3829        let joint_ll = workspace
3830            .joint_log_likelihood_evaluation()
3831            .expect("device joint log-likelihood")
3832            .expect("device joint log-likelihood must be present");
3833        let joint = workspace
3834            .joint_gradient_evaluation()
3835            .expect("device joint gradient")
3836            .expect("device joint gradient must be present");
3837        assert!(joint_ll.is_finite());
3838        assert_eq!(joint.log_likelihood.to_bits(), joint_ll.to_bits());
3839        assert_eq!(joint.gradient.len(), total);
3840        assert!(joint.gradient.iter().all(|value| value.is_finite()));
3841
3842        let hvp = workspace
3843            .hessian_matvec(&direction)
3844            .expect("device HVP")
3845            .expect("device HVP must be present");
3846        let mut hvp_into = Array1::from_elem(total, f64::NAN);
3847        assert!(
3848            workspace
3849                .hessian_matvec_into(&direction, &mut hvp_into)
3850                .expect("device HVP-into"),
3851            "device HVP-into must report that it handled the direction"
3852        );
3853        assert_array1_close_932("HVP owned/into", &hvp, &hvp_into);
3854
3855        let rhs = Array2::from_shape_fn((total, 3), |(row, column)| {
3856            (row as f64 + 1.0)
3857                * (column as f64 + 0.5)
3858                * 0.011
3859                * if (row + column) % 3 == 0 { -1.0 } else { 1.0 }
3860        });
3861        let mut applied = Array2::<f64>::from_elem((total, rhs.ncols()), f64::NAN);
3862        assert!(
3863            workspace
3864                .hessian_apply_mat(&rhs, &mut applied)
3865                .expect("device multi-RHS apply"),
3866            "device multi-RHS apply must report that it handled the matrix"
3867        );
3868        let diagonal = workspace
3869            .hessian_diagonal()
3870            .expect("device diagonal")
3871            .expect("device diagonal must be present");
3872        let dense = workspace
3873            .hessian_dense_forced()
3874            .expect("device forced dense Hessian")
3875            .expect("device forced dense Hessian must be present");
3876        assert_eq!(dense.dim(), (total, total));
3877        assert_array1_close_932("dense * v / HVP", &dense.dot(&direction), &hvp);
3878        assert_array1_close_932("dense diagonal", &dense.diag().to_owned(), &diagonal);
3879        let dense_applied = dense.dot(&rhs);
3880        for column in 0..rhs.ncols() {
3881            assert_array1_close_932(
3882                &format!("dense * V / apply_mat column {column}"),
3883                &dense_applied.column(column).to_owned(),
3884                &applied.column(column).to_owned(),
3885            );
3886        }
3887
3888        // The resident cache is the numerical authority. Poisoning every host
3889        // block-state number after construction must not alter HVP/diagonal;
3890        // any accidental host replay would either propagate NaNs or error.
3891        for state in &mut workspace.block_states {
3892            state.beta.fill(f64::NAN);
3893            state.eta.fill(f64::NAN);
3894        }
3895        let poisoned_hvp = workspace
3896            .hessian_matvec(&direction)
3897            .expect("device HVP after host-state poison")
3898            .expect("device HVP after host-state poison must be present");
3899        let poisoned_diagonal = workspace
3900            .hessian_diagonal()
3901            .expect("device diagonal after host-state poison")
3902            .expect("device diagonal after host-state poison must be present");
3903        assert_eq!(
3904            hvp.as_slice(),
3905            poisoned_hvp.as_slice(),
3906            "fixed-order device HVP changed after poisoning host block state"
3907        );
3908        assert_eq!(
3909            diagonal.as_slice(),
3910            poisoned_diagonal.as_slice(),
3911            "fixed-order device diagonal changed after poisoning host block state"
3912        );
3913    }
3914
3915    /// Temporary #932 release-only evidence hook. It times the strongest
3916    /// production CPU row batch (the Rayon `build_row_primary_hessian_pin`)
3917    /// against the complete generated GPU row path: host packing, device
3918    /// moment production, every transfer/allocation, row launch, synchronize,
3919    /// and status download. Run this exact test in a fresh release process so
3920    /// `cold_gpu_e2e_nvrtc_ms` includes the first NVRTC loads and the 21 ABBA
3921    /// samples describe only the subsequently cached compiler state.
3922    #[test]
3923    fn release_measure_generated_bms_full_row_vs_strongest_cpu_932() {
3924        const N: usize = 32_768;
3925        const WARMUPS: usize = 3;
3926        const SAMPLES: usize = 21;
3927
3928        configure_global_policy(GpuPolicy::Required);
3929        assert_eq!(gam_gpu::global_policy(), GpuPolicy::Required);
3930        gam_gpu::device_runtime::GpuRuntime::require()
3931            .expect("#932 full-row release measurement requires CUDA");
3932
3933        // Cubic deviation runtimes expose `num_internal_knots + 1` live
3934        // controls since the #2319 knot-selection orbit canonicalization, so
3935        // 9/7 internal knots give p_h=10, p_w=8 — the same r=20 measurement
3936        // shape this cell has always timed.
3937        let (family, states) = row_kernel_tests::parity_415::make_flex_parity_family(N, 9, 7);
3938        let cache = family
3939            .build_exact_eval_cache(&states)
3940            .expect("full-row timing exact cache");
3941        let r = cache.primary.total;
3942        assert_eq!(r, 20, "9/7 knot fixture must expose primary width r=20");
3943        let marginal = family
3944            .marginal_design
3945            .as_dense_ref()
3946            .expect("timing fixture marginal design must be dense");
3947        let logslope = family
3948            .logslope_design
3949            .as_dense_ref()
3950            .expect("timing fixture logslope design must be dense");
3951        assert!(marginal.is_standard_layout() && logslope.is_standard_layout());
3952        let marginal_slice = marginal
3953            .as_slice()
3954            .expect("timing fixture marginal design is contiguous");
3955        let logslope_slice = logslope
3956            .as_slice()
3957            .expect("timing fixture logslope design is contiguous");
3958        let block = BmsFlexBlockLayout {
3959            p_m: cache.slices.marginal.len(),
3960            p_g: cache.slices.logslope.len(),
3961            h: cache.slices.h.clone(),
3962            w: cache.slices.w.clone(),
3963            p_total: cache.slices.total,
3964        };
3965        let primary = BmsFlexPrimaryLayout {
3966            h: cache.primary.h.clone(),
3967            w: cache.primary.w.clone(),
3968            r,
3969        };
3970        assert!(
3971            primary.h.as_ref().is_some_and(|range| !range.is_empty())
3972                && primary.w.as_ref().is_some_and(|range| !range.is_empty()),
3973            "full-row timing fixture must exercise both h and w"
3974        );
3975        let pin_bytes =
3976            crate::bms::family::BernoulliMarginalSlopeFamily::row_primary_eval_tile_bytes(N, r);
3977
3978        let run_cpu = || {
3979            let completed = AtomicUsize::new(0);
3980            family
3981                .build_row_primary_hessian_pin(
3982                    &states,
3983                    &cache,
3984                    0..N,
3985                    &completed,
3986                    N.saturating_add(1),
3987                    Instant::now(),
3988                    pin_bytes,
3989                )
3990                .expect("production Rayon row-primary batch")
3991        };
3992        let run_gpu = || {
3993            let owned = family
3994                .pack_bms_flex_row_kernel_inputs(&states, &cache)
3995                .expect("production BMS GPU packing")
3996                .expect("StandardNormal full-FLEX timing fixture must pack");
3997            launch_bms_flex_row_kernel_device_resident(
3998                owned.as_borrowed(),
3999                marginal_slice,
4000                logslope_slice,
4001                block.clone(),
4002                primary.clone(),
4003            )
4004            .expect("production device-resident row launch")
4005        };
4006        let measure_cpu = || {
4007            let started = Instant::now();
4008            let output = black_box(run_cpu());
4009            (started.elapsed(), output)
4010        };
4011        let measure_gpu = || {
4012            let started = Instant::now();
4013            let output = black_box(run_gpu());
4014            (started.elapsed(), output)
4015        };
4016
4017        let cold_started = Instant::now();
4018        let cold_gpu = black_box(run_gpu());
4019        let cold_gpu_e2e_nvrtc = cold_started.elapsed();
4020        drop(cold_gpu);
4021        for _ in 0..WARMUPS {
4022            black_box(run_cpu());
4023            black_box(run_gpu());
4024        }
4025
4026        let mut cpu_samples = Vec::<Duration>::with_capacity(SAMPLES);
4027        let mut gpu_samples = Vec::<Duration>::with_capacity(SAMPLES);
4028        let mut last_cpu = None;
4029        let mut last_gpu = None;
4030        for sample in 0..SAMPLES {
4031            // Alternating AB/BA pairs yield the repeating ABBA ordering and
4032            // cancel monotone thermal/frequency drift without averaging away
4033            // an individually slow cell.
4034            if sample % 2 == 0 {
4035                let (cpu_elapsed, cpu) = measure_cpu();
4036                cpu_samples.push(cpu_elapsed);
4037                let (gpu_elapsed, gpu) = measure_gpu();
4038                gpu_samples.push(gpu_elapsed);
4039                if sample + 1 == SAMPLES {
4040                    last_cpu = Some(cpu);
4041                    last_gpu = Some(gpu);
4042                }
4043            } else {
4044                let (gpu_elapsed, gpu) = measure_gpu();
4045                gpu_samples.push(gpu_elapsed);
4046                let (cpu_elapsed, cpu) = measure_cpu();
4047                cpu_samples.push(cpu_elapsed);
4048                drop(gpu);
4049                drop(cpu);
4050            }
4051        }
4052        let cpu = last_cpu.expect("final CPU sample retained for parity");
4053        let gpu = last_gpu.expect("final GPU sample retained for parity");
4054
4055        let stream = HvpKernelBackend::probe()
4056            .expect("HVP backend remains available")
4057            .stream
4058            .clone();
4059        let gpu_neglog = stream
4060            .clone_dtoh(&gpu.neglog)
4061            .expect("download timed GPU neglog for parity");
4062        let gpu_grad = stream
4063            .clone_dtoh(&gpu.grad)
4064            .expect("download timed GPU gradient for parity");
4065        let gpu_hess = stream
4066            .clone_dtoh(&gpu.hess)
4067            .expect("download timed GPU Hessian for parity");
4068        let cpu_channels = [
4069            cpu.neglog().as_slice().expect("CPU neglog is contiguous"),
4070            cpu.grad().as_slice().expect("CPU gradient is contiguous"),
4071            cpu.hess().as_slice().expect("CPU Hessian is contiguous"),
4072        ];
4073        let gpu_channels = [
4074            gpu_neglog.as_slice(),
4075            gpu_grad.as_slice(),
4076            gpu_hess.as_slice(),
4077        ];
4078        let mut nonfinite = 0_usize;
4079        let mut max_abs = 0.0_f64;
4080        let mut max_scaled = 0.0_f64;
4081        let mut cpu_digest = 0.0_f64;
4082        let mut gpu_digest = 0.0_f64;
4083        let mut digest_index = 0_usize;
4084        for (cpu_channel, gpu_channel) in cpu_channels.iter().zip(gpu_channels) {
4085            assert_eq!(cpu_channel.len(), gpu_channel.len());
4086            for (&host, &device) in cpu_channel.iter().zip(gpu_channel) {
4087                if !host.is_finite() || !device.is_finite() {
4088                    nonfinite += 1;
4089                }
4090                let difference = (host - device).abs();
4091                let tolerance = 1.0e-8 * (1.0 + host.abs());
4092                max_abs = max_abs.max(difference);
4093                max_scaled = max_scaled.max(difference / tolerance);
4094                let weight = 1.0 + (digest_index % 251) as f64 / 251.0;
4095                cpu_digest += weight * host;
4096                gpu_digest += weight * device;
4097                digest_index += 1;
4098            }
4099        }
4100        assert_eq!(
4101            nonfinite, 0,
4102            "full-row CPU/GPU output contains non-finite values"
4103        );
4104        assert!(
4105            max_scaled <= 1.0,
4106            "full-row CPU/GPU parity exceeded tolerance: max_abs={max_abs:.3e} max_scaled={max_scaled:.3e}"
4107        );
4108
4109        let mut cpu_ms = cpu_samples
4110            .iter()
4111            .map(|sample| sample.as_secs_f64() * 1.0e3)
4112            .collect::<Vec<_>>();
4113        let mut gpu_ms = gpu_samples
4114            .iter()
4115            .map(|sample| sample.as_secs_f64() * 1.0e3)
4116            .collect::<Vec<_>>();
4117        cpu_ms.sort_by(f64::total_cmp);
4118        gpu_ms.sort_by(f64::total_cmp);
4119        let p25 = SAMPLES / 4;
4120        let p50 = SAMPLES / 2;
4121        let p75 = 3 * SAMPLES / 4;
4122        let conservative_speedup = cpu_ms[p25] / gpu_ms[p75];
4123        let median_speedup = cpu_ms[p50] / gpu_ms[p50];
4124        let cpu_distribution = cpu_ms
4125            .iter()
4126            .map(|value| format!("{value:.6}"))
4127            .collect::<Vec<_>>()
4128            .join(",");
4129        let gpu_distribution = gpu_ms
4130            .iter()
4131            .map(|value| format!("{value:.6}"))
4132            .collect::<Vec<_>>()
4133            .join(",");
4134        println!(
4135            "G932_BMS_FULL_ROW n={N} r={r} warmups={WARMUPS} samples={SAMPLES} \
4136             cold_gpu_e2e_nvrtc_ms={:.6} cpu_ms_p25={:.6} cpu_ms_p50={:.6} cpu_ms_p75={:.6} \
4137             gpu_ms_p25={:.6} gpu_ms_p50={:.6} gpu_ms_p75={:.6} \
4138             speedup_conservative_cpu_p25_over_gpu_p75={conservative_speedup:.6} \
4139             speedup_median={median_speedup:.6} parity_max_abs={max_abs:.9e} \
4140             parity_max_scaled={max_scaled:.9e} cpu_digest={cpu_digest:.17e} \
4141             gpu_digest={gpu_digest:.17e} nonfinite={nonfinite} \
4142             cpu_ms_sorted=[{cpu_distribution}] gpu_ms_sorted=[{gpu_distribution}]",
4143            cold_gpu_e2e_nvrtc.as_secs_f64() * 1.0e3,
4144            cpu_ms[p25],
4145            cpu_ms[p50],
4146            cpu_ms[p75],
4147            gpu_ms[p25],
4148            gpu_ms[p50],
4149            gpu_ms[p75],
4150        );
4151    }
4152
4153    #[test]
4154    fn dense_hvp_batches_transpose_column_images_in_bounded_groups_932() {
4155        let p_total = 2 * BMS_FLEX_ROW_HVP_MAX_RHS + 3;
4156        let matrix = (0..p_total * p_total)
4157            .map(|index| {
4158                let row = index / p_total;
4159                let column = index % p_total;
4160                1000.0 * row as f64 + column as f64 + 0.25
4161            })
4162            .collect::<Vec<_>>();
4163        let mut observed_batch_sizes = Vec::new();
4164        let dense = materialize_dense_from_hvp_batches(p_total, |basis, rhs_count| {
4165            observed_batch_sizes.push(rhs_count);
4166            let mut images = vec![0.0_f64; rhs_count * p_total];
4167            for rhs in 0..rhs_count {
4168                for row in 0..p_total {
4169                    images[rhs * p_total + row] = (0..p_total)
4170                        .map(|column| {
4171                            matrix[row * p_total + column] * basis[rhs * p_total + column]
4172                        })
4173                        .sum();
4174                }
4175            }
4176            Ok(images)
4177        })
4178        .expect("synthetic H*I batches must materialize");
4179        assert_eq!(dense, matrix);
4180        assert_eq!(
4181            observed_batch_sizes,
4182            vec![BMS_FLEX_ROW_HVP_MAX_RHS, BMS_FLEX_ROW_HVP_MAX_RHS, 3]
4183        );
4184    }
4185
4186    pub(crate) fn minimal_inputs<'a>(buffers: &'a TestBuffers) -> BmsFlexRowKernelInputs<'a> {
4187        BmsFlexRowKernelInputs {
4188            n_rows: 1,
4189            r: 4,
4190            p_h: 1,
4191            p_w: 1,
4192            q: &buffers.q,
4193            b: &buffers.b,
4194            mu_1: &buffers.mu_1,
4195            mu_2: &buffers.mu_2,
4196            z_obs: &buffers.z_obs,
4197            y: &buffers.y,
4198            w: &buffers.w,
4199            e_obs: &buffers.e_obs,
4200            s_f: 1.0,
4201            cell_offsets: &buffers.cell_offsets,
4202            cell_c0: &buffers.cell_c0,
4203            cell_c1: &buffers.cell_c1,
4204            cell_c2: &buffers.cell_c2,
4205            cell_c3: &buffers.cell_c3,
4206            cell_a: &buffers.cell_a,
4207            cell_aa: &buffers.cell_aa,
4208            cell_r: &buffers.cell_r,
4209            cell_ar: &buffers.cell_ar,
4210            cell_sbb: &buffers.cell_sbb,
4211            cell_sbh: &buffers.cell_sbh,
4212            cell_sbw: &buffers.cell_sbw,
4213            cell_moments: CellMomentsSource::Host(&buffers.cell_moments),
4214            chi_obs: &buffers.chi_obs,
4215            xi_obs: &buffers.xi_obs,
4216            rho_u: &buffers.rho_u,
4217            tau_u: &buffers.tau_u,
4218            r_uv: &buffers.r_uv,
4219        }
4220    }
4221
4222    pub(crate) struct TestBuffers {
4223        pub(crate) q: Vec<f64>,
4224        pub(crate) b: Vec<f64>,
4225        pub(crate) mu_1: Vec<f64>,
4226        pub(crate) mu_2: Vec<f64>,
4227        pub(crate) z_obs: Vec<f64>,
4228        pub(crate) y: Vec<f64>,
4229        pub(crate) w: Vec<f64>,
4230        pub(crate) e_obs: Vec<f64>,
4231        pub(crate) cell_offsets: Vec<u32>,
4232        pub(crate) cell_c0: Vec<f64>,
4233        pub(crate) cell_c1: Vec<f64>,
4234        pub(crate) cell_c2: Vec<f64>,
4235        pub(crate) cell_c3: Vec<f64>,
4236        pub(crate) cell_a: Vec<f64>,
4237        pub(crate) cell_aa: Vec<f64>,
4238        pub(crate) cell_r: Vec<f64>,
4239        pub(crate) cell_ar: Vec<f64>,
4240        pub(crate) cell_sbb: Vec<f64>,
4241        pub(crate) cell_sbh: Vec<f64>,
4242        pub(crate) cell_sbw: Vec<f64>,
4243        pub(crate) cell_moments: Vec<f64>,
4244        pub(crate) chi_obs: Vec<f64>,
4245        pub(crate) xi_obs: Vec<f64>,
4246        pub(crate) rho_u: Vec<f64>,
4247        pub(crate) tau_u: Vec<f64>,
4248        pub(crate) r_uv: Vec<f64>,
4249    }
4250
4251    pub(crate) fn make_buffers(n_cells: u32, r: usize, p_h: usize, p_w: usize) -> TestBuffers {
4252        let cells = n_cells as usize;
4253        TestBuffers {
4254            q: vec![0.1; 1],
4255            b: vec![0.5; 1],
4256            mu_1: vec![0.3; 1],
4257            mu_2: vec![0.07; 1],
4258            z_obs: vec![0.0; 1],
4259            y: vec![1.0; 1],
4260            w: vec![1.0; 1],
4261            e_obs: vec![0.15; 1],
4262            cell_offsets: vec![0, n_cells],
4263            cell_c0: vec![0.2; cells],
4264            cell_c1: vec![-0.1; cells],
4265            cell_c2: vec![0.05; cells],
4266            cell_c3: vec![-0.02; cells],
4267            cell_a: vec![0.1; cells * 4],
4268            cell_aa: vec![0.0; cells * 4],
4269            cell_r: vec![0.05; cells * (r - 1) * 4],
4270            cell_ar: vec![0.0; cells * (r - 1) * 4],
4271            cell_sbb: vec![0.0; cells * 4],
4272            cell_sbh: vec![0.0; cells * p_h * 4],
4273            cell_sbw: vec![0.0; cells * p_w * 4],
4274            cell_moments: vec![1.0; cells * MOMENT_STRIDE],
4275            chi_obs: vec![1.0; 1],
4276            xi_obs: vec![0.0; 1],
4277            rho_u: vec![0.0; r],
4278            tau_u: vec![0.0; r],
4279            r_uv: vec![0.0; r * r],
4280        }
4281    }
4282
4283    #[test]
4284    pub(crate) fn validate_accepts_minimal_inputs() {
4285        let buffers = make_buffers(2, 4, 1, 1);
4286        let inputs = minimal_inputs(&buffers);
4287        assert!(inputs.validate().is_ok());
4288    }
4289
4290    #[test]
4291    pub(crate) fn validate_accepts_r33_with_active_h_and_w_blocks() {
4292        let r = 33;
4293        let p_h = 16;
4294        let p_w = 15;
4295        let buffers = make_buffers(1, r, p_h, p_w);
4296        let inputs = BmsFlexRowKernelInputs {
4297            r,
4298            p_h,
4299            p_w,
4300            rho_u: &buffers.rho_u,
4301            tau_u: &buffers.tau_u,
4302            r_uv: &buffers.r_uv,
4303            cell_r: &buffers.cell_r,
4304            cell_ar: &buffers.cell_ar,
4305            cell_sbh: &buffers.cell_sbh,
4306            cell_sbw: &buffers.cell_sbw,
4307            ..minimal_inputs(&buffers)
4308        };
4309        inputs
4310            .validate()
4311            .expect("r=33 is a valid checked shape, not a semantic width boundary");
4312    }
4313
4314    #[test]
4315    pub(crate) fn checked_shape_len_rejects_arithmetic_overflow() {
4316        let err = checked_shape_len("overflow test", &[usize::MAX, 2])
4317            .expect_err("shape multiplication must fail closed");
4318        assert!(err.to_string().contains("shape product overflow"));
4319    }
4320
4321    #[test]
4322    pub(crate) fn validate_rejects_zero_rows_before_cuda_grid_construction() {
4323        let buffers = make_buffers(1, 4, 1, 1);
4324        let inputs = BmsFlexRowKernelInputs {
4325            n_rows: 0,
4326            ..minimal_inputs(&buffers)
4327        };
4328        let err = inputs
4329            .validate()
4330            .expect_err("zero-row launch must fail closed");
4331        assert!(err.to_string().contains("n_rows must be > 0"));
4332    }
4333
4334    #[test]
4335    pub(crate) fn validate_rejects_mismatched_r_decomposition() {
4336        let buffers = make_buffers(1, 4, 1, 1);
4337        let bad_inputs = BmsFlexRowKernelInputs {
4338            r: 4,
4339            p_h: 1,
4340            p_w: 2, // inconsistent with r = 4
4341            ..minimal_inputs(&buffers)
4342        };
4343        let err = bad_inputs
4344            .validate()
4345            .expect_err("inconsistent r vs p_h+p_w must fail");
4346        let msg = err.to_string();
4347        assert!(msg.contains("p_h"), "got: {msg}");
4348        assert!(msg.contains("p_w"), "got: {msg}");
4349    }
4350
4351    #[test]
4352    pub(crate) fn validate_rejects_non_monotone_offsets() {
4353        // `minimal_inputs` hard-codes `n_rows = 1`, so the CSR-style row
4354        // pointer length is `n + 1 = 2`. Pin both `offsets[1] = total_cells`
4355        // and `cell_c0.len() = total_cells = 2` from `make_buffers(2, …)`,
4356        // then violate monotonicity by setting `offsets[0] > offsets[1]`;
4357        // every length / per-cell-count check is satisfied so the only
4358        // failure mode left is the monotonicity guard.
4359        let mut buffers = make_buffers(2, 4, 1, 1);
4360        buffers.cell_offsets = vec![5, 2];
4361        let inputs = minimal_inputs(&buffers);
4362        let err = inputs
4363            .validate()
4364            .expect_err("non-monotone offsets must fail");
4365        let msg = err.to_string();
4366        assert!(msg.contains("monotone"), "got: {msg}");
4367    }
4368
4369    #[test]
4370    pub(crate) fn validate_rejects_mismatched_cell_moments_length() {
4371        let mut buffers = make_buffers(2, 4, 1, 1);
4372        buffers.cell_moments.pop(); // length now 2*10 - 1
4373        let inputs = minimal_inputs(&buffers);
4374        let err = inputs.validate().expect_err("short cell_moments must fail");
4375        let msg = err.to_string();
4376        assert!(msg.contains("cell_moments"), "got: {msg}");
4377    }
4378
4379    #[test]
4380    pub(crate) fn launch_on_non_linux_reports_driver_library_unavailable() {
4381        // Mac/Windows builds must surface a typed `DriverLibraryUnavailable`
4382        // rather than panicking or returning Ok. On Linux this test is
4383        // skipped because the kernel actually launches.
4384        #[cfg(target_os = "linux")]
4385        {
4386            if cuda_runtime_for_test("bms_flex_row launch smoke test").is_none() {
4387                return;
4388            }
4389            let buffers = make_buffers(1, 4, 1, 1);
4390            let inputs = minimal_inputs(&buffers);
4391            launch_bms_flex_row_kernel(inputs)
4392                .expect("BMS FLEX row kernel must launch after CUDA admission");
4393        }
4394        #[cfg(not(target_os = "linux"))]
4395        {
4396            let buffers = make_buffers(1, 4, 1, 1);
4397            let inputs = minimal_inputs(&buffers);
4398            match launch_bms_flex_row_kernel(inputs) {
4399                Err(GpuError::DriverLibraryUnavailable { reason }) => {
4400                    assert!(
4401                        reason.contains("Linux-only"),
4402                        "expected Linux-only hint, got: {reason}"
4403                    );
4404                }
4405                other => panic!("expected DriverLibraryUnavailable on non-Linux, got {other:?}"),
4406            }
4407        }
4408    }
4409
4410    #[test]
4411    pub(crate) fn s_f_must_be_positive_and_finite() {
4412        let buffers = make_buffers(1, 4, 1, 1);
4413        let mut inputs = minimal_inputs(&buffers);
4414        inputs.s_f = 0.0;
4415        match launch_bms_flex_row_kernel(inputs) {
4416            Err(GpuError::DriverCallFailed { reason }) => {
4417                assert!(reason.contains("s_f"), "got: {reason}");
4418            }
4419            other => panic!("expected DriverCallFailed for s_f=0, got {other:?}"),
4420        }
4421    }
4422
4423    /// Independent finite-difference correctness lock on the device probit
4424    /// Mills layer — the most optimizer-sensitive, drift-prone term in the
4425    /// whole row kernel (issue #415: "third/fourth-order derivative
4426    /// contractions drift silently … formulas are complex and
4427    /// optimizer-sensitive"). The generated device kernel closes with this
4428    /// Mills algebra:
4429    ///
4430    /// ```text
4431    ///     m       = s · e_obs ;  s = 2y − 1
4432    ///     A       = −w · s · λ(m)
4433    ///     B       =  w · λ(m) · (m + λ(m))
4434    ///     neglog  = −w · log Φ(s · e_obs)
4435    ///     g_u     = A · bar_e_u
4436    ///     H_uv    = B · bar_e_u · bar_e_v + A · bar_e_uv
4437    /// ```
4438    ///
4439    /// Holding the observed derivative jets `bar_e_u`/`bar_e_uv` fixed, the
4440    /// row neglog is a function of the observed predictor VALUE `e := e_obs`,
4441    /// not of the q-axis first derivative `bar_e_u[0]`; by the assembled
4442    /// formula `∂neglog/∂e = A` and `∂²neglog/∂e² = B`. This test reconstructs
4443    /// `A`, `B`, and `neglog` through the canonical host numerics, then verifies the
4444    /// analytic `A`/`B` against high-order central differences of
4445    /// `e ↦ −w · log Φ(s·e)`. A drift in the kernel's Mills derivatives —
4446    /// fails independently of the CPU↔CUDA production parity check. Bounds are
4447    /// the genuine fifth-order central-difference
4448    /// truncation floor; they are not weakened to pass.
4449    #[test]
4450    pub(crate) fn device_mills_layer_matches_finite_differences() {
4451        // Probit neglog as a function of the
4452        // observed scalar predictor `e` with weight `w` and label `y`.
4453        let neglog_of = |e: f64, y: f64, w: f64| -> f64 {
4454            let s = 2.0 * y - 1.0;
4455            let (log_cdf, _) = host_log_ndtr_and_mills(s * e);
4456            -w * log_cdf
4457        };
4458        // Analytic first/second derivatives wrt `e` — the exact `A`/`B` the
4459        // kernel writes into `grad`/`hess`.
4460        let ab_of = |e: f64, y: f64, w: f64| -> (f64, f64) {
4461            let s = 2.0 * y - 1.0;
4462            let m_arg = s * e;
4463            let (_, lambda, probit_curvature) = host_log_ndtr_mills_curvature(m_arg);
4464            let a_i = -w * s * lambda;
4465            let b_i = w * probit_curvature;
4466            (a_i, b_i)
4467        };
4468
4469        // Sweep both labels (s = ±1), both tails of the predictor, and a
4470        // non-unit weight so every sign/scale path of the Mills algebra is
4471        // exercised. Points stay clear of the deep-tail asymptote where a
4472        // central-difference reference loses its own accuracy.
4473        let cases: [(f64, f64, f64); 12] = [
4474            (-1.6, 1.0, 1.0),
4475            (-0.7, 1.0, 1.0),
4476            (0.0, 1.0, 1.0),
4477            (0.9, 1.0, 1.0),
4478            (1.8, 1.0, 1.0),
4479            (-1.4, 0.0, 1.0),
4480            (-0.3, 0.0, 1.0),
4481            (0.0, 0.0, 1.0),
4482            (0.6, 0.0, 1.0),
4483            (1.5, 0.0, 1.0),
4484            (0.4, 1.0, 0.75),
4485            (-0.8, 0.0, 1.3),
4486        ];
4487        // Fifth-order central stencils; `h` chosen near the f64 sweet spot for
4488        // first/second derivatives of a smooth O(1) function.
4489        let h = 1e-3_f64;
4490        for (e, y, w) in cases {
4491            let (a_ana, b_ana) = ab_of(e, y, w);
4492
4493            let fp2 = neglog_of(e + 2.0 * h, y, w);
4494            let fp1 = neglog_of(e + h, y, w);
4495            let f0 = neglog_of(e, y, w);
4496            let fm1 = neglog_of(e - h, y, w);
4497            let fm2 = neglog_of(e - 2.0 * h, y, w);
4498
4499            // 5-point central first derivative: O(h⁴).
4500            let d1_fd = (-fp2 + 8.0 * fp1 - 8.0 * fm1 + fm2) / (12.0 * h);
4501            // 5-point central second derivative: O(h⁴).
4502            let d2_fd = (-fp2 + 16.0 * fp1 - 30.0 * f0 + 16.0 * fm1 - fm2) / (12.0 * h * h);
4503
4504            let a_abs = (a_ana - d1_fd).abs();
4505            let a_rel = a_abs / a_ana.abs().max(1.0);
4506            assert!(
4507                a_abs <= 5e-8 || a_rel <= 5e-8,
4508                "Mills A (∂neglog/∂e) drift at e={e} y={y} w={w}: \
4509                 analytic={a_ana:.17e} fd={d1_fd:.17e} abs={a_abs:.3e} rel={a_rel:.3e}"
4510            );
4511
4512            let b_abs = (b_ana - d2_fd).abs();
4513            let b_rel = b_abs / b_ana.abs().max(1.0);
4514            assert!(
4515                b_abs <= 5e-6 || b_rel <= 5e-6,
4516                "Mills B (∂²neglog/∂e²) drift at e={e} y={y} w={w}: \
4517                 analytic={b_ana:.17e} fd={d2_fd:.17e} abs={b_abs:.3e} rel={b_rel:.3e}"
4518            );
4519        }
4520    }
4521
4522    #[test]
4523    pub(crate) fn generated_source_interprets_compact_canonical_phase_streams() {
4524        let source = generated_row_kernel_source();
4525        assert!(!source.contains("__BMS_FLEX_CALIBRATION_ORDER2__"));
4526        assert!(!source.contains("__BMS_FLEX_ORDER2_FINALIZER__"));
4527        assert!(!source.contains("__BMS_FLEX_ROW_THREADS__"));
4528        assert!(source.contains("for (int u = 1; u < r; ++u)"));
4529        assert!(source.contains("for (int v = u; v < r; ++v)"));
4530        assert!(source.contains("Canonical implicit-first stage complete"));
4531        assert!(source.contains("double *F_u = out_grad + row_r_base"));
4532        assert!(source.contains("double *F_au = row_f_au + row_r_base"));
4533        assert!(source.contains("double *F_uv = out_hess + row_rr_base"));
4534        for forbidden in [
4535            "MAX_R",
4536            "double F_u[",
4537            "double F_au[",
4538            "double F_uv[",
4539            "double a_u[",
4540            "double a_uv[",
4541            "double bar_e_u[",
4542        ] {
4543            assert!(
4544                !source.contains(forbidden),
4545                "generated row source restored width-bound scratch: {forbidden}"
4546            );
4547        }
4548        for forbidden in [
4549            "MAX_R",
4550            "double row_dir[",
4551            "double action[",
4552            "bms_flex_row_hvp_partial_packed",
4553            "bms_flex_row_diag_partial_packed",
4554            "bms_flex_row_pack_upper",
4555        ] {
4556            assert!(
4557                !HVP_KERNEL_SOURCE.contains(forbidden),
4558                "HVP source restored a dead or width-bound path: {forbidden}"
4559            );
4560        }
4561        assert!(HVP_KERNEL_SOURCE.contains("bms_flex_primary_direction"));
4562        assert!(HVP_KERNEL_SOURCE.contains("direction_q[MAX_MULTI_RHS]"));
4563        assert!(HVP_KERNEL_SOURCE.contains("action_g[MAX_MULTI_RHS]"));
4564        let mut cursor = 0usize;
4565        for marker in [
4566            "canonical calibration phase: InterceptFirst",
4567            "canonical calibration phase: InterceptSecond",
4568            "canonical calibration phase: PrimaryFirstAndInterceptSecond",
4569            "canonical calibration phase: PrimaryPairSecond",
4570            "canonical finalizer phase: ImplicitFirst",
4571            "canonical finalizer phase: ImplicitFirstComplete",
4572            "canonical finalizer phase: ImplicitSecond",
4573            "canonical finalizer phase: ObservedFirst",
4574            "canonical finalizer phase: ObservedScoreSensitivity",
4575            "canonical finalizer phase: ObservedSecond",
4576            "canonical finalizer phase: NegLogFirst",
4577        ] {
4578            let relative = source[cursor..]
4579                .find(marker)
4580                .unwrap_or_else(|| panic!("generated CUDA source omitted phase {marker}"));
4581            cursor += relative + marker.len();
4582        }
4583        assert!(
4584            source.len() < 40_000,
4585            "generated CUDA source unexpectedly bloated"
4586        );
4587    }
4588
4589    // ── Phase-3 HVP / diagonal CPU oracles + GPU parity tests ────────────────
4590
4591    /// CPU oracle for [`launch_bms_flex_row_hvp`]. Mirrors the device kernel
4592    /// element-for-element so the GPU parity test runs against the same algebra.
4593    pub(crate) fn cpu_oracle_bms_flex_row_hvp(
4594        row_hessians: &[f64],
4595        marginal_design: &[f64],
4596        logslope_design: &[f64],
4597        block: &BmsFlexBlockLayout,
4598        primary: &BmsFlexPrimaryLayout,
4599        n: usize,
4600        v: &[f64],
4601    ) -> Vec<f64> {
4602        let r = primary.r;
4603        let p_m = block.p_m;
4604        let p_g = block.p_g;
4605        assert_eq!(v.len(), block.p_total);
4606        assert_eq!(row_hessians.len(), n * r * r);
4607        assert_eq!(marginal_design.len(), n * p_m);
4608        assert_eq!(logslope_design.len(), n * p_g);
4609        let mut out = vec![0.0_f64; block.p_total];
4610        let mut row_dir = vec![0.0_f64; r];
4611        let mut action = vec![0.0_f64; r];
4612        for row in 0..n {
4613            let mrow = &marginal_design[row * p_m..(row + 1) * p_m];
4614            let grow = &logslope_design[row * p_g..(row + 1) * p_g];
4615            let mut acc_q = 0.0_f64;
4616            for j in 0..p_m {
4617                acc_q += mrow[j] * v[j];
4618            }
4619            let mut acc_g = 0.0_f64;
4620            for j in 0..p_g {
4621                acc_g += grow[j] * v[p_m + j];
4622            }
4623            row_dir[0] = acc_q;
4624            row_dir[1] = acc_g;
4625            if let (Some(prange), Some(brange)) = (primary.h.as_ref(), block.h.as_ref()) {
4626                for (k, ii) in prange.clone().enumerate() {
4627                    row_dir[ii] = v[brange.start + k];
4628                }
4629            }
4630            if let (Some(prange), Some(brange)) = (primary.w.as_ref(), block.w.as_ref()) {
4631                for (k, ii) in prange.clone().enumerate() {
4632                    row_dir[ii] = v[brange.start + k];
4633                }
4634            }
4635            let h_slice = &row_hessians[row * r * r..(row + 1) * r * r];
4636            for u in 0..r {
4637                let mut acc = 0.0_f64;
4638                for v_idx in 0..r {
4639                    acc += h_slice[u * r + v_idx] * row_dir[v_idx];
4640                }
4641                action[u] = acc;
4642            }
4643            let a0 = action[0];
4644            for j in 0..p_m {
4645                out[j] += a0 * mrow[j];
4646            }
4647            let a1 = action[1];
4648            for j in 0..p_g {
4649                out[p_m + j] += a1 * grow[j];
4650            }
4651            if let (Some(prange), Some(brange)) = (primary.h.as_ref(), block.h.as_ref()) {
4652                for (k, ii) in prange.clone().enumerate() {
4653                    out[brange.start + k] += action[ii];
4654                }
4655            }
4656            if let (Some(prange), Some(brange)) = (primary.w.as_ref(), block.w.as_ref()) {
4657                for (k, ii) in prange.clone().enumerate() {
4658                    out[brange.start + k] += action[ii];
4659                }
4660            }
4661        }
4662        out
4663    }
4664
4665    pub(crate) fn cpu_oracle_bms_flex_row_diagonal(
4666        row_hessians: &[f64],
4667        marginal_design: &[f64],
4668        logslope_design: &[f64],
4669        block: &BmsFlexBlockLayout,
4670        primary: &BmsFlexPrimaryLayout,
4671        n: usize,
4672    ) -> Vec<f64> {
4673        let r = primary.r;
4674        let p_m = block.p_m;
4675        let p_g = block.p_g;
4676        let mut out = vec![0.0_f64; block.p_total];
4677        for row in 0..n {
4678            let h_slice = &row_hessians[row * r * r..(row + 1) * r * r];
4679            let h00 = h_slice[0];
4680            let h11 = h_slice[r + 1];
4681            let mrow = &marginal_design[row * p_m..(row + 1) * p_m];
4682            let grow = &logslope_design[row * p_g..(row + 1) * p_g];
4683            for j in 0..p_m {
4684                out[j] += h00 * mrow[j] * mrow[j];
4685            }
4686            for j in 0..p_g {
4687                out[p_m + j] += h11 * grow[j] * grow[j];
4688            }
4689            if let (Some(prange), Some(brange)) = (primary.h.as_ref(), block.h.as_ref()) {
4690                for (k, ii) in prange.clone().enumerate() {
4691                    out[brange.start + k] += h_slice[ii * r + ii];
4692                }
4693            }
4694            if let (Some(prange), Some(brange)) = (primary.w.as_ref(), block.w.as_ref()) {
4695                for (k, ii) in prange.clone().enumerate() {
4696                    out[brange.start + k] += h_slice[ii * r + ii];
4697                }
4698            }
4699        }
4700        out
4701    }
4702
4703    pub(crate) fn cpu_oracle_bms_flex_row_joint_gradient(
4704        row_neglog: &[f64],
4705        row_grad: &[f64],
4706        marginal_design: &[f64],
4707        logslope_design: &[f64],
4708        block: &BmsFlexBlockLayout,
4709        primary: &BmsFlexPrimaryLayout,
4710        n: usize,
4711    ) -> (f64, Vec<f64>) {
4712        let r = primary.r;
4713        assert_eq!(row_neglog.len(), n);
4714        assert_eq!(row_grad.len(), n * r);
4715        assert_eq!(marginal_design.len(), n * block.p_m);
4716        assert_eq!(logslope_design.len(), n * block.p_g);
4717        let mut log_likelihood = 0.0_f64;
4718        let mut gradient = vec![0.0_f64; block.p_total];
4719        for row in 0..n {
4720            log_likelihood -= row_neglog[row];
4721            let grow = &row_grad[row * r..(row + 1) * r];
4722            for j in 0..block.p_m {
4723                gradient[j] -= grow[0] * marginal_design[row * block.p_m + j];
4724            }
4725            for j in 0..block.p_g {
4726                gradient[block.p_m + j] -= grow[1] * logslope_design[row * block.p_g + j];
4727            }
4728            if let (Some(primary_h), Some(block_h)) = (primary.h.as_ref(), block.h.as_ref()) {
4729                for (offset, primary_idx) in primary_h.clone().enumerate() {
4730                    gradient[block_h.start + offset] -= grow[primary_idx];
4731                }
4732            }
4733            if let (Some(primary_w), Some(block_w)) = (primary.w.as_ref(), block.w.as_ref()) {
4734                for (offset, primary_idx) in primary_w.clone().enumerate() {
4735                    gradient[block_w.start + offset] -= grow[primary_idx];
4736                }
4737            }
4738        }
4739        (log_likelihood, gradient)
4740    }
4741
4742    #[test]
4743    fn cpu_joint_gradient_oracle_pins_score_sign_and_active_hw_pullback() {
4744        let n = 2_usize;
4745        let r = 5_usize;
4746        let block = BmsFlexBlockLayout {
4747            p_m: 2,
4748            p_g: 1,
4749            h: Some(3..5),
4750            w: Some(5..6),
4751            p_total: 6,
4752        };
4753        let primary = BmsFlexPrimaryLayout {
4754            h: Some(2..4),
4755            w: Some(4..5),
4756            r,
4757        };
4758        let row_neglog = [1.25, 0.75];
4759        let row_grad = [
4760            2.0, -3.0, 5.0, -7.0, 11.0, // row 0
4761            -13.0, 17.0, -19.0, 23.0, -29.0, // row 1
4762        ];
4763        let marginal = [1.0, 2.0, -0.5, 3.0];
4764        let logslope = [4.0, -2.0];
4765        let (log_likelihood, gradient) = cpu_oracle_bms_flex_row_joint_gradient(
4766            &row_neglog,
4767            &row_grad,
4768            &marginal,
4769            &logslope,
4770            &block,
4771            &primary,
4772            n,
4773        );
4774        assert_eq!(log_likelihood, -2.0);
4775        assert_eq!(
4776            gradient,
4777            vec![-8.5, 35.0, 46.0, 14.0, -16.0, 18.0],
4778            "joint output must be the score/log-likelihood sign, with h/w direct slots"
4779        );
4780    }
4781
4782    /// Hand-construct a small symmetric per-row Hessian + small designs and
4783    /// verify the CPU oracle satisfies the expected algebra. Platform-
4784    /// independent (runs on macOS / Linux without CUDA).
4785    #[test]
4786    pub(crate) fn cpu_oracle_hvp_matches_hand_computation_no_hw() {
4787        let n = 4_usize;
4788        let r = 4_usize; // q, logslope, h(1), w(1)
4789        let p_m = 2_usize;
4790        let p_g = 2_usize;
4791        let p_h_dim = 1_usize;
4792        let p_w_dim = 1_usize;
4793        let p_total = p_m + p_g + p_h_dim + p_w_dim;
4794        let block = BmsFlexBlockLayout {
4795            p_m,
4796            p_g,
4797            h: Some(p_m + p_g..p_m + p_g + p_h_dim),
4798            w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
4799            p_total,
4800        };
4801        let primary = BmsFlexPrimaryLayout {
4802            h: Some(2..3),
4803            w: Some(3..4),
4804            r,
4805        };
4806        // Symmetric per-row Hessian: H_row[u,v] = (row + 1) * (1 + u + 2v) symmetrised.
4807        let mut row_hessians = vec![0.0_f64; n * r * r];
4808        for row in 0..n {
4809            for u in 0..r {
4810                for v in u..r {
4811                    let val = ((row + 1) as f64) * (1.0 + (u as f64) + 2.0 * (v as f64));
4812                    row_hessians[row * r * r + u * r + v] = val;
4813                    row_hessians[row * r * r + v * r + u] = val;
4814                }
4815            }
4816        }
4817        let mut marginal = vec![0.0_f64; n * p_m];
4818        for row in 0..n {
4819            for j in 0..p_m {
4820                marginal[row * p_m + j] = 0.5 + (row as f64) * 0.1 - (j as f64) * 0.2;
4821            }
4822        }
4823        let mut logslope = vec![0.0_f64; n * p_g];
4824        for row in 0..n {
4825            for j in 0..p_g {
4826                logslope[row * p_g + j] = -0.3 + (row as f64) * 0.05 + (j as f64) * 0.15;
4827            }
4828        }
4829        let v: Vec<f64> = (0..p_total).map(|i| 0.1 + (i as f64) * 0.25).collect();
4830        let out = cpu_oracle_bms_flex_row_hvp(
4831            &row_hessians,
4832            &marginal,
4833            &logslope,
4834            &block,
4835            &primary,
4836            n,
4837            &v,
4838        );
4839        // Hand check the first marginal slot: out[0] = Σ_row action[0]·mrow[0].
4840        let mut expect_out_0 = 0.0_f64;
4841        for row in 0..n {
4842            let mrow = &marginal[row * p_m..(row + 1) * p_m];
4843            let grow = &logslope[row * p_g..(row + 1) * p_g];
4844            let mut row_dir = vec![0.0_f64; r];
4845            row_dir[0] = mrow[0] * v[0] + mrow[1] * v[1];
4846            row_dir[1] = grow[0] * v[p_m] + grow[1] * v[p_m + 1];
4847            row_dir[2] = v[p_m + p_g];
4848            row_dir[3] = v[p_m + p_g + p_h_dim];
4849            let h_slice = &row_hessians[row * r * r..(row + 1) * r * r];
4850            let mut action0 = 0.0_f64;
4851            // h_slice is the row-major r×r Hessian for this row; we want
4852            // row 0, i.e. entries (0, vv) for vv in 0..r, which lives at
4853            // `vv` in the flat layout.
4854            for vv in 0..r {
4855                action0 += h_slice[vv] * row_dir[vv];
4856            }
4857            expect_out_0 += action0 * mrow[0];
4858        }
4859        assert!(
4860            (out[0] - expect_out_0).abs() < 1e-12,
4861            "cpu oracle HVP out[0] mismatch: {} vs hand-check {}",
4862            out[0],
4863            expect_out_0
4864        );
4865        assert!(out.iter().all(|x| x.is_finite()));
4866        assert_eq!(out.len(), p_total);
4867    }
4868
4869    /// Diagonal oracle equals the explicit per-row design² accumulator.
4870    #[test]
4871    pub(crate) fn cpu_oracle_diagonal_matches_hand_computation() {
4872        let n = 3_usize;
4873        let r = 4_usize;
4874        let p_m = 2_usize;
4875        let p_g = 2_usize;
4876        let p_h_dim = 1_usize;
4877        let p_w_dim = 1_usize;
4878        let p_total = p_m + p_g + p_h_dim + p_w_dim;
4879        let block = BmsFlexBlockLayout {
4880            p_m,
4881            p_g,
4882            h: Some(p_m + p_g..p_m + p_g + p_h_dim),
4883            w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
4884            p_total,
4885        };
4886        let primary = BmsFlexPrimaryLayout {
4887            h: Some(2..3),
4888            w: Some(3..4),
4889            r,
4890        };
4891        let mut row_hessians = vec![0.0_f64; n * r * r];
4892        for row in 0..n {
4893            for u in 0..r {
4894                row_hessians[row * r * r + u * r + u] = 1.0 + (row as f64) + (u as f64) * 0.5;
4895            }
4896        }
4897        let mut marginal = vec![0.0_f64; n * p_m];
4898        let mut logslope = vec![0.0_f64; n * p_g];
4899        for row in 0..n {
4900            for j in 0..p_m {
4901                marginal[row * p_m + j] = 0.2 + (row as f64) * 0.3 + (j as f64) * 0.1;
4902            }
4903            for j in 0..p_g {
4904                logslope[row * p_g + j] = -0.4 + (row as f64) * 0.1 + (j as f64) * 0.2;
4905            }
4906        }
4907        let out = cpu_oracle_bms_flex_row_diagonal(
4908            &row_hessians,
4909            &marginal,
4910            &logslope,
4911            &block,
4912            &primary,
4913            n,
4914        );
4915        // Hand check: out[0] = Σ_row H[row,0,0] · marginal[row,0]^2.
4916        let mut expect = 0.0_f64;
4917        for row in 0..n {
4918            let h00 = row_hessians[row * r * r];
4919            expect += h00 * marginal[row * p_m].powi(2);
4920        }
4921        assert!(
4922            (out[0] - expect).abs() < 1e-12,
4923            "out[0] {} vs {}",
4924            out[0],
4925            expect
4926        );
4927        // h slot = sum of H[row, 2, 2] across rows.
4928        let mut expect_h = 0.0_f64;
4929        for row in 0..n {
4930            expect_h += row_hessians[row * r * r + 2 * r + 2];
4931        }
4932        let h_slot = p_m + p_g;
4933        assert!(
4934            (out[h_slot] - expect_h).abs() < 1e-12,
4935            "h slot {} vs {}",
4936            out[h_slot],
4937            expect_h
4938        );
4939    }
4940
4941    /// Mandatory GPU↔CPU parity for every device-resident row consumer at
4942    /// `r=33`, with both direct h/w blocks active.
4943    /// Hand-constructs a small `DeviceResidentRowHess` by
4944    /// allocating the device slices directly, uploading the same arrays the
4945    /// CPU oracle consumes, then dispatching the device kernels.
4946    #[test]
4947    pub(crate) fn bms_flex_row_r33_consumers_match_cpu_oracles_when_cuda_available() {
4948        configure_global_policy(GpuPolicy::Required);
4949        assert_eq!(
4950            gam_gpu::global_policy(),
4951            GpuPolicy::Required,
4952            "fresh-process r=33 consumer parity must claim Required before runtime discovery"
4953        );
4954        gam_gpu::device_runtime::GpuRuntime::require()
4955            .expect("#932 mandatory r=33 consumer CUDA runtime");
4956        let n = 3_usize;
4957        let p_h_dim = 16_usize;
4958        let p_w_dim = 15_usize;
4959        let r = 2 + p_h_dim + p_w_dim;
4960        let p_m = 2_usize;
4961        let p_g = 2_usize;
4962        let p_total = p_m + p_g + p_h_dim + p_w_dim;
4963        let block = BmsFlexBlockLayout {
4964            p_m,
4965            p_g,
4966            h: Some(p_m + p_g..p_m + p_g + p_h_dim),
4967            w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
4968            p_total,
4969        };
4970        let primary = BmsFlexPrimaryLayout {
4971            h: Some(2..2 + p_h_dim),
4972            w: Some(2 + p_h_dim..2 + p_h_dim + p_w_dim),
4973            r,
4974        };
4975        let mut row_hessians = vec![0.0_f64; n * r * r];
4976        for row in 0..n {
4977            for u in 0..r {
4978                for v in u..r {
4979                    let val = 0.001 * ((row + 1) as f64) * (1.0 + (u as f64) + 2.0 * (v as f64));
4980                    row_hessians[row * r * r + u * r + v] = val;
4981                    row_hessians[row * r * r + v * r + u] = val;
4982                }
4983            }
4984        }
4985        let mut marginal = vec![0.0_f64; n * p_m];
4986        for row in 0..n {
4987            for j in 0..p_m {
4988                marginal[row * p_m + j] = 0.5 + (row as f64) * 0.1 - (j as f64) * 0.2;
4989            }
4990        }
4991        let mut logslope = vec![0.0_f64; n * p_g];
4992        for row in 0..n {
4993            for j in 0..p_g {
4994                logslope[row * p_g + j] = -0.3 + (row as f64) * 0.05 + (j as f64) * 0.15;
4995            }
4996        }
4997        let v: Vec<f64> = (0..p_total).map(|i| 0.1 + (i as f64) * 0.25).collect();
4998        let cpu_hvp = cpu_oracle_bms_flex_row_hvp(
4999            &row_hessians,
5000            &marginal,
5001            &logslope,
5002            &block,
5003            &primary,
5004            n,
5005            &v,
5006        );
5007        let cpu_diag = cpu_oracle_bms_flex_row_diagonal(
5008            &row_hessians,
5009            &marginal,
5010            &logslope,
5011            &block,
5012            &primary,
5013            n,
5014        );
5015        let row_neglog = (0..n)
5016            .map(|row| 0.25 + 0.125 * row as f64)
5017            .collect::<Vec<_>>();
5018        let row_grad = (0..n * r)
5019            .map(|index| {
5020                let row = index / r;
5021                let primary_idx = index % r;
5022                (row as f64 + 0.75) * (primary_idx as f64 - 1.25)
5023            })
5024            .collect::<Vec<_>>();
5025        let (cpu_log_likelihood, cpu_gradient) = cpu_oracle_bms_flex_row_joint_gradient(
5026            &row_neglog,
5027            &row_grad,
5028            &marginal,
5029            &logslope,
5030            &block,
5031            &primary,
5032            n,
5033        );
5034        let mut cpu_dense = vec![0.0_f64; p_total * p_total];
5035        for column in 0..p_total {
5036            let mut basis = vec![0.0_f64; p_total];
5037            basis[column] = 1.0;
5038            let image = cpu_oracle_bms_flex_row_hvp(
5039                &row_hessians,
5040                &marginal,
5041                &logslope,
5042                &block,
5043                &primary,
5044                n,
5045                &basis,
5046            );
5047            for (row, value) in image.into_iter().enumerate() {
5048                cpu_dense[row * p_total + column] = value;
5049            }
5050        }
5051
5052        // Allocate a DeviceResidentRowHess by hand using the HVP backend's
5053        // stream + module so we don't need to drive the full BMS row kernel.
5054        // Past the lossless Auto-resolution gate above: a probe/upload failure
5055        // here is a real device fault on a CUDA host, not a no-CUDA skip. Fail
5056        // loud (the device-PCG skip-pass class, eee12f6b2) — the old arms
5057        // returned and the test passed while exercising nothing.
5058        let backend = HvpKernelBackend::probe()
5059            .expect("[bms_flex_row hvp parity] backend probe must succeed on CUDA host");
5060        let stream = backend.stream.clone();
5061        let d_h = stream
5062            .clone_htod(&row_hessians)
5063            .expect("[bms_flex_row hvp parity] upload h must succeed on CUDA host");
5064        let d_m = stream
5065            .clone_htod(&marginal)
5066            .expect("[bms_flex_row hvp parity] upload marg must succeed on CUDA host");
5067        let d_g = stream
5068            .clone_htod(&logslope)
5069            .expect("[bms_flex_row hvp parity] upload logslope must succeed on CUDA host");
5070        let storage = DeviceResidentRowHess {
5071            neglog: stream
5072                .clone_htod(&row_neglog)
5073                .expect("[bms_flex_row hvp parity] upload neglog"),
5074            grad: stream
5075                .clone_htod(&row_grad)
5076                .expect("[bms_flex_row hvp parity] upload grad"),
5077            hess: d_h,
5078            marginal_design: d_m,
5079            logslope_design: d_g,
5080            n,
5081            r,
5082            block: block.clone(),
5083            primary: primary.clone(),
5084
5085            bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
5086                as u64,
5087        };
5088        let gpu_hvp =
5089            launch_bms_flex_row_hvp(&storage, &v).expect("HVP kernel must launch on CUDA host");
5090        let gpu_diag = launch_bms_flex_row_diagonal(&storage)
5091            .expect("diagonal kernel must launch on CUDA host");
5092        let gpu_joint = launch_bms_flex_row_joint_gradient(&storage)
5093            .expect("joint-gradient kernel must launch on CUDA host");
5094        let gpu_dense = launch_bms_flex_row_dense(&storage)
5095            .expect("dense kernel must launch at r=33 on CUDA host");
5096        assert_eq!(gpu_hvp.len(), cpu_hvp.len());
5097        assert_eq!(gpu_diag.len(), cpu_diag.len());
5098        assert_eq!(gpu_joint.gradient.len(), cpu_gradient.len());
5099        assert!(
5100            (gpu_joint.log_likelihood - cpu_log_likelihood).abs() <= 1e-12,
5101            "loglik: cpu={} gpu={}",
5102            cpu_log_likelihood,
5103            gpu_joint.log_likelihood
5104        );
5105        for i in 0..p_total {
5106            let diff = (cpu_hvp[i] - gpu_hvp[i]).abs();
5107            assert!(
5108                diff <= 1e-10,
5109                "HVP[{i}]: cpu={} gpu={} |Δ|={diff:.3e}",
5110                cpu_hvp[i],
5111                gpu_hvp[i]
5112            );
5113            let ddiff = (cpu_diag[i] - gpu_diag[i]).abs();
5114            assert!(
5115                ddiff <= 1e-10,
5116                "diag[{i}]: cpu={} gpu={} |Δ|={ddiff:.3e}",
5117                cpu_diag[i],
5118                gpu_diag[i]
5119            );
5120            let gdiff = (cpu_gradient[i] - gpu_joint.gradient[i]).abs();
5121            assert!(
5122                gdiff <= 1e-10,
5123                "joint gradient[{i}]: cpu={} gpu={} |Δ|={gdiff:.3e}",
5124                cpu_gradient[i],
5125                gpu_joint.gradient[i]
5126            );
5127        }
5128        assert_eq!(gpu_dense.len(), cpu_dense.len());
5129        for (index, (&cpu, &gpu)) in cpu_dense.iter().zip(&gpu_dense).enumerate() {
5130            let tolerance = 1e-10 * (1.0 + cpu.abs());
5131            assert!(
5132                (cpu - gpu).abs() <= tolerance,
5133                "dense[{index}] at r=33: cpu={cpu} gpu={gpu} tolerance={tolerance}"
5134            );
5135        }
5136    }
5137
5138    #[test]
5139    pub(crate) fn bms_flex_row_hvp_multi_scratch_is_bounded_at_large_scale_shape() {
5140        let n = 195_000_usize;
5141        let r = 20_usize;
5142        let p_total = 44_usize;
5143        let rhs_count = 4_usize;
5144        let scratch = bms_flex_row_hvp_multi_scratch_bytes_for_shape(n, p_total, rhs_count)
5145            .expect("large-scale multi-RHS scratch budget");
5146        let per_rhs_full_row_cache =
5147            (n * r * r * std::mem::size_of::<f64>()) as u64 * rhs_count as u64;
5148        assert!(
5149            scratch < per_rhs_full_row_cache / 100,
5150            "multi-RHS scratch must tile by row chunks instead of materializing \
5151             a row-Hessian copy per RHS: scratch={scratch} full_per_rhs={per_rhs_full_row_cache}"
5152        );
5153        assert!(
5154            bms_flex_row_hvp_multi_scratch_bytes_for_shape(
5155                n,
5156                p_total,
5157                BMS_FLEX_ROW_HVP_MAX_RHS + 1
5158            )
5159            .is_err(),
5160            "multi-RHS launch must reject unbounded RHS counts"
5161        );
5162    }
5163
5164    #[test]
5165    pub(crate) fn bms_flex_row_hvp_multi_kernel_matches_cpu_oracle_when_cuda_available() {
5166        if cuda_runtime_for_test("bms_flex_row hvp_multi parity").is_none() {
5167            return;
5168        }
5169        let n = 5_usize;
5170        let r = 4_usize;
5171        let p_m = 2_usize;
5172        let p_g = 2_usize;
5173        let p_h_dim = 1_usize;
5174        let p_w_dim = 1_usize;
5175        let p_total = p_m + p_g + p_h_dim + p_w_dim;
5176        let rhs_count = 3_usize;
5177        let block = BmsFlexBlockLayout {
5178            p_m,
5179            p_g,
5180            h: Some(p_m + p_g..p_m + p_g + p_h_dim),
5181            w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
5182            p_total,
5183        };
5184        let primary = BmsFlexPrimaryLayout {
5185            h: Some(2..3),
5186            w: Some(3..4),
5187            r,
5188        };
5189        let mut row_hessians = vec![0.0_f64; n * r * r];
5190        for row in 0..n {
5191            for u in 0..r {
5192                for v in u..r {
5193                    let val = ((row + 1) as f64) * (1.0 + (u as f64) + 2.0 * (v as f64));
5194                    row_hessians[row * r * r + u * r + v] = val;
5195                    row_hessians[row * r * r + v * r + u] = val;
5196                }
5197            }
5198        }
5199        let mut marginal = vec![0.0_f64; n * p_m];
5200        let mut logslope = vec![0.0_f64; n * p_g];
5201        for row in 0..n {
5202            for j in 0..p_m {
5203                marginal[row * p_m + j] = 0.5 + (row as f64) * 0.1 - (j as f64) * 0.2;
5204            }
5205            for j in 0..p_g {
5206                logslope[row * p_g + j] = -0.3 + (row as f64) * 0.05 + (j as f64) * 0.15;
5207            }
5208        }
5209        let mut v_rhs = vec![0.0_f64; rhs_count * p_total];
5210        for rhs in 0..rhs_count {
5211            for j in 0..p_total {
5212                let seed = (rhs as f64) * 0.37 + (j as f64) * 0.19 + 0.4;
5213                v_rhs[rhs * p_total + j] = seed.sin() * 0.4 + seed.cos() * 0.2;
5214            }
5215        }
5216
5217        // Past the lossless Auto-resolution gate: a probe/upload failure here is a
5218        // real device fault on a CUDA host, not a no-CUDA skip — fail loud
5219        // (device-PCG skip-pass class, eee12f6b2).
5220        let backend = HvpKernelBackend::probe()
5221            .expect("[bms_flex_row hvp_multi parity] backend probe must succeed on CUDA host");
5222        let stream = backend.stream.clone();
5223        let d_h = stream
5224            .clone_htod(&row_hessians)
5225            .expect("[bms_flex_row hvp_multi parity] upload h must succeed on CUDA host");
5226        let d_m = stream
5227            .clone_htod(&marginal)
5228            .expect("[bms_flex_row hvp_multi parity] upload marg must succeed on CUDA host");
5229        let d_g = stream
5230            .clone_htod(&logslope)
5231            .expect("[bms_flex_row hvp_multi parity] upload logslope must succeed on CUDA host");
5232        let storage = DeviceResidentRowHess {
5233            neglog: stream
5234                .alloc_zeros::<f64>(n)
5235                .expect("[bms_flex_row hvp_multi parity] alloc neglog"),
5236            grad: stream
5237                .alloc_zeros::<f64>(n * r)
5238                .expect("[bms_flex_row hvp_multi parity] alloc grad"),
5239            hess: d_h,
5240            marginal_design: d_m,
5241            logslope_design: d_g,
5242            n,
5243            r,
5244            block: block.clone(),
5245            primary: primary.clone(),
5246
5247            bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
5248                as u64,
5249        };
5250        let scratch = bms_flex_row_hvp_multi_scratch_bytes_for_shape(n, p_total, rhs_count)
5251            .expect("storage scratch budget");
5252        assert!(
5253            scratch < storage.bytes,
5254            "multi-RHS scratch should stay below resident cache bytes"
5255        );
5256        let gpu = launch_bms_flex_row_hvp_multi(&storage, &v_rhs, rhs_count)
5257            .expect("multi-RHS HVP kernel must launch on CUDA host");
5258        assert_eq!(gpu.len(), rhs_count * p_total);
5259        for rhs in 0..rhs_count {
5260            let v = &v_rhs[rhs * p_total..(rhs + 1) * p_total];
5261            let cpu = cpu_oracle_bms_flex_row_hvp(
5262                &row_hessians,
5263                &marginal,
5264                &logslope,
5265                &block,
5266                &primary,
5267                n,
5268                v,
5269            );
5270            let single = launch_bms_flex_row_hvp(&storage, v)
5271                .expect("single-RHS HVP kernel must launch on CUDA host");
5272            for j in 0..p_total {
5273                let got = gpu[rhs * p_total + j];
5274                let diff = (cpu[j] - got).abs();
5275                assert!(
5276                    diff <= 1e-10,
5277                    "multi-RHS HVP rhs={rhs} j={j}: cpu={} gpu={} |diff|={diff:.3e}",
5278                    cpu[j],
5279                    got
5280                );
5281                assert_eq!(
5282                    got, single[j],
5283                    "multi-RHS and single-RHS host launch diverged at rhs={rhs} j={j}"
5284                );
5285            }
5286        }
5287    }
5288
5289    /// Parity for the third launch mode — device-output HVP
5290    /// ([`launch_bms_flex_row_hvp_into_device`]) — which the
5291    /// `run_bms_flex_row_partial_reduce` unification routes through the same
5292    /// partial+reduce engine as the host-returning `_hvp` / `_diagonal`
5293    /// adapters. Confirms that keeping the result on-stream (no internal sync /
5294    /// DtoH) reaches bit-identical output to both the CPU oracle and the
5295    /// host-out adapter, so the engine's mode/output split is faithful.
5296    ///
5297    /// Skips cleanly on non-Linux / no-CUDA hosts using the convention shared
5298    /// with the sibling parity tests.
5299    #[test]
5300    pub(crate) fn bms_flex_row_hvp_into_device_matches_cpu_oracle_and_host_out() {
5301        #[cfg(not(target_os = "linux"))]
5302        {
5303            eprintln!(
5304                "[bms_flex_row hvp_into_device parity] non-Linux host — skipping \
5305                 CUDA parity (CPU oracle exercised by sibling tests)"
5306            );
5307        }
5308        #[cfg(target_os = "linux")]
5309        {
5310            if cuda_runtime_for_test("bms_flex_row hvp_into_device parity").is_none() {
5311                return;
5312            }
5313            let n = 4_usize;
5314            let r = 4_usize;
5315            let p_m = 2_usize;
5316            let p_g = 2_usize;
5317            let p_h_dim = 1_usize;
5318            let p_w_dim = 1_usize;
5319            let p_total = p_m + p_g + p_h_dim + p_w_dim;
5320            let block = BmsFlexBlockLayout {
5321                p_m,
5322                p_g,
5323                h: Some(p_m + p_g..p_m + p_g + p_h_dim),
5324                w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
5325                p_total,
5326            };
5327            let primary = BmsFlexPrimaryLayout {
5328                h: Some(2..3),
5329                w: Some(3..4),
5330                r,
5331            };
5332            let mut row_hessians = vec![0.0_f64; n * r * r];
5333            for row in 0..n {
5334                for u in 0..r {
5335                    for v in u..r {
5336                        let val = ((row + 1) as f64) * (1.0 + (u as f64) + 2.0 * (v as f64));
5337                        row_hessians[row * r * r + u * r + v] = val;
5338                        row_hessians[row * r * r + v * r + u] = val;
5339                    }
5340                }
5341            }
5342            let mut marginal = vec![0.0_f64; n * p_m];
5343            for row in 0..n {
5344                for j in 0..p_m {
5345                    marginal[row * p_m + j] = 0.5 + (row as f64) * 0.1 - (j as f64) * 0.2;
5346                }
5347            }
5348            let mut logslope = vec![0.0_f64; n * p_g];
5349            for row in 0..n {
5350                for j in 0..p_g {
5351                    logslope[row * p_g + j] = -0.3 + (row as f64) * 0.05 + (j as f64) * 0.15;
5352                }
5353            }
5354            let v: Vec<f64> = (0..p_total).map(|i| 0.1 + (i as f64) * 0.25).collect();
5355            let cpu_hvp = cpu_oracle_bms_flex_row_hvp(
5356                &row_hessians,
5357                &marginal,
5358                &logslope,
5359                &block,
5360                &primary,
5361                n,
5362                &v,
5363            );
5364
5365            // Past the lossless Auto-resolution gate: probe/upload failures are
5366            // real device faults on a CUDA host — fail loud (device-PCG class).
5367            let backend = HvpKernelBackend::probe().expect(
5368                "[bms_flex_row hvp_into_device parity] backend probe must succeed on CUDA host",
5369            );
5370            let stream = backend.stream.clone();
5371            let d_h = stream
5372                .clone_htod(&row_hessians)
5373                .expect("[bms_flex_row hvp_into_device parity] upload h must succeed on CUDA host");
5374            let d_m = stream.clone_htod(&marginal).expect(
5375                "[bms_flex_row hvp_into_device parity] upload marg must succeed on CUDA host",
5376            );
5377            let d_g = stream.clone_htod(&logslope).expect(
5378                "[bms_flex_row hvp_into_device parity] upload logslope must succeed on CUDA host",
5379            );
5380            let storage = DeviceResidentRowHess {
5381                neglog: stream
5382                    .alloc_zeros::<f64>(n)
5383                    .expect("[bms_flex_row hvp_into_device parity] alloc neglog"),
5384                grad: stream
5385                    .alloc_zeros::<f64>(n * r)
5386                    .expect("[bms_flex_row hvp_into_device parity] alloc grad"),
5387                hess: d_h,
5388                marginal_design: d_m,
5389                logslope_design: d_g,
5390                n,
5391                r,
5392                block: block.clone(),
5393                primary: primary.clone(),
5394
5395                bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
5396                    as u64,
5397            };
5398
5399            // Host-out adapter (allocates its own d_out, syncs + downloads).
5400            let host_out_hvp = launch_bms_flex_row_hvp(&storage, &v)
5401                .expect("host-out HVP kernel must launch on CUDA host");
5402
5403            // Device-out adapter: caller owns d_v + d_out; the engine performs
5404            // no sync / DtoH, so we synchronize + download here.
5405            let d_v = stream
5406                .clone_htod(&v)
5407                .expect("upload direction for device-out HVP");
5408            let mut d_out = stream
5409                .alloc_zeros::<f64>(p_total)
5410                .expect("alloc device-out HVP output");
5411            launch_bms_flex_row_hvp_into_device(&storage, &d_v, &mut d_out)
5412                .expect("device-out HVP kernel must launch on CUDA host");
5413            stream
5414                .synchronize()
5415                .expect("synchronize after device-out HVP");
5416            let device_out_hvp = stream
5417                .clone_dtoh(&d_out)
5418                .expect("download device-out HVP output");
5419
5420            assert_eq!(device_out_hvp.len(), cpu_hvp.len());
5421            assert_eq!(device_out_hvp.len(), host_out_hvp.len());
5422            for i in 0..p_total {
5423                let diff = (cpu_hvp[i] - device_out_hvp[i]).abs();
5424                assert!(
5425                    diff <= 1e-10,
5426                    "device-out HVP[{i}] vs CPU: cpu={} gpu={} |Δ|={diff:.3e}",
5427                    cpu_hvp[i],
5428                    device_out_hvp[i]
5429                );
5430                // Both adapters share the engine; the only difference is the
5431                // copy-back path, so they must be bit-identical.
5432                let host_diff = (host_out_hvp[i] - device_out_hvp[i]).abs();
5433                assert!(
5434                    host_diff == 0.0,
5435                    "device-out vs host-out HVP[{i}]: host={} device={} |Δ|={host_diff:.3e}",
5436                    host_out_hvp[i],
5437                    device_out_hvp[i]
5438                );
5439            }
5440        }
5441    }
5442
5443    /// Block 9 Phase 2 parity gate at the shape specified by the
5444    /// charter task: `n = 64`, `r = 20`, `p_total = 44`. Splits
5445    /// `p_total` as `p_m = 14`, `p_g = 12`, `p_h = 10`, `p_w = 8` so
5446    /// `r = 2 + p_h + p_w = 20` and every primary block participates
5447    /// in both the device pullback and the reduce pass. Tolerance is
5448    /// `|Δ| ≤ 1e-8` per the task description (looser than the 1e-10
5449    /// hand-fixture parity, since accumulation order across HVP CTAs
5450    /// differs from the CPU oracle's row-major sum even with the
5451    /// deterministic reduction policy).
5452    ///
5453    /// Skips cleanly on non-Linux and no-CUDA hosts using the same
5454    /// convention as the hand-fixture parity above.
5455    #[test]
5456    pub(crate) fn bms_flex_row_hvp_kernel_matches_cpu_oracle_at_n64_r20_p44() {
5457        #[cfg(not(target_os = "linux"))]
5458        {
5459            eprintln!(
5460                "[bms_flex_row hvp parity n64_r20_p44] non-Linux host — \
5461                 skipping CUDA parity"
5462            );
5463        }
5464        #[cfg(target_os = "linux")]
5465        {
5466            if cuda_runtime_for_test("bms_flex_row hvp parity n64_r20_p44").is_none() {
5467                return;
5468            }
5469            let n = 64_usize;
5470            let p_m = 14_usize;
5471            let p_g = 12_usize;
5472            let p_h_dim = 10_usize;
5473            let p_w_dim = 8_usize;
5474            let r = 2 + p_h_dim + p_w_dim;
5475            assert_eq!(r, 20);
5476            let p_total = p_m + p_g + p_h_dim + p_w_dim;
5477            assert_eq!(p_total, 44);
5478            let block = BmsFlexBlockLayout {
5479                p_m,
5480                p_g,
5481                h: Some(p_m + p_g..p_m + p_g + p_h_dim),
5482                w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
5483                p_total,
5484            };
5485            let primary = BmsFlexPrimaryLayout {
5486                h: Some(2..2 + p_h_dim),
5487                w: Some(2 + p_h_dim..2 + p_h_dim + p_w_dim),
5488                r,
5489            };
5490
5491            // Deterministic symmetric per-row Hessians + designs +
5492            // direction. Same scrambling family as
5493            // `row_hessian_ops::tests::make_fixture` so any regression
5494            // surfaces consistently across the host-pinned and
5495            // device-resident parity tests.
5496            let mut row_hessians = vec![0.0_f64; n * r * r];
5497            for row in 0..n {
5498                let base = row * r * r;
5499                for u in 0..r {
5500                    for v in 0..r {
5501                        let seed = (row as f64) * 0.137 + (u as f64) * 1.901 + (v as f64) * 0.317;
5502                        let a = (seed.sin() * 1.7 + (seed * 0.5).cos() * 0.9) * 0.5;
5503                        row_hessians[base + u * r + v] = a;
5504                    }
5505                }
5506                for u in 0..r {
5507                    for v in (u + 1)..r {
5508                        let upper = row_hessians[base + u * r + v];
5509                        let lower = row_hessians[base + v * r + u];
5510                        let sym = 0.5 * (upper + lower);
5511                        row_hessians[base + u * r + v] = sym;
5512                        row_hessians[base + v * r + u] = sym;
5513                    }
5514                    row_hessians[base + u * r + u] += r as f64;
5515                }
5516            }
5517            let mut marginal = vec![0.0_f64; n * p_m];
5518            for row in 0..n {
5519                for j in 0..p_m {
5520                    let seed = (row as f64) * 0.073 + (j as f64) * 0.211 + 0.4;
5521                    marginal[row * p_m + j] = seed.sin() * 0.8 - (seed * 0.7).cos() * 0.3;
5522                }
5523            }
5524            let mut logslope = vec![0.0_f64; n * p_g];
5525            for row in 0..n {
5526                for j in 0..p_g {
5527                    let seed = (row as f64) * 0.091 + (j as f64) * 0.179 - 0.2;
5528                    logslope[row * p_g + j] = seed.cos() * 0.7 + (seed * 0.3).sin() * 0.25;
5529                }
5530            }
5531            let v: Vec<f64> = (0..p_total)
5532                .map(|i| {
5533                    let seed = (i as f64) * 0.157 + 0.6;
5534                    seed.sin() * 0.55 + (seed * 0.4).cos() * 0.35
5535                })
5536                .collect();
5537
5538            let cpu_hvp = cpu_oracle_bms_flex_row_hvp(
5539                &row_hessians,
5540                &marginal,
5541                &logslope,
5542                &block,
5543                &primary,
5544                n,
5545                &v,
5546            );
5547            let cpu_diag = cpu_oracle_bms_flex_row_diagonal(
5548                &row_hessians,
5549                &marginal,
5550                &logslope,
5551                &block,
5552                &primary,
5553                n,
5554            );
5555
5556            let backend = match HvpKernelBackend::probe() {
5557                Ok(b) => b,
5558                Err(err) => {
5559                    eprintln!(
5560                        "[bms_flex_row hvp parity n64_r20_p44] backend probe \
5561                         failed: {err}"
5562                    );
5563                    return;
5564                }
5565            };
5566            let stream = backend.stream.clone();
5567            let d_h = match stream.clone_htod(&row_hessians) {
5568                Ok(s) => s,
5569                Err(err) => {
5570                    eprintln!(
5571                        "[bms_flex_row hvp parity n64_r20_p44] upload h \
5572                         failed: {err}"
5573                    );
5574                    return;
5575                }
5576            };
5577            let d_m = match stream.clone_htod(&marginal) {
5578                Ok(s) => s,
5579                Err(err) => {
5580                    eprintln!(
5581                        "[bms_flex_row hvp parity n64_r20_p44] upload marg \
5582                         failed: {err}"
5583                    );
5584                    return;
5585                }
5586            };
5587            let d_g = match stream.clone_htod(&logslope) {
5588                Ok(s) => s,
5589                Err(err) => {
5590                    eprintln!(
5591                        "[bms_flex_row hvp parity n64_r20_p44] upload logslope \
5592                         failed: {err}"
5593                    );
5594                    return;
5595                }
5596            };
5597            let storage = DeviceResidentRowHess {
5598                neglog: stream
5599                    .alloc_zeros::<f64>(n)
5600                    .expect("[bms_flex_row hvp parity n64_r20_p44] alloc neglog"),
5601                grad: stream
5602                    .alloc_zeros::<f64>(n * r)
5603                    .expect("[bms_flex_row hvp parity n64_r20_p44] alloc grad"),
5604                hess: d_h,
5605                marginal_design: d_m,
5606                logslope_design: d_g,
5607                n,
5608                r,
5609                block: block.clone(),
5610                primary: primary.clone(),
5611
5612                bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
5613                    as u64,
5614            };
5615            let gpu_hvp = launch_bms_flex_row_hvp(&storage, &v)
5616                .expect("HVP kernel must launch on CUDA host at n64/r20/p44");
5617            let gpu_diag = launch_bms_flex_row_diagonal(&storage)
5618                .expect("diagonal kernel must launch on CUDA host at n64/r20/p44");
5619            assert_eq!(gpu_hvp.len(), cpu_hvp.len());
5620            assert_eq!(gpu_diag.len(), cpu_diag.len());
5621            for i in 0..p_total {
5622                let diff = (cpu_hvp[i] - gpu_hvp[i]).abs();
5623                assert!(
5624                    diff <= 1e-8,
5625                    "n64_r20_p44 HVP[{i}]: cpu={} gpu={} |Δ|={diff:.3e}",
5626                    cpu_hvp[i],
5627                    gpu_hvp[i]
5628                );
5629                let ddiff = (cpu_diag[i] - gpu_diag[i]).abs();
5630                assert!(
5631                    ddiff <= 1e-8,
5632                    "n64_r20_p44 diag[{i}]: cpu={} gpu={} |Δ|={ddiff:.3e}",
5633                    cpu_diag[i],
5634                    gpu_diag[i]
5635                );
5636            }
5637        }
5638    }
5639
5640    /// Block 9 Phase 6 — small-fixture parity for the dense-block kernel
5641    /// against the host-side P_i pullback oracle.
5642    /// Verifies bit-equality (modulo reduction-order f.p. noise) between
5643    /// the device-resident dense build and the host accumulator over the
5644    /// same per-row Hessian + designs + P_i pullback.
5645    #[test]
5646    pub(crate) fn bms_flex_row_dense_block_kernel_matches_cpu_pullback() {
5647        #[cfg(not(target_os = "linux"))]
5648        {
5649            eprintln!("[bms_flex_row dense_block parity] non-Linux host — skipping CUDA parity");
5650        }
5651        #[cfg(target_os = "linux")]
5652        {
5653            if cuda_runtime_for_test("bms_flex_row dense_block parity").is_none() {
5654                return;
5655            }
5656            // Small fixture: n=24, r=8 (2 + 3 + 3), p_total=18 (4+4+3+3).
5657            // Keeps the CPU pullback fast while still exercising every
5658            // primary slot (q, g, h, w).
5659            let n = 24_usize;
5660            let p_m = 4_usize;
5661            let p_g = 4_usize;
5662            let p_h_dim = 3_usize;
5663            let p_w_dim = 3_usize;
5664            let r = 2 + p_h_dim + p_w_dim;
5665            let p_total = p_m + p_g + p_h_dim + p_w_dim;
5666            let block = BmsFlexBlockLayout {
5667                p_m,
5668                p_g,
5669                h: Some(p_m + p_g..p_m + p_g + p_h_dim),
5670                w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
5671                p_total,
5672            };
5673            let primary = BmsFlexPrimaryLayout {
5674                h: Some(2..2 + p_h_dim),
5675                w: Some(2 + p_h_dim..2 + p_h_dim + p_w_dim),
5676                r,
5677            };
5678
5679            let mut row_hessians = vec![0.0_f64; n * r * r];
5680            for row in 0..n {
5681                let base = row * r * r;
5682                for u in 0..r {
5683                    for v in 0..r {
5684                        let seed = (row as f64) * 0.21 + (u as f64) * 1.13 + (v as f64) * 0.47;
5685                        let a = (seed.sin() * 1.4 + (seed * 0.6).cos() * 0.7) * 0.5;
5686                        row_hessians[base + u * r + v] = a;
5687                    }
5688                }
5689                for u in 0..r {
5690                    for v in (u + 1)..r {
5691                        let upper = row_hessians[base + u * r + v];
5692                        let lower = row_hessians[base + v * r + u];
5693                        let sym = 0.5 * (upper + lower);
5694                        row_hessians[base + u * r + v] = sym;
5695                        row_hessians[base + v * r + u] = sym;
5696                    }
5697                    row_hessians[base + u * r + u] += r as f64;
5698                }
5699            }
5700            let mut marginal = vec![0.0_f64; n * p_m];
5701            for row in 0..n {
5702                for j in 0..p_m {
5703                    let seed = (row as f64) * 0.083 + (j as f64) * 0.171 + 0.31;
5704                    marginal[row * p_m + j] = seed.sin() * 0.7 - (seed * 0.5).cos() * 0.25;
5705                }
5706            }
5707            let mut logslope = vec![0.0_f64; n * p_g];
5708            for row in 0..n {
5709                for j in 0..p_g {
5710                    let seed = (row as f64) * 0.097 + (j as f64) * 0.143 - 0.15;
5711                    logslope[row * p_g + j] = seed.cos() * 0.65 + (seed * 0.4).sin() * 0.2;
5712                }
5713            }
5714
5715            // CPU oracle — same pullback math the device kernel mirrors.
5716            let h_block_start = block.h.as_ref().map(|r| r.start).unwrap_or(0);
5717            let h_block_len = block.h.as_ref().map(|r| r.len()).unwrap_or(0);
5718            let w_block_start = block.w.as_ref().map(|r| r.start).unwrap_or(0);
5719            let w_block_len = block.w.as_ref().map(|r| r.len()).unwrap_or(0);
5720            let h_primary_start = primary.h.as_ref().map(|r| r.start).unwrap_or(0);
5721            let w_primary_start = primary.w.as_ref().map(|r| r.start).unwrap_or(0);
5722            let mut h_cpu = vec![0.0_f64; p_total * p_total];
5723            for row in 0..n {
5724                let mrow = &marginal[row * p_m..(row + 1) * p_m];
5725                let grow = &logslope[row * p_g..(row + 1) * p_g];
5726                let hrow = &row_hessians[row * r * r..(row + 1) * r * r];
5727                // Build per-row phi (r length-p_total vectors).
5728                let mut phi = vec![vec![0.0_f64; p_total]; r];
5729                for k in 0..p_m {
5730                    phi[0][k] = mrow[k];
5731                }
5732                for k in 0..p_g {
5733                    phi[1][p_m + k] = grow[k];
5734                }
5735                for k in 0..h_block_len {
5736                    phi[h_primary_start + k][h_block_start + k] = 1.0;
5737                }
5738                for k in 0..w_block_len {
5739                    phi[w_primary_start + k][w_block_start + k] = 1.0;
5740                }
5741                for u in 0..r {
5742                    for v in 0..r {
5743                        let huv = hrow[u * r + v];
5744                        if huv == 0.0 {
5745                            continue;
5746                        }
5747                        for m in 0..p_total {
5748                            let pm = phi[u][m];
5749                            if pm == 0.0 {
5750                                continue;
5751                            }
5752                            let scaled = huv * pm;
5753                            for nn in 0..p_total {
5754                                h_cpu[m * p_total + nn] += scaled * phi[v][nn];
5755                            }
5756                        }
5757                    }
5758                }
5759            }
5760
5761            // Build a transient device-resident storage and launch the
5762            // dense-block kernel.
5763            // Past the lossless Auto-resolution gate: probe/upload failures are
5764            // real device faults on a CUDA host — fail loud (device-PCG class).
5765            let backend = HvpKernelBackend::probe().expect(
5766                "[bms_flex_row dense_block parity] backend probe must succeed on CUDA host",
5767            );
5768            let stream = backend.stream.clone();
5769            let d_h = stream
5770                .clone_htod(&row_hessians)
5771                .expect("[bms_flex_row dense_block parity] upload h must succeed on CUDA host");
5772            let d_m = stream
5773                .clone_htod(&marginal)
5774                .expect("[bms_flex_row dense_block parity] upload marg must succeed on CUDA host");
5775            let d_g = stream.clone_htod(&logslope).expect(
5776                "[bms_flex_row dense_block parity] upload logslope must succeed on CUDA host",
5777            );
5778            let storage = DeviceResidentRowHess {
5779                neglog: stream
5780                    .alloc_zeros::<f64>(n)
5781                    .expect("[bms_flex_row dense_block parity] alloc neglog"),
5782                grad: stream
5783                    .alloc_zeros::<f64>(n * r)
5784                    .expect("[bms_flex_row dense_block parity] alloc grad"),
5785                hess: d_h,
5786                marginal_design: d_m,
5787                logslope_design: d_g,
5788                n,
5789                r,
5790                block: block.clone(),
5791                primary: primary.clone(),
5792
5793                bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
5794                    as u64,
5795            };
5796            let h_gpu = launch_bms_flex_row_dense_block(&storage)
5797                .expect("dense_block kernel must launch on CUDA host");
5798            assert_eq!(h_gpu.len(), p_total * p_total);
5799
5800            // Compare entry-by-entry with a tolerance that absorbs
5801            // reduction-order f.p. noise from the CTA chunk sum.
5802            let mut max_abs = 0.0_f64;
5803            for i in 0..p_total {
5804                for j in 0..p_total {
5805                    let a = h_cpu[i * p_total + j];
5806                    let b = h_gpu[i * p_total + j];
5807                    let diff = (a - b).abs();
5808                    if diff > max_abs {
5809                        max_abs = diff;
5810                    }
5811                    assert!(
5812                        diff <= 1e-9 * a.abs().max(b.abs()).max(1.0),
5813                        "dense_block[{i},{j}]: cpu={a} gpu={b} |Δ|={diff:.3e}"
5814                    );
5815                }
5816            }
5817            eprintln!(
5818                "[bms_flex_row dense_block parity] n={n} r={r} p={p_total}: max|Δ|={max_abs:.3e}"
5819            );
5820        }
5821    }
5822
5823    #[test]
5824    pub(crate) fn bms_flex_row_dense_hvp_materialization_matches_cpu_above_block_cap_932() {
5825        if cuda_runtime_for_test("bms_flex_row dense HVP parity").is_none() {
5826            return;
5827        }
5828        let n = 1_usize;
5829        let r = 2_usize;
5830        let p_m = 37_usize;
5831        let p_g = 36_usize;
5832        let p_total = p_m + p_g;
5833        assert_eq!(p_total, DENSE_BLOCK_MAX_P + 1);
5834        let block = BmsFlexBlockLayout {
5835            p_m,
5836            p_g,
5837            h: None,
5838            w: None,
5839            p_total,
5840        };
5841        let primary = BmsFlexPrimaryLayout {
5842            h: None,
5843            w: None,
5844            r,
5845        };
5846        let row_hessians = vec![2.5_f64, -0.75, -0.75, 1.25];
5847        let marginal = (0..p_m)
5848            .map(|column| 0.15 + (column as f64 * 0.17).sin())
5849            .collect::<Vec<_>>();
5850        let logslope = (0..p_g)
5851            .map(|column| -0.2 + (column as f64 * 0.11).cos())
5852            .collect::<Vec<_>>();
5853        let mut expected = vec![0.0_f64; p_total * p_total];
5854        for row in 0..p_total {
5855            for column in 0..p_total {
5856                expected[row * p_total + column] = match (row < p_m, column < p_m) {
5857                    (true, true) => row_hessians[0] * marginal[row] * marginal[column],
5858                    (true, false) => row_hessians[1] * marginal[row] * logslope[column - p_m],
5859                    (false, true) => row_hessians[2] * logslope[row - p_m] * marginal[column],
5860                    (false, false) => {
5861                        row_hessians[3] * logslope[row - p_m] * logslope[column - p_m]
5862                    }
5863                };
5864            }
5865        }
5866
5867        let backend = HvpKernelBackend::probe()
5868            .expect("[bms_flex_row dense HVP parity] backend probe must succeed");
5869        let stream = backend.stream.clone();
5870        let storage = DeviceResidentRowHess {
5871            neglog: stream
5872                .alloc_zeros::<f64>(n)
5873                .expect("dense HVP parity neglog allocation"),
5874            grad: stream
5875                .alloc_zeros::<f64>(n * r)
5876                .expect("dense HVP parity grad allocation"),
5877            hess: stream
5878                .clone_htod(&row_hessians)
5879                .expect("dense HVP parity hessian upload"),
5880            marginal_design: stream
5881                .clone_htod(&marginal)
5882                .expect("dense HVP parity marginal upload"),
5883            logslope_design: stream
5884                .clone_htod(&logslope)
5885                .expect("dense HVP parity logslope upload"),
5886            n,
5887            r,
5888            block,
5889            primary,
5890            bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
5891                as u64,
5892        };
5893        let actual = launch_bms_flex_row_dense(&storage)
5894            .expect("wide dense HVP materialization must stay on CUDA");
5895        assert_eq!(actual.len(), expected.len());
5896        for (index, (&actual, &expected)) in actual.iter().zip(&expected).enumerate() {
5897            let tolerance = 1.0e-10 * actual.abs().max(expected.abs()).max(1.0);
5898            assert!(
5899                (actual - expected).abs() <= tolerance,
5900                "wide dense entry {index}: CUDA={actual:.17e} CPU={expected:.17e} tolerance={tolerance:.3e}"
5901            );
5902        }
5903    }
5904
5905    /// Block 9 final hill-climb gate — GPU HVP must be at least 5× faster
5906    /// than a Rayon-parallel CPU HVP at large-scale shape (n=195_000, r=20,
5907    /// p_total=44). This is the charter pass/fail metric for whether the
5908    /// device-resident row-Hessian path is a real perf win for the
5909    /// production marginal-slope fit.
5910    ///
5911    /// Methodology:
5912    ///   * Build the same deterministic fixture as the parity tests.
5913    ///   * GPU: median of `iters` `launch_bms_flex_row_hvp` wall-times
5914    ///     after `warmup` warm-up launches (kernel compile + L2 prime).
5915    ///   * CPU: median of `iters` `cpu_oracle_bms_flex_row_hvp` wall-times,
5916    ///     parallelised over rows via Rayon — this mirrors the actual
5917    ///     production CPU path in
5918    ///     `exact_newton_joint_hessian_matvec_from_cache` (which uses
5919    ///     `ROW_CHUNK_SIZE` chunked `into_par_iter()` for the same
5920    ///     contraction).
5921    ///   * The gate is the calibrated policy's decision that this row count
5922    ///     belongs on the device; cpu_median / gpu_median is a printed perf
5923    ///     record. It asserted `ratio >= 5` until #2487.
5924    ///
5925    /// Skips on non-Linux / no-CUDA hosts.
5926    #[test]
5927    pub(crate) fn bms_flex_row_hvp_dispatch_worthiness_at_large_scale() {
5928        #[cfg(not(target_os = "linux"))]
5929        {
5930            eprintln!("[bms_flex_row hvp hill-climb] non-Linux host — skipping V100 perf gate");
5931        }
5932        #[cfg(target_os = "linux")]
5933        {
5934            let Some(runtime) = cuda_runtime_for_test("bms_flex_row hvp hill-climb") else {
5935                return;
5936            };
5937            let n = 195_000_usize;
5938            let p_m = 14_usize;
5939            let p_g = 12_usize;
5940            let p_h_dim = 10_usize;
5941            let p_w_dim = 8_usize;
5942            let r = 2 + p_h_dim + p_w_dim;
5943            let p_total = p_m + p_g + p_h_dim + p_w_dim;
5944            let block = BmsFlexBlockLayout {
5945                p_m,
5946                p_g,
5947                h: Some(p_m + p_g..p_m + p_g + p_h_dim),
5948                w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
5949                p_total,
5950            };
5951            let primary = BmsFlexPrimaryLayout {
5952                h: Some(2..2 + p_h_dim),
5953                w: Some(2 + p_h_dim..2 + p_h_dim + p_w_dim),
5954                r,
5955            };
5956
5957            // Same deterministic fixture as the Phase 4 large-scale benchmark.
5958            let mut row_hessians = vec![0.0_f64; n * r * r];
5959            for row in 0..n {
5960                let base = row * r * r;
5961                for u in 0..r {
5962                    for vv in 0..r {
5963                        let seed = (row as f64) * 0.137 + (u as f64) * 1.901 + (vv as f64) * 0.317;
5964                        let a = (seed.sin() * 1.7 + (seed * 0.5).cos() * 0.9) * 0.5;
5965                        row_hessians[base + u * r + vv] = a;
5966                    }
5967                }
5968                for u in 0..r {
5969                    for vv in (u + 1)..r {
5970                        let upper = row_hessians[base + u * r + vv];
5971                        let lower = row_hessians[base + vv * r + u];
5972                        let sym = 0.5 * (upper + lower);
5973                        row_hessians[base + u * r + vv] = sym;
5974                        row_hessians[base + vv * r + u] = sym;
5975                    }
5976                    row_hessians[base + u * r + u] += r as f64;
5977                }
5978            }
5979            let mut marginal = vec![0.0_f64; n * p_m];
5980            for row in 0..n {
5981                for j in 0..p_m {
5982                    let seed = (row as f64) * 0.073 + (j as f64) * 0.211 + 0.4;
5983                    marginal[row * p_m + j] = seed.sin() * 0.8 - (seed * 0.7).cos() * 0.3;
5984                }
5985            }
5986            let mut logslope = vec![0.0_f64; n * p_g];
5987            for row in 0..n {
5988                for j in 0..p_g {
5989                    let seed = (row as f64) * 0.091 + (j as f64) * 0.179 - 0.2;
5990                    logslope[row * p_g + j] = seed.cos() * 0.7 + (seed * 0.3).sin() * 0.25;
5991                }
5992            }
5993            let v: Vec<f64> = (0..p_total)
5994                .map(|i| {
5995                    let seed = (i as f64) * 0.157 + 0.6;
5996                    seed.sin() * 0.55 + (seed * 0.4).cos() * 0.35
5997                })
5998                .collect();
5999
6000            // ── GPU side: upload once, time HVP launches ─────────────
6001            let backend = match HvpKernelBackend::probe() {
6002                Ok(b) => b,
6003                Err(err) => {
6004                    eprintln!("[bms_flex_row hvp hill-climb] backend probe failed: {err}");
6005                    return;
6006                }
6007            };
6008            let stream = backend.stream.clone();
6009            let d_h = match stream.clone_htod(&row_hessians) {
6010                Ok(s) => s,
6011                Err(err) => {
6012                    eprintln!("[bms_flex_row hvp hill-climb] upload h failed (likely OOM): {err}");
6013                    return;
6014                }
6015            };
6016            let d_m = match stream.clone_htod(&marginal) {
6017                Ok(s) => s,
6018                Err(err) => {
6019                    eprintln!("[bms_flex_row hvp hill-climb] upload marg failed: {err}");
6020                    return;
6021                }
6022            };
6023            let d_g = match stream.clone_htod(&logslope) {
6024                Ok(s) => s,
6025                Err(err) => {
6026                    eprintln!("[bms_flex_row hvp hill-climb] upload logslope failed: {err}");
6027                    return;
6028                }
6029            };
6030            let storage = DeviceResidentRowHess {
6031                neglog: stream
6032                    .alloc_zeros::<f64>(n)
6033                    .expect("[bms_flex_row hvp hill-climb] alloc neglog"),
6034                grad: stream
6035                    .alloc_zeros::<f64>(n * r)
6036                    .expect("[bms_flex_row hvp hill-climb] alloc grad"),
6037                hess: d_h,
6038                marginal_design: d_m,
6039                logslope_design: d_g,
6040                n,
6041                r,
6042                block: block.clone(),
6043                primary: primary.clone(),
6044
6045                bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
6046                    as u64,
6047            };
6048            let warmup: usize = 3;
6049            let iters: usize = 15;
6050            for _ in 0..warmup {
6051                let out =
6052                    launch_bms_flex_row_hvp(&storage, &v).expect("warmup GPU HVP must launch");
6053                assert_eq!(out.len(), p_total);
6054            }
6055            let mut gpu_us: Vec<u128> = Vec::with_capacity(iters);
6056            for _ in 0..iters {
6057                let t0 = std::time::Instant::now();
6058                let out = launch_bms_flex_row_hvp(&storage, &v).expect("GPU HVP must launch");
6059                gpu_us.push(t0.elapsed().as_micros());
6060                assert_eq!(out.len(), p_total);
6061            }
6062            gpu_us.sort_unstable();
6063            let gpu_median = gpu_us[iters / 2];
6064
6065            // ── CPU side: chunked Rayon HVP over rows, mirroring the
6066            //    production `exact_newton_joint_hessian_matvec_from_cache`
6067            //    parallelisation pattern (ROW_CHUNK_SIZE-row chunks,
6068            //    try_fold + try_reduce). The per-chunk worker calls the
6069            //    single-threaded oracle on its row slice.
6070            const CHUNK_ROWS: usize = 4096;
6071            let cpu_hvp_parallel = || -> Vec<f64> {
6072                let nchunks = n.div_ceil(CHUNK_ROWS);
6073                gam_linalg::pairwise_reduce::par_deterministic_block_fold(
6074                    nchunks,
6075                    |ci_range| {
6076                        let mut acc = vec![0.0_f64; p_total];
6077                        for ci in ci_range {
6078                            let lo = ci * CHUNK_ROWS;
6079                            let hi = (lo + CHUNK_ROWS).min(n);
6080                            let m = hi - lo;
6081                            let partial = cpu_oracle_bms_flex_row_hvp(
6082                                &row_hessians[lo * r * r..hi * r * r],
6083                                &marginal[lo * p_m..hi * p_m],
6084                                &logslope[lo * p_g..hi * p_g],
6085                                &block,
6086                                &primary,
6087                                m,
6088                                &v,
6089                            );
6090                            for (a, &p) in acc.iter_mut().zip(partial.iter()) {
6091                                *a += p;
6092                            }
6093                        }
6094                        acc
6095                    },
6096                    |mut a, b| {
6097                        for (ax, bx) in a.iter_mut().zip(b.iter()) {
6098                            *ax += *bx;
6099                        }
6100                        a
6101                    },
6102                )
6103                .unwrap_or_else(|| vec![0.0_f64; p_total])
6104            };
6105            // Warmup once to populate L3 / steady-state Rayon thread pool.
6106            let warm = cpu_hvp_parallel();
6107            assert_eq!(warm.len(), p_total);
6108            let mut cpu_us: Vec<u128> = Vec::with_capacity(iters);
6109            for _ in 0..iters {
6110                let t0 = std::time::Instant::now();
6111                let out = cpu_hvp_parallel();
6112                cpu_us.push(t0.elapsed().as_micros());
6113                assert_eq!(out.len(), p_total);
6114            }
6115            cpu_us.sort_unstable();
6116            let cpu_median = cpu_us[iters / 2];
6117
6118            let speedup = (cpu_median as f64) / (gpu_median.max(1) as f64);
6119            eprintln!(
6120                "[bms_flex_row hvp hill-climb] large-scale n={n} r={r} p={p_total}: \
6121                 cpu_median={cpu_median}us gpu_median={gpu_median}us \
6122                 speedup={speedup:.2}× (perf record; the gate is the policy decision)"
6123            );
6124            assert_row_batch_dispatch_worthy(
6125                "large-scale HVP dispatch-worthiness gate",
6126                runtime.policy(),
6127                n,
6128            );
6129        }
6130    }
6131
6132    /// Companion to the HVP hill-climb: GPU dense-block build must be at
6133    /// least 10× faster than a Rayon-parallel CPU dense build at large-scale
6134    /// shape. The dense build is `O(n * r² * p_total)` work for both
6135    /// paths so the ratio is well-defined.
6136    #[test]
6137    pub(crate) fn bms_flex_row_dense_block_dispatch_worthiness_at_large_scale() {
6138        #[cfg(not(target_os = "linux"))]
6139        {
6140            eprintln!(
6141                "[bms_flex_row dense_block hill-climb] non-Linux host — skipping V100 perf gate"
6142            );
6143        }
6144        #[cfg(target_os = "linux")]
6145        {
6146            let Some(runtime) = cuda_runtime_for_test("bms_flex_row dense_block hill-climb")
6147            else {
6148                return;
6149            };
6150            let n = 195_000_usize;
6151            let p_m = 14_usize;
6152            let p_g = 12_usize;
6153            let p_h_dim = 10_usize;
6154            let p_w_dim = 8_usize;
6155            let r = 2 + p_h_dim + p_w_dim;
6156            let p_total = p_m + p_g + p_h_dim + p_w_dim;
6157            let block = BmsFlexBlockLayout {
6158                p_m,
6159                p_g,
6160                h: Some(p_m + p_g..p_m + p_g + p_h_dim),
6161                w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
6162                p_total,
6163            };
6164            let primary = BmsFlexPrimaryLayout {
6165                h: Some(2..2 + p_h_dim),
6166                w: Some(2 + p_h_dim..2 + p_h_dim + p_w_dim),
6167                r,
6168            };
6169
6170            // Reuse the same large-scale fixture recipe.
6171            let mut row_hessians = vec![0.0_f64; n * r * r];
6172            for row in 0..n {
6173                let base = row * r * r;
6174                for u in 0..r {
6175                    for vv in 0..r {
6176                        let seed = (row as f64) * 0.137 + (u as f64) * 1.901 + (vv as f64) * 0.317;
6177                        let a = (seed.sin() * 1.7 + (seed * 0.5).cos() * 0.9) * 0.5;
6178                        row_hessians[base + u * r + vv] = a;
6179                    }
6180                }
6181                for u in 0..r {
6182                    for vv in (u + 1)..r {
6183                        let upper = row_hessians[base + u * r + vv];
6184                        let lower = row_hessians[base + vv * r + u];
6185                        let sym = 0.5 * (upper + lower);
6186                        row_hessians[base + u * r + vv] = sym;
6187                        row_hessians[base + vv * r + u] = sym;
6188                    }
6189                    row_hessians[base + u * r + u] += r as f64;
6190                }
6191            }
6192            let mut marginal = vec![0.0_f64; n * p_m];
6193            for row in 0..n {
6194                for j in 0..p_m {
6195                    let seed = (row as f64) * 0.073 + (j as f64) * 0.211 + 0.4;
6196                    marginal[row * p_m + j] = seed.sin() * 0.8 - (seed * 0.7).cos() * 0.3;
6197                }
6198            }
6199            let mut logslope = vec![0.0_f64; n * p_g];
6200            for row in 0..n {
6201                for j in 0..p_g {
6202                    let seed = (row as f64) * 0.091 + (j as f64) * 0.179 - 0.2;
6203                    logslope[row * p_g + j] = seed.cos() * 0.7 + (seed * 0.3).sin() * 0.25;
6204                }
6205            }
6206
6207            // GPU dense_block kernel rejects p_total > DENSE_BLOCK_MAX_P
6208            // (72 at V100 48 KiB/block). LargeScale's p_total = 44 fits.
6209            if p_total > DENSE_BLOCK_MAX_P {
6210                eprintln!(
6211                    "[bms_flex_row dense_block hill-climb] p_total={p_total} > MAX={DENSE_BLOCK_MAX_P}, skipping"
6212                );
6213                return;
6214            }
6215            let backend = match HvpKernelBackend::probe() {
6216                Ok(b) => b,
6217                Err(err) => {
6218                    eprintln!("[bms_flex_row dense_block hill-climb] backend probe failed: {err}");
6219                    return;
6220                }
6221            };
6222            let stream = backend.stream.clone();
6223            let d_h = match stream.clone_htod(&row_hessians) {
6224                Ok(s) => s,
6225                Err(err) => {
6226                    eprintln!("[bms_flex_row dense_block hill-climb] upload h failed: {err}");
6227                    return;
6228                }
6229            };
6230            let d_m = match stream.clone_htod(&marginal) {
6231                Ok(s) => s,
6232                Err(err) => {
6233                    eprintln!("[bms_flex_row dense_block hill-climb] upload marg failed: {err}");
6234                    return;
6235                }
6236            };
6237            let d_g = match stream.clone_htod(&logslope) {
6238                Ok(s) => s,
6239                Err(err) => {
6240                    eprintln!(
6241                        "[bms_flex_row dense_block hill-climb] upload logslope failed: {err}"
6242                    );
6243                    return;
6244                }
6245            };
6246            let storage = DeviceResidentRowHess {
6247                neglog: stream
6248                    .alloc_zeros::<f64>(n)
6249                    .expect("[bms_flex_row dense_block hill-climb] alloc neglog"),
6250                grad: stream
6251                    .alloc_zeros::<f64>(n * r)
6252                    .expect("[bms_flex_row dense_block hill-climb] alloc grad"),
6253                hess: d_h,
6254                marginal_design: d_m,
6255                logslope_design: d_g,
6256                n,
6257                r,
6258                block: block.clone(),
6259                primary: primary.clone(),
6260
6261                bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
6262                    as u64,
6263            };
6264            // Warmup + 5-iter median (dense build is heavier than HVP).
6265            let warmup: usize = 2;
6266            let iters: usize = 5;
6267            for _ in 0..warmup {
6268                let out = launch_bms_flex_row_dense_block(&storage)
6269                    .expect("warmup GPU dense_block must launch");
6270                assert_eq!(out.len(), p_total * p_total);
6271            }
6272            let mut gpu_us: Vec<u128> = Vec::with_capacity(iters);
6273            for _ in 0..iters {
6274                let t0 = std::time::Instant::now();
6275                let out =
6276                    launch_bms_flex_row_dense_block(&storage).expect("GPU dense_block must launch");
6277                gpu_us.push(t0.elapsed().as_micros());
6278                assert_eq!(out.len(), p_total * p_total);
6279            }
6280            gpu_us.sort_unstable();
6281            let gpu_median = gpu_us[iters / 2];
6282
6283            // CPU side: chunked Rayon dense build over rows. Each chunk
6284            // builds a `[p_total, p_total]` partial then we reduce-add.
6285            const CHUNK_ROWS: usize = 2048;
6286            let h_block_start = block.h.as_ref().map(|r| r.start).unwrap_or(0);
6287            let h_block_len = block.h.as_ref().map(|r| r.len()).unwrap_or(0);
6288            let w_block_start = block.w.as_ref().map(|r| r.start).unwrap_or(0);
6289            let w_block_len = block.w.as_ref().map(|r| r.len()).unwrap_or(0);
6290            let h_primary_start = primary.h.as_ref().map(|r| r.start).unwrap_or(0);
6291            let w_primary_start = primary.w.as_ref().map(|r| r.start).unwrap_or(0);
6292            let cpu_build_parallel = || -> Vec<f64> {
6293                let nchunks = n.div_ceil(CHUNK_ROWS);
6294                gam_linalg::pairwise_reduce::par_deterministic_block_fold(
6295                    nchunks,
6296                    |ci_range| {
6297                        let mut acc = vec![0.0_f64; p_total * p_total];
6298                        let mut phi: Vec<Vec<f64>> = vec![vec![0.0_f64; p_total]; r];
6299                        for ci in ci_range {
6300                            let lo = ci * CHUNK_ROWS;
6301                            let hi = (lo + CHUNK_ROWS).min(n);
6302                            for row in lo..hi {
6303                                for col in phi.iter_mut() {
6304                                    col.iter_mut().for_each(|v| *v = 0.0);
6305                                }
6306                                let mrow = &marginal[row * p_m..(row + 1) * p_m];
6307                                let grow = &logslope[row * p_g..(row + 1) * p_g];
6308                                for k in 0..p_m {
6309                                    phi[0][k] = mrow[k];
6310                                }
6311                                for k in 0..p_g {
6312                                    phi[1][p_m + k] = grow[k];
6313                                }
6314                                for k in 0..h_block_len {
6315                                    phi[h_primary_start + k][h_block_start + k] = 1.0;
6316                                }
6317                                for k in 0..w_block_len {
6318                                    phi[w_primary_start + k][w_block_start + k] = 1.0;
6319                                }
6320                                let hrow = &row_hessians[row * r * r..(row + 1) * r * r];
6321                                for u in 0..r {
6322                                    for v_idx in 0..r {
6323                                        let huv = hrow[u * r + v_idx];
6324                                        if huv == 0.0 {
6325                                            continue;
6326                                        }
6327                                        for m in 0..p_total {
6328                                            let pm = phi[u][m];
6329                                            if pm == 0.0 {
6330                                                continue;
6331                                            }
6332                                            let scaled = huv * pm;
6333                                            for nn in 0..p_total {
6334                                                acc[m * p_total + nn] += scaled * phi[v_idx][nn];
6335                                            }
6336                                        }
6337                                    }
6338                                }
6339                            }
6340                        }
6341                        acc
6342                    },
6343                    |mut a, b| {
6344                        for (ax, bx) in a.iter_mut().zip(b.iter()) {
6345                            *ax += *bx;
6346                        }
6347                        a
6348                    },
6349                )
6350                .unwrap_or_else(|| vec![0.0_f64; p_total * p_total])
6351            };
6352            let warm_cpu = cpu_build_parallel();
6353            assert_eq!(warm_cpu.len(), p_total * p_total);
6354            let mut cpu_us: Vec<u128> = Vec::with_capacity(iters);
6355            for _ in 0..iters {
6356                let t0 = std::time::Instant::now();
6357                let out = cpu_build_parallel();
6358                cpu_us.push(t0.elapsed().as_micros());
6359                assert_eq!(out.len(), p_total * p_total);
6360            }
6361            cpu_us.sort_unstable();
6362            let cpu_median = cpu_us[iters / 2];
6363
6364            let speedup = (cpu_median as f64) / (gpu_median.max(1) as f64);
6365            eprintln!(
6366                "[bms_flex_row dense_block hill-climb] large-scale n={n} r={r} p={p_total}: \
6367                 cpu_median={cpu_median}us gpu_median={gpu_median}us \
6368                 speedup={speedup:.2}× (perf record; the gate is the policy decision)"
6369            );
6370            assert_row_batch_dispatch_worthy(
6371                "large-scale dense-H dispatch-worthiness gate",
6372                runtime.policy(),
6373                n,
6374            );
6375        }
6376    }
6377}