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    fn cuda_runtime_for_test(
3691        test_name: &str,
3692    ) -> Option<&'static gam_gpu::device_runtime::GpuRuntime> {
3693        match gam_gpu::device_runtime::GpuRuntime::resolve(GpuPolicy::Auto) {
3694            Ok(Some(runtime)) => Some(runtime),
3695            Ok(None) => {
3696                eprintln!("[{test_name}] no CUDA device — skipping");
3697                None
3698            }
3699            Err(error) => panic!("[{test_name}] CUDA probe failed: {error}"),
3700        }
3701    }
3702
3703    fn assert_array1_close_932(label: &str, expected: &Array1<f64>, actual: &Array1<f64>) {
3704        assert_eq!(expected.len(), actual.len(), "{label}: length mismatch");
3705        for (index, (&want, &got)) in expected.iter().zip(actual).enumerate() {
3706            let tolerance = 2.0e-8 * (1.0 + want.abs());
3707            assert!(
3708                want.is_finite() && got.is_finite() && (want - got).abs() <= tolerance,
3709                "{label}[{index}]: expected={want:.17e} actual={got:.17e} tolerance={tolerance:.3e}"
3710            );
3711        }
3712    }
3713
3714    /// Mandatory A100 acceptance hook. Run this exact test in a fresh process:
3715    /// configuring `Required` is deliberately the first GPU action, and every
3716    /// missing-runtime, probe, upload, launch, synchronization, status, or
3717    /// download failure aborts the test instead of turning into a skip.
3718    #[test]
3719    fn mandatory_required_gpu_workspace_consumes_device_cache_end_to_end_932() {
3720        configure_global_policy(GpuPolicy::Required);
3721        assert_eq!(
3722            gam_gpu::global_policy(),
3723            GpuPolicy::Required,
3724            "fresh-process acceptance test must claim Required before any competing policy"
3725        );
3726        gam_gpu::device_runtime::GpuRuntime::require().expect("#932 mandatory CUDA runtime");
3727
3728        let (family, states) = row_kernel_tests::parity_415::make_flex_parity_family(256, 8, 6);
3729        let mut workspace = BernoulliMarginalSlopeExactNewtonJointHessianWorkspace::new(
3730            family,
3731            states,
3732            BlockwiseFitOptions::default(),
3733        )
3734        .expect("#932 Required workspace must build its device row cache");
3735
3736        assert!(
3737            matches!(
3738                &workspace.cache.row_primary_hessians,
3739                RowPrimaryEvalCache::Device(_)
3740            ),
3741            "Required full-FLEX workspace must retain RowPrimaryEvalCache::Device"
3742        );
3743        {
3744            let device = workspace
3745                .cache
3746                .row_primary_hessians
3747                .device()
3748                .expect("device cache variant");
3749            assert!(
3750                device
3751                    .primary
3752                    .h
3753                    .as_ref()
3754                    .is_some_and(|range| !range.is_empty())
3755                    && device
3756                        .primary
3757                        .w
3758                        .as_ref()
3759                        .is_some_and(|range| !range.is_empty()),
3760                "mandatory fixture must carry active h and w primary blocks"
3761            );
3762            assert!(
3763                device
3764                    .block
3765                    .h
3766                    .as_ref()
3767                    .is_some_and(|range| !range.is_empty())
3768                    && device
3769                        .block
3770                        .w
3771                        .as_ref()
3772                        .is_some_and(|range| !range.is_empty()),
3773                "mandatory fixture must carry active h and w coefficient blocks"
3774            );
3775        }
3776        for operation in ["host HVP replay", "host diagonal replay"] {
3777            let error = workspace
3778                .cache
3779                .row_primary_hessians
3780                .reject_device_cpu_recompute(operation)
3781                .expect_err("a selected device cache must reject host row recomputation");
3782            assert!(
3783                error.contains("device-resident row evaluation selected")
3784                    && error.contains("CPU row recomputation is forbidden"),
3785                "unexpected fail-closed diagnostic: {error}"
3786            );
3787        }
3788
3789        let total = workspace.cache.slices.total;
3790        let direction = Array1::from_shape_fn(total, |index| {
3791            let sign = if index % 2 == 0 { 1.0 } else { -1.0 };
3792            sign * (0.025 + 0.0075 * index as f64)
3793        });
3794        let joint_ll = workspace
3795            .joint_log_likelihood_evaluation()
3796            .expect("device joint log-likelihood")
3797            .expect("device joint log-likelihood must be present");
3798        let joint = workspace
3799            .joint_gradient_evaluation()
3800            .expect("device joint gradient")
3801            .expect("device joint gradient must be present");
3802        assert!(joint_ll.is_finite());
3803        assert_eq!(joint.log_likelihood.to_bits(), joint_ll.to_bits());
3804        assert_eq!(joint.gradient.len(), total);
3805        assert!(joint.gradient.iter().all(|value| value.is_finite()));
3806
3807        let hvp = workspace
3808            .hessian_matvec(&direction)
3809            .expect("device HVP")
3810            .expect("device HVP must be present");
3811        let mut hvp_into = Array1::from_elem(total, f64::NAN);
3812        assert!(
3813            workspace
3814                .hessian_matvec_into(&direction, &mut hvp_into)
3815                .expect("device HVP-into"),
3816            "device HVP-into must report that it handled the direction"
3817        );
3818        assert_array1_close_932("HVP owned/into", &hvp, &hvp_into);
3819
3820        let rhs = Array2::from_shape_fn((total, 3), |(row, column)| {
3821            (row as f64 + 1.0)
3822                * (column as f64 + 0.5)
3823                * 0.011
3824                * if (row + column) % 3 == 0 { -1.0 } else { 1.0 }
3825        });
3826        let mut applied = Array2::<f64>::from_elem((total, rhs.ncols()), f64::NAN);
3827        assert!(
3828            workspace
3829                .hessian_apply_mat(&rhs, &mut applied)
3830                .expect("device multi-RHS apply"),
3831            "device multi-RHS apply must report that it handled the matrix"
3832        );
3833        let diagonal = workspace
3834            .hessian_diagonal()
3835            .expect("device diagonal")
3836            .expect("device diagonal must be present");
3837        let dense = workspace
3838            .hessian_dense_forced()
3839            .expect("device forced dense Hessian")
3840            .expect("device forced dense Hessian must be present");
3841        assert_eq!(dense.dim(), (total, total));
3842        assert_array1_close_932("dense * v / HVP", &dense.dot(&direction), &hvp);
3843        assert_array1_close_932("dense diagonal", &dense.diag().to_owned(), &diagonal);
3844        let dense_applied = dense.dot(&rhs);
3845        for column in 0..rhs.ncols() {
3846            assert_array1_close_932(
3847                &format!("dense * V / apply_mat column {column}"),
3848                &dense_applied.column(column).to_owned(),
3849                &applied.column(column).to_owned(),
3850            );
3851        }
3852
3853        // The resident cache is the numerical authority. Poisoning every host
3854        // block-state number after construction must not alter HVP/diagonal;
3855        // any accidental host replay would either propagate NaNs or error.
3856        for state in &mut workspace.block_states {
3857            state.beta.fill(f64::NAN);
3858            state.eta.fill(f64::NAN);
3859        }
3860        let poisoned_hvp = workspace
3861            .hessian_matvec(&direction)
3862            .expect("device HVP after host-state poison")
3863            .expect("device HVP after host-state poison must be present");
3864        let poisoned_diagonal = workspace
3865            .hessian_diagonal()
3866            .expect("device diagonal after host-state poison")
3867            .expect("device diagonal after host-state poison must be present");
3868        assert_eq!(
3869            hvp.as_slice(),
3870            poisoned_hvp.as_slice(),
3871            "fixed-order device HVP changed after poisoning host block state"
3872        );
3873        assert_eq!(
3874            diagonal.as_slice(),
3875            poisoned_diagonal.as_slice(),
3876            "fixed-order device diagonal changed after poisoning host block state"
3877        );
3878    }
3879
3880    /// Temporary #932 release-only evidence hook. It times the strongest
3881    /// production CPU row batch (the Rayon `build_row_primary_hessian_pin`)
3882    /// against the complete generated GPU row path: host packing, device
3883    /// moment production, every transfer/allocation, row launch, synchronize,
3884    /// and status download. Run this exact test in a fresh release process so
3885    /// `cold_gpu_e2e_nvrtc_ms` includes the first NVRTC loads and the 21 ABBA
3886    /// samples describe only the subsequently cached compiler state.
3887    #[test]
3888    fn release_measure_generated_bms_full_row_vs_strongest_cpu_932() {
3889        const N: usize = 32_768;
3890        const WARMUPS: usize = 3;
3891        const SAMPLES: usize = 21;
3892
3893        configure_global_policy(GpuPolicy::Required);
3894        assert_eq!(gam_gpu::global_policy(), GpuPolicy::Required);
3895        gam_gpu::device_runtime::GpuRuntime::require()
3896            .expect("#932 full-row release measurement requires CUDA");
3897
3898        // Cubic deviation runtimes expose `num_internal_knots + 1` live
3899        // controls since the #2319 knot-selection orbit canonicalization, so
3900        // 9/7 internal knots give p_h=10, p_w=8 — the same r=20 measurement
3901        // shape this cell has always timed.
3902        let (family, states) = row_kernel_tests::parity_415::make_flex_parity_family(N, 9, 7);
3903        let cache = family
3904            .build_exact_eval_cache(&states)
3905            .expect("full-row timing exact cache");
3906        let r = cache.primary.total;
3907        assert_eq!(r, 20, "9/7 knot fixture must expose primary width r=20");
3908        let marginal = family
3909            .marginal_design
3910            .as_dense_ref()
3911            .expect("timing fixture marginal design must be dense");
3912        let logslope = family
3913            .logslope_design
3914            .as_dense_ref()
3915            .expect("timing fixture logslope design must be dense");
3916        assert!(marginal.is_standard_layout() && logslope.is_standard_layout());
3917        let marginal_slice = marginal
3918            .as_slice()
3919            .expect("timing fixture marginal design is contiguous");
3920        let logslope_slice = logslope
3921            .as_slice()
3922            .expect("timing fixture logslope design is contiguous");
3923        let block = BmsFlexBlockLayout {
3924            p_m: cache.slices.marginal.len(),
3925            p_g: cache.slices.logslope.len(),
3926            h: cache.slices.h.clone(),
3927            w: cache.slices.w.clone(),
3928            p_total: cache.slices.total,
3929        };
3930        let primary = BmsFlexPrimaryLayout {
3931            h: cache.primary.h.clone(),
3932            w: cache.primary.w.clone(),
3933            r,
3934        };
3935        assert!(
3936            primary.h.as_ref().is_some_and(|range| !range.is_empty())
3937                && primary.w.as_ref().is_some_and(|range| !range.is_empty()),
3938            "full-row timing fixture must exercise both h and w"
3939        );
3940        let pin_bytes =
3941            crate::bms::family::BernoulliMarginalSlopeFamily::row_primary_eval_tile_bytes(N, r);
3942
3943        let run_cpu = || {
3944            let completed = AtomicUsize::new(0);
3945            family
3946                .build_row_primary_hessian_pin(
3947                    &states,
3948                    &cache,
3949                    0..N,
3950                    &completed,
3951                    N.saturating_add(1),
3952                    Instant::now(),
3953                    pin_bytes,
3954                )
3955                .expect("production Rayon row-primary batch")
3956        };
3957        let run_gpu = || {
3958            let owned = family
3959                .pack_bms_flex_row_kernel_inputs(&states, &cache)
3960                .expect("production BMS GPU packing")
3961                .expect("StandardNormal full-FLEX timing fixture must pack");
3962            launch_bms_flex_row_kernel_device_resident(
3963                owned.as_borrowed(),
3964                marginal_slice,
3965                logslope_slice,
3966                block.clone(),
3967                primary.clone(),
3968            )
3969            .expect("production device-resident row launch")
3970        };
3971        let measure_cpu = || {
3972            let started = Instant::now();
3973            let output = black_box(run_cpu());
3974            (started.elapsed(), output)
3975        };
3976        let measure_gpu = || {
3977            let started = Instant::now();
3978            let output = black_box(run_gpu());
3979            (started.elapsed(), output)
3980        };
3981
3982        let cold_started = Instant::now();
3983        let cold_gpu = black_box(run_gpu());
3984        let cold_gpu_e2e_nvrtc = cold_started.elapsed();
3985        drop(cold_gpu);
3986        for _ in 0..WARMUPS {
3987            black_box(run_cpu());
3988            black_box(run_gpu());
3989        }
3990
3991        let mut cpu_samples = Vec::<Duration>::with_capacity(SAMPLES);
3992        let mut gpu_samples = Vec::<Duration>::with_capacity(SAMPLES);
3993        let mut last_cpu = None;
3994        let mut last_gpu = None;
3995        for sample in 0..SAMPLES {
3996            // Alternating AB/BA pairs yield the repeating ABBA ordering and
3997            // cancel monotone thermal/frequency drift without averaging away
3998            // an individually slow cell.
3999            if sample % 2 == 0 {
4000                let (cpu_elapsed, cpu) = measure_cpu();
4001                cpu_samples.push(cpu_elapsed);
4002                let (gpu_elapsed, gpu) = measure_gpu();
4003                gpu_samples.push(gpu_elapsed);
4004                if sample + 1 == SAMPLES {
4005                    last_cpu = Some(cpu);
4006                    last_gpu = Some(gpu);
4007                }
4008            } else {
4009                let (gpu_elapsed, gpu) = measure_gpu();
4010                gpu_samples.push(gpu_elapsed);
4011                let (cpu_elapsed, cpu) = measure_cpu();
4012                cpu_samples.push(cpu_elapsed);
4013                drop(gpu);
4014                drop(cpu);
4015            }
4016        }
4017        let cpu = last_cpu.expect("final CPU sample retained for parity");
4018        let gpu = last_gpu.expect("final GPU sample retained for parity");
4019
4020        let stream = HvpKernelBackend::probe()
4021            .expect("HVP backend remains available")
4022            .stream
4023            .clone();
4024        let gpu_neglog = stream
4025            .clone_dtoh(&gpu.neglog)
4026            .expect("download timed GPU neglog for parity");
4027        let gpu_grad = stream
4028            .clone_dtoh(&gpu.grad)
4029            .expect("download timed GPU gradient for parity");
4030        let gpu_hess = stream
4031            .clone_dtoh(&gpu.hess)
4032            .expect("download timed GPU Hessian for parity");
4033        let cpu_channels = [
4034            cpu.neglog().as_slice().expect("CPU neglog is contiguous"),
4035            cpu.grad().as_slice().expect("CPU gradient is contiguous"),
4036            cpu.hess().as_slice().expect("CPU Hessian is contiguous"),
4037        ];
4038        let gpu_channels = [
4039            gpu_neglog.as_slice(),
4040            gpu_grad.as_slice(),
4041            gpu_hess.as_slice(),
4042        ];
4043        let mut nonfinite = 0_usize;
4044        let mut max_abs = 0.0_f64;
4045        let mut max_scaled = 0.0_f64;
4046        let mut cpu_digest = 0.0_f64;
4047        let mut gpu_digest = 0.0_f64;
4048        let mut digest_index = 0_usize;
4049        for (cpu_channel, gpu_channel) in cpu_channels.iter().zip(gpu_channels) {
4050            assert_eq!(cpu_channel.len(), gpu_channel.len());
4051            for (&host, &device) in cpu_channel.iter().zip(gpu_channel) {
4052                if !host.is_finite() || !device.is_finite() {
4053                    nonfinite += 1;
4054                }
4055                let difference = (host - device).abs();
4056                let tolerance = 1.0e-8 * (1.0 + host.abs());
4057                max_abs = max_abs.max(difference);
4058                max_scaled = max_scaled.max(difference / tolerance);
4059                let weight = 1.0 + (digest_index % 251) as f64 / 251.0;
4060                cpu_digest += weight * host;
4061                gpu_digest += weight * device;
4062                digest_index += 1;
4063            }
4064        }
4065        assert_eq!(
4066            nonfinite, 0,
4067            "full-row CPU/GPU output contains non-finite values"
4068        );
4069        assert!(
4070            max_scaled <= 1.0,
4071            "full-row CPU/GPU parity exceeded tolerance: max_abs={max_abs:.3e} max_scaled={max_scaled:.3e}"
4072        );
4073
4074        let mut cpu_ms = cpu_samples
4075            .iter()
4076            .map(|sample| sample.as_secs_f64() * 1.0e3)
4077            .collect::<Vec<_>>();
4078        let mut gpu_ms = gpu_samples
4079            .iter()
4080            .map(|sample| sample.as_secs_f64() * 1.0e3)
4081            .collect::<Vec<_>>();
4082        cpu_ms.sort_by(f64::total_cmp);
4083        gpu_ms.sort_by(f64::total_cmp);
4084        let p25 = SAMPLES / 4;
4085        let p50 = SAMPLES / 2;
4086        let p75 = 3 * SAMPLES / 4;
4087        let conservative_speedup = cpu_ms[p25] / gpu_ms[p75];
4088        let median_speedup = cpu_ms[p50] / gpu_ms[p50];
4089        let cpu_distribution = cpu_ms
4090            .iter()
4091            .map(|value| format!("{value:.6}"))
4092            .collect::<Vec<_>>()
4093            .join(",");
4094        let gpu_distribution = gpu_ms
4095            .iter()
4096            .map(|value| format!("{value:.6}"))
4097            .collect::<Vec<_>>()
4098            .join(",");
4099        println!(
4100            "G932_BMS_FULL_ROW n={N} r={r} warmups={WARMUPS} samples={SAMPLES} \
4101             cold_gpu_e2e_nvrtc_ms={:.6} cpu_ms_p25={:.6} cpu_ms_p50={:.6} cpu_ms_p75={:.6} \
4102             gpu_ms_p25={:.6} gpu_ms_p50={:.6} gpu_ms_p75={:.6} \
4103             speedup_conservative_cpu_p25_over_gpu_p75={conservative_speedup:.6} \
4104             speedup_median={median_speedup:.6} parity_max_abs={max_abs:.9e} \
4105             parity_max_scaled={max_scaled:.9e} cpu_digest={cpu_digest:.17e} \
4106             gpu_digest={gpu_digest:.17e} nonfinite={nonfinite} \
4107             cpu_ms_sorted=[{cpu_distribution}] gpu_ms_sorted=[{gpu_distribution}]",
4108            cold_gpu_e2e_nvrtc.as_secs_f64() * 1.0e3,
4109            cpu_ms[p25],
4110            cpu_ms[p50],
4111            cpu_ms[p75],
4112            gpu_ms[p25],
4113            gpu_ms[p50],
4114            gpu_ms[p75],
4115        );
4116    }
4117
4118    #[test]
4119    fn dense_hvp_batches_transpose_column_images_in_bounded_groups_932() {
4120        let p_total = 2 * BMS_FLEX_ROW_HVP_MAX_RHS + 3;
4121        let matrix = (0..p_total * p_total)
4122            .map(|index| {
4123                let row = index / p_total;
4124                let column = index % p_total;
4125                1000.0 * row as f64 + column as f64 + 0.25
4126            })
4127            .collect::<Vec<_>>();
4128        let mut observed_batch_sizes = Vec::new();
4129        let dense = materialize_dense_from_hvp_batches(p_total, |basis, rhs_count| {
4130            observed_batch_sizes.push(rhs_count);
4131            let mut images = vec![0.0_f64; rhs_count * p_total];
4132            for rhs in 0..rhs_count {
4133                for row in 0..p_total {
4134                    images[rhs * p_total + row] = (0..p_total)
4135                        .map(|column| {
4136                            matrix[row * p_total + column] * basis[rhs * p_total + column]
4137                        })
4138                        .sum();
4139                }
4140            }
4141            Ok(images)
4142        })
4143        .expect("synthetic H*I batches must materialize");
4144        assert_eq!(dense, matrix);
4145        assert_eq!(
4146            observed_batch_sizes,
4147            vec![BMS_FLEX_ROW_HVP_MAX_RHS, BMS_FLEX_ROW_HVP_MAX_RHS, 3]
4148        );
4149    }
4150
4151    pub(crate) fn minimal_inputs<'a>(buffers: &'a TestBuffers) -> BmsFlexRowKernelInputs<'a> {
4152        BmsFlexRowKernelInputs {
4153            n_rows: 1,
4154            r: 4,
4155            p_h: 1,
4156            p_w: 1,
4157            q: &buffers.q,
4158            b: &buffers.b,
4159            mu_1: &buffers.mu_1,
4160            mu_2: &buffers.mu_2,
4161            z_obs: &buffers.z_obs,
4162            y: &buffers.y,
4163            w: &buffers.w,
4164            e_obs: &buffers.e_obs,
4165            s_f: 1.0,
4166            cell_offsets: &buffers.cell_offsets,
4167            cell_c0: &buffers.cell_c0,
4168            cell_c1: &buffers.cell_c1,
4169            cell_c2: &buffers.cell_c2,
4170            cell_c3: &buffers.cell_c3,
4171            cell_a: &buffers.cell_a,
4172            cell_aa: &buffers.cell_aa,
4173            cell_r: &buffers.cell_r,
4174            cell_ar: &buffers.cell_ar,
4175            cell_sbb: &buffers.cell_sbb,
4176            cell_sbh: &buffers.cell_sbh,
4177            cell_sbw: &buffers.cell_sbw,
4178            cell_moments: CellMomentsSource::Host(&buffers.cell_moments),
4179            chi_obs: &buffers.chi_obs,
4180            xi_obs: &buffers.xi_obs,
4181            rho_u: &buffers.rho_u,
4182            tau_u: &buffers.tau_u,
4183            r_uv: &buffers.r_uv,
4184        }
4185    }
4186
4187    pub(crate) struct TestBuffers {
4188        pub(crate) q: Vec<f64>,
4189        pub(crate) b: Vec<f64>,
4190        pub(crate) mu_1: Vec<f64>,
4191        pub(crate) mu_2: Vec<f64>,
4192        pub(crate) z_obs: Vec<f64>,
4193        pub(crate) y: Vec<f64>,
4194        pub(crate) w: Vec<f64>,
4195        pub(crate) e_obs: Vec<f64>,
4196        pub(crate) cell_offsets: Vec<u32>,
4197        pub(crate) cell_c0: Vec<f64>,
4198        pub(crate) cell_c1: Vec<f64>,
4199        pub(crate) cell_c2: Vec<f64>,
4200        pub(crate) cell_c3: Vec<f64>,
4201        pub(crate) cell_a: Vec<f64>,
4202        pub(crate) cell_aa: Vec<f64>,
4203        pub(crate) cell_r: Vec<f64>,
4204        pub(crate) cell_ar: Vec<f64>,
4205        pub(crate) cell_sbb: Vec<f64>,
4206        pub(crate) cell_sbh: Vec<f64>,
4207        pub(crate) cell_sbw: Vec<f64>,
4208        pub(crate) cell_moments: Vec<f64>,
4209        pub(crate) chi_obs: Vec<f64>,
4210        pub(crate) xi_obs: Vec<f64>,
4211        pub(crate) rho_u: Vec<f64>,
4212        pub(crate) tau_u: Vec<f64>,
4213        pub(crate) r_uv: Vec<f64>,
4214    }
4215
4216    pub(crate) fn make_buffers(n_cells: u32, r: usize, p_h: usize, p_w: usize) -> TestBuffers {
4217        let cells = n_cells as usize;
4218        TestBuffers {
4219            q: vec![0.1; 1],
4220            b: vec![0.5; 1],
4221            mu_1: vec![0.3; 1],
4222            mu_2: vec![0.07; 1],
4223            z_obs: vec![0.0; 1],
4224            y: vec![1.0; 1],
4225            w: vec![1.0; 1],
4226            e_obs: vec![0.15; 1],
4227            cell_offsets: vec![0, n_cells],
4228            cell_c0: vec![0.2; cells],
4229            cell_c1: vec![-0.1; cells],
4230            cell_c2: vec![0.05; cells],
4231            cell_c3: vec![-0.02; cells],
4232            cell_a: vec![0.1; cells * 4],
4233            cell_aa: vec![0.0; cells * 4],
4234            cell_r: vec![0.05; cells * (r - 1) * 4],
4235            cell_ar: vec![0.0; cells * (r - 1) * 4],
4236            cell_sbb: vec![0.0; cells * 4],
4237            cell_sbh: vec![0.0; cells * p_h * 4],
4238            cell_sbw: vec![0.0; cells * p_w * 4],
4239            cell_moments: vec![1.0; cells * MOMENT_STRIDE],
4240            chi_obs: vec![1.0; 1],
4241            xi_obs: vec![0.0; 1],
4242            rho_u: vec![0.0; r],
4243            tau_u: vec![0.0; r],
4244            r_uv: vec![0.0; r * r],
4245        }
4246    }
4247
4248    #[test]
4249    pub(crate) fn validate_accepts_minimal_inputs() {
4250        let buffers = make_buffers(2, 4, 1, 1);
4251        let inputs = minimal_inputs(&buffers);
4252        assert!(inputs.validate().is_ok());
4253    }
4254
4255    #[test]
4256    pub(crate) fn validate_accepts_r33_with_active_h_and_w_blocks() {
4257        let r = 33;
4258        let p_h = 16;
4259        let p_w = 15;
4260        let buffers = make_buffers(1, r, p_h, p_w);
4261        let inputs = BmsFlexRowKernelInputs {
4262            r,
4263            p_h,
4264            p_w,
4265            rho_u: &buffers.rho_u,
4266            tau_u: &buffers.tau_u,
4267            r_uv: &buffers.r_uv,
4268            cell_r: &buffers.cell_r,
4269            cell_ar: &buffers.cell_ar,
4270            cell_sbh: &buffers.cell_sbh,
4271            cell_sbw: &buffers.cell_sbw,
4272            ..minimal_inputs(&buffers)
4273        };
4274        inputs
4275            .validate()
4276            .expect("r=33 is a valid checked shape, not a semantic width boundary");
4277    }
4278
4279    #[test]
4280    pub(crate) fn checked_shape_len_rejects_arithmetic_overflow() {
4281        let err = checked_shape_len("overflow test", &[usize::MAX, 2])
4282            .expect_err("shape multiplication must fail closed");
4283        assert!(err.to_string().contains("shape product overflow"));
4284    }
4285
4286    #[test]
4287    pub(crate) fn validate_rejects_zero_rows_before_cuda_grid_construction() {
4288        let buffers = make_buffers(1, 4, 1, 1);
4289        let inputs = BmsFlexRowKernelInputs {
4290            n_rows: 0,
4291            ..minimal_inputs(&buffers)
4292        };
4293        let err = inputs
4294            .validate()
4295            .expect_err("zero-row launch must fail closed");
4296        assert!(err.to_string().contains("n_rows must be > 0"));
4297    }
4298
4299    #[test]
4300    pub(crate) fn validate_rejects_mismatched_r_decomposition() {
4301        let buffers = make_buffers(1, 4, 1, 1);
4302        let bad_inputs = BmsFlexRowKernelInputs {
4303            r: 4,
4304            p_h: 1,
4305            p_w: 2, // inconsistent with r = 4
4306            ..minimal_inputs(&buffers)
4307        };
4308        let err = bad_inputs
4309            .validate()
4310            .expect_err("inconsistent r vs p_h+p_w must fail");
4311        let msg = err.to_string();
4312        assert!(msg.contains("p_h"), "got: {msg}");
4313        assert!(msg.contains("p_w"), "got: {msg}");
4314    }
4315
4316    #[test]
4317    pub(crate) fn validate_rejects_non_monotone_offsets() {
4318        // `minimal_inputs` hard-codes `n_rows = 1`, so the CSR-style row
4319        // pointer length is `n + 1 = 2`. Pin both `offsets[1] = total_cells`
4320        // and `cell_c0.len() = total_cells = 2` from `make_buffers(2, …)`,
4321        // then violate monotonicity by setting `offsets[0] > offsets[1]`;
4322        // every length / per-cell-count check is satisfied so the only
4323        // failure mode left is the monotonicity guard.
4324        let mut buffers = make_buffers(2, 4, 1, 1);
4325        buffers.cell_offsets = vec![5, 2];
4326        let inputs = minimal_inputs(&buffers);
4327        let err = inputs
4328            .validate()
4329            .expect_err("non-monotone offsets must fail");
4330        let msg = err.to_string();
4331        assert!(msg.contains("monotone"), "got: {msg}");
4332    }
4333
4334    #[test]
4335    pub(crate) fn validate_rejects_mismatched_cell_moments_length() {
4336        let mut buffers = make_buffers(2, 4, 1, 1);
4337        buffers.cell_moments.pop(); // length now 2*10 - 1
4338        let inputs = minimal_inputs(&buffers);
4339        let err = inputs.validate().expect_err("short cell_moments must fail");
4340        let msg = err.to_string();
4341        assert!(msg.contains("cell_moments"), "got: {msg}");
4342    }
4343
4344    #[test]
4345    pub(crate) fn launch_on_non_linux_reports_driver_library_unavailable() {
4346        // Mac/Windows builds must surface a typed `DriverLibraryUnavailable`
4347        // rather than panicking or returning Ok. On Linux this test is
4348        // skipped because the kernel actually launches.
4349        #[cfg(target_os = "linux")]
4350        {
4351            if cuda_runtime_for_test("bms_flex_row launch smoke test").is_none() {
4352                return;
4353            }
4354            let buffers = make_buffers(1, 4, 1, 1);
4355            let inputs = minimal_inputs(&buffers);
4356            launch_bms_flex_row_kernel(inputs)
4357                .expect("BMS FLEX row kernel must launch after CUDA admission");
4358        }
4359        #[cfg(not(target_os = "linux"))]
4360        {
4361            let buffers = make_buffers(1, 4, 1, 1);
4362            let inputs = minimal_inputs(&buffers);
4363            match launch_bms_flex_row_kernel(inputs) {
4364                Err(GpuError::DriverLibraryUnavailable { reason }) => {
4365                    assert!(
4366                        reason.contains("Linux-only"),
4367                        "expected Linux-only hint, got: {reason}"
4368                    );
4369                }
4370                other => panic!("expected DriverLibraryUnavailable on non-Linux, got {other:?}"),
4371            }
4372        }
4373    }
4374
4375    #[test]
4376    pub(crate) fn s_f_must_be_positive_and_finite() {
4377        let buffers = make_buffers(1, 4, 1, 1);
4378        let mut inputs = minimal_inputs(&buffers);
4379        inputs.s_f = 0.0;
4380        match launch_bms_flex_row_kernel(inputs) {
4381            Err(GpuError::DriverCallFailed { reason }) => {
4382                assert!(reason.contains("s_f"), "got: {reason}");
4383            }
4384            other => panic!("expected DriverCallFailed for s_f=0, got {other:?}"),
4385        }
4386    }
4387
4388    /// Independent finite-difference correctness lock on the device probit
4389    /// Mills layer — the most optimizer-sensitive, drift-prone term in the
4390    /// whole row kernel (issue #415: "third/fourth-order derivative
4391    /// contractions drift silently … formulas are complex and
4392    /// optimizer-sensitive"). The generated device kernel closes with this
4393    /// Mills algebra:
4394    ///
4395    /// ```text
4396    ///     m       = s · e_obs ;  s = 2y − 1
4397    ///     A       = −w · s · λ(m)
4398    ///     B       =  w · λ(m) · (m + λ(m))
4399    ///     neglog  = −w · log Φ(s · e_obs)
4400    ///     g_u     = A · bar_e_u
4401    ///     H_uv    = B · bar_e_u · bar_e_v + A · bar_e_uv
4402    /// ```
4403    ///
4404    /// Holding the observed derivative jets `bar_e_u`/`bar_e_uv` fixed, the
4405    /// row neglog is a function of the observed predictor VALUE `e := e_obs`,
4406    /// not of the q-axis first derivative `bar_e_u[0]`; by the assembled
4407    /// formula `∂neglog/∂e = A` and `∂²neglog/∂e² = B`. This test reconstructs
4408    /// `A`, `B`, and `neglog` through the canonical host numerics, then verifies the
4409    /// analytic `A`/`B` against high-order central differences of
4410    /// `e ↦ −w · log Φ(s·e)`. A drift in the kernel's Mills derivatives —
4411    /// fails independently of the CPU↔CUDA production parity check. Bounds are
4412    /// the genuine fifth-order central-difference
4413    /// truncation floor; they are not weakened to pass.
4414    #[test]
4415    pub(crate) fn device_mills_layer_matches_finite_differences() {
4416        // Probit neglog as a function of the
4417        // observed scalar predictor `e` with weight `w` and label `y`.
4418        let neglog_of = |e: f64, y: f64, w: f64| -> f64 {
4419            let s = 2.0 * y - 1.0;
4420            let (log_cdf, _) = host_log_ndtr_and_mills(s * e);
4421            -w * log_cdf
4422        };
4423        // Analytic first/second derivatives wrt `e` — the exact `A`/`B` the
4424        // kernel writes into `grad`/`hess`.
4425        let ab_of = |e: f64, y: f64, w: f64| -> (f64, f64) {
4426            let s = 2.0 * y - 1.0;
4427            let m_arg = s * e;
4428            let (_, lambda, probit_curvature) = host_log_ndtr_mills_curvature(m_arg);
4429            let a_i = -w * s * lambda;
4430            let b_i = w * probit_curvature;
4431            (a_i, b_i)
4432        };
4433
4434        // Sweep both labels (s = ±1), both tails of the predictor, and a
4435        // non-unit weight so every sign/scale path of the Mills algebra is
4436        // exercised. Points stay clear of the deep-tail asymptote where a
4437        // central-difference reference loses its own accuracy.
4438        let cases: [(f64, f64, f64); 12] = [
4439            (-1.6, 1.0, 1.0),
4440            (-0.7, 1.0, 1.0),
4441            (0.0, 1.0, 1.0),
4442            (0.9, 1.0, 1.0),
4443            (1.8, 1.0, 1.0),
4444            (-1.4, 0.0, 1.0),
4445            (-0.3, 0.0, 1.0),
4446            (0.0, 0.0, 1.0),
4447            (0.6, 0.0, 1.0),
4448            (1.5, 0.0, 1.0),
4449            (0.4, 1.0, 0.75),
4450            (-0.8, 0.0, 1.3),
4451        ];
4452        // Fifth-order central stencils; `h` chosen near the f64 sweet spot for
4453        // first/second derivatives of a smooth O(1) function.
4454        let h = 1e-3_f64;
4455        for (e, y, w) in cases {
4456            let (a_ana, b_ana) = ab_of(e, y, w);
4457
4458            let fp2 = neglog_of(e + 2.0 * h, y, w);
4459            let fp1 = neglog_of(e + h, y, w);
4460            let f0 = neglog_of(e, y, w);
4461            let fm1 = neglog_of(e - h, y, w);
4462            let fm2 = neglog_of(e - 2.0 * h, y, w);
4463
4464            // 5-point central first derivative: O(h⁴).
4465            let d1_fd = (-fp2 + 8.0 * fp1 - 8.0 * fm1 + fm2) / (12.0 * h);
4466            // 5-point central second derivative: O(h⁴).
4467            let d2_fd = (-fp2 + 16.0 * fp1 - 30.0 * f0 + 16.0 * fm1 - fm2) / (12.0 * h * h);
4468
4469            let a_abs = (a_ana - d1_fd).abs();
4470            let a_rel = a_abs / a_ana.abs().max(1.0);
4471            assert!(
4472                a_abs <= 5e-8 || a_rel <= 5e-8,
4473                "Mills A (∂neglog/∂e) drift at e={e} y={y} w={w}: \
4474                 analytic={a_ana:.17e} fd={d1_fd:.17e} abs={a_abs:.3e} rel={a_rel:.3e}"
4475            );
4476
4477            let b_abs = (b_ana - d2_fd).abs();
4478            let b_rel = b_abs / b_ana.abs().max(1.0);
4479            assert!(
4480                b_abs <= 5e-6 || b_rel <= 5e-6,
4481                "Mills B (∂²neglog/∂e²) drift at e={e} y={y} w={w}: \
4482                 analytic={b_ana:.17e} fd={d2_fd:.17e} abs={b_abs:.3e} rel={b_rel:.3e}"
4483            );
4484        }
4485    }
4486
4487    #[test]
4488    pub(crate) fn generated_source_interprets_compact_canonical_phase_streams() {
4489        let source = generated_row_kernel_source();
4490        assert!(!source.contains("__BMS_FLEX_CALIBRATION_ORDER2__"));
4491        assert!(!source.contains("__BMS_FLEX_ORDER2_FINALIZER__"));
4492        assert!(!source.contains("__BMS_FLEX_ROW_THREADS__"));
4493        assert!(source.contains("for (int u = 1; u < r; ++u)"));
4494        assert!(source.contains("for (int v = u; v < r; ++v)"));
4495        assert!(source.contains("Canonical implicit-first stage complete"));
4496        assert!(source.contains("double *F_u = out_grad + row_r_base"));
4497        assert!(source.contains("double *F_au = row_f_au + row_r_base"));
4498        assert!(source.contains("double *F_uv = out_hess + row_rr_base"));
4499        for forbidden in [
4500            "MAX_R",
4501            "double F_u[",
4502            "double F_au[",
4503            "double F_uv[",
4504            "double a_u[",
4505            "double a_uv[",
4506            "double bar_e_u[",
4507        ] {
4508            assert!(
4509                !source.contains(forbidden),
4510                "generated row source restored width-bound scratch: {forbidden}"
4511            );
4512        }
4513        for forbidden in [
4514            "MAX_R",
4515            "double row_dir[",
4516            "double action[",
4517            "bms_flex_row_hvp_partial_packed",
4518            "bms_flex_row_diag_partial_packed",
4519            "bms_flex_row_pack_upper",
4520        ] {
4521            assert!(
4522                !HVP_KERNEL_SOURCE.contains(forbidden),
4523                "HVP source restored a dead or width-bound path: {forbidden}"
4524            );
4525        }
4526        assert!(HVP_KERNEL_SOURCE.contains("bms_flex_primary_direction"));
4527        assert!(HVP_KERNEL_SOURCE.contains("direction_q[MAX_MULTI_RHS]"));
4528        assert!(HVP_KERNEL_SOURCE.contains("action_g[MAX_MULTI_RHS]"));
4529        let mut cursor = 0usize;
4530        for marker in [
4531            "canonical calibration phase: InterceptFirst",
4532            "canonical calibration phase: InterceptSecond",
4533            "canonical calibration phase: PrimaryFirstAndInterceptSecond",
4534            "canonical calibration phase: PrimaryPairSecond",
4535            "canonical finalizer phase: ImplicitFirst",
4536            "canonical finalizer phase: ImplicitFirstComplete",
4537            "canonical finalizer phase: ImplicitSecond",
4538            "canonical finalizer phase: ObservedFirst",
4539            "canonical finalizer phase: ObservedScoreSensitivity",
4540            "canonical finalizer phase: ObservedSecond",
4541            "canonical finalizer phase: NegLogFirst",
4542        ] {
4543            let relative = source[cursor..]
4544                .find(marker)
4545                .unwrap_or_else(|| panic!("generated CUDA source omitted phase {marker}"));
4546            cursor += relative + marker.len();
4547        }
4548        assert!(
4549            source.len() < 40_000,
4550            "generated CUDA source unexpectedly bloated"
4551        );
4552    }
4553
4554    // ── Phase-3 HVP / diagonal CPU oracles + GPU parity tests ────────────────
4555
4556    /// CPU oracle for [`launch_bms_flex_row_hvp`]. Mirrors the device kernel
4557    /// element-for-element so the GPU parity test runs against the same algebra.
4558    pub(crate) fn cpu_oracle_bms_flex_row_hvp(
4559        row_hessians: &[f64],
4560        marginal_design: &[f64],
4561        logslope_design: &[f64],
4562        block: &BmsFlexBlockLayout,
4563        primary: &BmsFlexPrimaryLayout,
4564        n: usize,
4565        v: &[f64],
4566    ) -> Vec<f64> {
4567        let r = primary.r;
4568        let p_m = block.p_m;
4569        let p_g = block.p_g;
4570        assert_eq!(v.len(), block.p_total);
4571        assert_eq!(row_hessians.len(), n * r * r);
4572        assert_eq!(marginal_design.len(), n * p_m);
4573        assert_eq!(logslope_design.len(), n * p_g);
4574        let mut out = vec![0.0_f64; block.p_total];
4575        let mut row_dir = vec![0.0_f64; r];
4576        let mut action = vec![0.0_f64; r];
4577        for row in 0..n {
4578            let mrow = &marginal_design[row * p_m..(row + 1) * p_m];
4579            let grow = &logslope_design[row * p_g..(row + 1) * p_g];
4580            let mut acc_q = 0.0_f64;
4581            for j in 0..p_m {
4582                acc_q += mrow[j] * v[j];
4583            }
4584            let mut acc_g = 0.0_f64;
4585            for j in 0..p_g {
4586                acc_g += grow[j] * v[p_m + j];
4587            }
4588            row_dir[0] = acc_q;
4589            row_dir[1] = acc_g;
4590            if let (Some(prange), Some(brange)) = (primary.h.as_ref(), block.h.as_ref()) {
4591                for (k, ii) in prange.clone().enumerate() {
4592                    row_dir[ii] = v[brange.start + k];
4593                }
4594            }
4595            if let (Some(prange), Some(brange)) = (primary.w.as_ref(), block.w.as_ref()) {
4596                for (k, ii) in prange.clone().enumerate() {
4597                    row_dir[ii] = v[brange.start + k];
4598                }
4599            }
4600            let h_slice = &row_hessians[row * r * r..(row + 1) * r * r];
4601            for u in 0..r {
4602                let mut acc = 0.0_f64;
4603                for v_idx in 0..r {
4604                    acc += h_slice[u * r + v_idx] * row_dir[v_idx];
4605                }
4606                action[u] = acc;
4607            }
4608            let a0 = action[0];
4609            for j in 0..p_m {
4610                out[j] += a0 * mrow[j];
4611            }
4612            let a1 = action[1];
4613            for j in 0..p_g {
4614                out[p_m + j] += a1 * grow[j];
4615            }
4616            if let (Some(prange), Some(brange)) = (primary.h.as_ref(), block.h.as_ref()) {
4617                for (k, ii) in prange.clone().enumerate() {
4618                    out[brange.start + k] += action[ii];
4619                }
4620            }
4621            if let (Some(prange), Some(brange)) = (primary.w.as_ref(), block.w.as_ref()) {
4622                for (k, ii) in prange.clone().enumerate() {
4623                    out[brange.start + k] += action[ii];
4624                }
4625            }
4626        }
4627        out
4628    }
4629
4630    pub(crate) fn cpu_oracle_bms_flex_row_diagonal(
4631        row_hessians: &[f64],
4632        marginal_design: &[f64],
4633        logslope_design: &[f64],
4634        block: &BmsFlexBlockLayout,
4635        primary: &BmsFlexPrimaryLayout,
4636        n: usize,
4637    ) -> Vec<f64> {
4638        let r = primary.r;
4639        let p_m = block.p_m;
4640        let p_g = block.p_g;
4641        let mut out = vec![0.0_f64; block.p_total];
4642        for row in 0..n {
4643            let h_slice = &row_hessians[row * r * r..(row + 1) * r * r];
4644            let h00 = h_slice[0];
4645            let h11 = h_slice[r + 1];
4646            let mrow = &marginal_design[row * p_m..(row + 1) * p_m];
4647            let grow = &logslope_design[row * p_g..(row + 1) * p_g];
4648            for j in 0..p_m {
4649                out[j] += h00 * mrow[j] * mrow[j];
4650            }
4651            for j in 0..p_g {
4652                out[p_m + j] += h11 * grow[j] * grow[j];
4653            }
4654            if let (Some(prange), Some(brange)) = (primary.h.as_ref(), block.h.as_ref()) {
4655                for (k, ii) in prange.clone().enumerate() {
4656                    out[brange.start + k] += h_slice[ii * r + ii];
4657                }
4658            }
4659            if let (Some(prange), Some(brange)) = (primary.w.as_ref(), block.w.as_ref()) {
4660                for (k, ii) in prange.clone().enumerate() {
4661                    out[brange.start + k] += h_slice[ii * r + ii];
4662                }
4663            }
4664        }
4665        out
4666    }
4667
4668    pub(crate) fn cpu_oracle_bms_flex_row_joint_gradient(
4669        row_neglog: &[f64],
4670        row_grad: &[f64],
4671        marginal_design: &[f64],
4672        logslope_design: &[f64],
4673        block: &BmsFlexBlockLayout,
4674        primary: &BmsFlexPrimaryLayout,
4675        n: usize,
4676    ) -> (f64, Vec<f64>) {
4677        let r = primary.r;
4678        assert_eq!(row_neglog.len(), n);
4679        assert_eq!(row_grad.len(), n * r);
4680        assert_eq!(marginal_design.len(), n * block.p_m);
4681        assert_eq!(logslope_design.len(), n * block.p_g);
4682        let mut log_likelihood = 0.0_f64;
4683        let mut gradient = vec![0.0_f64; block.p_total];
4684        for row in 0..n {
4685            log_likelihood -= row_neglog[row];
4686            let grow = &row_grad[row * r..(row + 1) * r];
4687            for j in 0..block.p_m {
4688                gradient[j] -= grow[0] * marginal_design[row * block.p_m + j];
4689            }
4690            for j in 0..block.p_g {
4691                gradient[block.p_m + j] -= grow[1] * logslope_design[row * block.p_g + j];
4692            }
4693            if let (Some(primary_h), Some(block_h)) = (primary.h.as_ref(), block.h.as_ref()) {
4694                for (offset, primary_idx) in primary_h.clone().enumerate() {
4695                    gradient[block_h.start + offset] -= grow[primary_idx];
4696                }
4697            }
4698            if let (Some(primary_w), Some(block_w)) = (primary.w.as_ref(), block.w.as_ref()) {
4699                for (offset, primary_idx) in primary_w.clone().enumerate() {
4700                    gradient[block_w.start + offset] -= grow[primary_idx];
4701                }
4702            }
4703        }
4704        (log_likelihood, gradient)
4705    }
4706
4707    #[test]
4708    fn cpu_joint_gradient_oracle_pins_score_sign_and_active_hw_pullback() {
4709        let n = 2_usize;
4710        let r = 5_usize;
4711        let block = BmsFlexBlockLayout {
4712            p_m: 2,
4713            p_g: 1,
4714            h: Some(3..5),
4715            w: Some(5..6),
4716            p_total: 6,
4717        };
4718        let primary = BmsFlexPrimaryLayout {
4719            h: Some(2..4),
4720            w: Some(4..5),
4721            r,
4722        };
4723        let row_neglog = [1.25, 0.75];
4724        let row_grad = [
4725            2.0, -3.0, 5.0, -7.0, 11.0, // row 0
4726            -13.0, 17.0, -19.0, 23.0, -29.0, // row 1
4727        ];
4728        let marginal = [1.0, 2.0, -0.5, 3.0];
4729        let logslope = [4.0, -2.0];
4730        let (log_likelihood, gradient) = cpu_oracle_bms_flex_row_joint_gradient(
4731            &row_neglog,
4732            &row_grad,
4733            &marginal,
4734            &logslope,
4735            &block,
4736            &primary,
4737            n,
4738        );
4739        assert_eq!(log_likelihood, -2.0);
4740        assert_eq!(
4741            gradient,
4742            vec![-8.5, 35.0, 46.0, 14.0, -16.0, 18.0],
4743            "joint output must be the score/log-likelihood sign, with h/w direct slots"
4744        );
4745    }
4746
4747    /// Hand-construct a small symmetric per-row Hessian + small designs and
4748    /// verify the CPU oracle satisfies the expected algebra. Platform-
4749    /// independent (runs on macOS / Linux without CUDA).
4750    #[test]
4751    pub(crate) fn cpu_oracle_hvp_matches_hand_computation_no_hw() {
4752        let n = 4_usize;
4753        let r = 4_usize; // q, logslope, h(1), w(1)
4754        let p_m = 2_usize;
4755        let p_g = 2_usize;
4756        let p_h_dim = 1_usize;
4757        let p_w_dim = 1_usize;
4758        let p_total = p_m + p_g + p_h_dim + p_w_dim;
4759        let block = BmsFlexBlockLayout {
4760            p_m,
4761            p_g,
4762            h: Some(p_m + p_g..p_m + p_g + p_h_dim),
4763            w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
4764            p_total,
4765        };
4766        let primary = BmsFlexPrimaryLayout {
4767            h: Some(2..3),
4768            w: Some(3..4),
4769            r,
4770        };
4771        // Symmetric per-row Hessian: H_row[u,v] = (row + 1) * (1 + u + 2v) symmetrised.
4772        let mut row_hessians = vec![0.0_f64; n * r * r];
4773        for row in 0..n {
4774            for u in 0..r {
4775                for v in u..r {
4776                    let val = ((row + 1) as f64) * (1.0 + (u as f64) + 2.0 * (v as f64));
4777                    row_hessians[row * r * r + u * r + v] = val;
4778                    row_hessians[row * r * r + v * r + u] = val;
4779                }
4780            }
4781        }
4782        let mut marginal = vec![0.0_f64; n * p_m];
4783        for row in 0..n {
4784            for j in 0..p_m {
4785                marginal[row * p_m + j] = 0.5 + (row as f64) * 0.1 - (j as f64) * 0.2;
4786            }
4787        }
4788        let mut logslope = vec![0.0_f64; n * p_g];
4789        for row in 0..n {
4790            for j in 0..p_g {
4791                logslope[row * p_g + j] = -0.3 + (row as f64) * 0.05 + (j as f64) * 0.15;
4792            }
4793        }
4794        let v: Vec<f64> = (0..p_total).map(|i| 0.1 + (i as f64) * 0.25).collect();
4795        let out = cpu_oracle_bms_flex_row_hvp(
4796            &row_hessians,
4797            &marginal,
4798            &logslope,
4799            &block,
4800            &primary,
4801            n,
4802            &v,
4803        );
4804        // Hand check the first marginal slot: out[0] = Σ_row action[0]·mrow[0].
4805        let mut expect_out_0 = 0.0_f64;
4806        for row in 0..n {
4807            let mrow = &marginal[row * p_m..(row + 1) * p_m];
4808            let grow = &logslope[row * p_g..(row + 1) * p_g];
4809            let mut row_dir = vec![0.0_f64; r];
4810            row_dir[0] = mrow[0] * v[0] + mrow[1] * v[1];
4811            row_dir[1] = grow[0] * v[p_m] + grow[1] * v[p_m + 1];
4812            row_dir[2] = v[p_m + p_g];
4813            row_dir[3] = v[p_m + p_g + p_h_dim];
4814            let h_slice = &row_hessians[row * r * r..(row + 1) * r * r];
4815            let mut action0 = 0.0_f64;
4816            // h_slice is the row-major r×r Hessian for this row; we want
4817            // row 0, i.e. entries (0, vv) for vv in 0..r, which lives at
4818            // `vv` in the flat layout.
4819            for vv in 0..r {
4820                action0 += h_slice[vv] * row_dir[vv];
4821            }
4822            expect_out_0 += action0 * mrow[0];
4823        }
4824        assert!(
4825            (out[0] - expect_out_0).abs() < 1e-12,
4826            "cpu oracle HVP out[0] mismatch: {} vs hand-check {}",
4827            out[0],
4828            expect_out_0
4829        );
4830        assert!(out.iter().all(|x| x.is_finite()));
4831        assert_eq!(out.len(), p_total);
4832    }
4833
4834    /// Diagonal oracle equals the explicit per-row design² accumulator.
4835    #[test]
4836    pub(crate) fn cpu_oracle_diagonal_matches_hand_computation() {
4837        let n = 3_usize;
4838        let r = 4_usize;
4839        let p_m = 2_usize;
4840        let p_g = 2_usize;
4841        let p_h_dim = 1_usize;
4842        let p_w_dim = 1_usize;
4843        let p_total = p_m + p_g + p_h_dim + p_w_dim;
4844        let block = BmsFlexBlockLayout {
4845            p_m,
4846            p_g,
4847            h: Some(p_m + p_g..p_m + p_g + p_h_dim),
4848            w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
4849            p_total,
4850        };
4851        let primary = BmsFlexPrimaryLayout {
4852            h: Some(2..3),
4853            w: Some(3..4),
4854            r,
4855        };
4856        let mut row_hessians = vec![0.0_f64; n * r * r];
4857        for row in 0..n {
4858            for u in 0..r {
4859                row_hessians[row * r * r + u * r + u] = 1.0 + (row as f64) + (u as f64) * 0.5;
4860            }
4861        }
4862        let mut marginal = vec![0.0_f64; n * p_m];
4863        let mut logslope = vec![0.0_f64; n * p_g];
4864        for row in 0..n {
4865            for j in 0..p_m {
4866                marginal[row * p_m + j] = 0.2 + (row as f64) * 0.3 + (j as f64) * 0.1;
4867            }
4868            for j in 0..p_g {
4869                logslope[row * p_g + j] = -0.4 + (row as f64) * 0.1 + (j as f64) * 0.2;
4870            }
4871        }
4872        let out = cpu_oracle_bms_flex_row_diagonal(
4873            &row_hessians,
4874            &marginal,
4875            &logslope,
4876            &block,
4877            &primary,
4878            n,
4879        );
4880        // Hand check: out[0] = Σ_row H[row,0,0] · marginal[row,0]^2.
4881        let mut expect = 0.0_f64;
4882        for row in 0..n {
4883            let h00 = row_hessians[row * r * r];
4884            expect += h00 * marginal[row * p_m].powi(2);
4885        }
4886        assert!(
4887            (out[0] - expect).abs() < 1e-12,
4888            "out[0] {} vs {}",
4889            out[0],
4890            expect
4891        );
4892        // h slot = sum of H[row, 2, 2] across rows.
4893        let mut expect_h = 0.0_f64;
4894        for row in 0..n {
4895            expect_h += row_hessians[row * r * r + 2 * r + 2];
4896        }
4897        let h_slot = p_m + p_g;
4898        assert!(
4899            (out[h_slot] - expect_h).abs() < 1e-12,
4900            "h slot {} vs {}",
4901            out[h_slot],
4902            expect_h
4903        );
4904    }
4905
4906    /// Mandatory GPU↔CPU parity for every device-resident row consumer at
4907    /// `r=33`, with both direct h/w blocks active.
4908    /// Hand-constructs a small `DeviceResidentRowHess` by
4909    /// allocating the device slices directly, uploading the same arrays the
4910    /// CPU oracle consumes, then dispatching the device kernels.
4911    #[test]
4912    pub(crate) fn bms_flex_row_r33_consumers_match_cpu_oracles_when_cuda_available() {
4913        configure_global_policy(GpuPolicy::Required);
4914        assert_eq!(
4915            gam_gpu::global_policy(),
4916            GpuPolicy::Required,
4917            "fresh-process r=33 consumer parity must claim Required before runtime discovery"
4918        );
4919        gam_gpu::device_runtime::GpuRuntime::require()
4920            .expect("#932 mandatory r=33 consumer CUDA runtime");
4921        let n = 3_usize;
4922        let p_h_dim = 16_usize;
4923        let p_w_dim = 15_usize;
4924        let r = 2 + p_h_dim + p_w_dim;
4925        let p_m = 2_usize;
4926        let p_g = 2_usize;
4927        let p_total = p_m + p_g + p_h_dim + p_w_dim;
4928        let block = BmsFlexBlockLayout {
4929            p_m,
4930            p_g,
4931            h: Some(p_m + p_g..p_m + p_g + p_h_dim),
4932            w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
4933            p_total,
4934        };
4935        let primary = BmsFlexPrimaryLayout {
4936            h: Some(2..2 + p_h_dim),
4937            w: Some(2 + p_h_dim..2 + p_h_dim + p_w_dim),
4938            r,
4939        };
4940        let mut row_hessians = vec![0.0_f64; n * r * r];
4941        for row in 0..n {
4942            for u in 0..r {
4943                for v in u..r {
4944                    let val = 0.001 * ((row + 1) as f64) * (1.0 + (u as f64) + 2.0 * (v as f64));
4945                    row_hessians[row * r * r + u * r + v] = val;
4946                    row_hessians[row * r * r + v * r + u] = val;
4947                }
4948            }
4949        }
4950        let mut marginal = vec![0.0_f64; n * p_m];
4951        for row in 0..n {
4952            for j in 0..p_m {
4953                marginal[row * p_m + j] = 0.5 + (row as f64) * 0.1 - (j as f64) * 0.2;
4954            }
4955        }
4956        let mut logslope = vec![0.0_f64; n * p_g];
4957        for row in 0..n {
4958            for j in 0..p_g {
4959                logslope[row * p_g + j] = -0.3 + (row as f64) * 0.05 + (j as f64) * 0.15;
4960            }
4961        }
4962        let v: Vec<f64> = (0..p_total).map(|i| 0.1 + (i as f64) * 0.25).collect();
4963        let cpu_hvp = cpu_oracle_bms_flex_row_hvp(
4964            &row_hessians,
4965            &marginal,
4966            &logslope,
4967            &block,
4968            &primary,
4969            n,
4970            &v,
4971        );
4972        let cpu_diag = cpu_oracle_bms_flex_row_diagonal(
4973            &row_hessians,
4974            &marginal,
4975            &logslope,
4976            &block,
4977            &primary,
4978            n,
4979        );
4980        let row_neglog = (0..n)
4981            .map(|row| 0.25 + 0.125 * row as f64)
4982            .collect::<Vec<_>>();
4983        let row_grad = (0..n * r)
4984            .map(|index| {
4985                let row = index / r;
4986                let primary_idx = index % r;
4987                (row as f64 + 0.75) * (primary_idx as f64 - 1.25)
4988            })
4989            .collect::<Vec<_>>();
4990        let (cpu_log_likelihood, cpu_gradient) = cpu_oracle_bms_flex_row_joint_gradient(
4991            &row_neglog,
4992            &row_grad,
4993            &marginal,
4994            &logslope,
4995            &block,
4996            &primary,
4997            n,
4998        );
4999        let mut cpu_dense = vec![0.0_f64; p_total * p_total];
5000        for column in 0..p_total {
5001            let mut basis = vec![0.0_f64; p_total];
5002            basis[column] = 1.0;
5003            let image = cpu_oracle_bms_flex_row_hvp(
5004                &row_hessians,
5005                &marginal,
5006                &logslope,
5007                &block,
5008                &primary,
5009                n,
5010                &basis,
5011            );
5012            for (row, value) in image.into_iter().enumerate() {
5013                cpu_dense[row * p_total + column] = value;
5014            }
5015        }
5016
5017        // Allocate a DeviceResidentRowHess by hand using the HVP backend's
5018        // stream + module so we don't need to drive the full BMS row kernel.
5019        // Past the lossless Auto-resolution gate above: a probe/upload failure
5020        // here is a real device fault on a CUDA host, not a no-CUDA skip. Fail
5021        // loud (the device-PCG skip-pass class, eee12f6b2) — the old arms
5022        // returned and the test passed while exercising nothing.
5023        let backend = HvpKernelBackend::probe()
5024            .expect("[bms_flex_row hvp parity] backend probe must succeed on CUDA host");
5025        let stream = backend.stream.clone();
5026        let d_h = stream
5027            .clone_htod(&row_hessians)
5028            .expect("[bms_flex_row hvp parity] upload h must succeed on CUDA host");
5029        let d_m = stream
5030            .clone_htod(&marginal)
5031            .expect("[bms_flex_row hvp parity] upload marg must succeed on CUDA host");
5032        let d_g = stream
5033            .clone_htod(&logslope)
5034            .expect("[bms_flex_row hvp parity] upload logslope must succeed on CUDA host");
5035        let storage = DeviceResidentRowHess {
5036            neglog: stream
5037                .clone_htod(&row_neglog)
5038                .expect("[bms_flex_row hvp parity] upload neglog"),
5039            grad: stream
5040                .clone_htod(&row_grad)
5041                .expect("[bms_flex_row hvp parity] upload grad"),
5042            hess: d_h,
5043            marginal_design: d_m,
5044            logslope_design: d_g,
5045            n,
5046            r,
5047            block: block.clone(),
5048            primary: primary.clone(),
5049
5050            bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
5051                as u64,
5052        };
5053        let gpu_hvp =
5054            launch_bms_flex_row_hvp(&storage, &v).expect("HVP kernel must launch on CUDA host");
5055        let gpu_diag = launch_bms_flex_row_diagonal(&storage)
5056            .expect("diagonal kernel must launch on CUDA host");
5057        let gpu_joint = launch_bms_flex_row_joint_gradient(&storage)
5058            .expect("joint-gradient kernel must launch on CUDA host");
5059        let gpu_dense = launch_bms_flex_row_dense(&storage)
5060            .expect("dense kernel must launch at r=33 on CUDA host");
5061        assert_eq!(gpu_hvp.len(), cpu_hvp.len());
5062        assert_eq!(gpu_diag.len(), cpu_diag.len());
5063        assert_eq!(gpu_joint.gradient.len(), cpu_gradient.len());
5064        assert!(
5065            (gpu_joint.log_likelihood - cpu_log_likelihood).abs() <= 1e-12,
5066            "loglik: cpu={} gpu={}",
5067            cpu_log_likelihood,
5068            gpu_joint.log_likelihood
5069        );
5070        for i in 0..p_total {
5071            let diff = (cpu_hvp[i] - gpu_hvp[i]).abs();
5072            assert!(
5073                diff <= 1e-10,
5074                "HVP[{i}]: cpu={} gpu={} |Δ|={diff:.3e}",
5075                cpu_hvp[i],
5076                gpu_hvp[i]
5077            );
5078            let ddiff = (cpu_diag[i] - gpu_diag[i]).abs();
5079            assert!(
5080                ddiff <= 1e-10,
5081                "diag[{i}]: cpu={} gpu={} |Δ|={ddiff:.3e}",
5082                cpu_diag[i],
5083                gpu_diag[i]
5084            );
5085            let gdiff = (cpu_gradient[i] - gpu_joint.gradient[i]).abs();
5086            assert!(
5087                gdiff <= 1e-10,
5088                "joint gradient[{i}]: cpu={} gpu={} |Δ|={gdiff:.3e}",
5089                cpu_gradient[i],
5090                gpu_joint.gradient[i]
5091            );
5092        }
5093        assert_eq!(gpu_dense.len(), cpu_dense.len());
5094        for (index, (&cpu, &gpu)) in cpu_dense.iter().zip(&gpu_dense).enumerate() {
5095            let tolerance = 1e-10 * (1.0 + cpu.abs());
5096            assert!(
5097                (cpu - gpu).abs() <= tolerance,
5098                "dense[{index}] at r=33: cpu={cpu} gpu={gpu} tolerance={tolerance}"
5099            );
5100        }
5101    }
5102
5103    #[test]
5104    pub(crate) fn bms_flex_row_hvp_multi_scratch_is_bounded_at_large_scale_shape() {
5105        let n = 195_000_usize;
5106        let r = 20_usize;
5107        let p_total = 44_usize;
5108        let rhs_count = 4_usize;
5109        let scratch = bms_flex_row_hvp_multi_scratch_bytes_for_shape(n, p_total, rhs_count)
5110            .expect("large-scale multi-RHS scratch budget");
5111        let per_rhs_full_row_cache =
5112            (n * r * r * std::mem::size_of::<f64>()) as u64 * rhs_count as u64;
5113        assert!(
5114            scratch < per_rhs_full_row_cache / 100,
5115            "multi-RHS scratch must tile by row chunks instead of materializing \
5116             a row-Hessian copy per RHS: scratch={scratch} full_per_rhs={per_rhs_full_row_cache}"
5117        );
5118        assert!(
5119            bms_flex_row_hvp_multi_scratch_bytes_for_shape(
5120                n,
5121                p_total,
5122                BMS_FLEX_ROW_HVP_MAX_RHS + 1
5123            )
5124            .is_err(),
5125            "multi-RHS launch must reject unbounded RHS counts"
5126        );
5127    }
5128
5129    #[test]
5130    pub(crate) fn bms_flex_row_hvp_multi_kernel_matches_cpu_oracle_when_cuda_available() {
5131        if cuda_runtime_for_test("bms_flex_row hvp_multi parity").is_none() {
5132            return;
5133        }
5134        let n = 5_usize;
5135        let r = 4_usize;
5136        let p_m = 2_usize;
5137        let p_g = 2_usize;
5138        let p_h_dim = 1_usize;
5139        let p_w_dim = 1_usize;
5140        let p_total = p_m + p_g + p_h_dim + p_w_dim;
5141        let rhs_count = 3_usize;
5142        let block = BmsFlexBlockLayout {
5143            p_m,
5144            p_g,
5145            h: Some(p_m + p_g..p_m + p_g + p_h_dim),
5146            w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
5147            p_total,
5148        };
5149        let primary = BmsFlexPrimaryLayout {
5150            h: Some(2..3),
5151            w: Some(3..4),
5152            r,
5153        };
5154        let mut row_hessians = vec![0.0_f64; n * r * r];
5155        for row in 0..n {
5156            for u in 0..r {
5157                for v in u..r {
5158                    let val = ((row + 1) as f64) * (1.0 + (u as f64) + 2.0 * (v as f64));
5159                    row_hessians[row * r * r + u * r + v] = val;
5160                    row_hessians[row * r * r + v * r + u] = val;
5161                }
5162            }
5163        }
5164        let mut marginal = vec![0.0_f64; n * p_m];
5165        let mut logslope = vec![0.0_f64; n * p_g];
5166        for row in 0..n {
5167            for j in 0..p_m {
5168                marginal[row * p_m + j] = 0.5 + (row as f64) * 0.1 - (j as f64) * 0.2;
5169            }
5170            for j in 0..p_g {
5171                logslope[row * p_g + j] = -0.3 + (row as f64) * 0.05 + (j as f64) * 0.15;
5172            }
5173        }
5174        let mut v_rhs = vec![0.0_f64; rhs_count * p_total];
5175        for rhs in 0..rhs_count {
5176            for j in 0..p_total {
5177                let seed = (rhs as f64) * 0.37 + (j as f64) * 0.19 + 0.4;
5178                v_rhs[rhs * p_total + j] = seed.sin() * 0.4 + seed.cos() * 0.2;
5179            }
5180        }
5181
5182        // Past the lossless Auto-resolution gate: a probe/upload failure here is a
5183        // real device fault on a CUDA host, not a no-CUDA skip — fail loud
5184        // (device-PCG skip-pass class, eee12f6b2).
5185        let backend = HvpKernelBackend::probe()
5186            .expect("[bms_flex_row hvp_multi parity] backend probe must succeed on CUDA host");
5187        let stream = backend.stream.clone();
5188        let d_h = stream
5189            .clone_htod(&row_hessians)
5190            .expect("[bms_flex_row hvp_multi parity] upload h must succeed on CUDA host");
5191        let d_m = stream
5192            .clone_htod(&marginal)
5193            .expect("[bms_flex_row hvp_multi parity] upload marg must succeed on CUDA host");
5194        let d_g = stream
5195            .clone_htod(&logslope)
5196            .expect("[bms_flex_row hvp_multi parity] upload logslope must succeed on CUDA host");
5197        let storage = DeviceResidentRowHess {
5198            neglog: stream
5199                .alloc_zeros::<f64>(n)
5200                .expect("[bms_flex_row hvp_multi parity] alloc neglog"),
5201            grad: stream
5202                .alloc_zeros::<f64>(n * r)
5203                .expect("[bms_flex_row hvp_multi parity] alloc grad"),
5204            hess: d_h,
5205            marginal_design: d_m,
5206            logslope_design: d_g,
5207            n,
5208            r,
5209            block: block.clone(),
5210            primary: primary.clone(),
5211
5212            bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
5213                as u64,
5214        };
5215        let scratch = bms_flex_row_hvp_multi_scratch_bytes_for_shape(n, p_total, rhs_count)
5216            .expect("storage scratch budget");
5217        assert!(
5218            scratch < storage.bytes,
5219            "multi-RHS scratch should stay below resident cache bytes"
5220        );
5221        let gpu = launch_bms_flex_row_hvp_multi(&storage, &v_rhs, rhs_count)
5222            .expect("multi-RHS HVP kernel must launch on CUDA host");
5223        assert_eq!(gpu.len(), rhs_count * p_total);
5224        for rhs in 0..rhs_count {
5225            let v = &v_rhs[rhs * p_total..(rhs + 1) * p_total];
5226            let cpu = cpu_oracle_bms_flex_row_hvp(
5227                &row_hessians,
5228                &marginal,
5229                &logslope,
5230                &block,
5231                &primary,
5232                n,
5233                v,
5234            );
5235            let single = launch_bms_flex_row_hvp(&storage, v)
5236                .expect("single-RHS HVP kernel must launch on CUDA host");
5237            for j in 0..p_total {
5238                let got = gpu[rhs * p_total + j];
5239                let diff = (cpu[j] - got).abs();
5240                assert!(
5241                    diff <= 1e-10,
5242                    "multi-RHS HVP rhs={rhs} j={j}: cpu={} gpu={} |diff|={diff:.3e}",
5243                    cpu[j],
5244                    got
5245                );
5246                assert_eq!(
5247                    got, single[j],
5248                    "multi-RHS and single-RHS host launch diverged at rhs={rhs} j={j}"
5249                );
5250            }
5251        }
5252    }
5253
5254    /// Parity for the third launch mode — device-output HVP
5255    /// ([`launch_bms_flex_row_hvp_into_device`]) — which the
5256    /// `run_bms_flex_row_partial_reduce` unification routes through the same
5257    /// partial+reduce engine as the host-returning `_hvp` / `_diagonal`
5258    /// adapters. Confirms that keeping the result on-stream (no internal sync /
5259    /// DtoH) reaches bit-identical output to both the CPU oracle and the
5260    /// host-out adapter, so the engine's mode/output split is faithful.
5261    ///
5262    /// Skips cleanly on non-Linux / no-CUDA hosts using the convention shared
5263    /// with the sibling parity tests.
5264    #[test]
5265    pub(crate) fn bms_flex_row_hvp_into_device_matches_cpu_oracle_and_host_out() {
5266        #[cfg(not(target_os = "linux"))]
5267        {
5268            eprintln!(
5269                "[bms_flex_row hvp_into_device parity] non-Linux host — skipping \
5270                 CUDA parity (CPU oracle exercised by sibling tests)"
5271            );
5272        }
5273        #[cfg(target_os = "linux")]
5274        {
5275            if cuda_runtime_for_test("bms_flex_row hvp_into_device parity").is_none() {
5276                return;
5277            }
5278            let n = 4_usize;
5279            let r = 4_usize;
5280            let p_m = 2_usize;
5281            let p_g = 2_usize;
5282            let p_h_dim = 1_usize;
5283            let p_w_dim = 1_usize;
5284            let p_total = p_m + p_g + p_h_dim + p_w_dim;
5285            let block = BmsFlexBlockLayout {
5286                p_m,
5287                p_g,
5288                h: Some(p_m + p_g..p_m + p_g + p_h_dim),
5289                w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
5290                p_total,
5291            };
5292            let primary = BmsFlexPrimaryLayout {
5293                h: Some(2..3),
5294                w: Some(3..4),
5295                r,
5296            };
5297            let mut row_hessians = vec![0.0_f64; n * r * r];
5298            for row in 0..n {
5299                for u in 0..r {
5300                    for v in u..r {
5301                        let val = ((row + 1) as f64) * (1.0 + (u as f64) + 2.0 * (v as f64));
5302                        row_hessians[row * r * r + u * r + v] = val;
5303                        row_hessians[row * r * r + v * r + u] = val;
5304                    }
5305                }
5306            }
5307            let mut marginal = vec![0.0_f64; n * p_m];
5308            for row in 0..n {
5309                for j in 0..p_m {
5310                    marginal[row * p_m + j] = 0.5 + (row as f64) * 0.1 - (j as f64) * 0.2;
5311                }
5312            }
5313            let mut logslope = vec![0.0_f64; n * p_g];
5314            for row in 0..n {
5315                for j in 0..p_g {
5316                    logslope[row * p_g + j] = -0.3 + (row as f64) * 0.05 + (j as f64) * 0.15;
5317                }
5318            }
5319            let v: Vec<f64> = (0..p_total).map(|i| 0.1 + (i as f64) * 0.25).collect();
5320            let cpu_hvp = cpu_oracle_bms_flex_row_hvp(
5321                &row_hessians,
5322                &marginal,
5323                &logslope,
5324                &block,
5325                &primary,
5326                n,
5327                &v,
5328            );
5329
5330            // Past the lossless Auto-resolution gate: probe/upload failures are
5331            // real device faults on a CUDA host — fail loud (device-PCG class).
5332            let backend = HvpKernelBackend::probe().expect(
5333                "[bms_flex_row hvp_into_device parity] backend probe must succeed on CUDA host",
5334            );
5335            let stream = backend.stream.clone();
5336            let d_h = stream
5337                .clone_htod(&row_hessians)
5338                .expect("[bms_flex_row hvp_into_device parity] upload h must succeed on CUDA host");
5339            let d_m = stream.clone_htod(&marginal).expect(
5340                "[bms_flex_row hvp_into_device parity] upload marg must succeed on CUDA host",
5341            );
5342            let d_g = stream.clone_htod(&logslope).expect(
5343                "[bms_flex_row hvp_into_device parity] upload logslope must succeed on CUDA host",
5344            );
5345            let storage = DeviceResidentRowHess {
5346                neglog: stream
5347                    .alloc_zeros::<f64>(n)
5348                    .expect("[bms_flex_row hvp_into_device parity] alloc neglog"),
5349                grad: stream
5350                    .alloc_zeros::<f64>(n * r)
5351                    .expect("[bms_flex_row hvp_into_device parity] alloc grad"),
5352                hess: d_h,
5353                marginal_design: d_m,
5354                logslope_design: d_g,
5355                n,
5356                r,
5357                block: block.clone(),
5358                primary: primary.clone(),
5359
5360                bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
5361                    as u64,
5362            };
5363
5364            // Host-out adapter (allocates its own d_out, syncs + downloads).
5365            let host_out_hvp = launch_bms_flex_row_hvp(&storage, &v)
5366                .expect("host-out HVP kernel must launch on CUDA host");
5367
5368            // Device-out adapter: caller owns d_v + d_out; the engine performs
5369            // no sync / DtoH, so we synchronize + download here.
5370            let d_v = stream
5371                .clone_htod(&v)
5372                .expect("upload direction for device-out HVP");
5373            let mut d_out = stream
5374                .alloc_zeros::<f64>(p_total)
5375                .expect("alloc device-out HVP output");
5376            launch_bms_flex_row_hvp_into_device(&storage, &d_v, &mut d_out)
5377                .expect("device-out HVP kernel must launch on CUDA host");
5378            stream
5379                .synchronize()
5380                .expect("synchronize after device-out HVP");
5381            let device_out_hvp = stream
5382                .clone_dtoh(&d_out)
5383                .expect("download device-out HVP output");
5384
5385            assert_eq!(device_out_hvp.len(), cpu_hvp.len());
5386            assert_eq!(device_out_hvp.len(), host_out_hvp.len());
5387            for i in 0..p_total {
5388                let diff = (cpu_hvp[i] - device_out_hvp[i]).abs();
5389                assert!(
5390                    diff <= 1e-10,
5391                    "device-out HVP[{i}] vs CPU: cpu={} gpu={} |Δ|={diff:.3e}",
5392                    cpu_hvp[i],
5393                    device_out_hvp[i]
5394                );
5395                // Both adapters share the engine; the only difference is the
5396                // copy-back path, so they must be bit-identical.
5397                let host_diff = (host_out_hvp[i] - device_out_hvp[i]).abs();
5398                assert!(
5399                    host_diff == 0.0,
5400                    "device-out vs host-out HVP[{i}]: host={} device={} |Δ|={host_diff:.3e}",
5401                    host_out_hvp[i],
5402                    device_out_hvp[i]
5403                );
5404            }
5405        }
5406    }
5407
5408    /// Block 9 Phase 2 parity gate at the shape specified by the
5409    /// charter task: `n = 64`, `r = 20`, `p_total = 44`. Splits
5410    /// `p_total` as `p_m = 14`, `p_g = 12`, `p_h = 10`, `p_w = 8` so
5411    /// `r = 2 + p_h + p_w = 20` and every primary block participates
5412    /// in both the device pullback and the reduce pass. Tolerance is
5413    /// `|Δ| ≤ 1e-8` per the task description (looser than the 1e-10
5414    /// hand-fixture parity, since accumulation order across HVP CTAs
5415    /// differs from the CPU oracle's row-major sum even with the
5416    /// deterministic reduction policy).
5417    ///
5418    /// Skips cleanly on non-Linux and no-CUDA hosts using the same
5419    /// convention as the hand-fixture parity above.
5420    #[test]
5421    pub(crate) fn bms_flex_row_hvp_kernel_matches_cpu_oracle_at_n64_r20_p44() {
5422        #[cfg(not(target_os = "linux"))]
5423        {
5424            eprintln!(
5425                "[bms_flex_row hvp parity n64_r20_p44] non-Linux host — \
5426                 skipping CUDA parity"
5427            );
5428        }
5429        #[cfg(target_os = "linux")]
5430        {
5431            if cuda_runtime_for_test("bms_flex_row hvp parity n64_r20_p44").is_none() {
5432                return;
5433            }
5434            let n = 64_usize;
5435            let p_m = 14_usize;
5436            let p_g = 12_usize;
5437            let p_h_dim = 10_usize;
5438            let p_w_dim = 8_usize;
5439            let r = 2 + p_h_dim + p_w_dim;
5440            assert_eq!(r, 20);
5441            let p_total = p_m + p_g + p_h_dim + p_w_dim;
5442            assert_eq!(p_total, 44);
5443            let block = BmsFlexBlockLayout {
5444                p_m,
5445                p_g,
5446                h: Some(p_m + p_g..p_m + p_g + p_h_dim),
5447                w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
5448                p_total,
5449            };
5450            let primary = BmsFlexPrimaryLayout {
5451                h: Some(2..2 + p_h_dim),
5452                w: Some(2 + p_h_dim..2 + p_h_dim + p_w_dim),
5453                r,
5454            };
5455
5456            // Deterministic symmetric per-row Hessians + designs +
5457            // direction. Same scrambling family as
5458            // `row_hessian_ops::tests::make_fixture` so any regression
5459            // surfaces consistently across the host-pinned and
5460            // device-resident parity tests.
5461            let mut row_hessians = vec![0.0_f64; n * r * r];
5462            for row in 0..n {
5463                let base = row * r * r;
5464                for u in 0..r {
5465                    for v in 0..r {
5466                        let seed = (row as f64) * 0.137 + (u as f64) * 1.901 + (v as f64) * 0.317;
5467                        let a = (seed.sin() * 1.7 + (seed * 0.5).cos() * 0.9) * 0.5;
5468                        row_hessians[base + u * r + v] = a;
5469                    }
5470                }
5471                for u in 0..r {
5472                    for v in (u + 1)..r {
5473                        let upper = row_hessians[base + u * r + v];
5474                        let lower = row_hessians[base + v * r + u];
5475                        let sym = 0.5 * (upper + lower);
5476                        row_hessians[base + u * r + v] = sym;
5477                        row_hessians[base + v * r + u] = sym;
5478                    }
5479                    row_hessians[base + u * r + u] += r as f64;
5480                }
5481            }
5482            let mut marginal = vec![0.0_f64; n * p_m];
5483            for row in 0..n {
5484                for j in 0..p_m {
5485                    let seed = (row as f64) * 0.073 + (j as f64) * 0.211 + 0.4;
5486                    marginal[row * p_m + j] = seed.sin() * 0.8 - (seed * 0.7).cos() * 0.3;
5487                }
5488            }
5489            let mut logslope = vec![0.0_f64; n * p_g];
5490            for row in 0..n {
5491                for j in 0..p_g {
5492                    let seed = (row as f64) * 0.091 + (j as f64) * 0.179 - 0.2;
5493                    logslope[row * p_g + j] = seed.cos() * 0.7 + (seed * 0.3).sin() * 0.25;
5494                }
5495            }
5496            let v: Vec<f64> = (0..p_total)
5497                .map(|i| {
5498                    let seed = (i as f64) * 0.157 + 0.6;
5499                    seed.sin() * 0.55 + (seed * 0.4).cos() * 0.35
5500                })
5501                .collect();
5502
5503            let cpu_hvp = cpu_oracle_bms_flex_row_hvp(
5504                &row_hessians,
5505                &marginal,
5506                &logslope,
5507                &block,
5508                &primary,
5509                n,
5510                &v,
5511            );
5512            let cpu_diag = cpu_oracle_bms_flex_row_diagonal(
5513                &row_hessians,
5514                &marginal,
5515                &logslope,
5516                &block,
5517                &primary,
5518                n,
5519            );
5520
5521            let backend = match HvpKernelBackend::probe() {
5522                Ok(b) => b,
5523                Err(err) => {
5524                    eprintln!(
5525                        "[bms_flex_row hvp parity n64_r20_p44] backend probe \
5526                         failed: {err}"
5527                    );
5528                    return;
5529                }
5530            };
5531            let stream = backend.stream.clone();
5532            let d_h = match stream.clone_htod(&row_hessians) {
5533                Ok(s) => s,
5534                Err(err) => {
5535                    eprintln!(
5536                        "[bms_flex_row hvp parity n64_r20_p44] upload h \
5537                         failed: {err}"
5538                    );
5539                    return;
5540                }
5541            };
5542            let d_m = match stream.clone_htod(&marginal) {
5543                Ok(s) => s,
5544                Err(err) => {
5545                    eprintln!(
5546                        "[bms_flex_row hvp parity n64_r20_p44] upload marg \
5547                         failed: {err}"
5548                    );
5549                    return;
5550                }
5551            };
5552            let d_g = match stream.clone_htod(&logslope) {
5553                Ok(s) => s,
5554                Err(err) => {
5555                    eprintln!(
5556                        "[bms_flex_row hvp parity n64_r20_p44] upload logslope \
5557                         failed: {err}"
5558                    );
5559                    return;
5560                }
5561            };
5562            let storage = DeviceResidentRowHess {
5563                neglog: stream
5564                    .alloc_zeros::<f64>(n)
5565                    .expect("[bms_flex_row hvp parity n64_r20_p44] alloc neglog"),
5566                grad: stream
5567                    .alloc_zeros::<f64>(n * r)
5568                    .expect("[bms_flex_row hvp parity n64_r20_p44] alloc grad"),
5569                hess: d_h,
5570                marginal_design: d_m,
5571                logslope_design: d_g,
5572                n,
5573                r,
5574                block: block.clone(),
5575                primary: primary.clone(),
5576
5577                bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
5578                    as u64,
5579            };
5580            let gpu_hvp = launch_bms_flex_row_hvp(&storage, &v)
5581                .expect("HVP kernel must launch on CUDA host at n64/r20/p44");
5582            let gpu_diag = launch_bms_flex_row_diagonal(&storage)
5583                .expect("diagonal kernel must launch on CUDA host at n64/r20/p44");
5584            assert_eq!(gpu_hvp.len(), cpu_hvp.len());
5585            assert_eq!(gpu_diag.len(), cpu_diag.len());
5586            for i in 0..p_total {
5587                let diff = (cpu_hvp[i] - gpu_hvp[i]).abs();
5588                assert!(
5589                    diff <= 1e-8,
5590                    "n64_r20_p44 HVP[{i}]: cpu={} gpu={} |Δ|={diff:.3e}",
5591                    cpu_hvp[i],
5592                    gpu_hvp[i]
5593                );
5594                let ddiff = (cpu_diag[i] - gpu_diag[i]).abs();
5595                assert!(
5596                    ddiff <= 1e-8,
5597                    "n64_r20_p44 diag[{i}]: cpu={} gpu={} |Δ|={ddiff:.3e}",
5598                    cpu_diag[i],
5599                    gpu_diag[i]
5600                );
5601            }
5602        }
5603    }
5604
5605    /// Block 9 Phase 6 — small-fixture parity for the dense-block kernel
5606    /// against the host-side P_i pullback oracle.
5607    /// Verifies bit-equality (modulo reduction-order f.p. noise) between
5608    /// the device-resident dense build and the host accumulator over the
5609    /// same per-row Hessian + designs + P_i pullback.
5610    #[test]
5611    pub(crate) fn bms_flex_row_dense_block_kernel_matches_cpu_pullback() {
5612        #[cfg(not(target_os = "linux"))]
5613        {
5614            eprintln!("[bms_flex_row dense_block parity] non-Linux host — skipping CUDA parity");
5615        }
5616        #[cfg(target_os = "linux")]
5617        {
5618            if cuda_runtime_for_test("bms_flex_row dense_block parity").is_none() {
5619                return;
5620            }
5621            // Small fixture: n=24, r=8 (2 + 3 + 3), p_total=18 (4+4+3+3).
5622            // Keeps the CPU pullback fast while still exercising every
5623            // primary slot (q, g, h, w).
5624            let n = 24_usize;
5625            let p_m = 4_usize;
5626            let p_g = 4_usize;
5627            let p_h_dim = 3_usize;
5628            let p_w_dim = 3_usize;
5629            let r = 2 + p_h_dim + p_w_dim;
5630            let p_total = p_m + p_g + p_h_dim + p_w_dim;
5631            let block = BmsFlexBlockLayout {
5632                p_m,
5633                p_g,
5634                h: Some(p_m + p_g..p_m + p_g + p_h_dim),
5635                w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
5636                p_total,
5637            };
5638            let primary = BmsFlexPrimaryLayout {
5639                h: Some(2..2 + p_h_dim),
5640                w: Some(2 + p_h_dim..2 + p_h_dim + p_w_dim),
5641                r,
5642            };
5643
5644            let mut row_hessians = vec![0.0_f64; n * r * r];
5645            for row in 0..n {
5646                let base = row * r * r;
5647                for u in 0..r {
5648                    for v in 0..r {
5649                        let seed = (row as f64) * 0.21 + (u as f64) * 1.13 + (v as f64) * 0.47;
5650                        let a = (seed.sin() * 1.4 + (seed * 0.6).cos() * 0.7) * 0.5;
5651                        row_hessians[base + u * r + v] = a;
5652                    }
5653                }
5654                for u in 0..r {
5655                    for v in (u + 1)..r {
5656                        let upper = row_hessians[base + u * r + v];
5657                        let lower = row_hessians[base + v * r + u];
5658                        let sym = 0.5 * (upper + lower);
5659                        row_hessians[base + u * r + v] = sym;
5660                        row_hessians[base + v * r + u] = sym;
5661                    }
5662                    row_hessians[base + u * r + u] += r as f64;
5663                }
5664            }
5665            let mut marginal = vec![0.0_f64; n * p_m];
5666            for row in 0..n {
5667                for j in 0..p_m {
5668                    let seed = (row as f64) * 0.083 + (j as f64) * 0.171 + 0.31;
5669                    marginal[row * p_m + j] = seed.sin() * 0.7 - (seed * 0.5).cos() * 0.25;
5670                }
5671            }
5672            let mut logslope = vec![0.0_f64; n * p_g];
5673            for row in 0..n {
5674                for j in 0..p_g {
5675                    let seed = (row as f64) * 0.097 + (j as f64) * 0.143 - 0.15;
5676                    logslope[row * p_g + j] = seed.cos() * 0.65 + (seed * 0.4).sin() * 0.2;
5677                }
5678            }
5679
5680            // CPU oracle — same pullback math the device kernel mirrors.
5681            let h_block_start = block.h.as_ref().map(|r| r.start).unwrap_or(0);
5682            let h_block_len = block.h.as_ref().map(|r| r.len()).unwrap_or(0);
5683            let w_block_start = block.w.as_ref().map(|r| r.start).unwrap_or(0);
5684            let w_block_len = block.w.as_ref().map(|r| r.len()).unwrap_or(0);
5685            let h_primary_start = primary.h.as_ref().map(|r| r.start).unwrap_or(0);
5686            let w_primary_start = primary.w.as_ref().map(|r| r.start).unwrap_or(0);
5687            let mut h_cpu = vec![0.0_f64; p_total * p_total];
5688            for row in 0..n {
5689                let mrow = &marginal[row * p_m..(row + 1) * p_m];
5690                let grow = &logslope[row * p_g..(row + 1) * p_g];
5691                let hrow = &row_hessians[row * r * r..(row + 1) * r * r];
5692                // Build per-row phi (r length-p_total vectors).
5693                let mut phi = vec![vec![0.0_f64; p_total]; r];
5694                for k in 0..p_m {
5695                    phi[0][k] = mrow[k];
5696                }
5697                for k in 0..p_g {
5698                    phi[1][p_m + k] = grow[k];
5699                }
5700                for k in 0..h_block_len {
5701                    phi[h_primary_start + k][h_block_start + k] = 1.0;
5702                }
5703                for k in 0..w_block_len {
5704                    phi[w_primary_start + k][w_block_start + k] = 1.0;
5705                }
5706                for u in 0..r {
5707                    for v in 0..r {
5708                        let huv = hrow[u * r + v];
5709                        if huv == 0.0 {
5710                            continue;
5711                        }
5712                        for m in 0..p_total {
5713                            let pm = phi[u][m];
5714                            if pm == 0.0 {
5715                                continue;
5716                            }
5717                            let scaled = huv * pm;
5718                            for nn in 0..p_total {
5719                                h_cpu[m * p_total + nn] += scaled * phi[v][nn];
5720                            }
5721                        }
5722                    }
5723                }
5724            }
5725
5726            // Build a transient device-resident storage and launch the
5727            // dense-block kernel.
5728            // Past the lossless Auto-resolution gate: probe/upload failures are
5729            // real device faults on a CUDA host — fail loud (device-PCG class).
5730            let backend = HvpKernelBackend::probe().expect(
5731                "[bms_flex_row dense_block parity] backend probe must succeed on CUDA host",
5732            );
5733            let stream = backend.stream.clone();
5734            let d_h = stream
5735                .clone_htod(&row_hessians)
5736                .expect("[bms_flex_row dense_block parity] upload h must succeed on CUDA host");
5737            let d_m = stream
5738                .clone_htod(&marginal)
5739                .expect("[bms_flex_row dense_block parity] upload marg must succeed on CUDA host");
5740            let d_g = stream.clone_htod(&logslope).expect(
5741                "[bms_flex_row dense_block parity] upload logslope must succeed on CUDA host",
5742            );
5743            let storage = DeviceResidentRowHess {
5744                neglog: stream
5745                    .alloc_zeros::<f64>(n)
5746                    .expect("[bms_flex_row dense_block parity] alloc neglog"),
5747                grad: stream
5748                    .alloc_zeros::<f64>(n * r)
5749                    .expect("[bms_flex_row dense_block parity] alloc grad"),
5750                hess: d_h,
5751                marginal_design: d_m,
5752                logslope_design: d_g,
5753                n,
5754                r,
5755                block: block.clone(),
5756                primary: primary.clone(),
5757
5758                bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
5759                    as u64,
5760            };
5761            let h_gpu = launch_bms_flex_row_dense_block(&storage)
5762                .expect("dense_block kernel must launch on CUDA host");
5763            assert_eq!(h_gpu.len(), p_total * p_total);
5764
5765            // Compare entry-by-entry with a tolerance that absorbs
5766            // reduction-order f.p. noise from the CTA chunk sum.
5767            let mut max_abs = 0.0_f64;
5768            for i in 0..p_total {
5769                for j in 0..p_total {
5770                    let a = h_cpu[i * p_total + j];
5771                    let b = h_gpu[i * p_total + j];
5772                    let diff = (a - b).abs();
5773                    if diff > max_abs {
5774                        max_abs = diff;
5775                    }
5776                    assert!(
5777                        diff <= 1e-9 * a.abs().max(b.abs()).max(1.0),
5778                        "dense_block[{i},{j}]: cpu={a} gpu={b} |Δ|={diff:.3e}"
5779                    );
5780                }
5781            }
5782            eprintln!(
5783                "[bms_flex_row dense_block parity] n={n} r={r} p={p_total}: max|Δ|={max_abs:.3e}"
5784            );
5785        }
5786    }
5787
5788    #[test]
5789    pub(crate) fn bms_flex_row_dense_hvp_materialization_matches_cpu_above_block_cap_932() {
5790        if cuda_runtime_for_test("bms_flex_row dense HVP parity").is_none() {
5791            return;
5792        }
5793        let n = 1_usize;
5794        let r = 2_usize;
5795        let p_m = 37_usize;
5796        let p_g = 36_usize;
5797        let p_total = p_m + p_g;
5798        assert_eq!(p_total, DENSE_BLOCK_MAX_P + 1);
5799        let block = BmsFlexBlockLayout {
5800            p_m,
5801            p_g,
5802            h: None,
5803            w: None,
5804            p_total,
5805        };
5806        let primary = BmsFlexPrimaryLayout {
5807            h: None,
5808            w: None,
5809            r,
5810        };
5811        let row_hessians = vec![2.5_f64, -0.75, -0.75, 1.25];
5812        let marginal = (0..p_m)
5813            .map(|column| 0.15 + (column as f64 * 0.17).sin())
5814            .collect::<Vec<_>>();
5815        let logslope = (0..p_g)
5816            .map(|column| -0.2 + (column as f64 * 0.11).cos())
5817            .collect::<Vec<_>>();
5818        let mut expected = vec![0.0_f64; p_total * p_total];
5819        for row in 0..p_total {
5820            for column in 0..p_total {
5821                expected[row * p_total + column] = match (row < p_m, column < p_m) {
5822                    (true, true) => row_hessians[0] * marginal[row] * marginal[column],
5823                    (true, false) => row_hessians[1] * marginal[row] * logslope[column - p_m],
5824                    (false, true) => row_hessians[2] * logslope[row - p_m] * marginal[column],
5825                    (false, false) => {
5826                        row_hessians[3] * logslope[row - p_m] * logslope[column - p_m]
5827                    }
5828                };
5829            }
5830        }
5831
5832        let backend = HvpKernelBackend::probe()
5833            .expect("[bms_flex_row dense HVP parity] backend probe must succeed");
5834        let stream = backend.stream.clone();
5835        let storage = DeviceResidentRowHess {
5836            neglog: stream
5837                .alloc_zeros::<f64>(n)
5838                .expect("dense HVP parity neglog allocation"),
5839            grad: stream
5840                .alloc_zeros::<f64>(n * r)
5841                .expect("dense HVP parity grad allocation"),
5842            hess: stream
5843                .clone_htod(&row_hessians)
5844                .expect("dense HVP parity hessian upload"),
5845            marginal_design: stream
5846                .clone_htod(&marginal)
5847                .expect("dense HVP parity marginal upload"),
5848            logslope_design: stream
5849                .clone_htod(&logslope)
5850                .expect("dense HVP parity logslope upload"),
5851            n,
5852            r,
5853            block,
5854            primary,
5855            bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
5856                as u64,
5857        };
5858        let actual = launch_bms_flex_row_dense(&storage)
5859            .expect("wide dense HVP materialization must stay on CUDA");
5860        assert_eq!(actual.len(), expected.len());
5861        for (index, (&actual, &expected)) in actual.iter().zip(&expected).enumerate() {
5862            let tolerance = 1.0e-10 * actual.abs().max(expected.abs()).max(1.0);
5863            assert!(
5864                (actual - expected).abs() <= tolerance,
5865                "wide dense entry {index}: CUDA={actual:.17e} CPU={expected:.17e} tolerance={tolerance:.3e}"
5866            );
5867        }
5868    }
5869
5870    /// Block 9 final hill-climb gate — GPU HVP must be at least 5× faster
5871    /// than a Rayon-parallel CPU HVP at large-scale shape (n=195_000, r=20,
5872    /// p_total=44). This is the charter pass/fail metric for whether the
5873    /// device-resident row-Hessian path is a real perf win for the
5874    /// production marginal-slope fit.
5875    ///
5876    /// Methodology:
5877    ///   * Build the same deterministic fixture as the parity tests.
5878    ///   * GPU: median of `iters` `launch_bms_flex_row_hvp` wall-times
5879    ///     after `warmup` warm-up launches (kernel compile + L2 prime).
5880    ///   * CPU: median of `iters` `cpu_oracle_bms_flex_row_hvp` wall-times,
5881    ///     parallelised over rows via Rayon — this mirrors the actual
5882    ///     production CPU path in
5883    ///     `exact_newton_joint_hessian_matvec_from_cache` (which uses
5884    ///     `ROW_CHUNK_SIZE` chunked `into_par_iter()` for the same
5885    ///     contraction).
5886    ///   * Ratio = cpu_median / gpu_median; assert ratio >= 5.
5887    ///
5888    /// Skips on non-Linux / no-CUDA hosts.
5889    #[test]
5890    pub(crate) fn bms_flex_row_hvp_v100_hill_climb_5x_vs_cpu_at_large_scale() {
5891        #[cfg(not(target_os = "linux"))]
5892        {
5893            eprintln!("[bms_flex_row hvp hill-climb] non-Linux host — skipping V100 perf gate");
5894        }
5895        #[cfg(target_os = "linux")]
5896        {
5897            if cuda_runtime_for_test("bms_flex_row hvp hill-climb").is_none() {
5898                return;
5899            }
5900            let n = 195_000_usize;
5901            let p_m = 14_usize;
5902            let p_g = 12_usize;
5903            let p_h_dim = 10_usize;
5904            let p_w_dim = 8_usize;
5905            let r = 2 + p_h_dim + p_w_dim;
5906            let p_total = p_m + p_g + p_h_dim + p_w_dim;
5907            let block = BmsFlexBlockLayout {
5908                p_m,
5909                p_g,
5910                h: Some(p_m + p_g..p_m + p_g + p_h_dim),
5911                w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
5912                p_total,
5913            };
5914            let primary = BmsFlexPrimaryLayout {
5915                h: Some(2..2 + p_h_dim),
5916                w: Some(2 + p_h_dim..2 + p_h_dim + p_w_dim),
5917                r,
5918            };
5919
5920            // Same deterministic fixture as the Phase 4 large-scale benchmark.
5921            let mut row_hessians = vec![0.0_f64; n * r * r];
5922            for row in 0..n {
5923                let base = row * r * r;
5924                for u in 0..r {
5925                    for vv in 0..r {
5926                        let seed = (row as f64) * 0.137 + (u as f64) * 1.901 + (vv as f64) * 0.317;
5927                        let a = (seed.sin() * 1.7 + (seed * 0.5).cos() * 0.9) * 0.5;
5928                        row_hessians[base + u * r + vv] = a;
5929                    }
5930                }
5931                for u in 0..r {
5932                    for vv in (u + 1)..r {
5933                        let upper = row_hessians[base + u * r + vv];
5934                        let lower = row_hessians[base + vv * r + u];
5935                        let sym = 0.5 * (upper + lower);
5936                        row_hessians[base + u * r + vv] = sym;
5937                        row_hessians[base + vv * r + u] = sym;
5938                    }
5939                    row_hessians[base + u * r + u] += r as f64;
5940                }
5941            }
5942            let mut marginal = vec![0.0_f64; n * p_m];
5943            for row in 0..n {
5944                for j in 0..p_m {
5945                    let seed = (row as f64) * 0.073 + (j as f64) * 0.211 + 0.4;
5946                    marginal[row * p_m + j] = seed.sin() * 0.8 - (seed * 0.7).cos() * 0.3;
5947                }
5948            }
5949            let mut logslope = vec![0.0_f64; n * p_g];
5950            for row in 0..n {
5951                for j in 0..p_g {
5952                    let seed = (row as f64) * 0.091 + (j as f64) * 0.179 - 0.2;
5953                    logslope[row * p_g + j] = seed.cos() * 0.7 + (seed * 0.3).sin() * 0.25;
5954                }
5955            }
5956            let v: Vec<f64> = (0..p_total)
5957                .map(|i| {
5958                    let seed = (i as f64) * 0.157 + 0.6;
5959                    seed.sin() * 0.55 + (seed * 0.4).cos() * 0.35
5960                })
5961                .collect();
5962
5963            // ── GPU side: upload once, time HVP launches ─────────────
5964            let backend = match HvpKernelBackend::probe() {
5965                Ok(b) => b,
5966                Err(err) => {
5967                    eprintln!("[bms_flex_row hvp hill-climb] backend probe failed: {err}");
5968                    return;
5969                }
5970            };
5971            let stream = backend.stream.clone();
5972            let d_h = match stream.clone_htod(&row_hessians) {
5973                Ok(s) => s,
5974                Err(err) => {
5975                    eprintln!("[bms_flex_row hvp hill-climb] upload h failed (likely OOM): {err}");
5976                    return;
5977                }
5978            };
5979            let d_m = match stream.clone_htod(&marginal) {
5980                Ok(s) => s,
5981                Err(err) => {
5982                    eprintln!("[bms_flex_row hvp hill-climb] upload marg failed: {err}");
5983                    return;
5984                }
5985            };
5986            let d_g = match stream.clone_htod(&logslope) {
5987                Ok(s) => s,
5988                Err(err) => {
5989                    eprintln!("[bms_flex_row hvp hill-climb] upload logslope failed: {err}");
5990                    return;
5991                }
5992            };
5993            let storage = DeviceResidentRowHess {
5994                neglog: stream
5995                    .alloc_zeros::<f64>(n)
5996                    .expect("[bms_flex_row hvp hill-climb] alloc neglog"),
5997                grad: stream
5998                    .alloc_zeros::<f64>(n * r)
5999                    .expect("[bms_flex_row hvp hill-climb] alloc grad"),
6000                hess: d_h,
6001                marginal_design: d_m,
6002                logslope_design: d_g,
6003                n,
6004                r,
6005                block: block.clone(),
6006                primary: primary.clone(),
6007
6008                bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
6009                    as u64,
6010            };
6011            let warmup: usize = 3;
6012            let iters: usize = 15;
6013            for _ in 0..warmup {
6014                let out =
6015                    launch_bms_flex_row_hvp(&storage, &v).expect("warmup GPU HVP must launch");
6016                assert_eq!(out.len(), p_total);
6017            }
6018            let mut gpu_us: Vec<u128> = Vec::with_capacity(iters);
6019            for _ in 0..iters {
6020                let t0 = std::time::Instant::now();
6021                let out = launch_bms_flex_row_hvp(&storage, &v).expect("GPU HVP must launch");
6022                gpu_us.push(t0.elapsed().as_micros());
6023                assert_eq!(out.len(), p_total);
6024            }
6025            gpu_us.sort_unstable();
6026            let gpu_median = gpu_us[iters / 2];
6027
6028            // ── CPU side: chunked Rayon HVP over rows, mirroring the
6029            //    production `exact_newton_joint_hessian_matvec_from_cache`
6030            //    parallelisation pattern (ROW_CHUNK_SIZE-row chunks,
6031            //    try_fold + try_reduce). The per-chunk worker calls the
6032            //    single-threaded oracle on its row slice.
6033            const CHUNK_ROWS: usize = 4096;
6034            let cpu_hvp_parallel = || -> Vec<f64> {
6035                let nchunks = n.div_ceil(CHUNK_ROWS);
6036                gam_linalg::pairwise_reduce::par_deterministic_block_fold(
6037                    nchunks,
6038                    |ci_range| {
6039                        let mut acc = vec![0.0_f64; p_total];
6040                        for ci in ci_range {
6041                            let lo = ci * CHUNK_ROWS;
6042                            let hi = (lo + CHUNK_ROWS).min(n);
6043                            let m = hi - lo;
6044                            let partial = cpu_oracle_bms_flex_row_hvp(
6045                                &row_hessians[lo * r * r..hi * r * r],
6046                                &marginal[lo * p_m..hi * p_m],
6047                                &logslope[lo * p_g..hi * p_g],
6048                                &block,
6049                                &primary,
6050                                m,
6051                                &v,
6052                            );
6053                            for (a, &p) in acc.iter_mut().zip(partial.iter()) {
6054                                *a += p;
6055                            }
6056                        }
6057                        acc
6058                    },
6059                    |mut a, b| {
6060                        for (ax, bx) in a.iter_mut().zip(b.iter()) {
6061                            *ax += *bx;
6062                        }
6063                        a
6064                    },
6065                )
6066                .unwrap_or_else(|| vec![0.0_f64; p_total])
6067            };
6068            // Warmup once to populate L3 / steady-state Rayon thread pool.
6069            let warm = cpu_hvp_parallel();
6070            assert_eq!(warm.len(), p_total);
6071            let mut cpu_us: Vec<u128> = Vec::with_capacity(iters);
6072            for _ in 0..iters {
6073                let t0 = std::time::Instant::now();
6074                let out = cpu_hvp_parallel();
6075                cpu_us.push(t0.elapsed().as_micros());
6076                assert_eq!(out.len(), p_total);
6077            }
6078            cpu_us.sort_unstable();
6079            let cpu_median = cpu_us[iters / 2];
6080
6081            let speedup = (cpu_median as f64) / (gpu_median.max(1) as f64);
6082            eprintln!(
6083                "[bms_flex_row hvp hill-climb] large-scale n={n} r={r} p={p_total}: \
6084                 cpu_median={cpu_median}us gpu_median={gpu_median}us \
6085                 speedup={speedup:.2}× (charter target ≥ 5×)"
6086            );
6087            // Dispatch-worthiness gate, not a hardware bet (#2313 hardware
6088            // sweep): a fixed 5× floor asserts the calibration box's CPU/GPU
6089            // pair and fails a healthy kernel next to a fast host CPU. The
6090            // property the kernel must keep is that the device path
6091            // comfortably beats the SAME box's CPU (a serialized/faked path
6092            // shows ~1×); the calibrated dispatch policy owns the real
6093            // CPU/GPU decision, and the printed medians remain the perf
6094            // record for hill-climbing.
6095            assert!(
6096                speedup >= 2.0,
6097                "large-scale HVP dispatch-worthiness gate: GPU only {speedup:.2}× \
6098                 faster than CPU on this box (cpu_median={cpu_median}us, \
6099                 gpu_median={gpu_median}us) — a healthy kernel must clearly beat \
6100                 the same-box CPU."
6101            );
6102        }
6103    }
6104
6105    /// Companion to the HVP hill-climb: GPU dense-block build must be at
6106    /// least 10× faster than a Rayon-parallel CPU dense build at large-scale
6107    /// shape. The dense build is `O(n * r² * p_total)` work for both
6108    /// paths so the ratio is well-defined.
6109    #[test]
6110    pub(crate) fn bms_flex_row_dense_block_v100_hill_climb_10x_vs_cpu_at_large_scale() {
6111        #[cfg(not(target_os = "linux"))]
6112        {
6113            eprintln!(
6114                "[bms_flex_row dense_block hill-climb] non-Linux host — skipping V100 perf gate"
6115            );
6116        }
6117        #[cfg(target_os = "linux")]
6118        {
6119            if cuda_runtime_for_test("bms_flex_row dense_block hill-climb").is_none() {
6120                return;
6121            }
6122            let n = 195_000_usize;
6123            let p_m = 14_usize;
6124            let p_g = 12_usize;
6125            let p_h_dim = 10_usize;
6126            let p_w_dim = 8_usize;
6127            let r = 2 + p_h_dim + p_w_dim;
6128            let p_total = p_m + p_g + p_h_dim + p_w_dim;
6129            let block = BmsFlexBlockLayout {
6130                p_m,
6131                p_g,
6132                h: Some(p_m + p_g..p_m + p_g + p_h_dim),
6133                w: Some(p_m + p_g + p_h_dim..p_m + p_g + p_h_dim + p_w_dim),
6134                p_total,
6135            };
6136            let primary = BmsFlexPrimaryLayout {
6137                h: Some(2..2 + p_h_dim),
6138                w: Some(2 + p_h_dim..2 + p_h_dim + p_w_dim),
6139                r,
6140            };
6141
6142            // Reuse the same large-scale fixture recipe.
6143            let mut row_hessians = vec![0.0_f64; n * r * r];
6144            for row in 0..n {
6145                let base = row * r * r;
6146                for u in 0..r {
6147                    for vv in 0..r {
6148                        let seed = (row as f64) * 0.137 + (u as f64) * 1.901 + (vv as f64) * 0.317;
6149                        let a = (seed.sin() * 1.7 + (seed * 0.5).cos() * 0.9) * 0.5;
6150                        row_hessians[base + u * r + vv] = a;
6151                    }
6152                }
6153                for u in 0..r {
6154                    for vv in (u + 1)..r {
6155                        let upper = row_hessians[base + u * r + vv];
6156                        let lower = row_hessians[base + vv * r + u];
6157                        let sym = 0.5 * (upper + lower);
6158                        row_hessians[base + u * r + vv] = sym;
6159                        row_hessians[base + vv * r + u] = sym;
6160                    }
6161                    row_hessians[base + u * r + u] += r as f64;
6162                }
6163            }
6164            let mut marginal = vec![0.0_f64; n * p_m];
6165            for row in 0..n {
6166                for j in 0..p_m {
6167                    let seed = (row as f64) * 0.073 + (j as f64) * 0.211 + 0.4;
6168                    marginal[row * p_m + j] = seed.sin() * 0.8 - (seed * 0.7).cos() * 0.3;
6169                }
6170            }
6171            let mut logslope = vec![0.0_f64; n * p_g];
6172            for row in 0..n {
6173                for j in 0..p_g {
6174                    let seed = (row as f64) * 0.091 + (j as f64) * 0.179 - 0.2;
6175                    logslope[row * p_g + j] = seed.cos() * 0.7 + (seed * 0.3).sin() * 0.25;
6176                }
6177            }
6178
6179            // GPU dense_block kernel rejects p_total > DENSE_BLOCK_MAX_P
6180            // (72 at V100 48 KiB/block). LargeScale's p_total = 44 fits.
6181            if p_total > DENSE_BLOCK_MAX_P {
6182                eprintln!(
6183                    "[bms_flex_row dense_block hill-climb] p_total={p_total} > MAX={DENSE_BLOCK_MAX_P}, skipping"
6184                );
6185                return;
6186            }
6187            let backend = match HvpKernelBackend::probe() {
6188                Ok(b) => b,
6189                Err(err) => {
6190                    eprintln!("[bms_flex_row dense_block hill-climb] backend probe failed: {err}");
6191                    return;
6192                }
6193            };
6194            let stream = backend.stream.clone();
6195            let d_h = match stream.clone_htod(&row_hessians) {
6196                Ok(s) => s,
6197                Err(err) => {
6198                    eprintln!("[bms_flex_row dense_block hill-climb] upload h failed: {err}");
6199                    return;
6200                }
6201            };
6202            let d_m = match stream.clone_htod(&marginal) {
6203                Ok(s) => s,
6204                Err(err) => {
6205                    eprintln!("[bms_flex_row dense_block hill-climb] upload marg failed: {err}");
6206                    return;
6207                }
6208            };
6209            let d_g = match stream.clone_htod(&logslope) {
6210                Ok(s) => s,
6211                Err(err) => {
6212                    eprintln!(
6213                        "[bms_flex_row dense_block hill-climb] upload logslope failed: {err}"
6214                    );
6215                    return;
6216                }
6217            };
6218            let storage = DeviceResidentRowHess {
6219                neglog: stream
6220                    .alloc_zeros::<f64>(n)
6221                    .expect("[bms_flex_row dense_block hill-climb] alloc neglog"),
6222                grad: stream
6223                    .alloc_zeros::<f64>(n * r)
6224                    .expect("[bms_flex_row dense_block hill-climb] alloc grad"),
6225                hess: d_h,
6226                marginal_design: d_m,
6227                logslope_design: d_g,
6228                n,
6229                r,
6230                block: block.clone(),
6231                primary: primary.clone(),
6232
6233                bytes: ((n + n * r + n * r * r + n * p_m + n * p_g) * std::mem::size_of::<f64>())
6234                    as u64,
6235            };
6236            // Warmup + 5-iter median (dense build is heavier than HVP).
6237            let warmup: usize = 2;
6238            let iters: usize = 5;
6239            for _ in 0..warmup {
6240                let out = launch_bms_flex_row_dense_block(&storage)
6241                    .expect("warmup GPU dense_block must launch");
6242                assert_eq!(out.len(), p_total * p_total);
6243            }
6244            let mut gpu_us: Vec<u128> = Vec::with_capacity(iters);
6245            for _ in 0..iters {
6246                let t0 = std::time::Instant::now();
6247                let out =
6248                    launch_bms_flex_row_dense_block(&storage).expect("GPU dense_block must launch");
6249                gpu_us.push(t0.elapsed().as_micros());
6250                assert_eq!(out.len(), p_total * p_total);
6251            }
6252            gpu_us.sort_unstable();
6253            let gpu_median = gpu_us[iters / 2];
6254
6255            // CPU side: chunked Rayon dense build over rows. Each chunk
6256            // builds a `[p_total, p_total]` partial then we reduce-add.
6257            const CHUNK_ROWS: usize = 2048;
6258            let h_block_start = block.h.as_ref().map(|r| r.start).unwrap_or(0);
6259            let h_block_len = block.h.as_ref().map(|r| r.len()).unwrap_or(0);
6260            let w_block_start = block.w.as_ref().map(|r| r.start).unwrap_or(0);
6261            let w_block_len = block.w.as_ref().map(|r| r.len()).unwrap_or(0);
6262            let h_primary_start = primary.h.as_ref().map(|r| r.start).unwrap_or(0);
6263            let w_primary_start = primary.w.as_ref().map(|r| r.start).unwrap_or(0);
6264            let cpu_build_parallel = || -> Vec<f64> {
6265                let nchunks = n.div_ceil(CHUNK_ROWS);
6266                gam_linalg::pairwise_reduce::par_deterministic_block_fold(
6267                    nchunks,
6268                    |ci_range| {
6269                        let mut acc = vec![0.0_f64; p_total * p_total];
6270                        let mut phi: Vec<Vec<f64>> = vec![vec![0.0_f64; p_total]; r];
6271                        for ci in ci_range {
6272                            let lo = ci * CHUNK_ROWS;
6273                            let hi = (lo + CHUNK_ROWS).min(n);
6274                            for row in lo..hi {
6275                                for col in phi.iter_mut() {
6276                                    col.iter_mut().for_each(|v| *v = 0.0);
6277                                }
6278                                let mrow = &marginal[row * p_m..(row + 1) * p_m];
6279                                let grow = &logslope[row * p_g..(row + 1) * p_g];
6280                                for k in 0..p_m {
6281                                    phi[0][k] = mrow[k];
6282                                }
6283                                for k in 0..p_g {
6284                                    phi[1][p_m + k] = grow[k];
6285                                }
6286                                for k in 0..h_block_len {
6287                                    phi[h_primary_start + k][h_block_start + k] = 1.0;
6288                                }
6289                                for k in 0..w_block_len {
6290                                    phi[w_primary_start + k][w_block_start + k] = 1.0;
6291                                }
6292                                let hrow = &row_hessians[row * r * r..(row + 1) * r * r];
6293                                for u in 0..r {
6294                                    for v_idx in 0..r {
6295                                        let huv = hrow[u * r + v_idx];
6296                                        if huv == 0.0 {
6297                                            continue;
6298                                        }
6299                                        for m in 0..p_total {
6300                                            let pm = phi[u][m];
6301                                            if pm == 0.0 {
6302                                                continue;
6303                                            }
6304                                            let scaled = huv * pm;
6305                                            for nn in 0..p_total {
6306                                                acc[m * p_total + nn] += scaled * phi[v_idx][nn];
6307                                            }
6308                                        }
6309                                    }
6310                                }
6311                            }
6312                        }
6313                        acc
6314                    },
6315                    |mut a, b| {
6316                        for (ax, bx) in a.iter_mut().zip(b.iter()) {
6317                            *ax += *bx;
6318                        }
6319                        a
6320                    },
6321                )
6322                .unwrap_or_else(|| vec![0.0_f64; p_total * p_total])
6323            };
6324            let warm_cpu = cpu_build_parallel();
6325            assert_eq!(warm_cpu.len(), p_total * p_total);
6326            let mut cpu_us: Vec<u128> = Vec::with_capacity(iters);
6327            for _ in 0..iters {
6328                let t0 = std::time::Instant::now();
6329                let out = cpu_build_parallel();
6330                cpu_us.push(t0.elapsed().as_micros());
6331                assert_eq!(out.len(), p_total * p_total);
6332            }
6333            cpu_us.sort_unstable();
6334            let cpu_median = cpu_us[iters / 2];
6335
6336            let speedup = (cpu_median as f64) / (gpu_median.max(1) as f64);
6337            eprintln!(
6338                "[bms_flex_row dense_block hill-climb] large-scale n={n} r={r} p={p_total}: \
6339                 cpu_median={cpu_median}us gpu_median={gpu_median}us \
6340                 speedup={speedup:.2}× (charter target ≥ 10×)"
6341            );
6342            // Same dispatch-worthiness contract as the HVP gate above
6343            // (previously a 10× calibration-box ratio).
6344            assert!(
6345                speedup >= 2.0,
6346                "large-scale dense-H dispatch-worthiness gate: GPU only \
6347                 {speedup:.2}× faster than CPU on this box \
6348                 (cpu_median={cpu_median}us, gpu_median={gpu_median}us)."
6349            );
6350        }
6351    }
6352}