Skip to main content

gam_solve/gpu_kernels/
arrow_schur.rs

1//! Fully GPU-resident batched Arrow-Schur dense Cholesky solver.
2//!
3//! Implements the square-root Schur form: each local block `D_i = L_i L_i^T`
4//! is factored on device, `u_i = L_i^{-1} g_i` and `Y_i = L_i^{-1} B_i` are
5//! formed by triangular solves, the reduced shared system
6//!     `S_β = C + ρ_β I − Σ_i Y_i^T Y_i,  r_β = -g_β + Σ_i Y_i^T u_i`
7//! is assembled on device, factored once, and the back-substitution
8//!     `w_i = u_i + Y_i · δβ,  L_i^T x_i = w_i,  δt_i = -x_i`
9//! is run on device. Only the final `(δt, δβ, log|H|)` triple is downloaded.
10//!
11//! The current caller (Arrow-Schur Newton step inside PIRLS) feeds uniform
12//! local block size `d` and uniform shared width `k`, so the entire pipeline
13//! is dispatched as a single p-group; per-p grouping for heterogenous blocks
14//! is Layer D's NVRTC fused-kernel concern and lives in this module's
15//! follow-up implementation rather than in policy plumbing.
16//!
17//! On non-Linux builds the entire module degrades to a CPU-fallback shim.
18
19use ndarray::{Array1, Array2};
20
21use gam_linalg::triangular::{CholeskyGuard, cholesky_factor_in_place, cholesky_solve_vector};
22use crate::arrow_schur::{ArrowSchurSystem, DeviceSaePcgData, PcgDiagnostics};
23
24/// Outcome of a single Arrow-Schur Newton solve.
25pub struct ArrowSchurGpuSolution {
26    pub delta_t: Array1<f64>,
27    pub delta_beta: Array1<f64>,
28    /// Natural log of the determinant of the full bordered Hessian, computed
29    /// from the local Cholesky factors and the Schur factor on device.
30    pub log_det_hessian: f64,
31}
32
33/// Reason a device path declined to run; lets the host caller decide between
34/// CPU fallback and per-row escalation. `RidgeBumpRequired` carries the
35/// estimated diagonal bump needed to clear the failed pivot.
36#[derive(Debug, Clone)]
37pub enum ArrowSchurGpuFailure {
38    /// CUDA runtime unavailable, allocation failed, or workload below policy.
39    Unavailable,
40    /// A row block was not positive definite even after the requested ridge.
41    /// Caller may retry with `ridge_t + bump`.
42    RidgeBumpRequired { row: usize, bump: f64 },
43    /// Shared Schur factor failed; bordered system is rank-deficient at the
44    /// requested ridges and the CPU path should handle escalation.
45    SchurFactorFailed { reason: String },
46    /// The system carries matrix-free `H_ββ` or per-row `H_tβ` operators that
47    /// the dense GPU Schur path cannot consume. The caller should route to CPU
48    /// `InexactPCG` (or supply dense buffers) rather than treating this as a
49    /// numerical failure. See `gpu/arrow_schur.rs` Part B for the planned GPU
50    /// PCG path that will lift this restriction at K ≥ 5000.
51    GpuRequiresDenseSystem {
52        had_hbb_matvec: bool,
53        had_htbeta_matvec: bool,
54    },
55}
56
57/// Safety-margin multiplier on `√(machine ε)` for the diagonal ridge bump
58/// suggested when a local block fails Cholesky.
59///
60/// The estimated bump is `diag_scale · |pivot| · √ε · RIDGE_BUMP_EPS_MARGIN`.
61/// A bare `diag_scale · √ε` ridge is the smallest perturbation that makes a
62/// marginally-indefinite block PD in exact arithmetic, but a single retry at
63/// that magnitude is routinely re-rejected by the next POTRF because the
64/// rounding error of forming `D + ridge·I` and re-factoring is itself O(√ε).
65/// The 1024× headroom (≈ 2¹⁰, i.e. ten extra bits below the f64 mantissa's
66/// 52) clears the pivot on the first retry without materially perturbing the
67/// curvature the Newton step sees. Shared by the per-row scalar path and the
68/// batched-tile path so both suggest an identical bump.
69const RIDGE_BUMP_EPS_MARGIN: f64 = 1024.0;
70
71/// Entry point: attempt the fully device-resident Arrow-Schur Newton solve.
72/// Returns `Err(ArrowSchurGpuFailure::Unavailable)` to indicate "device path
73/// declined, fall back to CPU" — never panics.
74pub fn solve_arrow_newton_step(
75    sys: &ArrowSchurSystem,
76    ridge_t: f64,
77    ridge_beta: f64,
78) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
79    let n = sys.rows.len();
80    let d = sys.d;
81    let k = sys.k;
82
83    // Detect matrix-free operators before any dim() checks so callers get a
84    // clear, actionable error instead of a generic SchurFactorFailed. The GPU
85    // dense-Schur path requires materialised H_ββ and per-row H_tβ slabs;
86    // CPU InexactPCG is the correct fallback when either operator is abstract.
87    let had_hbb_matvec = sys.hbb_matvec.is_some();
88    let had_htbeta_matvec = sys.htbeta_matvec.is_some();
89    if had_hbb_matvec || had_htbeta_matvec {
90        return Err(ArrowSchurGpuFailure::GpuRequiresDenseSystem {
91            had_hbb_matvec,
92            had_htbeta_matvec,
93        });
94    }
95
96    if sys.hbb.dim() != (k, k) {
97        return Err(ArrowSchurGpuFailure::SchurFactorFailed {
98            reason: "CUDA arrow-Schur requires a dense shared beta block".to_string(),
99        });
100    }
101    if n == 0 || d == 0 {
102        return Err(ArrowSchurGpuFailure::Unavailable);
103    }
104    if sys
105        .rows
106        .iter()
107        .any(|row| row.htt.dim() != (d, d) || row.htbeta.dim() != (d, k) || row.gt.len() != d)
108    {
109        return Err(ArrowSchurGpuFailure::SchurFactorFailed {
110            reason: "row block dimension mismatch".to_string(),
111        });
112    }
113
114    #[cfg(not(target_os = "linux"))]
115    {
116        if ridge_t.is_nan() || ridge_beta.is_nan() {
117            return Err(ArrowSchurGpuFailure::SchurFactorFailed {
118                reason: "ridge is NaN".to_string(),
119            });
120        }
121        Err(ArrowSchurGpuFailure::Unavailable)
122    }
123
124    #[cfg(target_os = "linux")]
125    {
126        // Multi-GPU: the arrow-Schur solve is row-block separable in its forward
127        // (per-row factor / whiten / partial-Schur) and backward (per-row
128        // back-sub) phases — only the small shared K×K reduce+factor+δβ is
129        // central. When more than one device is usable, split the WHOLE solve at
130        // row-block granularity across all GPUs. The POTRF stays fused with its
131        // dependent TRSM+GEMM on each tile's own stream, so no on-stream solve is
132        // orphaned. On `Unavailable` (one device, shape below policy, transient)
133        // fall through to the single-device fused / Layer-A paths below.
134        if gam_gpu::device_runtime::GpuRuntime::global()
135            .map(gam_gpu::device_runtime::GpuRuntime::device_count)
136            .unwrap_or(0)
137            > 1
138        {
139            match cuda::solve_multi_gpu(sys, ridge_t, ridge_beta) {
140                Ok(sol) => return Ok(sol),
141                Err(ArrowSchurGpuFailure::RidgeBumpRequired { row, bump }) => {
142                    return Err(ArrowSchurGpuFailure::RidgeBumpRequired { row, bump });
143                }
144                Err(ArrowSchurGpuFailure::SchurFactorFailed { reason }) => {
145                    return Err(ArrowSchurGpuFailure::SchurFactorFailed { reason });
146                }
147                // Unavailable / GpuRequiresDenseSystem: fall through to the
148                // single-device paths (already shape-validated above).
149                Err(_) => {}
150            }
151        }
152        // Layer D admission: when the system shape passes the
153        // (Σ p³ ≥ 1e5 OR R ≥ 16) heuristic and `p ≤ MAX_FUSED_P`, the fused
154        // NVRTC kernel replaces the cuSOLVER/cuBLAS Layer A+B+C path with a
155        // single per-row block. Layer C↔D parity (math block 3 §16 test 6)
156        // requires both paths to agree to 1e-10 on identical inputs.
157        if crate::gpu_kernels::arrow_schur_nvrtc::system_admits_fused_path(sys) {
158            match cuda::solve_fused(sys, ridge_t, ridge_beta) {
159                Ok(sol) => return Ok(sol),
160                // RidgeBumpRequired must surface to the outer escalation loop —
161                // the fused path's pivot diagnostic is identical in semantics
162                // to the cuSOLVER batched POTRF info code.
163                Err(ArrowSchurGpuFailure::RidgeBumpRequired { row, bump }) => {
164                    return Err(ArrowSchurGpuFailure::RidgeBumpRequired { row, bump });
165                }
166                // Any other failure (Unavailable, SchurFactorFailed) falls
167                // through to the unfused path so a flaky NVRTC compile or
168                // shared-mem allocation does not abort the outer Newton step.
169                Err(_) => {}
170            }
171        }
172        cuda::solve(sys, ridge_t, ridge_beta)
173    }
174}
175
176/// Build the stacked column-major D buffer (n local d×d blocks), the stacked
177/// stacked B buffer (n local d×k blocks), and the stacked g buffer
178/// (n local d-vectors) consumed by the device pipeline. Each block is laid
179/// out column-major so a single allocation + `cuMemcpyHtoD` reaches the
180/// device without per-row dispatch overhead.
181#[cfg(target_os = "linux")]
182fn pack_host(sys: &ArrowSchurSystem, ridge_t: f64) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
183    let n = sys.rows.len();
184    let d = sys.d;
185    let k = sys.k;
186    let mut d_buf = Vec::with_capacity(n * d * d);
187    let mut b_buf = Vec::with_capacity(n * d * k);
188    let mut g_buf = Vec::with_capacity(n * d);
189    for row in &sys.rows {
190        pack_block(row, ridge_t, d, k, &mut d_buf, &mut b_buf, &mut g_buf);
191    }
192    (d_buf, b_buf, g_buf)
193}
194
195#[cfg(target_os = "linux")]
196#[inline]
197fn pack_block(
198    row: &crate::arrow_schur::ArrowRowBlock,
199    ridge_t: f64,
200    d: usize,
201    k: usize,
202    d_buf: &mut Vec<f64>,
203    b_buf: &mut Vec<f64>,
204    g_buf: &mut Vec<f64>,
205) {
206    for col in 0..d {
207        for r in 0..d {
208            let mut value = row.htt[[r, col]];
209            if r == col {
210                value += ridge_t;
211            }
212            d_buf.push(value);
213        }
214    }
215    for col in 0..k {
216        for r in 0..d {
217            b_buf.push(row.htbeta[[r, col]]);
218        }
219    }
220    for r in 0..d {
221        g_buf.push(row.gt[r]);
222    }
223}
224
225/// Test-only entry that forces the Layer D + E fused NVRTC path regardless
226/// of the admission heuristic. Used by the V100 Layer C↔D parity test to
227/// drive the fused kernel at small shapes the heuristic would otherwise
228/// route through the cuSOLVER/cuBLAS Layer A+B+C path.
229#[doc(hidden)]
230#[cfg_attr(not(target_os = "linux"), allow(unused_variables))] // `sys` is consumed only by the linux branch
231pub fn solve_arrow_newton_step_fused_force(
232    sys: &ArrowSchurSystem,
233    ridge_t: f64,
234    ridge_beta: f64,
235) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
236    if ridge_t.is_nan() || ridge_beta.is_nan() {
237        return Err(ArrowSchurGpuFailure::SchurFactorFailed {
238            reason: "ridge is NaN".to_string(),
239        });
240    }
241    #[cfg(not(target_os = "linux"))]
242    {
243        // No NVRTC toolchain off linux: the fused path is unconditionally
244        // unavailable. `sys` is consumed only by the linux branch below; the
245        // fn-level cfg_attr allows it to read as unused here without a banned
246        // `let _` binding or a no-op `drop` of the reference.
247        Err(ArrowSchurGpuFailure::Unavailable)
248    }
249    #[cfg(target_os = "linux")]
250    {
251        if crate::gpu_kernels::arrow_schur_nvrtc::plan_fused_launch(sys.rows.len(), sys.d, sys.k)
252            .is_none()
253        {
254            return Err(ArrowSchurGpuFailure::Unavailable);
255        }
256        cuda::solve_fused(sys, ridge_t, ridge_beta)
257    }
258}
259
260/// #1017 Phase 3: a device-resident Arrow-Schur frame whose constant Hessian
261/// blocks (`D = H_tt`, `B = H_tβ`, border `H_ββ`) and their factors stay on the
262/// device across the inner Newton loop. Construct once per frozen gate/basis
263/// frame, then call [`ResidentArrowFrameHandle::solve_gradient`] once per
264/// iterate with the fresh residual gradient — only the `O(n·d + p)` gradient
265/// crosses to the device and only `δ` crosses back, in contrast to
266/// [`solve_arrow_newton_step`] which re-uploads and re-factors the full system
267/// every call. On a non-CUDA host construction returns
268/// `ArrowSchurGpuFailure::Unavailable`.
269pub struct ResidentArrowFrameHandle {
270    #[cfg(target_os = "linux")]
271    inner: cuda::ResidentArrowFrame,
272    #[cfg(not(target_os = "linux"))]
273    _never: std::convert::Infallible,
274}
275
276impl ResidentArrowFrameHandle {
277    /// Upload the constant Hessian blocks and perform the one-time factor work.
278    pub fn new(
279        sys: &ArrowSchurSystem,
280        ridge_t: f64,
281        ridge_beta: f64,
282    ) -> Result<Self, ArrowSchurGpuFailure> {
283        // The dense device path requires materialised blocks, same admission as
284        // `solve_arrow_newton_step`.
285        if sys.hbb_matvec.is_some() || sys.htbeta_matvec.is_some() {
286            return Err(ArrowSchurGpuFailure::GpuRequiresDenseSystem {
287                had_hbb_matvec: sys.hbb_matvec.is_some(),
288                had_htbeta_matvec: sys.htbeta_matvec.is_some(),
289            });
290        }
291        #[cfg(not(target_os = "linux"))]
292        {
293            if ridge_t.is_nan() || ridge_beta.is_nan() {
294                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
295                    reason: "ridge is NaN".to_string(),
296                });
297            }
298            Err(ArrowSchurGpuFailure::Unavailable)
299        }
300        #[cfg(target_os = "linux")]
301        {
302            Ok(Self {
303                inner: cuda::ResidentArrowFrame::new(sys, ridge_t, ridge_beta)?,
304            })
305        }
306    }
307
308    /// Solve `H δ = −gradient` for a fresh gradient reusing the resident factors.
309    pub fn solve_gradient(
310        &self,
311        g_t: &[f64],
312        g_beta: &[f64],
313    ) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
314        #[cfg(not(target_os = "linux"))]
315        {
316            if g_t.iter().chain(g_beta).any(|v| !v.is_finite()) {
317                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
318                    reason: "non-finite gradient entry".to_string(),
319                });
320            }
321            Err(ArrowSchurGpuFailure::Unavailable)
322        }
323        #[cfg(target_os = "linux")]
324        {
325            self.inner.solve_gradient(g_t, g_beta)
326        }
327    }
328
329    /// `log|H|` for the frame (constant; depends only on the factored Hessian).
330    #[must_use]
331    pub fn log_det_hessian(&self) -> f64 {
332        #[cfg(not(target_os = "linux"))]
333        {
334            // SAFETY: off-CUDA, `ResidentArrowFrameHandle::new` always returns
335            // `Err(Unavailable)`, so no handle of this type is ever constructed and
336            // this method is statically unreachable on non-Linux targets. A NaN
337            // sentinel would silently corrupt any consumer of the log-determinant,
338            // so fail loudly on the impossible path instead.
339            panic!("ResidentArrowFrameHandle cannot be constructed off CUDA")
340        }
341        #[cfg(target_os = "linux")]
342        {
343            self.inner.log_det_hessian()
344        }
345    }
346}
347
348/// Build a GPU-backed Schur matvec closure for CPU-driven PCG at K ≥ 5000.
349///
350/// Runs the fused NVRTC forward kernel once on the dense per-row `H_tβ` slabs
351/// to compute `Y_i = L_i^{-1} H_tβ^(i)` for all rows, persists the `Y_i`
352/// factors in a host-side buffer, and returns an `Arc<dyn Fn(...)>` closure
353/// that computes the full Schur matvec
354///
355/// ```text
356/// S·x = (H_ββ + ridge_beta·I)·x  −  Σ_i Y_i^T (Y_i·x)
357/// ```
358///
359/// each time it is called. At K ≥ 5000 the `Σ_i Y_i^T (Y_i·x)` term
360/// dominates over the host↔device transfer of the K-vector `x`, so the GPU
361/// path is a clear win even with per-iteration transfer.
362///
363/// `H_ββ·x` is evaluated on the CPU using `sys.hbb_matvec` when present (the
364/// matrix-free hook for SAE-manifold scale callers) or the dense `sys.hbb`
365/// block otherwise. The `Y_i` term uses cuBLAS batched GEMV device-side; only
366/// `x` (K doubles) and `out` (K doubles) cross the host↔device boundary per
367/// PCG iteration.
368///
369/// Returns `Err(ArrowSchurGpuFailure::Unavailable)` if CUDA is unavailable or
370/// the system shape is outside the fused kernel's admission range (e.g.
371/// `d > MAX_FUSED_P = 32` or no CUDA context). Callers should fall back to CPU
372/// `InexactPCG` on `Unavailable`.
373///
374/// Returns `Err(ArrowSchurGpuFailure::RidgeBumpRequired)` if a per-row Cholesky
375/// factor failed at the requested `ridge_t`; the outer LM escalation should
376/// bump `ridge_t` and retry.
377///
378/// # Composition with the matrix-free SAE Kronecker operator
379///
380/// When `sys.htbeta_matvec` is set (matrix-free `H_tβ` Kronecker operator),
381/// the dense `H_tβ` slabs are absent — the dense forward kernel above cannot
382/// run, and at `K = 100K` the dense `Y_i = L_i^{-1} H_tβ^(i)` (`d × K` per row)
383/// could not be materialised anyway. Instead, `build_row_procedural_matvec`
384/// returns a row-procedural Schur matvec: per row it gathers
385/// `v_i = H_tβ^(i)·x` through the forward operator (sparse `O(m_i · p)`),
386/// solves `(H_tt^(i) + ρ_t·I)^{-1} v_i` through a pre-computed per-row Cholesky
387/// factor, and scatters `H_βt^(i)·w_i` through the sparse transpose operator
388/// (`O(m_i · p)`, replacing the old `O(K)` column-probe). This is the
389/// row-procedural `a_ik · Φ_k[i,m]` Kronecker apply over the active atoms only.
390pub fn gpu_schur_matvec_backend(
391    sys: &ArrowSchurSystem,
392    ridge_t: f64,
393    ridge_beta: f64,
394) -> Result<crate::arrow_schur::GpuSchurMatvec, ArrowSchurGpuFailure> {
395    // Matrix-free H_tβ operator present: drive the row-procedural sparse
396    // Kronecker apply (active atoms only) instead of the dense forward kernel.
397    if sys.htbeta_matvec.is_some() {
398        return build_row_procedural_matvec(sys, ridge_t, ridge_beta);
399    }
400
401    #[cfg(not(target_os = "linux"))]
402    {
403        // No CUDA runtime on non-Linux. NaN ridges are validated to ensure the
404        // same contract as the Linux path.
405        if ridge_t.is_nan() || ridge_beta.is_nan() {
406            return Err(ArrowSchurGpuFailure::Unavailable);
407        }
408        Err(ArrowSchurGpuFailure::Unavailable)
409    }
410
411    #[cfg(target_os = "linux")]
412    {
413        cuda::build_schur_matvec_backend(sys, ridge_t, ridge_beta)
414    }
415}
416
417/// Build a row-procedural reduced-Schur matvec for matrix-free SAE Kronecker
418/// systems, eliminating the per-row latent block via cached per-row Cholesky
419/// factors and applying the cross-block through the sparse forward/transpose
420/// Kronecker operators (active atoms only).
421///
422/// The returned closure evaluates
423/// `S·x = (H_ββ + ρ_β·I)·x − Σ_i H_βt^(i) (H_tt^(i) + ρ_t·I)^{-1} H_tβ^(i)·x`,
424/// the same reduced Schur complement the dense path forms, but never
425/// materialises the `d × K` cross-block `H_tβ^(i)`: the forward operator
426/// (`out = H_tβ^(i)·x`) and transpose operator (`out += H_βt^(i)·v`) are the
427/// sparse Kronecker gather/scatter from `SaeKroneckerRows`. The per-row factor
428/// of `H_tt^(i) + ρ_t·I` is computed once when the closure is built and reused
429/// across every CG iteration.
430///
431/// Returns `RidgeBumpRequired` if a per-row block is not positive definite at
432/// the requested `ridge_t`; the outer LM escalation bumps `ridge_t` and retries.
433fn build_row_procedural_matvec(
434    sys: &ArrowSchurSystem,
435    ridge_t: f64,
436    ridge_beta: f64,
437) -> Result<crate::arrow_schur::GpuSchurMatvec, ArrowSchurGpuFailure> {
438    use std::sync::Arc;
439    let n = sys.rows.len();
440    let k = sys.k;
441    let forward = sys
442        .htbeta_matvec
443        .clone()
444        .ok_or(ArrowSchurGpuFailure::Unavailable)?;
445    let transpose = sys.htbeta_transpose_matvec.clone().ok_or_else(|| {
446        // A forward operator without its sparse adjoint cannot be applied
447        // row-procedurally; this is a wiring error, surfaced as a Schur failure
448        // so the caller routes to the dense CPU path rather than misreporting a
449        // numerical bump.
450        ArrowSchurGpuFailure::SchurFactorFailed {
451            reason: "row-procedural Schur matvec requires htbeta_transpose_matvec; \
452                     forward operator installed without its sparse adjoint"
453                .to_string(),
454        }
455    })?;
456
457    // Pre-factor each per-row block H_tt^(i) + ρ_t·I = L_i L_iᵀ on the host.
458    // The blocks are tiny (d_i ≲ 32) and the dense cross-block slabs are
459    // absent, so there is no device forward-kernel work to amortise here; the
460    // GPU win is the reduced K-system solve in `solve_reduced_beta_pcg`.
461    let mut factors: Vec<Array2<f64>> = Vec::with_capacity(n);
462    for (i, row) in sys.rows.iter().enumerate() {
463        let di = row.htt.nrows();
464        if row.htt.ncols() != di || row.gt.len() != di {
465            return Err(ArrowSchurGpuFailure::SchurFactorFailed {
466                reason: format!("row {i}: malformed H_tt block {:?}", row.htt.dim()),
467            });
468        }
469        let mut block = row.htt.clone();
470        for r in 0..di {
471            block[[r, r]] += ridge_t;
472        }
473        let factor = cholesky_factor_in_place(block.view(), CholeskyGuard::NonnegativePivot)
474            .ok_or_else(|| {
475                let scale = row
476                    .htt
477                    .diag()
478                    .iter()
479                    .map(|v| v.abs())
480                    .fold(0.0_f64, f64::max)
481                    .max(1.0);
482                ArrowSchurGpuFailure::RidgeBumpRequired {
483                    row: i,
484                    bump: scale * f64::EPSILON.sqrt() * RIDGE_BUMP_EPS_MARGIN,
485                }
486            })?;
487        factors.push(factor);
488    }
489
490    // The SAE-manifold β-Hessian lives in the structured penalty operator
491    // (data-fit Gauss-Newton `G ⊗ I_p` + smoothness Kronecker blocks + any
492    // dense analytic-β residual), NOT in the dense `hbb` accumulator — for
493    // matrix-free systems `hbb` is zero/absent. Capture the effective penalty
494    // operator so `H_ββ·x` matches the CPU `schur_matvec` path exactly. The
495    // operator's `matvec` adds (`y += P x`), so seed `out` from the ridge term.
496    let penalty_op = sys.effective_penalty_op();
497    let row_dims: Vec<usize> = sys.rows.iter().map(|row| row.htt.nrows()).collect();
498
499    let closure: crate::arrow_schur::GpuSchurMatvec =
500        Arc::new(move |x: &Array1<f64>, out: &mut Array1<f64>| {
501            assert_eq!(x.len(), k, "row-procedural matvec: x.len() != k");
502            assert_eq!(out.len(), k, "row-procedural matvec: out.len() != k");
503
504            // (H_ββ + ρ_β·I)·x into out. Seed with the ridge term, then add the
505            // structured penalty-side product (penalty_op.matvec is additive).
506            {
507                let x_slice = x.as_slice().expect("x must be contiguous");
508                let out_slice = out.as_slice_mut().expect("out must be contiguous");
509                for a in 0..k {
510                    out_slice[a] = ridge_beta * x_slice[a];
511                }
512                penalty_op.matvec(x_slice, out_slice);
513            }
514
515            // out -= Σ_i H_βt^(i) (H_tt^(i) + ρ_t·I)^{-1} H_tβ^(i)·x.
516            //
517            // #1017: this row-procedural reduced-Schur term is the matrix-free
518            // SAE path's matvec hot loop (`build_row_procedural_matvec` is the
519            // host backend `gpu_schur_matvec_backend` returns when the dense
520            // `H_tβ` slabs are absent — the production Qwen shape). At
521            // (n≈2000 rows) it ran SERIALLY on one core and allocated a fresh
522            // length-`K` `neg` plus per-row `v_i`/`w_i` on EVERY CG iteration —
523            // tens of thousands of tiny heap allocations across a solve. Each
524            // row contributes an independent length-`K` scatter, so the sum is
525            // embarrassingly parallel; fan it across rayon over fixed row chunks
526            // and fold the per-chunk length-`K` partials in chunk order so the
527            // f64 reduction is deterministic (bit-identical run-to-run)
528            // regardless of thread scheduling — it agrees with the serial sum up
529            // to ULP-scale chunk reassociation (the #1017 verification gate).
530            // Because that reassociation is a real (if tiny) departure from
531            // serial, the criterion ranking across topology candidates is stable
532            // except for candidates separated by less than the reassociation
533            // margin, where the near-tie winner can flip — not an exact no-move
534            // guarantee (#1211). Stay
535            // sequential below
536            // `SCHUR_MATVEC_PARALLEL_ROW_MIN` rows and when already inside a
537            // rayon worker (the topology race fans candidates with
538            // `run_topology_race_parallel`) — the same nested-rayon guard the
539            // CPU `schur_matvec` uses. Buffers (`v_i`, `neg`) are reused across
540            // rows within a chunk, so the per-row allocation churn is gone.
541            let parallel = n >= crate::arrow_schur::SCHUR_MATVEC_PARALLEL_ROW_MIN
542                && rayon::current_thread_index().is_none();
543            if parallel {
544                use rayon::prelude::*;
545                const CHUNK: usize = 64;
546                let partials: Vec<Array1<f64>> = (0..n)
547                    .into_par_iter()
548                    .chunks(CHUNK)
549                    .map(|idxs| {
550                        // One length-`K` scatter accumulator per chunk; the
551                        // per-row latent vector `v_i` (length `d_i ≲ 32`) is the
552                        // only per-row buffer, sized to the row's own `d_i`.
553                        let mut neg = Array1::<f64>::zeros(k);
554                        for i in idxs {
555                            let di = row_dims[i];
556                            // v_i = H_tβ^(i)·x (sparse Kronecker gather).
557                            let mut v_i = Array1::<f64>::zeros(di);
558                            forward(i, x.view(), &mut v_i);
559                            // w_i = (H_tt^(i) + ρ_t·I)^{-1} v_i via L_i L_iᵀ.
560                            let w_i = cholesky_solve_vector(factors[i].view(), v_i.view());
561                            // neg += H_βt^(i)·w_i (sparse scatter).
562                            transpose(i, w_i.view(), &mut neg);
563                        }
564                        neg
565                    })
566                    .collect();
567                // #1017/#1175 floating-point parity contract: each chunk's row
568                // sum is formed locally, then chunk partials are folded
569                // left-to-right. That makes the parallel row-procedural Schur
570                // term deterministic for a fixed input and chunking, but it is
571                // not required to be bit-identical to the serial path because
572                // the additions are reassociated at chunk boundaries. CPU/GPU
573                // validation should therefore allow ULP-scale drift while
574                // expecting stable run-to-run results.
575                let mut neg = Array1::<f64>::zeros(k);
576                for part in &partials {
577                    for a in 0..k {
578                        neg[a] += part[a];
579                    }
580                }
581                for a in 0..k {
582                    out[a] -= neg[a];
583                }
584            } else {
585                // Serial path: reuse one `neg` and one `v_i` across rows.
586                let mut neg = Array1::<f64>::zeros(k);
587                for i in 0..n {
588                    let di = row_dims[i];
589                    // v_i = H_tβ^(i)·x (sparse Kronecker gather, length d_i).
590                    let mut v_i = Array1::<f64>::zeros(di);
591                    forward(i, x.view(), &mut v_i);
592                    // w_i = (H_tt^(i) + ρ_t·I)^{-1} v_i via L_i L_iᵀ.
593                    let w_i = cholesky_solve_vector(factors[i].view(), v_i.view());
594                    // neg += H_βt^(i)·w_i (sparse scatter); subtract once at end.
595                    transpose(i, w_i.view(), &mut neg);
596                }
597                for a in 0..k {
598                    out[a] -= neg[a];
599                }
600            }
601        });
602
603    Ok(closure)
604}
605
606/// Solve the reduced shared β-system `S·δβ = r` fully on device with a
607/// Jacobi-preconditioned conjugate-gradient (Steihaug truncated-CG) loop.
608///
609/// `S` is the already-reduced symmetric positive-definite `K × K` Schur
610/// complement the streaming SAE joint fit accumulates across minibatches
611/// (`StreamingArrowSchur::take_accumulators` summed over chunks, with the
612/// global β ridge folded in). The per-row latent blocks have already been
613/// eliminated into `S` on the host streaming path; the device's job is the
614/// dense `K`-dimensional solve, which is the dominant cost at `K = 100K`.
615///
616/// The dense `S·p` matvec runs on device via cuBLAS `Dgemv`, and the PCG state
617/// vectors (`x`, `r`, `z`, `p`, `S·p`) remain device-resident for the solve.
618/// Jacobi preconditioning is an elementwise CUDA kernel; only convergence
619/// scalars (`pᵀSp`, `rᵀz`, `‖r‖`) cross the host boundary per iteration, plus the
620/// final solution vector.
621///
622/// Returns `Err(ArrowSchurGpuFailure::Unavailable)` when CUDA is unavailable
623/// or the workload is below the dispatch policy; the caller then runs the CPU
624/// reduced-β solve. Returns `Err(ArrowSchurGpuFailure::SchurFactorFailed)`
625/// when `S` carries a non-positive Jacobi diagonal (caller escalates the
626/// proximal ridge).
627pub fn solve_reduced_beta_pcg(
628    s_acc: &Array2<f64>,
629    rhs_beta: &Array1<f64>,
630    max_iterations: usize,
631    relative_tolerance: f64,
632) -> Result<Array1<f64>, ArrowSchurGpuFailure> {
633    solve_reduced_beta_pcg_with_diagnostics(s_acc, rhs_beta, max_iterations, relative_tolerance)
634        .map(|(x, _)| x)
635}
636
637#[doc(hidden)]
638pub fn solve_reduced_beta_pcg_with_diagnostics(
639    s_acc: &Array2<f64>,
640    rhs_beta: &Array1<f64>,
641    max_iterations: usize,
642    relative_tolerance: f64,
643) -> Result<(Array1<f64>, PcgDiagnostics), ArrowSchurGpuFailure> {
644    let k = rhs_beta.len();
645    if s_acc.dim() != (k, k) {
646        return Err(ArrowSchurGpuFailure::SchurFactorFailed {
647            reason: format!(
648                "reduced-β GPU PCG requires a square (k×k) Schur block; got {:?} for k={k}",
649                s_acc.dim()
650            ),
651        });
652    }
653    if k == 0 {
654        return Err(ArrowSchurGpuFailure::Unavailable);
655    }
656
657    #[cfg(not(target_os = "linux"))]
658    {
659        if relative_tolerance.is_nan() || max_iterations == 0 {
660            return Err(ArrowSchurGpuFailure::SchurFactorFailed {
661                reason: "reduced-β GPU PCG: invalid CG controls".to_string(),
662            });
663        }
664        Err(ArrowSchurGpuFailure::Unavailable)
665    }
666
667    #[cfg(target_os = "linux")]
668    {
669        cuda::solve_reduced_beta_pcg_with_diagnostics(
670            s_acc,
671            rhs_beta,
672            max_iterations,
673            relative_tolerance,
674        )
675    }
676}
677
678pub fn solve_sae_matrix_free_pcg(
679    sys: &ArrowSchurSystem,
680    data: &DeviceSaePcgData,
681    ridge_t: f64,
682    ridge_beta: f64,
683    rhs_beta: &Array1<f64>,
684    max_iterations: usize,
685    relative_tolerance: f64,
686) -> Result<(Array1<f64>, PcgDiagnostics), ArrowSchurGpuFailure> {
687    if sys.k != data.beta_dim || rhs_beta.len() != data.beta_dim || data.p == 0 {
688        return Err(ArrowSchurGpuFailure::Unavailable);
689    }
690    #[cfg(not(target_os = "linux"))]
691    {
692        if ridge_t.is_nan()
693            || ridge_beta.is_nan()
694            || relative_tolerance.is_nan()
695            || max_iterations == 0
696        {
697            return Err(ArrowSchurGpuFailure::SchurFactorFailed {
698                reason: "SAE matrix-free GPU PCG: invalid controls".to_string(),
699            });
700        }
701        Err(ArrowSchurGpuFailure::Unavailable)
702    }
703    #[cfg(target_os = "linux")]
704    {
705        // #1017/#1026 dispatch GUARD: framed data (frame metadata present) carries
706        // a factored β border `G ⊗ W_{ij}` data Hessian and dense per-row cross
707        // blocks the legacy `⊗ I_p` kernel CANNOT represent — feeding it framed
708        // data would silently return a WRONG Newton step (it returns Ok with no
709        // fallback). Route framed systems to the dedicated framed kernel and
710        // legacy full-`B` systems to the legacy kernel; the two never cross.
711        if data.frame.is_some() {
712            cuda::solve_sae_matrix_free_pcg_framed(
713                sys,
714                data,
715                ridge_t,
716                ridge_beta,
717                rhs_beta,
718                max_iterations,
719                relative_tolerance,
720            )
721        } else {
722            cuda::solve_sae_matrix_free_pcg(
723                sys,
724                data,
725                ridge_t,
726                ridge_beta,
727                rhs_beta,
728                max_iterations,
729                relative_tolerance,
730            )
731        }
732    }
733}
734
735/// Reference dense back-end used by tests and as the fallback when the
736/// GPU declines. Kept here (not in `arrow_schur_gpu.rs`) so the validation
737/// suite has one canonical baseline.
738#[doc(hidden)]
739pub fn solve_arrow_newton_step_dense_reference(
740    sys: &ArrowSchurSystem,
741    ridge_t: f64,
742    ridge_beta: f64,
743) -> Result<ArrowSchurGpuSolution, String> {
744    let n = sys.rows.len();
745    let d = sys.d;
746    let k = sys.k;
747    let total = n.checked_mul(d).ok_or("dimension overflow")? + k;
748    let mut h = Array2::<f64>::zeros((total, total));
749    let mut rhs = Array1::<f64>::zeros(total);
750    for (i, row) in sys.rows.iter().enumerate() {
751        let base = i * d;
752        for c in 0..d {
753            for r in 0..d {
754                h[[base + r, base + c]] = row.htt[[r, c]];
755            }
756            h[[base + c, base + c]] += ridge_t;
757        }
758        for c in 0..k {
759            for r in 0..d {
760                let value = row.htbeta[[r, c]];
761                h[[base + r, n * d + c]] = value;
762                h[[n * d + c, base + r]] = value;
763            }
764        }
765        for r in 0..d {
766            rhs[base + r] = -row.gt[r];
767        }
768    }
769    for c in 0..k {
770        for r in 0..k {
771            h[[n * d + r, n * d + c]] += sys.hbb[[r, c]];
772        }
773        h[[n * d + c, n * d + c]] += ridge_beta;
774        rhs[n * d + c] = -sys.gb[c];
775    }
776    let factor = cholesky_factor_in_place(h.view(), CholeskyGuard::NonnegativePivot)
777        .ok_or_else(|| "dense reference Cholesky failed".to_string())?;
778    let mut log_det = 0.0_f64;
779    for i in 0..total {
780        log_det += factor[[i, i]].ln();
781    }
782    log_det *= 2.0;
783    let solved = cholesky_solve_vector(factor.view(), rhs.view());
784    let delta_t = solved.slice(ndarray::s![..n * d]).to_owned();
785    let delta_beta = solved.slice(ndarray::s![n * d..]).to_owned();
786    Ok(ArrowSchurGpuSolution {
787        delta_t,
788        delta_beta,
789        log_det_hessian: log_det,
790    })
791}
792
793/// Frames-engaged reduced-Schur penalty-side matvec `out = (P_ββ + ρ_β I)·x`,
794/// computed purely from the factored device data (issue #1017/#1026). This is
795/// the CPU bit-parity ORACLE for the GPU `arrow_sae_*` penalty kernels on the
796/// frames path: smooth `λ S_k ⊗ I_{r_k}` (each `smooth_blocks[i]` at its
797/// `global_offset` with right-width `frame.smooth_ranks[i]`) plus data-fit
798/// `G_{ij} ⊗ W_{ij}` (each `frame.frame_blocks` entry, with the `μ`-major /
799/// frame-minor index `border_offset[atom] + basis·r + frame_coord`). The
800/// accumulation order matches the device kernels exactly.
801///
802/// `out` is OVERWRITTEN: first set to `ρ_β·x`, then the penalty blocks add in.
803#[doc(hidden)]
804pub fn sae_framed_penalty_matvec_cpu(
805    data: &DeviceSaePcgData,
806    ridge_beta: f64,
807    x: &[f64],
808    out: &mut [f64],
809) {
810    let frame = data
811        .frame
812        .as_ref()
813        .expect("sae_framed_penalty_matvec_cpu requires frame metadata");
814    let k = data.beta_dim;
815    for a in 0..k {
816        out[a] = ridge_beta * x[a];
817    }
818    // Smooth penalty `λ S_k ⊗ I_{r_k}`: y[off + ia·r + ib] += Σ_ja S[ia,ja]·x[off + ja·r + ib].
819    for (blk, &r) in data.smooth_blocks.iter().zip(frame.smooth_ranks.iter()) {
820        let off = blk.global_offset;
821        let m = blk.factor_a.nrows();
822        for i_a in 0..m {
823            for i_b in 0..r {
824                let mut acc = 0.0_f64;
825                for j_a in 0..m {
826                    let s = blk.factor_a[[i_a, j_a]];
827                    if s == 0.0 {
828                        continue;
829                    }
830                    acc += s * x[off + j_a * r + i_b];
831                }
832                out[off + i_a * r + i_b] += acc;
833            }
834        }
835    }
836    // Data-fit penalty `G_{ij} ⊗ W_{ij}`.
837    for blk in &frame.frame_blocks {
838        let r_i = frame.ranks[blk.atom_i];
839        let r_j = frame.ranks[blk.atom_j];
840        let off_i = frame.border_offsets[blk.atom_i];
841        let off_j = frame.border_offsets[blk.atom_j];
842        let (m_i, m_j) = blk.g.dim();
843        for li in 0..m_i {
844            let yi_base = off_i + li * r_i;
845            for lj in 0..m_j {
846                let g = blk.g[[li, lj]];
847                if g == 0.0 {
848                    continue;
849                }
850                let xj_base = off_j + lj * r_j;
851                for a in 0..r_i {
852                    let mut acc = 0.0_f64;
853                    for b in 0..r_j {
854                        acc += blk.w[[a, b]] * x[xj_base + b];
855                    }
856                    out[yi_base + a] += g * acc;
857                }
858            }
859        }
860    }
861}
862
863/// Frames-engaged FULL reduced-Schur matvec `out = S·x` purely from the device
864/// data, where `S = (P_ββ + ρ_β I) − Σ_i H_βt^(i)(H_tt^(i)+ρ_t I)⁻¹ H_tβ^(i)`
865/// (issue #1017/#1026). The penalty side is [`sae_framed_penalty_matvec_cpu`];
866/// the per-row reduced term reads the dense `frame.row_htbeta[i]`
867/// (`q_i × border_dim`, row-major), solves against the row's
868/// `H_tt^(i)+ρ_t I` Cholesky factor, and scatters the transpose back. This is
869/// the size-independent bit-parity oracle the device kernel mirrors; it is also
870/// the matvec the GPU PCG iterates.
871#[doc(hidden)]
872pub fn sae_framed_schur_matvec_cpu(
873    sys: &ArrowSchurSystem,
874    data: &DeviceSaePcgData,
875    ridge_t: f64,
876    ridge_beta: f64,
877    x: &[f64],
878    out: &mut [f64],
879) -> Result<(), String> {
880    let frame = data
881        .frame
882        .as_ref()
883        .ok_or("sae_framed_schur_matvec_cpu requires frame metadata")?;
884    let k = data.beta_dim;
885    sae_framed_penalty_matvec_cpu(data, ridge_beta, x, out);
886    if frame.row_htbeta.len() != sys.rows.len() {
887        return Err(format!(
888            "sae_framed_schur_matvec_cpu: {} row_htbeta slabs but {} rows",
889            frame.row_htbeta.len(),
890            sys.rows.len()
891        ));
892    }
893    for (i, row) in sys.rows.iter().enumerate() {
894        let slab = &frame.row_htbeta[i];
895        if slab.is_empty() {
896            continue;
897        }
898        let qi = sys.row_dims[i];
899        if qi == 0 || slab.len() != qi * k {
900            continue;
901        }
902        // h = H_tβ^(i) · x  (length q_i).
903        let mut h = vec![0.0_f64; qi];
904        for c in 0..qi {
905            let base = c * k;
906            let mut acc = 0.0_f64;
907            for a in 0..k {
908                acc += slab[base + a] * x[a];
909            }
910            h[c] = acc;
911        }
912        // solve (H_tt^(i)+ρ_t I) s = h.
913        let mut block = row.htt.clone();
914        for d in 0..qi {
915            block[[d, d]] += ridge_t;
916        }
917        let factor = cholesky_factor_in_place(block.view(), CholeskyGuard::NonnegativePivot)
918            .ok_or_else(|| format!("sae_framed_schur_matvec_cpu: row {i} H_tt not PD"))?;
919        let s = cholesky_solve_vector(factor.view(), Array1::from_vec(h).view());
920        // out -= H_βt^(i) · s = (H_tβ^(i))ᵀ · s.
921        for c in 0..qi {
922            let sc = s[c];
923            if sc == 0.0 {
924                continue;
925            }
926            let base = c * k;
927            for a in 0..k {
928                out[a] -= slab[base + a] * sc;
929            }
930        }
931    }
932    Ok(())
933}
934
935#[cfg(target_os = "linux")]
936mod cuda {
937    use super::{ArrowSchurGpuFailure, ArrowSchurGpuSolution, pack_block, pack_host};
938    use gam_gpu::driver::to_i32;
939    use gam_gpu::linalg_dispatch::{DispatchOp, route_through_gpu};
940    use crate::arrow_schur::{
941        ArrowSchurSystem, DeviceSaeFrameData, DeviceSaePcgData, PcgDiagnostics, PcgStopReason,
942    };
943    use cudarc::cublas::sys::{
944        cublasDiagType_t, cublasFillMode_t, cublasOperation_t, cublasSideMode_t, cublasStatus_t,
945    };
946    use cudarc::cublas::{CudaBlas, Gemm, GemmConfig, Gemv, GemvConfig};
947    use cudarc::cusolver::{DnHandle, sys as cusolver_sys};
948    use cudarc::driver::{
949        CudaContext, CudaModule, CudaSlice, CudaStream, DevicePtr, DevicePtrMut, LaunchConfig,
950        PushKernelArg,
951    };
952    use ndarray::Array1;
953    use std::sync::{Arc, OnceLock};
954
955    /// Per-row work slot for the row-block-granular multi-GPU solve. Inputs are
956    /// the packed single-row buffers (`d×d` D block + ρ_t ridge, `d×k` B block,
957    /// `d` g vector); the forward pass fills the whitened factors `l/u/y` and the
958    /// per-tile reduction lands in the tile's leading slot.
959    struct RowSlot {
960        // Inputs (packed once on the host, column-major).
961        d_block: Vec<f64>, // d*d
962        b_block: Vec<f64>, // d*k
963        g_vec: Vec<f64>,   // d
964        diag_scale: f64,   // |diag(H_tt)| scale for the ridge-bump diagnostic
965        // Forward outputs, kept on the host for the back-sub pass.
966        l_block: Vec<f64>, // d*d lower factor, column-major
967        u_vec: Vec<f64>,   // d   (= L^{-1} g)
968        y_block: Vec<f64>, // d*k (= L^{-1} B), column-major
969        log_det_local: f64,
970        // Set on a non-PD pivot so the orchestrator can raise RidgeBumpRequired
971        // for the offending global row instead of silently falling back.
972        bump: Option<f64>,
973        // Tile-level reduction, written into the tile's first slot only.
974        tile_partial_schur: Option<Vec<f64>>, // k*k col-major, = Σ Y_iᵀY_i
975        tile_partial_rhs: Option<Vec<f64>>,   // k, = Σ Y_iᵀu_i
976        // Back-sub output for this row.
977        delta_t_block: Vec<f64>, // d
978    }
979
980    /// Row-block-granular multi-GPU Arrow-Schur Newton solve.
981    ///
982    /// The solve is separable across row blocks in both phases:
983    ///   * forward — each row's local Cholesky `L_i`, whitening
984    ///     `u_i = L_i⁻¹g_i`, `Y_i = L_i⁻¹B_i`, and partial Schur
985    ///     `(Σ Y_iᵀY_i, Σ Y_iᵀu_i)` are independent;
986    ///   * backward — `δt_i = -L_iᵀ⁻¹(u_i + Y_iδβ)` is independent.
987    /// Only the small shared `K×K` reduce + factor + `δβ` solve is central.
988    ///
989    /// `gam_gpu::pool::scatter_batched` hands each device a contiguous row
990    /// tile on its own bound context/stream; the per-tile forward keeps the
991    /// POTRF fused with its dependent TRSM + Schur GEMM on that one stream, so no
992    /// on-stream solve is orphaned. Tile partials and per-tile `log|L|` are
993    /// reduced on the host (in tile/row order), `S_β` is factored on the primary
994    /// device, and the back-sub is scattered back across the same tiles.
995    ///
996    /// Returns `Unavailable` (caller uses a single-device path) when the system
997    /// carries matrix-free operators, the shared block is not dense `K×K`, the
998    /// pool is single-device, or any tile's device work declines. A non-PD tip
999    /// block surfaces as `RidgeBumpRequired` for the precise global row.
1000    pub(super) fn solve_multi_gpu(
1001        sys: &ArrowSchurSystem,
1002        ridge_t: f64,
1003        ridge_beta: f64,
1004    ) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
1005        let n = sys.rows.len();
1006        let d = sys.d;
1007        let k = sys.k;
1008        if n == 0 || d == 0 || k == 0 {
1009            return Err(ArrowSchurGpuFailure::Unavailable);
1010        }
1011        // Dense shared block + materialised per-row slabs are required; the
1012        // public entry already rejected matrix-free operators, but re-check so
1013        // this routine is safe in isolation.
1014        if sys.hbb_matvec.is_some() || sys.htbeta_matvec.is_some() || sys.hbb.dim() != (k, k) {
1015            return Err(ArrowSchurGpuFailure::Unavailable);
1016        }
1017
1018        let runtime = gam_gpu::device_runtime::GpuRuntime::global()
1019            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
1020        if runtime.device_count() < 2 {
1021            return Err(ArrowSchurGpuFailure::Unavailable);
1022        }
1023
1024        // Pack one slot per row (column-major), folding ρ_t into each D block.
1025        let mut slots: Vec<RowSlot> = Vec::with_capacity(n);
1026        for row in &sys.rows {
1027            if row.htt.dim() != (d, d) || row.htbeta.dim() != (d, k) || row.gt.len() != d {
1028                return Err(ArrowSchurGpuFailure::Unavailable);
1029            }
1030            let mut d_block = Vec::with_capacity(d * d);
1031            let mut b_block = Vec::with_capacity(d * k);
1032            let mut g_vec = Vec::with_capacity(d);
1033            pack_block(row, ridge_t, d, k, &mut d_block, &mut b_block, &mut g_vec);
1034            let diag_scale = row
1035                .htt
1036                .diag()
1037                .iter()
1038                .map(|v| v.abs())
1039                .fold(0.0_f64, f64::max)
1040                .max(1.0);
1041            slots.push(RowSlot {
1042                d_block,
1043                b_block,
1044                g_vec,
1045                diag_scale,
1046                l_block: Vec::new(),
1047                u_vec: Vec::new(),
1048                y_block: Vec::new(),
1049                log_det_local: 0.0,
1050                bump: None,
1051                tile_partial_schur: None,
1052                tile_partial_rhs: None,
1053                delta_t_block: vec![0.0; d],
1054            });
1055        }
1056
1057        // ---- Forward pass: per-device row tile, fused on its own stream ----
1058        let forward_ok = gam_gpu::pool::scatter_batched(runtime, &mut slots, |ordinal, tile| {
1059            forward_tile(ordinal, d, k, tile)
1060        });
1061        if forward_ok.is_none() {
1062            return Err(ArrowSchurGpuFailure::Unavailable);
1063        }
1064
1065        // Surface a non-PD tip block as a precise per-row ridge bump.
1066        let row_base_of_tile = gam_gpu::pool::balanced_partition(runtime, n);
1067        if let Some((row, bump)) = slots
1068            .iter()
1069            .enumerate()
1070            .find_map(|(i, slot)| slot.bump.map(|b| (i, b)))
1071        {
1072            return Err(ArrowSchurGpuFailure::RidgeBumpRequired { row, bump });
1073        }
1074
1075        // ---- Central: reduce tile partials → S_β, r_β; factor; solve δβ ----
1076        // Seed S_β with H_ββ + ρ_β I (column-major) and r_β with -g_β, then fold
1077        // in the per-tile partials in tile order so the reduction order tracks
1078        // the single-device accumulation (up to inter-tile reassociation).
1079        let mut schur_host = vec![0.0_f64; k * k];
1080        for col in 0..k {
1081            for row in 0..k {
1082                let mut v = sys.hbb[[row, col]];
1083                if row == col {
1084                    v += ridge_beta;
1085                }
1086                schur_host[col * k + row] = v;
1087            }
1088        }
1089        let mut rhs_host: Vec<f64> = sys.gb.iter().map(|v| -v).collect();
1090        let mut log_det = 0.0_f64;
1091        for start in tile_starts(&row_base_of_tile) {
1092            let slot = &slots[start];
1093            let partial_schur = slot
1094                .tile_partial_schur
1095                .as_ref()
1096                .ok_or(ArrowSchurGpuFailure::Unavailable)?;
1097            let partial_rhs = slot
1098                .tile_partial_rhs
1099                .as_ref()
1100                .ok_or(ArrowSchurGpuFailure::Unavailable)?;
1101            // `accumulate_schur` writes `partial_schur = -Σ_tile Y_iᵀY_i` (GEMM
1102            // α=-1, β=1 into a zero seed) and `partial_rhs = +Σ_tile Y_iᵀu_i`.
1103            // The reduced Schur is `S = (H_ββ+ρI) − Σ_all Y_iᵀY_i`, so adding the
1104            // (already-negated) partials reproduces the single-device sign.
1105            for idx in 0..k * k {
1106                schur_host[idx] += partial_schur[idx];
1107            }
1108            for a in 0..k {
1109                rhs_host[a] += partial_rhs[a];
1110            }
1111        }
1112        for slot in &slots {
1113            log_det += slot.log_det_local;
1114        }
1115
1116        // Factor S_β and solve δβ on the primary device (small K×K leaf). The
1117        // stream carries the primary context (same pattern as `solve()`); no
1118        // thread bind is needed for the cuSOLVER/cuBLAS handles created from it.
1119        let primary = runtime.selected_device().ordinal;
1120        let stream = gam_gpu::device_runtime::cuda_context_for(primary)
1121            .and_then(|ctx| ctx.new_stream().ok())
1122            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
1123        let solver =
1124            DnHandle::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1125        let blas = CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1126        let mut schur_dev = stream
1127            .clone_htod(&schur_host)
1128            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1129        let mut rhs_dev = stream
1130            .clone_htod(&rhs_host)
1131            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1132        let info = potrf_single(&solver, &stream, k, &mut schur_dev)?;
1133        if info != 0 {
1134            return Err(ArrowSchurGpuFailure::SchurFactorFailed {
1135                reason: format!("multi-GPU Schur Cholesky failed at pivot {info}"),
1136            });
1137        }
1138        trsm_single(&blas, &stream, k, &schur_dev, &mut rhs_dev, false, false)?;
1139        trsm_single(&blas, &stream, k, &schur_dev, &mut rhs_dev, false, true)?;
1140        let delta_beta_host = stream
1141            .clone_dtoh(&rhs_dev)
1142            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1143        let delta_beta = Array1::from_vec(delta_beta_host.clone());
1144        let l_schur_host = stream
1145            .clone_dtoh(&schur_dev)
1146            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1147        for j in 0..k {
1148            log_det += l_schur_host[j * k + j].ln();
1149        }
1150        log_det *= 2.0;
1151
1152        // ---- Backward pass: δt_i = -L_iᵀ⁻¹(u_i + Y_iδβ), per-device tile ----
1153        let delta_beta_ref = &delta_beta_host;
1154        let back_ok = gam_gpu::pool::scatter_batched(runtime, &mut slots, |ordinal, tile| {
1155            back_sub_tile(ordinal, d, k, delta_beta_ref, tile)
1156        });
1157        if back_ok.is_none() {
1158            return Err(ArrowSchurGpuFailure::Unavailable);
1159        }
1160
1161        // Stitch per-row δt into the stacked (n*d) result.
1162        let mut delta_t = Array1::<f64>::zeros(n * d);
1163        for (i, slot) in slots.iter().enumerate() {
1164            let base = i * d;
1165            for r in 0..d {
1166                delta_t[base + r] = slot.delta_t_block[r];
1167            }
1168        }
1169
1170        Ok(ArrowSchurGpuSolution {
1171            delta_t,
1172            delta_beta,
1173            log_det_hessian: log_det,
1174        })
1175    }
1176
1177    /// Tile starts: the leading global row index of each device tile (where the
1178    /// tile-level partial reduction was written by the forward pass).
1179    fn tile_starts(tiles: &[(usize, std::ops::Range<usize>)]) -> impl Iterator<Item = usize> + '_ {
1180        tiles.iter().map(|(_, range)| range.start)
1181    }
1182
1183    /// Forward pass for one device row tile, running on `ordinal`'s bound stream.
1184    /// Factors each row block, whitens `u`/`Y`, accumulates the tile's partial
1185    /// Schur `(Σ Y_iᵀY_i, Σ Y_iᵀu_i)` into the tile's leading slot, keeps the
1186    /// per-row `L`/`u`/`Y` on the host for back-sub, and records the per-row
1187    /// `Σ_j log L_jj`. A non-PD pivot is recorded in `slot.bump` (the tile still
1188    /// returns `Some(())` so the orchestrator raises a precise `RidgeBumpRequired`
1189    /// rather than collapsing the whole batch to CPU).
1190    fn forward_tile(ordinal: usize, d: usize, k: usize, tile: &mut [RowSlot]) -> Option<()> {
1191        if tile.is_empty() {
1192            return Some(());
1193        }
1194        // `scatter_batched` has already bound this ordinal's context on this
1195        // worker thread; the stream below targets that same device.
1196        let stream = gam_gpu::device_runtime::cuda_context_for(ordinal)
1197            .and_then(|ctx| ctx.new_stream().ok())?;
1198        let solver = DnHandle::new(stream.clone()).ok()?;
1199        let blas = CudaBlas::new(stream.clone()).ok()?;
1200        let m = tile.len();
1201
1202        // Stack the tile's D, B, g into contiguous device buffers (same layout
1203        // the single-device path packs for `m` rows).
1204        let mut d_host = Vec::with_capacity(m * d * d);
1205        let mut b_host = Vec::with_capacity(m * d * k);
1206        let mut g_host = Vec::with_capacity(m * d);
1207        for slot in tile.iter() {
1208            d_host.extend_from_slice(&slot.d_block);
1209            b_host.extend_from_slice(&slot.b_block);
1210            g_host.extend_from_slice(&slot.g_vec);
1211        }
1212        let mut d_dev = stream.clone_htod(&d_host).ok()?;
1213        let mut b_dev = stream.clone_htod(&b_host).ok()?;
1214        let mut g_dev = stream.clone_htod(&g_host).ok()?;
1215
1216        // Batched POTRF; a non-PD block records its bump and stops the tile.
1217        let info_host = potrf_batched(&solver, &stream, d, m, &mut d_dev).ok()?;
1218        if let Some(local) = info_host.iter().position(|info| *info != 0) {
1219            let pivot = info_host[local];
1220            tile[local].bump = Some(
1221                tile[local].diag_scale
1222                    * (f64::from(pivot).abs()).max(1.0)
1223                    * f64::EPSILON.sqrt()
1224                    * super::RIDGE_BUMP_EPS_MARGIN,
1225            );
1226            return Some(());
1227        }
1228
1229        // Whiten: u = L⁻¹ g, Y = L⁻¹ B.
1230        trsm_batched_lower_inplace(&blas, &stream, d, m, 1, &d_dev, &mut g_dev).ok()?;
1231        trsm_batched_lower_inplace(&blas, &stream, d, m, k, &d_dev, &mut b_dev).ok()?;
1232
1233        // Tile partial Schur: zero-seeded so the host adds the H_ββ seed once.
1234        let mut schur_dev = stream.alloc_zeros::<f64>(k * k).ok()?;
1235        let mut rhs_dev = stream.alloc_zeros::<f64>(k).ok()?;
1236        accumulate_schur(&blas, d, k, m, &b_dev, &g_dev, &mut schur_dev, &mut rhs_dev).ok()?;
1237
1238        // Download L, u, Y, and the tile partials.
1239        let l_host = stream.clone_dtoh(&d_dev).ok()?;
1240        let u_host = stream.clone_dtoh(&g_dev).ok()?;
1241        let y_host = stream.clone_dtoh(&b_dev).ok()?;
1242        let partial_schur = stream.clone_dtoh(&schur_dev).ok()?;
1243        let partial_rhs = stream.clone_dtoh(&rhs_dev).ok()?;
1244
1245        for (local, slot) in tile.iter_mut().enumerate() {
1246            let l_base = local * d * d;
1247            let u_base = local * d;
1248            let y_base = local * d * k;
1249            slot.l_block = l_host[l_base..l_base + d * d].to_vec();
1250            slot.u_vec = u_host[u_base..u_base + d].to_vec();
1251            slot.y_block = y_host[y_base..y_base + d * k].to_vec();
1252            let mut log_det_local = 0.0_f64;
1253            for j in 0..d {
1254                log_det_local += l_host[l_base + j * d + j].ln();
1255            }
1256            slot.log_det_local = log_det_local;
1257        }
1258        tile[0].tile_partial_schur = Some(partial_schur);
1259        tile[0].tile_partial_rhs = Some(partial_rhs);
1260        Some(())
1261    }
1262
1263    /// Back-substitution for one device row tile: `δt_i = -L_iᵀ⁻¹(u_i + Y_iδβ)`.
1264    /// Re-uploads the tile's kept `L`/`u`/`Y` to `ordinal`, applies the GEMV
1265    /// accumulate + transposed TRSM, and writes each row's `δt` into its slot.
1266    fn back_sub_tile(
1267        ordinal: usize,
1268        d: usize,
1269        k: usize,
1270        delta_beta: &[f64],
1271        tile: &mut [RowSlot],
1272    ) -> Option<()> {
1273        if tile.is_empty() {
1274            return Some(());
1275        }
1276        // `scatter_batched` has already bound this ordinal's context on this
1277        // worker thread; the stream below targets that same device.
1278        let stream = gam_gpu::device_runtime::cuda_context_for(ordinal)
1279            .and_then(|ctx| ctx.new_stream().ok())?;
1280        let blas = CudaBlas::new(stream.clone()).ok()?;
1281        let m = tile.len();
1282
1283        let mut l_host = Vec::with_capacity(m * d * d);
1284        let mut u_host = Vec::with_capacity(m * d);
1285        let mut y_host = Vec::with_capacity(m * d * k);
1286        for slot in tile.iter() {
1287            l_host.extend_from_slice(&slot.l_block);
1288            u_host.extend_from_slice(&slot.u_vec);
1289            y_host.extend_from_slice(&slot.y_block);
1290        }
1291        let d_dev = stream.clone_htod(&l_host).ok()?;
1292        let mut g_dev = stream.clone_htod(&u_host).ok()?;
1293        let b_dev = stream.clone_htod(&y_host).ok()?;
1294        let rhs_dev = stream.clone_htod(&delta_beta.to_vec()).ok()?;
1295
1296        // g ← u + Y·δβ, then x = L⁻ᵀ g; δt = -x.
1297        accumulate_back_sub_rhs(&blas, d, k, m, &b_dev, &rhs_dev, &mut g_dev).ok()?;
1298        trsm_batched_lower_inplace_transposed(&blas, &stream, d, m, 1, &d_dev, &mut g_dev).ok()?;
1299        let x_host = stream.clone_dtoh(&g_dev).ok()?;
1300        for (local, slot) in tile.iter_mut().enumerate() {
1301            let base = local * d;
1302            for r in 0..d {
1303                slot.delta_t_block[r] = -x_host[base + r];
1304            }
1305        }
1306        Some(())
1307    }
1308
1309    pub(super) fn solve(
1310        sys: &ArrowSchurSystem,
1311        ridge_t: f64,
1312        ridge_beta: f64,
1313    ) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
1314        let n = sys.rows.len();
1315        let d = sys.d;
1316        let k = sys.k;
1317        let runtime = route_through_gpu(DispatchOp::SmallDenseBatchedPotrf { p: d, batch: n })
1318            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
1319
1320        let stream = gam_gpu::device_runtime::cuda_context_for(runtime.device.ordinal)
1321            .and_then(|ctx| ctx.new_stream().ok())
1322            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
1323        let solver =
1324            DnHandle::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1325        let blas = CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1326
1327        // ----- Pack + upload D, B, g -----
1328        let (d_host, b_host, g_host) = pack_host(sys, ridge_t);
1329        let mut d_dev = stream
1330            .clone_htod(&d_host)
1331            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1332        let mut b_dev = stream
1333            .clone_htod(&b_host)
1334            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1335        let mut g_dev = stream
1336            .clone_htod(&g_host)
1337            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1338
1339        // ----- Layer A: batched lower Cholesky of D in place -----
1340        // This POTRF is fused with the downstream TRSM + Schur GEMM + back-sub
1341        // on this one stream, so splitting only the POTRF across devices would
1342        // orphan the dependent on-stream solves. Multi-GPU here is the
1343        // whole-solve row-block split in `solve_arrow_newton_step` (see
1344        // `solve_multi_gpu`), not a per-layer split — this device-resident path
1345        // is the single-device leaf the split dispatches per tile.
1346        let info_host = potrf_batched(&solver, &stream, d, n, &mut d_dev)?;
1347        if let Some(idx) = info_host.iter().position(|info| *info != 0) {
1348            let pivot = info_host[idx];
1349            let scale = sys.rows[idx]
1350                .htt
1351                .diag()
1352                .iter()
1353                .map(|v| v.abs())
1354                .fold(0.0_f64, f64::max)
1355                .max(1.0);
1356            return Err(ArrowSchurGpuFailure::RidgeBumpRequired {
1357                row: idx,
1358                bump: scale * (pivot.abs() as f64).max(1.0) * f64::EPSILON.sqrt() * 1024.0,
1359            });
1360        }
1361
1362        // ----- Layer B (1/2): in-place triangular solves -----
1363        // u_i = L_i^{-1} g_i, packed as a stacked (n*d) column-vector.
1364        trsm_batched_lower_inplace(&blas, &stream, d, n, 1, &d_dev, &mut g_dev)?;
1365        // Y_i = L_i^{-1} B_i, in place over the (n*d) × k buffer (laid out as
1366        // n stacked column-major d×k tiles).
1367        trsm_batched_lower_inplace(&blas, &stream, d, n, k, &d_dev, &mut b_dev)?;
1368
1369        // ----- Layer B (2/2): Schur reduction via single big GEMM / GEMV -----
1370        // Y_all is (n*d) × k column-major: viewing all n stacked d×k tiles as
1371        // one big matrix is bit-exact because each tile is column-major with
1372        // leading dim d and the tiles are contiguous in memory, so the
1373        // combined leading dim is n*d only for the *outer* matrix view. To
1374        // make the single-GEMM equivalence hold we must treat the stacked
1375        // buffer as (n*d) × k column-major with leading dim = n*d, which
1376        // means columns of Y_all are interleaved by row across blocks.
1377        // That is NOT what we packed. So we use the cuBLAS stride pattern
1378        // instead: stride-by-block, transpose-A, and *accumulate* into one
1379        // S_β buffer via beta=1 across batches. Equivalent flop count, no
1380        // extra reduction kernel, and correct layout.
1381        //
1382        // Concretely: schur ← C + ρ_β I; rhs ← -g_β; then for each block
1383        //   schur -= Y_i^T Y_i      (k×k)
1384        //   rhs   += Y_i^T u_i      (k)
1385        // We launch this as `n` sequential GEMMs/GEMVs with beta=1 on the
1386        // accumulator. Layer D fuses these into one NVRTC launch.
1387        let schur_init: Vec<f64> = {
1388            let mut tmp = Vec::with_capacity(k * k);
1389            for col in 0..k {
1390                for row in 0..k {
1391                    let mut v = sys.hbb[[row, col]];
1392                    if row == col {
1393                        v += ridge_beta;
1394                    }
1395                    tmp.push(v);
1396                }
1397            }
1398            tmp
1399        };
1400        let mut schur_dev = stream
1401            .clone_htod(&schur_init)
1402            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1403        let rhs_init: Vec<f64> = sys.gb.iter().map(|v| -v).collect();
1404        let mut rhs_dev = stream
1405            .clone_htod(&rhs_init)
1406            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1407
1408        accumulate_schur(&blas, d, k, n, &b_dev, &g_dev, &mut schur_dev, &mut rhs_dev)?;
1409
1410        // ----- Layer C (1/2): factor S_β and solve for δβ -----
1411        let info = potrf_single(&solver, &stream, k, &mut schur_dev)?;
1412        if info != 0 {
1413            return Err(ArrowSchurGpuFailure::SchurFactorFailed {
1414                reason: format!("Schur Cholesky failed at pivot {info}"),
1415            });
1416        }
1417        // δβ ← L_S^{-T} L_S^{-1} rhs
1418        trsm_single(&blas, &stream, k, &schur_dev, &mut rhs_dev, false, false)?;
1419        trsm_single(&blas, &stream, k, &schur_dev, &mut rhs_dev, false, true)?;
1420        let delta_beta_host = stream
1421            .clone_dtoh(&rhs_dev)
1422            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1423        let delta_beta = Array1::from_vec(delta_beta_host.clone());
1424
1425        // ----- Layer C (2/2): back-sub δt_i = -L_i^{-T} (u_i + Y_i δβ) -----
1426        // Already on device:
1427        //   g_dev holds u_i stacked (n*d).
1428        //   b_dev holds Y_i stacked column-major n×(d×k) tiles.
1429        // Compute g_dev ← g_dev + Y_block · δβ per block (cuBLAS gemv with beta=1),
1430        // then in-place trsm with L_i^T (CUBLAS_OP_T) to obtain x_i, and finally
1431        // δt_i = -x_i on host after download.
1432        accumulate_back_sub_rhs(&blas, d, k, n, &b_dev, &rhs_dev, &mut g_dev)?;
1433        trsm_batched_lower_inplace_transposed(&blas, &stream, d, n, 1, &d_dev, &mut g_dev)?;
1434
1435        let x_host = stream
1436            .clone_dtoh(&g_dev)
1437            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1438        let mut delta_t = Array1::<f64>::zeros(n * d);
1439        for (i, v) in x_host.iter().enumerate() {
1440            delta_t[i] = -*v;
1441        }
1442
1443        // ----- log|H| = 2 Σ log L_{i,jj} + 2 Σ log R_{β,aa} -----
1444        let l_local_host = stream
1445            .clone_dtoh(&d_dev)
1446            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1447        let l_schur_host = stream
1448            .clone_dtoh(&schur_dev)
1449            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1450        let mut log_det = 0.0_f64;
1451        for i in 0..n {
1452            let base = i * d * d;
1453            for j in 0..d {
1454                log_det += l_local_host[base + j * d + j].ln();
1455            }
1456        }
1457        for j in 0..k {
1458            log_det += l_schur_host[j * k + j].ln();
1459        }
1460        log_det *= 2.0;
1461
1462        Ok(ArrowSchurGpuSolution {
1463            delta_t,
1464            delta_beta,
1465            log_det_hessian: log_det,
1466        })
1467    }
1468
1469    fn potrf_batched(
1470        solver: &DnHandle,
1471        stream: &Arc<CudaStream>,
1472        p: usize,
1473        batch: usize,
1474        matrices: &mut CudaSlice<f64>,
1475    ) -> Result<Vec<i32>, ArrowSchurGpuFailure> {
1476        let p_i = to_i32(p).ok_or(ArrowSchurGpuFailure::Unavailable)?;
1477        let batch_i = to_i32(batch).ok_or(ArrowSchurGpuFailure::Unavailable)?;
1478        let matrix_len = p * p;
1479        let bytes_per = (matrix_len * std::mem::size_of::<f64>()) as u64;
1480        let (base_ptr, _record) = matrices.device_ptr_mut(stream);
1481        let mut ptrs = Vec::with_capacity(batch);
1482        for idx in 0..batch {
1483            ptrs.push(base_ptr + (idx as u64) * bytes_per);
1484        }
1485        let mut ptrs_dev = stream
1486            .clone_htod(&ptrs)
1487            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1488        let mut info_dev = stream
1489            .alloc_zeros::<i32>(batch)
1490            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1491        let status = {
1492            let (ptrs_ptr, _ptrs_record) = ptrs_dev.device_ptr_mut(stream);
1493            let (info_ptr, _info_record) = info_dev.device_ptr_mut(stream);
1494            // SAFETY: pointer array and info buffer live on the device,
1495            // matrices_dev holds `batch` contiguous p×p column-major blocks.
1496            unsafe {
1497                cusolver_sys::cusolverDnDpotrfBatched(
1498                    solver.cu(),
1499                    cusolver_sys::cublasFillMode_t::CUBLAS_FILL_MODE_LOWER,
1500                    p_i,
1501                    ptrs_ptr as *mut *mut f64,
1502                    p_i,
1503                    info_ptr as *mut i32,
1504                    batch_i,
1505                )
1506            }
1507        };
1508        if status != cusolver_sys::cusolverStatus_t::CUSOLVER_STATUS_SUCCESS {
1509            return Err(ArrowSchurGpuFailure::Unavailable);
1510        }
1511        stream
1512            .clone_dtoh(&info_dev)
1513            .map_err(|_| ArrowSchurGpuFailure::Unavailable)
1514    }
1515
1516    fn potrf_single(
1517        solver: &DnHandle,
1518        stream: &Arc<CudaStream>,
1519        p: usize,
1520        matrix: &mut CudaSlice<f64>,
1521    ) -> Result<i32, ArrowSchurGpuFailure> {
1522        let p_i = to_i32(p).ok_or(ArrowSchurGpuFailure::Unavailable)?;
1523        let uplo = cusolver_sys::cublasFillMode_t::CUBLAS_FILL_MODE_LOWER;
1524        let mut lwork = 0_i32;
1525        {
1526            let (mat_ptr, _rec) = matrix.device_ptr_mut(stream);
1527            // SAFETY: buffer query against a live p-by-p column-major device matrix.
1528            let status = unsafe {
1529                cusolver_sys::cusolverDnDpotrf_bufferSize(
1530                    solver.cu(),
1531                    uplo,
1532                    p_i,
1533                    mat_ptr as *mut f64,
1534                    p_i,
1535                    &mut lwork,
1536                )
1537            };
1538            if status != cusolver_sys::cusolverStatus_t::CUSOLVER_STATUS_SUCCESS {
1539                return Err(ArrowSchurGpuFailure::Unavailable);
1540            }
1541        }
1542        let lwork_usize = usize::try_from(lwork).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1543        let mut workspace = stream
1544            .alloc_zeros::<f64>(lwork_usize.max(1))
1545            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1546        let mut info_dev = stream
1547            .alloc_zeros::<i32>(1)
1548            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1549        {
1550            let (mat_ptr, _rec) = matrix.device_ptr_mut(stream);
1551            let (work_ptr, _wrec) = workspace.device_ptr_mut(stream);
1552            let (info_ptr, _irec) = info_dev.device_ptr_mut(stream);
1553            // SAFETY: all three pointers refer to live, correctly sized device buffers.
1554            let status = unsafe {
1555                cusolver_sys::cusolverDnDpotrf(
1556                    solver.cu(),
1557                    uplo,
1558                    p_i,
1559                    mat_ptr as *mut f64,
1560                    p_i,
1561                    work_ptr as *mut f64,
1562                    lwork,
1563                    info_ptr as *mut i32,
1564                )
1565            };
1566            if status != cusolver_sys::cusolverStatus_t::CUSOLVER_STATUS_SUCCESS {
1567                return Err(ArrowSchurGpuFailure::Unavailable);
1568            }
1569        }
1570        let info_host = stream
1571            .clone_dtoh(&info_dev)
1572            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1573        Ok(info_host[0])
1574    }
1575
1576    /// In-place lower-triangular solves `X_i ← L_i^{-1} X_i` over the n stacked
1577    /// d×nrhs RHS tiles in `rhs`. Uses `cublasDtrsmBatched` so all n solves
1578    /// hit the device in one launch.
1579    fn trsm_batched_lower_inplace(
1580        blas: &CudaBlas,
1581        stream: &Arc<CudaStream>,
1582        d: usize,
1583        n: usize,
1584        nrhs: usize,
1585        l_stack: &CudaSlice<f64>,
1586        rhs_stack: &mut CudaSlice<f64>,
1587    ) -> Result<(), ArrowSchurGpuFailure> {
1588        trsm_batched_inplace_inner(blas, stream, d, n, nrhs, l_stack, rhs_stack, false)
1589    }
1590
1591    /// As above but with `L_i^T` instead of `L_i`.
1592    fn trsm_batched_lower_inplace_transposed(
1593        blas: &CudaBlas,
1594        stream: &Arc<CudaStream>,
1595        d: usize,
1596        n: usize,
1597        nrhs: usize,
1598        l_stack: &CudaSlice<f64>,
1599        rhs_stack: &mut CudaSlice<f64>,
1600    ) -> Result<(), ArrowSchurGpuFailure> {
1601        trsm_batched_inplace_inner(blas, stream, d, n, nrhs, l_stack, rhs_stack, true)
1602    }
1603
1604    fn trsm_batched_inplace_inner(
1605        blas: &CudaBlas,
1606        stream: &Arc<CudaStream>,
1607        d: usize,
1608        n: usize,
1609        nrhs: usize,
1610        l_stack: &CudaSlice<f64>,
1611        rhs_stack: &mut CudaSlice<f64>,
1612        transposed: bool,
1613    ) -> Result<(), ArrowSchurGpuFailure> {
1614        let alpha = 1.0_f64;
1615        let d_i = to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?;
1616        let nrhs_i = to_i32(nrhs).ok_or(ArrowSchurGpuFailure::Unavailable)?;
1617        let batch_i = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
1618        let l_bytes_per = (d * d * std::mem::size_of::<f64>()) as u64;
1619        let rhs_bytes_per = (d * nrhs * std::mem::size_of::<f64>()) as u64;
1620        let (l_base, _l_record) = l_stack.device_ptr(stream);
1621        let (rhs_base, _rhs_record) = rhs_stack.device_ptr_mut(stream);
1622        let mut l_ptrs = Vec::with_capacity(n);
1623        let mut rhs_ptrs = Vec::with_capacity(n);
1624        for i in 0..n {
1625            l_ptrs.push(l_base + (i as u64) * l_bytes_per);
1626            rhs_ptrs.push(rhs_base + (i as u64) * rhs_bytes_per);
1627        }
1628        let mut l_ptrs_dev = stream
1629            .clone_htod(&l_ptrs)
1630            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1631        let mut rhs_ptrs_dev = stream
1632            .clone_htod(&rhs_ptrs)
1633            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1634        let (l_ptrs_ptr, _l_ptrs_rec) = l_ptrs_dev.device_ptr_mut(stream);
1635        let (rhs_ptrs_ptr, _rhs_ptrs_rec) = rhs_ptrs_dev.device_ptr_mut(stream);
1636        let op = if transposed {
1637            cublasOperation_t::CUBLAS_OP_T
1638        } else {
1639            cublasOperation_t::CUBLAS_OP_N
1640        };
1641        let handle = *blas.handle();
1642        // SAFETY: pointer arrays and base buffers were just constructed from
1643        // live device allocations covering the entire batch.
1644        let status = unsafe {
1645            cudarc::cublas::sys::cublasDtrsmBatched(
1646                handle,
1647                cublasSideMode_t::CUBLAS_SIDE_LEFT,
1648                cublasFillMode_t::CUBLAS_FILL_MODE_LOWER,
1649                op,
1650                cublasDiagType_t::CUBLAS_DIAG_NON_UNIT,
1651                d_i,
1652                nrhs_i,
1653                &alpha,
1654                l_ptrs_ptr as *const *const f64,
1655                d_i,
1656                rhs_ptrs_ptr as *const *mut f64,
1657                d_i,
1658                batch_i,
1659            )
1660        };
1661        if status != cublasStatus_t::CUBLAS_STATUS_SUCCESS {
1662            return Err(ArrowSchurGpuFailure::Unavailable);
1663        }
1664        Ok(())
1665    }
1666
1667    /// Single-matrix lower-triangular solve: `rhs ← L^{-1} rhs` (or
1668    /// `L^{-T} rhs` if `transposed`). For the Schur Cholesky back-sub.
1669    fn trsm_single(
1670        blas: &CudaBlas,
1671        stream: &Arc<CudaStream>,
1672        n: usize,
1673        l: &CudaSlice<f64>,
1674        rhs: &mut CudaSlice<f64>,
1675        upper: bool,
1676        transposed: bool,
1677    ) -> Result<(), ArrowSchurGpuFailure> {
1678        let alpha = 1.0_f64;
1679        let n_i = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
1680        let handle = *blas.handle();
1681        let (l_ptr, _l_rec) = l.device_ptr(stream);
1682        let (rhs_ptr, _rhs_rec) = rhs.device_ptr_mut(stream);
1683        // SAFETY: single n×n lower factor and n-vector RHS on device.
1684        let status = unsafe {
1685            cudarc::cublas::sys::cublasDtrsm_v2(
1686                handle,
1687                cublasSideMode_t::CUBLAS_SIDE_LEFT,
1688                if upper {
1689                    cublasFillMode_t::CUBLAS_FILL_MODE_UPPER
1690                } else {
1691                    cublasFillMode_t::CUBLAS_FILL_MODE_LOWER
1692                },
1693                if transposed {
1694                    cublasOperation_t::CUBLAS_OP_T
1695                } else {
1696                    cublasOperation_t::CUBLAS_OP_N
1697                },
1698                cublasDiagType_t::CUBLAS_DIAG_NON_UNIT,
1699                n_i,
1700                1,
1701                &alpha,
1702                l_ptr as *const f64,
1703                n_i,
1704                rhs_ptr as *mut f64,
1705                n_i,
1706            )
1707        };
1708        if status != cublasStatus_t::CUBLAS_STATUS_SUCCESS {
1709            return Err(ArrowSchurGpuFailure::Unavailable);
1710        }
1711        Ok(())
1712    }
1713
1714    /// Accumulate `schur ← schur − Σ_i Y_i^T Y_i` and `rhs ← rhs + Σ_i Y_i^T u_i`
1715    /// using one GEMM and one GEMV per block. Each call uses beta=1 to chain
1716    /// the accumulation device-side.
1717    fn accumulate_schur(
1718        blas: &CudaBlas,
1719        d: usize,
1720        k: usize,
1721        n: usize,
1722        y_stack: &CudaSlice<f64>,
1723        u_stack: &CudaSlice<f64>,
1724        schur: &mut CudaSlice<f64>,
1725        rhs: &mut CudaSlice<f64>,
1726    ) -> Result<(), ArrowSchurGpuFailure> {
1727        let y_block_elems = d * k;
1728        let u_block_elems = d;
1729        for i in 0..n {
1730            let y_slice = y_stack.slice(i * y_block_elems..(i + 1) * y_block_elems);
1731            let u_slice = u_stack.slice(i * u_block_elems..(i + 1) * u_block_elems);
1732            // GEMM: schur += (-1) · Y_i^T · Y_i  (Y_i is d×k col-major; out is k×k)
1733            let gemm_cfg = GemmConfig::<f64> {
1734                transa: cublasOperation_t::CUBLAS_OP_T,
1735                transb: cublasOperation_t::CUBLAS_OP_N,
1736                m: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1737                n: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1738                k: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1739                alpha: -1.0,
1740                lda: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1741                ldb: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1742                beta: 1.0,
1743                ldc: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1744            };
1745            // SAFETY: y_slice is d×k col-major, schur is k×k col-major; alpha/beta scalars set above.
1746            unsafe { blas.gemm(gemm_cfg, &y_slice, &y_slice, schur) }
1747                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1748            // GEMV: rhs += 1 · Y_i^T · u_i
1749            let gemv_cfg = GemvConfig::<f64> {
1750                trans: cublasOperation_t::CUBLAS_OP_T,
1751                m: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1752                n: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1753                alpha: 1.0,
1754                lda: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1755                incx: 1,
1756                beta: 1.0,
1757                incy: 1,
1758            };
1759            // SAFETY: y_slice (d×k col-major) and u_slice (length d) are live
1760            // device buffers; `rhs` is the length-k accumulator.
1761            unsafe { blas.gemv(gemv_cfg, &y_slice, &u_slice, rhs) }
1762                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1763        }
1764        Ok(())
1765    }
1766
1767    /// `#1017` resident gradient path: accumulate ONLY the Schur RHS term
1768    /// `rhs += Σ_i Y_iᵀ u_i`, skipping the `−Σ_i Y_iᵀ Y_i` matrix GEMM that the
1769    /// resident frame already folded into its persistent `L_S` factor. This is
1770    /// the per-iterate-cheap counterpart of [`accumulate_schur`]: the GEMV here
1771    /// is bit-identical to the GEMV inside `accumulate_schur` (same config, same
1772    /// `beta=1` accumulation order over rows), so the resident frame's `δβ`
1773    /// matches a full `solve()` at the same gradient.
1774    fn accumulate_schur_rhs_only(
1775        blas: &CudaBlas,
1776        d: usize,
1777        k: usize,
1778        n: usize,
1779        y_stack: &CudaSlice<f64>,
1780        u_stack: &CudaSlice<f64>,
1781        rhs: &mut CudaSlice<f64>,
1782    ) -> Result<(), ArrowSchurGpuFailure> {
1783        let y_block_elems = d * k;
1784        let u_block_elems = d;
1785        for i in 0..n {
1786            let y_slice = y_stack.slice(i * y_block_elems..(i + 1) * y_block_elems);
1787            let u_slice = u_stack.slice(i * u_block_elems..(i + 1) * u_block_elems);
1788            let gemv_cfg = GemvConfig::<f64> {
1789                trans: cublasOperation_t::CUBLAS_OP_T,
1790                m: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1791                n: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1792                alpha: 1.0,
1793                lda: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1794                incx: 1,
1795                beta: 1.0,
1796                incy: 1,
1797            };
1798            // SAFETY: y_slice (d×k col-major) and u_slice (length d) are live
1799            // device buffers; `rhs` is the length-k accumulator.
1800            unsafe { blas.gemv(gemv_cfg, &y_slice, &u_slice, rhs) }
1801                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1802        }
1803        Ok(())
1804    }
1805
1806    /// Accumulate `g_dev[i] ← u_i + Y_i · δβ` per block. This is the
1807    /// pre-trsm RHS for the back-substitution `L_i^T x_i = w_i`.
1808    fn accumulate_back_sub_rhs(
1809        blas: &CudaBlas,
1810        d: usize,
1811        k: usize,
1812        n: usize,
1813        y_stack: &CudaSlice<f64>,
1814        delta_beta: &CudaSlice<f64>,
1815        u_stack: &mut CudaSlice<f64>,
1816    ) -> Result<(), ArrowSchurGpuFailure> {
1817        let y_block_elems = d * k;
1818        let u_block_elems = d;
1819        for i in 0..n {
1820            let y_slice = y_stack.slice(i * y_block_elems..(i + 1) * y_block_elems);
1821            let mut u_slice = u_stack.slice_mut(i * u_block_elems..(i + 1) * u_block_elems);
1822            let gemv_cfg = GemvConfig::<f64> {
1823                trans: cublasOperation_t::CUBLAS_OP_N,
1824                m: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1825                n: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1826                alpha: 1.0,
1827                lda: to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?,
1828                incx: 1,
1829                beta: 1.0,
1830                incy: 1,
1831            };
1832            // SAFETY: y_slice / delta_beta / u_slice are live device buffers
1833            // of the expected sizes (d×k, k, d).
1834            unsafe { blas.gemv(gemv_cfg, &y_slice, delta_beta, &mut u_slice) }
1835                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1836        }
1837        Ok(())
1838    }
1839
1840    // ────────────────────────────────────────────────────────────────────
1841    // Layer D + E — fused NVRTC dispatch.
1842    //
1843    // The forward kernel (`arrow_schur_forward_pgroup`) is a single launch
1844    // that, per row block, factors `D_i + ρI = L_i L_iᵀ` in shared memory,
1845    // forward-solves `u_i = L_i⁻¹ g_i` and `Y_i = L_i⁻¹ B_i`, and emits the
1846    // per-block Schur partials `partial_S[i] = Yᵀ Y` (R×R) and
1847    // `partial_r[i] = Yᵀ u` (R). The host reduces partials on the CPU after
1848    // dtoh (one fused sum across `n` blocks of R²+R doubles; cheap because
1849    // n·R² ≲ 5M doubles at large scale), assembles `S_β`, factors it via
1850    // cuSOLVER, and launches the back-substitution kernel
1851    // `arrow_schur_back_sub_pgroup` to recover `δt_i = -L_i⁻ᵀ(u_i + Y_i δβ)`
1852    // without re-uploading the local factors.
1853    // ────────────────────────────────────────────────────────────────────
1854
1855    use std::collections::HashMap;
1856    use std::sync::Mutex;
1857
1858    /// One compiled NVRTC module per `(cc_major, cc_minor, p_max, r_template)`.
1859    /// `cc_*` lets one process drive multiple device generations; the
1860    /// `(p_max, r_template)` pair selects the shared-memory layout baked into
1861    /// the kernel source.
1862    struct FusedModuleCache {
1863        modules: Mutex<
1864            HashMap<crate::gpu_kernels::arrow_schur_nvrtc::FusedModuleCacheKey, Arc<CudaModule>>,
1865        >,
1866    }
1867
1868    fn fused_module_cache() -> &'static FusedModuleCache {
1869        static CACHE: OnceLock<FusedModuleCache> = OnceLock::new();
1870        CACHE.get_or_init(|| FusedModuleCache {
1871            modules: Mutex::new(HashMap::new()),
1872        })
1873    }
1874
1875    fn fused_module_for(
1876        ctx: &Arc<CudaContext>,
1877        key: crate::gpu_kernels::arrow_schur_nvrtc::FusedModuleCacheKey,
1878    ) -> Result<Arc<CudaModule>, ArrowSchurGpuFailure> {
1879        let cache = fused_module_cache();
1880        if let Ok(guard) = cache.modules.lock() {
1881            if let Some(existing) = guard.get(&key) {
1882                return Ok(existing.clone());
1883            }
1884        }
1885        let src = crate::gpu_kernels::arrow_schur_nvrtc::forward_kernel_source(
1886            key.p_max as usize,
1887            key.r_template as usize,
1888        );
1889        let ptx = cudarc::nvrtc::compile_ptx(&src).map_err(|err| {
1890            ArrowSchurGpuFailure::SchurFactorFailed {
1891                reason: format!(
1892                    "arrow-schur fused NVRTC compile (p_max={}, r={}): {err}",
1893                    key.p_max, key.r_template
1894                ),
1895            }
1896        })?;
1897        let module = ctx
1898            .load_module(ptx)
1899            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
1900        if let Ok(mut guard) = cache.modules.lock() {
1901            guard.entry(key).or_insert_with(|| module.clone());
1902        }
1903        Ok(module)
1904    }
1905
1906    const PCG_VECTOR_KERNEL_SOURCE: &str = r#"
1907extern "C" __global__ void arrow_pcg_jacobi_mul(
1908    const double* __restrict__ inv_diag,
1909    const double* __restrict__ r,
1910    double* __restrict__ z,
1911    int n
1912) {
1913    int idx = blockIdx.x * blockDim.x + threadIdx.x;
1914    if (idx < n) {
1915        z[idx] = inv_diag[idx] * r[idx];
1916    }
1917}
1918
1919extern "C" __global__ void arrow_pcg_update_p(
1920    const double* __restrict__ z,
1921    double beta,
1922    double* __restrict__ p,
1923    int n
1924) {
1925    int idx = blockIdx.x * blockDim.x + threadIdx.x;
1926    if (idx < n) {
1927        p[idx] = z[idx] + beta * p[idx];
1928    }
1929}
1930
1931extern "C" __global__ void arrow_sae_init(
1932    double* __restrict__ out,
1933    const double* __restrict__ x,
1934    double ridge,
1935    int n
1936) {
1937    int idx = blockIdx.x * blockDim.x + threadIdx.x;
1938    if (idx < n) {
1939        out[idx] = ridge * x[idx];
1940    }
1941}
1942
1943extern "C" __global__ void arrow_sae_smooth_matvec(
1944    const double* __restrict__ x,
1945    double* __restrict__ out,
1946    const int* __restrict__ block_offsets,
1947    const int* __restrict__ block_m,
1948    const int* __restrict__ factor_ptr,
1949    const double* __restrict__ factors,
1950    int p,
1951    int n_blocks
1952) {
1953    int block_id = blockIdx.y;
1954    int linear = blockIdx.x * blockDim.x + threadIdx.x;
1955    if (block_id >= n_blocks) {
1956        return;
1957    }
1958    int m = block_m[block_id];
1959    int total = m * p;
1960    if (linear >= total) {
1961        return;
1962    }
1963    int li = linear / p;
1964    int oc = linear - li * p;
1965    int off = block_offsets[block_id];
1966    int fbase = factor_ptr[block_id];
1967    double acc = 0.0;
1968    for (int lj = 0; lj < m; ++lj) {
1969        double a = factors[fbase + li * m + lj];
1970        acc += a * x[off + lj * p + oc];
1971    }
1972    out[off + li * p + oc] += acc;
1973}
1974
1975extern "C" __global__ void arrow_sae_sparse_g_matvec(
1976    const double* __restrict__ x,
1977    double* __restrict__ out,
1978    const int* __restrict__ row_off,
1979    const int* __restrict__ col_off,
1980    const int* __restrict__ rows,
1981    const int* __restrict__ cols,
1982    const int* __restrict__ data_ptr,
1983    const double* __restrict__ data,
1984    int p,
1985    int n_blocks
1986) {
1987    int block_id = blockIdx.y;
1988    int linear = blockIdx.x * blockDim.x + threadIdx.x;
1989    if (block_id >= n_blocks) {
1990        return;
1991    }
1992    int m_i = rows[block_id];
1993    int m_j = cols[block_id];
1994    int total = m_i * p;
1995    if (linear >= total) {
1996        return;
1997    }
1998    int li = linear / p;
1999    int oc = linear - li * p;
2000    int rbase = row_off[block_id];
2001    int cbase = col_off[block_id];
2002    int dbase = data_ptr[block_id];
2003    double acc = 0.0;
2004    for (int lj = 0; lj < m_j; ++lj) {
2005        acc += data[dbase + li * m_j + lj] * x[(cbase + lj) * p + oc];
2006    }
2007    out[(rbase + li) * p + oc] += acc;
2008}
2009
2010extern "C" __global__ void arrow_sae_gather_u(
2011    const double* __restrict__ x,
2012    const int* __restrict__ row_ptr,
2013    const int* __restrict__ beta_base,
2014    const double* __restrict__ phi,
2015    double* __restrict__ u,
2016    int p,
2017    int n_rows
2018) {
2019    int row = blockIdx.y;
2020    int oc = blockIdx.x * blockDim.x + threadIdx.x;
2021    if (row >= n_rows || oc >= p) {
2022        return;
2023    }
2024    double acc = 0.0;
2025    int start = row_ptr[row];
2026    int end = row_ptr[row + 1];
2027    for (int e = start; e < end; ++e) {
2028        acc += phi[e] * x[beta_base[e] + oc];
2029    }
2030    u[row * p + oc] = acc;
2031}
2032
2033extern "C" __global__ void arrow_sae_apply_l(
2034    const double* __restrict__ u,
2035    const int* __restrict__ jac_ptr,
2036    const double* __restrict__ jac,
2037    double* __restrict__ w,
2038    int p,
2039    int max_q,
2040    int n_rows
2041) {
2042    int row = blockIdx.y;
2043    int c = blockIdx.x * blockDim.x + threadIdx.x;
2044    if (row >= n_rows) {
2045        return;
2046    }
2047    int jstart = jac_ptr[row];
2048    int q = (jac_ptr[row + 1] - jstart) / p;
2049    if (c >= q) {
2050        return;
2051    }
2052    double acc = 0.0;
2053    for (int oc = 0; oc < p; ++oc) {
2054        acc += jac[jstart + c * p + oc] * u[row * p + oc];
2055    }
2056    w[row * max_q + c] = acc;
2057}
2058
2059extern "C" __global__ void arrow_sae_apply_ainv(
2060    const double* __restrict__ ainv,
2061    const double* __restrict__ w,
2062    double* __restrict__ v,
2063    int max_q,
2064    int n_rows
2065) {
2066    int row = blockIdx.y;
2067    int c = blockIdx.x * blockDim.x + threadIdx.x;
2068    if (row >= n_rows || c >= max_q) {
2069        return;
2070    }
2071    double acc = 0.0;
2072    int base = row * max_q * max_q;
2073    for (int j = 0; j < max_q; ++j) {
2074        acc += ainv[base + c * max_q + j] * w[row * max_q + j];
2075    }
2076    v[row * max_q + c] = acc;
2077}
2078
2079extern "C" __global__ void arrow_sae_scatter_sub(
2080    const double* __restrict__ v,
2081    const int* __restrict__ jac_ptr,
2082    const double* __restrict__ jac,
2083    const int* __restrict__ row_ptr,
2084    const int* __restrict__ beta_base,
2085    const double* __restrict__ phi,
2086    double* __restrict__ out,
2087    int p,
2088    int max_q,
2089    int n_rows
2090) {
2091    int row = blockIdx.y;
2092    int oc = blockIdx.x * blockDim.x + threadIdx.x;
2093    if (row >= n_rows || oc >= p) {
2094        return;
2095    }
2096    int jstart = jac_ptr[row];
2097    int q = (jac_ptr[row + 1] - jstart) / p;
2098    double lt_v = 0.0;
2099    for (int c = 0; c < q; ++c) {
2100        lt_v += jac[jstart + c * p + oc] * v[row * max_q + c];
2101    }
2102    int start = row_ptr[row];
2103    int end = row_ptr[row + 1];
2104    for (int e = start; e < end; ++e) {
2105        atomicAdd(&out[beta_base[e] + oc], -phi[e] * lt_v);
2106    }
2107}
2108
2109extern "C" __global__ void arrow_sae_diag_sub(
2110    double* __restrict__ diag,
2111    const double* __restrict__ ainv,
2112    const int* __restrict__ jac_ptr,
2113    const double* __restrict__ jac,
2114    const int* __restrict__ row_ptr,
2115    const int* __restrict__ beta_base,
2116    const double* __restrict__ phi,
2117    int p,
2118    int max_q,
2119    int n_rows
2120) {
2121    int row = blockIdx.y;
2122    int oc = blockIdx.x * blockDim.x + threadIdx.x;
2123    if (row >= n_rows || oc >= p) {
2124        return;
2125    }
2126    int jstart = jac_ptr[row];
2127    int q = (jac_ptr[row + 1] - jstart) / p;
2128    int abase = row * max_q * max_q;
2129    double quad = 0.0;
2130    for (int c = 0; c < q; ++c) {
2131        double lc = jac[jstart + c * p + oc];
2132        for (int d = 0; d < q; ++d) {
2133            quad += lc * ainv[abase + c * max_q + d] * jac[jstart + d * p + oc];
2134        }
2135    }
2136    int start = row_ptr[row];
2137    int end = row_ptr[row + 1];
2138    for (int e = start; e < end; ++e) {
2139        double pe = phi[e];
2140        atomicAdd(&diag[beta_base[e] + oc], -(pe * pe) * quad);
2141    }
2142}
2143
2144/* ── #1017/#1026 frames-engaged device kernels ─────────────────────────────
2145 * The factored β border is C-space (width Σ M_k·r_k). The penalty side is the
2146 * smooth `λ S_k ⊗ I_{r_k}` (per-block right-width r_k) plus the data-fit
2147 * `G_{ij} ⊗ W_{ij}` (W = U_iᵀU_j, dense r_i×r_j). The reduced-Schur term uses
2148 * the per-row DENSE cross-block H_tβ^(i) (q_i × border_dim, row-major). */
2149
2150extern "C" __global__ void arrow_sae_frame_smooth_matvec(
2151    const double* __restrict__ x,
2152    double* __restrict__ out,
2153    const int* __restrict__ block_offsets,
2154    const int* __restrict__ block_m,
2155    const int* __restrict__ block_r,
2156    const int* __restrict__ factor_ptr,
2157    const double* __restrict__ factors,
2158    int n_blocks
2159) {
2160    int block_id = blockIdx.y;
2161    int linear = blockIdx.x * blockDim.x + threadIdx.x;
2162    if (block_id >= n_blocks) {
2163        return;
2164    }
2165    int m = block_m[block_id];
2166    int r = block_r[block_id];
2167    int total = m * r;
2168    if (linear >= total) {
2169        return;
2170    }
2171    int li = linear / r;
2172    int ib = linear - li * r;
2173    int off = block_offsets[block_id];
2174    int fbase = factor_ptr[block_id];
2175    double acc = 0.0;
2176    for (int lj = 0; lj < m; ++lj) {
2177        double a = factors[fbase + li * m + lj];
2178        acc += a * x[off + lj * r + ib];
2179    }
2180    out[off + li * r + ib] += acc;
2181}
2182
2183extern "C" __global__ void arrow_sae_frame_g_matvec(
2184    const double* __restrict__ x,
2185    double* __restrict__ out,
2186    const int* __restrict__ off_i,
2187    const int* __restrict__ off_j,
2188    const int* __restrict__ r_i,
2189    const int* __restrict__ r_j,
2190    const int* __restrict__ m_i,
2191    const int* __restrict__ m_j,
2192    const int* __restrict__ g_ptr,
2193    const double* __restrict__ g_data,
2194    const int* __restrict__ w_ptr,
2195    const double* __restrict__ w_data,
2196    int n_blocks
2197) {
2198    int block_id = blockIdx.y;
2199    int linear = blockIdx.x * blockDim.x + threadIdx.x;
2200    if (block_id >= n_blocks) {
2201        return;
2202    }
2203    int ri = r_i[block_id];
2204    int rj = r_j[block_id];
2205    int mi = m_i[block_id];
2206    int mj = m_j[block_id];
2207    int total = mi * ri;
2208    if (linear >= total) {
2209        return;
2210    }
2211    int li = linear / ri;       // basis row in atom i
2212    int a = linear - li * ri;   // frame coord in atom i
2213    int oi = off_i[block_id];
2214    int oj = off_j[block_id];
2215    int gbase = g_ptr[block_id];
2216    int wbase = w_ptr[block_id];
2217    double acc = 0.0;
2218    for (int lj = 0; lj < mj; ++lj) {
2219        double g = g_data[gbase + li * mj + lj];
2220        if (g == 0.0) { continue; }
2221        int xj_base = oj + lj * rj;
2222        double inner = 0.0;
2223        for (int b = 0; b < rj; ++b) {
2224            inner += w_data[wbase + a * rj + b] * x[xj_base + b];
2225        }
2226        acc += g * inner;
2227    }
2228    out[oi + li * ri + a] += acc;
2229}
2230
2231/* Per-row reduced-Schur subtraction with a DENSE cross-block H_tβ^(i).
2232 *   h_i   = H_tβ^(i) · x                (length q_i)
2233 *   s_i   = (H_tt^(i)+ρ_t I)⁻¹ h_i      (apply cached ainv, length q_i)
2234 *   out  -= (H_tβ^(i))ᵀ · s_i           (scatter into border_dim)
2235 * `htb` is row-major (q_i × k) flattened, `htb_ptr` gives each row's base and
2236 * (htb_ptr[row+1]-htb_ptr[row])/k == q_i. `q_of` carries q_i directly. */
2237extern "C" __global__ void arrow_sae_frame_apply_h(
2238    const double* __restrict__ x,
2239    const int* __restrict__ htb_ptr,
2240    const double* __restrict__ htb,
2241    const int* __restrict__ q_of,
2242    double* __restrict__ hvec,
2243    int k,
2244    int max_q,
2245    int n_rows
2246) {
2247    int row = blockIdx.y;
2248    int c = blockIdx.x * blockDim.x + threadIdx.x;
2249    if (row >= n_rows) { return; }
2250    int q = q_of[row];
2251    if (c >= q) { return; }
2252    int base = htb_ptr[row] + c * k;
2253    double acc = 0.0;
2254    for (int a = 0; a < k; ++a) {
2255        acc += htb[base + a] * x[a];
2256    }
2257    hvec[row * max_q + c] = acc;
2258}
2259
2260extern "C" __global__ void arrow_sae_frame_apply_ainv(
2261    const double* __restrict__ ainv,
2262    const double* __restrict__ hvec,
2263    const int* __restrict__ q_of,
2264    double* __restrict__ svec,
2265    int max_q,
2266    int n_rows
2267) {
2268    int row = blockIdx.y;
2269    int c = blockIdx.x * blockDim.x + threadIdx.x;
2270    if (row >= n_rows || c >= max_q) { return; }
2271    int q = q_of[row];
2272    double acc = 0.0;
2273    int abase = row * max_q * max_q;
2274    for (int j = 0; j < q; ++j) {
2275        acc += ainv[abase + c * max_q + j] * hvec[row * max_q + j];
2276    }
2277    svec[row * max_q + c] = acc;
2278}
2279
2280extern "C" __global__ void arrow_sae_frame_scatter_h(
2281    const double* __restrict__ svec,
2282    const int* __restrict__ htb_ptr,
2283    const double* __restrict__ htb,
2284    const int* __restrict__ q_of,
2285    double* __restrict__ out,
2286    int k,
2287    int max_q,
2288    int n_rows
2289) {
2290    int row = blockIdx.y;
2291    int a = blockIdx.x * blockDim.x + threadIdx.x;
2292    if (row >= n_rows || a >= k) { return; }
2293    int q = q_of[row];
2294    int hbase = htb_ptr[row];
2295    double acc = 0.0;
2296    for (int c = 0; c < q; ++c) {
2297        acc += htb[hbase + c * k + a] * svec[row * max_q + c];
2298    }
2299    atomicAdd(&out[a], -acc);
2300}
2301
2302/* Frame Jacobi diagonal subtraction: diag[a] -= Σ_c Σ_d H_tβ[c,a]·ainv[c,d]·H_tβ[d,a]. */
2303extern "C" __global__ void arrow_sae_frame_diag_sub(
2304    double* __restrict__ diag,
2305    const double* __restrict__ ainv,
2306    const int* __restrict__ htb_ptr,
2307    const double* __restrict__ htb,
2308    const int* __restrict__ q_of,
2309    int k,
2310    int max_q,
2311    int n_rows
2312) {
2313    int row = blockIdx.y;
2314    int a = blockIdx.x * blockDim.x + threadIdx.x;
2315    if (row >= n_rows || a >= k) { return; }
2316    int q = q_of[row];
2317    int hbase = htb_ptr[row];
2318    int abase = row * max_q * max_q;
2319    double quad = 0.0;
2320    for (int c = 0; c < q; ++c) {
2321        double hc = htb[hbase + c * k + a];
2322        for (int d = 0; d < q; ++d) {
2323            quad += hc * ainv[abase + c * max_q + d] * htb[hbase + d * k + a];
2324        }
2325    }
2326    atomicAdd(&diag[a], -quad);
2327}
2328"#;
2329
2330    fn pcg_vector_module(
2331        ctx: &Arc<CudaContext>,
2332    ) -> Result<&'static Arc<CudaModule>, ArrowSchurGpuFailure> {
2333        static CACHE: gam_gpu::device_cache::PtxModuleCache =
2334            gam_gpu::device_cache::PtxModuleCache::new();
2335        CACHE
2336            .get_or_compile(ctx, "arrow_pcg_vector", PCG_VECTOR_KERNEL_SOURCE)
2337            .map_err(|err| {
2338                // #1551: an NVRTC compile / module-load failure of
2339                // PCG_VECTOR_KERNEL_SOURCE means the device SAE PCG cannot run;
2340                // log it (the historical silent collapse to `Unavailable` is what
2341                // masked the missing `--gpu-architecture` for so long) and fall
2342                // back to the CPU.
2343                log::warn!("[#1551] pcg_vector_module get_or_compile failed: {err}");
2344                ArrowSchurGpuFailure::Unavailable
2345            })
2346    }
2347
2348    fn pcg_launch_config(n: usize) -> Result<LaunchConfig, ArrowSchurGpuFailure> {
2349        let threads = 256u32;
2350        let blocks = ((n as u32).saturating_add(threads - 1) / threads).max(1);
2351        Ok(LaunchConfig {
2352            grid_dim: (blocks, 1, 1),
2353            block_dim: (threads, 1, 1),
2354            shared_mem_bytes: 0,
2355        })
2356    }
2357
2358    fn launch_jacobi_mul(
2359        stream: &Arc<CudaStream>,
2360        module: &Arc<CudaModule>,
2361        inv_diag: &CudaSlice<f64>,
2362        r: &CudaSlice<f64>,
2363        z: &mut CudaSlice<f64>,
2364        n: usize,
2365    ) -> Result<(), ArrowSchurGpuFailure> {
2366        let kernel = module
2367            .load_function("arrow_pcg_jacobi_mul")
2368            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2369        let n_i32 = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
2370        let mut builder = stream.launch_builder(&kernel);
2371        builder.arg(inv_diag).arg(r).arg(z).arg(&n_i32);
2372        // SAFETY: all buffers have length n and belong to `stream`; the kernel only
2373        // reads/writes indices `< n`.
2374        unsafe { builder.launch(pcg_launch_config(n)?) }
2375            .map(drop)
2376            .map_err(|_| ArrowSchurGpuFailure::Unavailable)
2377    }
2378
2379    fn launch_update_p(
2380        stream: &Arc<CudaStream>,
2381        module: &Arc<CudaModule>,
2382        z: &CudaSlice<f64>,
2383        beta: f64,
2384        p: &mut CudaSlice<f64>,
2385        n: usize,
2386    ) -> Result<(), ArrowSchurGpuFailure> {
2387        let kernel = module
2388            .load_function("arrow_pcg_update_p")
2389            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2390        let n_i32 = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
2391        let mut builder = stream.launch_builder(&kernel);
2392        builder.arg(z).arg(&beta).arg(p).arg(&n_i32);
2393        // SAFETY: z/p both have length n and belong to `stream`; the kernel only
2394        // reads/writes indices `< n`.
2395        unsafe { builder.launch(pcg_launch_config(n)?) }
2396            .map(drop)
2397            .map_err(|_| ArrowSchurGpuFailure::Unavailable)
2398    }
2399
2400    struct DeviceSaePcgBuffers {
2401        row_ptr: CudaSlice<i32>,
2402        beta_base: CudaSlice<i32>,
2403        phi: CudaSlice<f64>,
2404        jac_ptr: CudaSlice<i32>,
2405        jac: CudaSlice<f64>,
2406        smooth_offsets: CudaSlice<i32>,
2407        smooth_m: CudaSlice<i32>,
2408        smooth_ptr: CudaSlice<i32>,
2409        smooth_data: CudaSlice<f64>,
2410        g_row_off: CudaSlice<i32>,
2411        g_col_off: CudaSlice<i32>,
2412        g_rows: CudaSlice<i32>,
2413        g_cols: CudaSlice<i32>,
2414        g_ptr: CudaSlice<i32>,
2415        g_data: CudaSlice<f64>,
2416        ainv: CudaSlice<f64>,
2417        u: CudaSlice<f64>,
2418        w: CudaSlice<f64>,
2419        v: CudaSlice<f64>,
2420        n_rows: usize,
2421        p: usize,
2422        k: usize,
2423        max_q: usize,
2424        smooth_blocks: usize,
2425        g_blocks: usize,
2426    }
2427
2428    fn checked_i32(value: usize) -> Result<i32, ArrowSchurGpuFailure> {
2429        to_i32(value).ok_or(ArrowSchurGpuFailure::Unavailable)
2430    }
2431
2432    fn sae_penalty_diag_host(
2433        data: &DeviceSaePcgData,
2434        ridge_beta: f64,
2435    ) -> Result<Vec<f64>, ArrowSchurGpuFailure> {
2436        let mut diag = vec![ridge_beta; data.beta_dim];
2437        for block in &data.smooth_blocks {
2438            let (rows, cols) = block.factor_a.dim();
2439            if rows != cols {
2440                return Err(ArrowSchurGpuFailure::Unavailable);
2441            }
2442            for row in 0..rows {
2443                let coeff = block.factor_a[[row, row]];
2444                let base = block
2445                    .global_offset
2446                    .checked_add(
2447                        row.checked_mul(data.p)
2448                            .ok_or(ArrowSchurGpuFailure::Unavailable)?,
2449                    )
2450                    .ok_or(ArrowSchurGpuFailure::Unavailable)?;
2451                let end = base
2452                    .checked_add(data.p)
2453                    .ok_or(ArrowSchurGpuFailure::Unavailable)?;
2454                if end > diag.len() {
2455                    return Err(ArrowSchurGpuFailure::Unavailable);
2456                }
2457                for channel in 0..data.p {
2458                    diag[base + channel] += coeff;
2459                }
2460            }
2461        }
2462        for block in &data.sparse_g_blocks {
2463            if block.row_off != block.col_off {
2464                continue;
2465            }
2466            let (rows, cols) = block.data.dim();
2467            for row in 0..rows.min(cols) {
2468                let coeff = block.data[[row, row]];
2469                let beta_row = block
2470                    .row_off
2471                    .checked_add(row)
2472                    .ok_or(ArrowSchurGpuFailure::Unavailable)?;
2473                let base = beta_row
2474                    .checked_mul(data.p)
2475                    .ok_or(ArrowSchurGpuFailure::Unavailable)?;
2476                let end = base
2477                    .checked_add(data.p)
2478                    .ok_or(ArrowSchurGpuFailure::Unavailable)?;
2479                if end > diag.len() {
2480                    return Err(ArrowSchurGpuFailure::Unavailable);
2481                }
2482                for channel in 0..data.p {
2483                    diag[base + channel] += coeff;
2484                }
2485            }
2486        }
2487        Ok(diag)
2488    }
2489
2490    fn flatten_device_sae_data(
2491        sys: &ArrowSchurSystem,
2492        data: &DeviceSaePcgData,
2493        ridge_t: f64,
2494        stream: &Arc<CudaStream>,
2495    ) -> Result<DeviceSaePcgBuffers, ArrowSchurGpuFailure> {
2496        let n_rows = sys.rows.len();
2497        let p = data.p;
2498        let k = data.beta_dim;
2499        if data.a_phi.len() != n_rows || data.local_jac.len() != n_rows {
2500            return Err(ArrowSchurGpuFailure::Unavailable);
2501        }
2502
2503        let mut row_ptr_host = Vec::with_capacity(n_rows + 1);
2504        let mut beta_base_host = Vec::<i32>::new();
2505        let mut phi_host = Vec::<f64>::new();
2506        row_ptr_host.push(0_i32);
2507        for row in data.a_phi.iter() {
2508            for &(base, phi) in row {
2509                beta_base_host.push(checked_i32(base)?);
2510                phi_host.push(phi);
2511            }
2512            row_ptr_host.push(checked_i32(beta_base_host.len())?);
2513        }
2514
2515        let mut jac_ptr_host = Vec::with_capacity(n_rows + 1);
2516        let mut jac_host = Vec::<f64>::new();
2517        let mut max_q = 0usize;
2518        jac_ptr_host.push(0_i32);
2519        for row_jac in data.local_jac.iter() {
2520            if row_jac.len() % p != 0 {
2521                return Err(ArrowSchurGpuFailure::Unavailable);
2522            }
2523            max_q = max_q.max(row_jac.len() / p);
2524            jac_host.extend_from_slice(row_jac);
2525            jac_ptr_host.push(checked_i32(jac_host.len())?);
2526        }
2527        if max_q == 0 {
2528            return Err(ArrowSchurGpuFailure::Unavailable);
2529        }
2530
2531        let mut smooth_offsets_host = Vec::with_capacity(data.smooth_blocks.len());
2532        let mut smooth_m_host = Vec::with_capacity(data.smooth_blocks.len());
2533        let mut smooth_ptr_host = Vec::with_capacity(data.smooth_blocks.len() + 1);
2534        let mut smooth_data_host = Vec::<f64>::new();
2535        smooth_ptr_host.push(0_i32);
2536        for block in &data.smooth_blocks {
2537            let (rows, cols) = block.factor_a.dim();
2538            if rows != cols {
2539                return Err(ArrowSchurGpuFailure::Unavailable);
2540            }
2541            smooth_offsets_host.push(checked_i32(block.global_offset)?);
2542            smooth_m_host.push(checked_i32(rows)?);
2543            for r in 0..rows {
2544                for c in 0..cols {
2545                    smooth_data_host.push(block.factor_a[[r, c]]);
2546                }
2547            }
2548            smooth_ptr_host.push(checked_i32(smooth_data_host.len())?);
2549        }
2550
2551        let mut g_row_off_host = Vec::with_capacity(data.sparse_g_blocks.len());
2552        let mut g_col_off_host = Vec::with_capacity(data.sparse_g_blocks.len());
2553        let mut g_rows_host = Vec::with_capacity(data.sparse_g_blocks.len());
2554        let mut g_cols_host = Vec::with_capacity(data.sparse_g_blocks.len());
2555        let mut g_ptr_host = Vec::with_capacity(data.sparse_g_blocks.len() + 1);
2556        let mut g_data_host = Vec::<f64>::new();
2557        g_ptr_host.push(0_i32);
2558        for block in &data.sparse_g_blocks {
2559            let (rows, cols) = block.data.dim();
2560            g_row_off_host.push(checked_i32(block.row_off)?);
2561            g_col_off_host.push(checked_i32(block.col_off)?);
2562            g_rows_host.push(checked_i32(rows)?);
2563            g_cols_host.push(checked_i32(cols)?);
2564            for r in 0..rows {
2565                for c in 0..cols {
2566                    g_data_host.push(block.data[[r, c]]);
2567                }
2568            }
2569            g_ptr_host.push(checked_i32(g_data_host.len())?);
2570        }
2571
2572        let mut ainv_host = vec![0.0_f64; n_rows * max_q * max_q];
2573        for (row_idx, row) in sys.rows.iter().enumerate() {
2574            let q = data.local_jac[row_idx].len() / p;
2575            if row.htt.dim() != (q, q) {
2576                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
2577                    reason: format!(
2578                        "SAE device PCG row {row_idx}: H_tt shape {:?} != ({q}, {q})",
2579                        row.htt.dim()
2580                    ),
2581                });
2582            }
2583            let mut block = row.htt.clone();
2584            for d in 0..q {
2585                block[[d, d]] += ridge_t;
2586            }
2587            let factor = gam_linalg::triangular::cholesky_factor_in_place(
2588                block.view(),
2589                gam_linalg::triangular::CholeskyGuard::NonnegativePivot,
2590            )
2591            .ok_or_else(|| {
2592                let scale = row
2593                    .htt
2594                    .diag()
2595                    .iter()
2596                    .map(|v| v.abs())
2597                    .fold(0.0_f64, f64::max)
2598                    .max(1.0);
2599                ArrowSchurGpuFailure::RidgeBumpRequired {
2600                    row: row_idx,
2601                    bump: scale * f64::EPSILON.sqrt() * super::RIDGE_BUMP_EPS_MARGIN,
2602                }
2603            })?;
2604            for col in 0..q {
2605                let mut e = Array1::<f64>::zeros(q);
2606                e[col] = 1.0;
2607                let solved =
2608                    gam_linalg::triangular::cholesky_solve_vector(factor.view(), e.view());
2609                for r in 0..q {
2610                    ainv_host[row_idx * max_q * max_q + r * max_q + col] = solved[r];
2611                }
2612            }
2613        }
2614
2615        Ok(DeviceSaePcgBuffers {
2616            row_ptr: stream
2617                .clone_htod(&row_ptr_host)
2618                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2619            beta_base: stream
2620                .clone_htod(&beta_base_host)
2621                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2622            phi: stream
2623                .clone_htod(&phi_host)
2624                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2625            jac_ptr: stream
2626                .clone_htod(&jac_ptr_host)
2627                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2628            jac: stream
2629                .clone_htod(&jac_host)
2630                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2631            smooth_offsets: stream
2632                .clone_htod(&smooth_offsets_host)
2633                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2634            smooth_m: stream
2635                .clone_htod(&smooth_m_host)
2636                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2637            smooth_ptr: stream
2638                .clone_htod(&smooth_ptr_host)
2639                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2640            smooth_data: stream
2641                .clone_htod(&smooth_data_host)
2642                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2643            g_row_off: stream
2644                .clone_htod(&g_row_off_host)
2645                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2646            g_col_off: stream
2647                .clone_htod(&g_col_off_host)
2648                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2649            g_rows: stream
2650                .clone_htod(&g_rows_host)
2651                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2652            g_cols: stream
2653                .clone_htod(&g_cols_host)
2654                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2655            g_ptr: stream
2656                .clone_htod(&g_ptr_host)
2657                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2658            g_data: stream
2659                .clone_htod(&g_data_host)
2660                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2661            ainv: stream
2662                .clone_htod(&ainv_host)
2663                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2664            u: stream
2665                .alloc_zeros::<f64>(n_rows * p)
2666                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2667            w: stream
2668                .alloc_zeros::<f64>(n_rows * max_q)
2669                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2670            v: stream
2671                .alloc_zeros::<f64>(n_rows * max_q)
2672                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
2673            n_rows,
2674            p,
2675            k,
2676            max_q,
2677            smooth_blocks: data.smooth_blocks.len(),
2678            g_blocks: data.sparse_g_blocks.len(),
2679        })
2680    }
2681
2682    fn launch_sae_init(
2683        stream: &Arc<CudaStream>,
2684        module: &Arc<CudaModule>,
2685        out: &mut CudaSlice<f64>,
2686        x: &CudaSlice<f64>,
2687        ridge: f64,
2688        n: usize,
2689    ) -> Result<(), ArrowSchurGpuFailure> {
2690        let kernel = module
2691            .load_function("arrow_sae_init")
2692            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2693        let n_i32 = checked_i32(n)?;
2694        let mut builder = stream.launch_builder(&kernel);
2695        builder.arg(out).arg(x).arg(&ridge).arg(&n_i32);
2696        // SAFETY: `out` and `x` are live device buffers with at least `n`
2697        // entries on `stream`; the kernel writes one in-bounds element per
2698        // launched index below `n`.
2699        unsafe { builder.launch(pcg_launch_config(n)?) }
2700            .map(drop)
2701            .map_err(|_| ArrowSchurGpuFailure::Unavailable)
2702    }
2703
2704    fn launch_sae_penalty_matvec(
2705        stream: &Arc<CudaStream>,
2706        module: &Arc<CudaModule>,
2707        buffers: &mut DeviceSaePcgBuffers,
2708        x: &CudaSlice<f64>,
2709        out: &mut CudaSlice<f64>,
2710        ridge_beta: f64,
2711    ) -> Result<(), ArrowSchurGpuFailure> {
2712        launch_sae_init(stream, module, out, x, ridge_beta, buffers.k)?;
2713        if buffers.smooth_blocks > 0 {
2714            let kernel = module
2715                .load_function("arrow_sae_smooth_matvec")
2716                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2717            let max_m = buffers.k;
2718            let p_i32 = checked_i32(buffers.p)?;
2719            let blocks_i32 = checked_i32(buffers.smooth_blocks)?;
2720            let cfg = LaunchConfig {
2721                grid_dim: (
2722                    ((max_m as u32).saturating_add(255) / 256).max(1),
2723                    checked_i32(buffers.smooth_blocks)? as u32,
2724                    1,
2725                ),
2726                block_dim: (256, 1, 1),
2727                shared_mem_bytes: 0,
2728            };
2729            let mut builder = stream.launch_builder(&kernel);
2730            builder
2731                .arg(x)
2732                .arg(&mut *out)
2733                .arg(&buffers.smooth_offsets)
2734                .arg(&buffers.smooth_m)
2735                .arg(&buffers.smooth_ptr)
2736                .arg(&buffers.smooth_data)
2737                .arg(&p_i32)
2738                .arg(&blocks_i32);
2739            // SAFETY: smooth block metadata and dense smooth data were flattened
2740            // into live device buffers; the 2D grid covers only declared block
2741            // and coefficient-channel work items, and the kernel bounds-checks
2742            // against each block's stored size.
2743            unsafe { builder.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2744        }
2745        if buffers.g_blocks > 0 {
2746            let kernel = module
2747                .load_function("arrow_sae_sparse_g_matvec")
2748                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2749            let max_work = buffers
2750                .k
2751                .checked_div(buffers.p)
2752                .unwrap_or(0)
2753                .saturating_mul(buffers.p);
2754            let p_i32 = checked_i32(buffers.p)?;
2755            let blocks_i32 = checked_i32(buffers.g_blocks)?;
2756            let cfg = LaunchConfig {
2757                grid_dim: (
2758                    ((max_work as u32).saturating_add(255) / 256).max(1),
2759                    checked_i32(buffers.g_blocks)? as u32,
2760                    1,
2761                ),
2762                block_dim: (256, 1, 1),
2763                shared_mem_bytes: 0,
2764            };
2765            let mut builder = stream.launch_builder(&kernel);
2766            builder
2767                .arg(x)
2768                .arg(&mut *out)
2769                .arg(&buffers.g_row_off)
2770                .arg(&buffers.g_col_off)
2771                .arg(&buffers.g_rows)
2772                .arg(&buffers.g_cols)
2773                .arg(&buffers.g_ptr)
2774                .arg(&buffers.g_data)
2775                .arg(&p_i32)
2776                .arg(&blocks_i32);
2777            // SAFETY: sparse G block metadata/data are live device buffers built
2778            // from host CSR-like block descriptors; the launch dimensions cover
2779            // declared block work only and the kernel checks row/column bounds
2780            // before reading or accumulating.
2781            unsafe { builder.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2782        }
2783        Ok(())
2784    }
2785
2786    fn launch_sae_row_schur_sub(
2787        stream: &Arc<CudaStream>,
2788        module: &Arc<CudaModule>,
2789        buffers: &mut DeviceSaePcgBuffers,
2790        x: &CudaSlice<f64>,
2791        out: &mut CudaSlice<f64>,
2792    ) -> Result<(), ArrowSchurGpuFailure> {
2793        let p_i32 = checked_i32(buffers.p)?;
2794        let max_q_i32 = checked_i32(buffers.max_q)?;
2795        let n_rows_i32 = checked_i32(buffers.n_rows)?;
2796        let cfg_p_rows = LaunchConfig {
2797            grid_dim: (
2798                ((buffers.p as u32).saturating_add(255) / 256).max(1),
2799                checked_i32(buffers.n_rows)? as u32,
2800                1,
2801            ),
2802            block_dim: (256, 1, 1),
2803            shared_mem_bytes: 0,
2804        };
2805        let gather = module
2806            .load_function("arrow_sae_gather_u")
2807            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2808        {
2809            let mut builder = stream.launch_builder(&gather);
2810            builder
2811                .arg(x)
2812                .arg(&buffers.row_ptr)
2813                .arg(&buffers.beta_base)
2814                .arg(&buffers.phi)
2815                .arg(&mut buffers.u)
2816                .arg(&p_i32)
2817                .arg(&n_rows_i32);
2818            // SAFETY: `x`, row pointers, beta offsets, basis rows, and `u` are
2819            // live device buffers sized for `n_rows` by `p`; the kernel guards
2820            // row/channel indices before gathering.
2821            unsafe { builder.launch(cfg_p_rows) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2822        }
2823
2824        let cfg_q_rows = LaunchConfig {
2825            grid_dim: (
2826                ((buffers.max_q as u32).saturating_add(255) / 256).max(1),
2827                checked_i32(buffers.n_rows)? as u32,
2828                1,
2829            ),
2830            block_dim: (256, 1, 1),
2831            shared_mem_bytes: 0,
2832        };
2833        let apply_l = module
2834            .load_function("arrow_sae_apply_l")
2835            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2836        {
2837            let mut builder = stream.launch_builder(&apply_l);
2838            builder
2839                .arg(&buffers.u)
2840                .arg(&buffers.jac_ptr)
2841                .arg(&buffers.jac)
2842                .arg(&mut buffers.w)
2843                .arg(&p_i32)
2844                .arg(&max_q_i32)
2845                .arg(&n_rows_i32);
2846            // SAFETY: `u`, Jacobian row pointers/data, and `w` are live buffers
2847            // sized for the `(n_rows, p)` to `(n_rows, max_q)` multiply; the
2848            // kernel checks row and local-coordinate bounds.
2849            unsafe { builder.launch(cfg_q_rows) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2850        }
2851
2852        let apply_ainv = module
2853            .load_function("arrow_sae_apply_ainv")
2854            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2855        {
2856            let mut builder = stream.launch_builder(&apply_ainv);
2857            builder
2858                .arg(&buffers.ainv)
2859                .arg(&buffers.w)
2860                .arg(&mut buffers.v)
2861                .arg(&max_q_i32)
2862                .arg(&n_rows_i32);
2863            // SAFETY: `ainv`, `w`, and `v` are live device buffers sized for
2864            // `n_rows * max_q`; the kernel guards all row/local-coordinate
2865            // indices before reading or writing.
2866            unsafe { builder.launch(cfg_q_rows) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2867        }
2868
2869        let scatter = module
2870            .load_function("arrow_sae_scatter_sub")
2871            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2872        {
2873            let mut builder = stream.launch_builder(&scatter);
2874            builder
2875                .arg(&buffers.v)
2876                .arg(&buffers.jac_ptr)
2877                .arg(&buffers.jac)
2878                .arg(&buffers.row_ptr)
2879                .arg(&buffers.beta_base)
2880                .arg(&buffers.phi)
2881                .arg(out)
2882                .arg(&p_i32)
2883                .arg(&max_q_i32)
2884                .arg(&n_rows_i32);
2885            // SAFETY: `v`, Jacobian metadata, row pointers, beta offsets, basis
2886            // rows, and `out` are live buffers for `n_rows` by `p`; scatter
2887            // indices are checked against row and channel bounds in the kernel.
2888            unsafe { builder.launch(cfg_p_rows) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2889        }
2890        Ok(())
2891    }
2892
2893    fn launch_sae_diag_sub(
2894        stream: &Arc<CudaStream>,
2895        module: &Arc<CudaModule>,
2896        buffers: &DeviceSaePcgBuffers,
2897        diag: &mut CudaSlice<f64>,
2898    ) -> Result<(), ArrowSchurGpuFailure> {
2899        let kernel = module
2900            .load_function("arrow_sae_diag_sub")
2901            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
2902        let p_i32 = checked_i32(buffers.p)?;
2903        let max_q_i32 = checked_i32(buffers.max_q)?;
2904        let n_rows_i32 = checked_i32(buffers.n_rows)?;
2905        let cfg = LaunchConfig {
2906            grid_dim: (
2907                ((buffers.p as u32).saturating_add(255) / 256).max(1),
2908                checked_i32(buffers.n_rows)? as u32,
2909                1,
2910            ),
2911            block_dim: (256, 1, 1),
2912            shared_mem_bytes: 0,
2913        };
2914        let mut builder = stream.launch_builder(&kernel);
2915        builder
2916            .arg(diag)
2917            .arg(&buffers.ainv)
2918            .arg(&buffers.jac_ptr)
2919            .arg(&buffers.jac)
2920            .arg(&buffers.row_ptr)
2921            .arg(&buffers.beta_base)
2922            .arg(&buffers.phi)
2923            .arg(&p_i32)
2924            .arg(&max_q_i32)
2925            .arg(&n_rows_i32);
2926        // SAFETY: diagonal output and all read-only SAE row metadata buffers are
2927        // live on `stream` with sizes matching `n_rows`, `p`, and `max_q`; the
2928        // kernel bounds-checks its flattened work index.
2929        unsafe { builder.launch(cfg) }
2930            .map(drop)
2931            .map_err(|_| ArrowSchurGpuFailure::Unavailable)
2932    }
2933
2934    fn launch_sae_matvec(
2935        stream: &Arc<CudaStream>,
2936        module: &Arc<CudaModule>,
2937        buffers: &mut DeviceSaePcgBuffers,
2938        x: &CudaSlice<f64>,
2939        out: &mut CudaSlice<f64>,
2940        ridge_beta: f64,
2941    ) -> Result<(), ArrowSchurGpuFailure> {
2942        launch_sae_penalty_matvec(stream, module, buffers, x, out, ridge_beta)?;
2943        launch_sae_row_schur_sub(stream, module, buffers, x, out)
2944    }
2945
2946    /// Pack `D + ρ_t I`, `B`, and `g` into the strided `(n × P_MAX × P_MAX)`
2947    /// / `(n × P_MAX × R_TEMPLATE)` / `(n × P_MAX)` layout the fused kernel
2948    /// expects. Entries outside the runtime `(p, r)` window stay at zero so
2949    /// the kernel's per-element loops are safe to no-op there.
2950    fn pack_fused_host(
2951        sys: &ArrowSchurSystem,
2952        ridge_t: f64,
2953        p_max: usize,
2954        r_template: usize,
2955    ) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
2956        let n = sys.rows.len();
2957        let d = sys.d;
2958        let k = sys.k;
2959        let mut d_buf = vec![0.0_f64; n * p_max * p_max];
2960        let mut b_buf = vec![0.0_f64; n * p_max * r_template];
2961        let mut g_buf = vec![0.0_f64; n * p_max];
2962        for (i, row) in sys.rows.iter().enumerate() {
2963            // D_i + ρI, column-major in P_MAX×P_MAX strided block.
2964            for col in 0..d {
2965                let base = (i * p_max + col) * p_max;
2966                for r in 0..d {
2967                    let mut value = row.htt[[r, col]];
2968                    if r == col {
2969                        value += ridge_t;
2970                    }
2971                    d_buf[base + r] = value;
2972                }
2973            }
2974            // B_i in P_MAX×R_TEMPLATE strided block.
2975            for col in 0..k {
2976                let base = (i * p_max + col) * p_max;
2977                for r in 0..d {
2978                    b_buf[base + r] = row.htbeta[[r, col]];
2979                }
2980            }
2981            // g_i in P_MAX strided vector.
2982            let g_base = i * p_max;
2983            for r in 0..d {
2984                g_buf[g_base + r] = row.gt[r];
2985            }
2986        }
2987        (d_buf, b_buf, g_buf)
2988    }
2989
2990    // -----------------------------------------------------------------------
2991    // #1017 Phase 3: across-iteration device residency.
2992    //
2993    // `solve()` re-packs and re-uploads `D` (`H_tt`), `B` (`H_tβ`) and `g`,
2994    // then re-runs the per-row POTRF and the border Schur factorization on
2995    // EVERY call. For the SAE joint inner Newton at a frozen gate/basis frame
2996    // the Hessian blocks `D`, `B`, `H_ββ` are CONSTANT across the inner loop —
2997    // only the gradient `g = r(z) = H z − g₀` changes per iterate. So the
2998    // factor work (`O(n·d³ + p³)`) and the dominant `O(n·d·p)` cross-block
2999    // upload are pure waste when repeated per iterate.
3000    //
3001    // `ResidentArrowFrame` performs that constant work ONCE at construction:
3002    // upload+ridge+POTRF of `D` (keeping `L_i` resident in `l_dev`), the
3003    // forward solve `Y_i = L_i^{-1} B_i` (kept resident in `y_dev`), and the
3004    // Schur assembly + border POTRF (keeping `L_S` resident in `schur_dev`).
3005    // Each subsequent `solve_gradient(g)` uploads only the `n·d` row gradient,
3006    // runs the cheap residual path — `u_i = L_i^{-1} g_i` (one batched TRSM),
3007    // Schur RHS `−g_β + Σ Y_iᵀ u_i`, `δβ = L_S^{-T} L_S^{-1} rhs` (two TRSM,
3008    // NO POTRF), back-sub `δt_i = −L_i^{-T}(u_i + Y_i δβ)` — and reads back only
3009    // `δ` and the cached log|H|. The heavy buffers never leave the device
3010    // across iterations; the per-iterate host transfer is `O(n·d + p)`, not
3011    // `O(n·d·p)`. Numerics are bit-identical to a `solve()` at the same
3012    // `(D, B, H_ββ, g, ridge_t, ridge_beta)` because the factor buffers and the
3013    // helper kernels are the same; the resident path merely SKIPS re-deriving
3014    // the parts that do not depend on `g`. The CPU dense reference
3015    // (`solve_arrow_newton_step_dense_reference`) is the parity oracle.
3016    pub(super) struct ResidentArrowFrame {
3017        n: usize,
3018        d: usize,
3019        k: usize,
3020        stream: Arc<CudaStream>,
3021        blas: CudaBlas,
3022        /// Per-row lower Cholesky factors `L_i` of `H_tt + ρ_t I`, stacked
3023        /// column-major (`n` tiles of `d×d`). Resident across iterations.
3024        l_dev: CudaSlice<f64>,
3025        /// Whitened cross blocks `Y_i = L_i^{-1} H_tβ^(i)`, stacked column-major
3026        /// (`n` tiles of `d×k`). Resident across iterations.
3027        y_dev: CudaSlice<f64>,
3028        /// Lower Cholesky factor `L_S` of the reduced Schur complement
3029        /// `S_β = H_ββ + ρ_β I − Σ_i Y_iᵀ Y_i`. Resident across iterations.
3030        schur_dev: CudaSlice<f64>,
3031        /// `log|H| = 2 Σ log L_{i,jj} + 2 Σ log L_{S,aa}`, constant for the
3032        /// frame (depends only on the factored Hessian, not on `g`).
3033        log_det_hessian: f64,
3034    }
3035
3036    impl ResidentArrowFrame {
3037        /// Upload the constant Hessian blocks and perform the one-time factor
3038        /// work (`POTRF(D)`, `Y_i = L_i^{-1} B_i`, Schur assembly + border
3039        /// `POTRF`). The frame then serves cheap per-gradient solves.
3040        pub(super) fn new(
3041            sys: &ArrowSchurSystem,
3042            ridge_t: f64,
3043            ridge_beta: f64,
3044        ) -> Result<Self, ArrowSchurGpuFailure> {
3045            if ridge_t.is_nan() || ridge_beta.is_nan() {
3046                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
3047                    reason: "ridge is NaN".to_string(),
3048                });
3049            }
3050            let n = sys.rows.len();
3051            let d = sys.d;
3052            let k = sys.k;
3053            let runtime = route_through_gpu(DispatchOp::SmallDenseBatchedPotrf { p: d, batch: n })
3054                .ok_or(ArrowSchurGpuFailure::Unavailable)?;
3055            let stream = gam_gpu::device_runtime::cuda_context_for(runtime.device.ordinal)
3056                .and_then(|ctx| ctx.new_stream().ok())
3057                .ok_or(ArrowSchurGpuFailure::Unavailable)?;
3058            let solver =
3059                DnHandle::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3060            let blas =
3061                CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3062
3063            // Upload the constant blocks. `g` is uploaded per-gradient, not here.
3064            let (d_host, b_host, _g_host) = pack_host(sys, ridge_t);
3065            let mut l_dev = stream
3066                .clone_htod(&d_host)
3067                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3068            let mut y_dev = stream
3069                .clone_htod(&b_host)
3070                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3071
3072            // POTRF(D) → L_i, kept resident in l_dev.
3073            let info_host = potrf_batched(&solver, &stream, d, n, &mut l_dev)?;
3074            if let Some(idx) = info_host.iter().position(|info| *info != 0) {
3075                let pivot = info_host[idx];
3076                let scale = sys.rows[idx]
3077                    .htt
3078                    .diag()
3079                    .iter()
3080                    .map(|v| v.abs())
3081                    .fold(0.0_f64, f64::max)
3082                    .max(1.0);
3083                return Err(ArrowSchurGpuFailure::RidgeBumpRequired {
3084                    row: idx,
3085                    bump: scale * (pivot.abs() as f64).max(1.0) * f64::EPSILON.sqrt() * 1024.0,
3086                });
3087            }
3088
3089            // Y_i = L_i^{-1} B_i, in place over y_dev. Kept resident.
3090            trsm_batched_lower_inplace(&blas, &stream, d, n, k, &l_dev, &mut y_dev)?;
3091
3092            // Schur assembly S_β = (H_ββ + ρ_β I) − Σ Y_iᵀ Y_i, then POTRF → L_S.
3093            // The RHS accumulation is folded into the gradient path; here we
3094            // only need the (gradient-independent) Schur factor, so accumulate
3095            // into a throwaway rhs buffer.
3096            let schur_init: Vec<f64> = {
3097                let mut tmp = Vec::with_capacity(k * k);
3098                for col in 0..k {
3099                    for row in 0..k {
3100                        let mut v = sys.hbb[[row, col]];
3101                        if row == col {
3102                            v += ridge_beta;
3103                        }
3104                        tmp.push(v);
3105                    }
3106                }
3107                tmp
3108            };
3109            let mut schur_dev = stream
3110                .clone_htod(&schur_init)
3111                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3112            // A zero u-stack makes `Σ Y_iᵀ u_i = 0`, so only the `−Σ Y_iᵀ Y_i`
3113            // Schur term is accumulated (the rhs is rebuilt per gradient).
3114            let zero_u = stream
3115                .clone_htod(&vec![0.0_f64; n * d])
3116                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3117            let mut throwaway_rhs = stream
3118                .clone_htod(&vec![0.0_f64; k])
3119                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3120            accumulate_schur(
3121                &blas,
3122                d,
3123                k,
3124                n,
3125                &y_dev,
3126                &zero_u,
3127                &mut schur_dev,
3128                &mut throwaway_rhs,
3129            )?;
3130            let info = potrf_single(&solver, &stream, k, &mut schur_dev)?;
3131            if info != 0 {
3132                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
3133                    reason: format!("Schur Cholesky failed at pivot {info}"),
3134                });
3135            }
3136
3137            // log|H| from the resident factors (constant for the frame).
3138            let l_local_host = stream
3139                .clone_dtoh(&l_dev)
3140                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3141            let l_schur_host = stream
3142                .clone_dtoh(&schur_dev)
3143                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3144            let mut log_det = 0.0_f64;
3145            for i in 0..n {
3146                let base = i * d * d;
3147                for j in 0..d {
3148                    log_det += l_local_host[base + j * d + j].ln();
3149                }
3150            }
3151            for j in 0..k {
3152                log_det += l_schur_host[j * k + j].ln();
3153            }
3154            log_det *= 2.0;
3155
3156            Ok(Self {
3157                n,
3158                d,
3159                k,
3160                stream,
3161                blas,
3162                l_dev,
3163                y_dev,
3164                schur_dev,
3165                log_det_hessian: log_det,
3166            })
3167        }
3168
3169        #[inline]
3170        pub(super) fn log_det_hessian(&self) -> f64 {
3171            self.log_det_hessian
3172        }
3173
3174        /// Solve `H δ = −gradient` for a fresh gradient `(g_t, g_β)` reusing the
3175        /// resident factors. Uploads only `g_t` (`n·d` scalars); reads back only
3176        /// `δ`. No POTRF runs here — all factorization is amortized into `new`.
3177        pub(super) fn solve_gradient(
3178            &self,
3179            g_t: &[f64],
3180            g_beta: &[f64],
3181        ) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
3182            let n = self.n;
3183            let d = self.d;
3184            let k = self.k;
3185            if g_t.len() != n * d || g_beta.len() != k {
3186                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
3187                    reason: format!(
3188                        "resident gradient shape mismatch: g_t={} (want {}), g_beta={} (want {})",
3189                        g_t.len(),
3190                        n * d,
3191                        g_beta.len(),
3192                        k
3193                    ),
3194                });
3195            }
3196            // Upload the per-iterate row gradient → u_i = L_i^{-1} g_i in place.
3197            let mut u_dev = self
3198                .stream
3199                .clone_htod(&g_t.to_vec())
3200                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3201            trsm_batched_lower_inplace(&self.blas, &self.stream, d, n, 1, &self.l_dev, &mut u_dev)?;
3202
3203            // Schur RHS = −g_β + Σ_i Y_iᵀ u_i. Reuse the resident Schur factor
3204            // (no POTRF, and skip the −Σ Y_iᵀ Y_i GEMM already baked into L_S).
3205            let rhs_init: Vec<f64> = g_beta.iter().map(|v| -v).collect();
3206            let mut rhs_dev = self
3207                .stream
3208                .clone_htod(&rhs_init)
3209                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3210            accumulate_schur_rhs_only(&self.blas, d, k, n, &self.y_dev, &u_dev, &mut rhs_dev)?;
3211
3212            // δβ ← L_S^{-T} L_S^{-1} rhs using the resident border factor.
3213            trsm_single(
3214                &self.blas,
3215                &self.stream,
3216                k,
3217                &self.schur_dev,
3218                &mut rhs_dev,
3219                false,
3220                false,
3221            )?;
3222            trsm_single(
3223                &self.blas,
3224                &self.stream,
3225                k,
3226                &self.schur_dev,
3227                &mut rhs_dev,
3228                false,
3229                true,
3230            )?;
3231            let delta_beta_host = self
3232                .stream
3233                .clone_dtoh(&rhs_dev)
3234                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3235            let delta_beta = Array1::from_vec(delta_beta_host);
3236
3237            // Back-sub δt_i = −L_i^{-T}(u_i + Y_i δβ).
3238            accumulate_back_sub_rhs(&self.blas, d, k, n, &self.y_dev, &rhs_dev, &mut u_dev)?;
3239            trsm_batched_lower_inplace_transposed(
3240                &self.blas,
3241                &self.stream,
3242                d,
3243                n,
3244                1,
3245                &self.l_dev,
3246                &mut u_dev,
3247            )?;
3248            let x_host = self
3249                .stream
3250                .clone_dtoh(&u_dev)
3251                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3252            let mut delta_t = Array1::<f64>::zeros(n * d);
3253            for (i, v) in x_host.iter().enumerate() {
3254                delta_t[i] = -*v;
3255            }
3256
3257            Ok(ArrowSchurGpuSolution {
3258                delta_t,
3259                delta_beta,
3260                log_det_hessian: self.log_det_hessian,
3261            })
3262        }
3263    }
3264
3265    pub(super) fn solve_fused(
3266        sys: &ArrowSchurSystem,
3267        ridge_t: f64,
3268        ridge_beta: f64,
3269    ) -> Result<ArrowSchurGpuSolution, ArrowSchurGpuFailure> {
3270        let n = sys.rows.len();
3271        let d = sys.d;
3272        let k = sys.k;
3273        let plan = crate::gpu_kernels::arrow_schur_nvrtc::plan_fused_launch(n, d, k)
3274            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
3275        let p_max = plan.p_max;
3276        let r_template = plan.r_template;
3277
3278        let runtime = gam_gpu::linalg_dispatch::route_through_gpu(
3279            gam_gpu::linalg_dispatch::DispatchOp::SmallDenseBatchedPotrf { p: d, batch: n },
3280        )
3281        .ok_or(ArrowSchurGpuFailure::Unavailable)?;
3282        let ctx = gam_gpu::device_runtime::cuda_context_for(runtime.device.ordinal)
3283            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
3284        let stream = ctx
3285            .new_stream()
3286            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3287        let cap = &runtime.device.capability;
3288        let key = crate::gpu_kernels::arrow_schur_nvrtc::FusedModuleCacheKey {
3289            cc_major: cap.compute_major,
3290            cc_minor: cap.compute_minor,
3291            p_max: p_max as u32,
3292            r_template: r_template as u32,
3293        };
3294        let module = fused_module_for(&ctx, key)?;
3295        let forward = module
3296            .load_function("arrow_schur_forward_pgroup")
3297            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3298        let back_sub = module
3299            .load_function("arrow_schur_back_sub_pgroup")
3300            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3301
3302        // ----- Upload packed D, B, g -----
3303        let (d_host, b_host, g_host) = pack_fused_host(sys, ridge_t, p_max, r_template);
3304        let d_dev = stream
3305            .clone_htod(&d_host)
3306            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3307        let b_dev = stream
3308            .clone_htod(&b_host)
3309            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3310        let g_dev = stream
3311            .clone_htod(&g_host)
3312            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3313        let mut l_out = stream
3314            .alloc_zeros::<f64>(n * p_max * p_max)
3315            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3316        let mut u_out = stream
3317            .alloc_zeros::<f64>(n * p_max)
3318            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3319        let mut y_out = stream
3320            .alloc_zeros::<f64>(n * p_max * r_template)
3321            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3322        let mut partial_s = stream
3323            .alloc_zeros::<f64>(plan.partial_s_doubles)
3324            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3325        let mut partial_r = stream
3326            .alloc_zeros::<f64>(plan.partial_r_doubles)
3327            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3328        let mut status_dev = stream
3329            .alloc_zeros::<i32>(n)
3330            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3331
3332        // ----- Launch forward kernel: 1 block per row, P_MAX threads -----
3333        let cfg = LaunchConfig {
3334            grid_dim: (plan.blocks, 1, 1),
3335            block_dim: (plan.threads_per_block, 1, 1),
3336            shared_mem_bytes: 0,
3337        };
3338        let n_i32 = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
3339        let p_i32 = to_i32(d).ok_or(ArrowSchurGpuFailure::Unavailable)?;
3340        let r_i32 = to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?;
3341        let ridge_arg = ridge_t;
3342        {
3343            let mut builder = stream.launch_builder(&forward);
3344            builder
3345                .arg(&d_dev)
3346                .arg(&b_dev)
3347                .arg(&g_dev)
3348                .arg(&n_i32)
3349                .arg(&p_i32)
3350                .arg(&r_i32)
3351                .arg(&ridge_arg)
3352                .arg(&mut l_out)
3353                .arg(&mut u_out)
3354                .arg(&mut y_out)
3355                .arg(&mut partial_s)
3356                .arg(&mut partial_r)
3357                .arg(&mut status_dev);
3358            // SAFETY: all buffers were just allocated on `stream` with sizes
3359            // derived from `plan`; kernel parameter list matches the
3360            // FORWARD_KERNEL_SOURCE signature.
3361            unsafe { builder.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3362        }
3363        stream
3364            .synchronize()
3365            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3366
3367        // ----- Check per-block pivot status -----
3368        let status_host = stream
3369            .clone_dtoh(&status_dev)
3370            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3371        if let Some(row) = status_host.iter().position(|s| *s != 0) {
3372            let pivot = status_host[row];
3373            let scale = sys.rows[row]
3374                .htt
3375                .diag()
3376                .iter()
3377                .map(|v| v.abs())
3378                .fold(0.0_f64, f64::max)
3379                .max(1.0);
3380            return Err(ArrowSchurGpuFailure::RidgeBumpRequired {
3381                row,
3382                bump: scale * (pivot.abs() as f64).max(1.0) * f64::EPSILON.sqrt() * 1024.0,
3383            });
3384        }
3385
3386        // ----- Reduce partials on host into S_β and r_β -----
3387        let partial_s_host = stream
3388            .clone_dtoh(&partial_s)
3389            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3390        let partial_r_host = stream
3391            .clone_dtoh(&partial_r)
3392            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3393        let mut schur_host = vec![0.0_f64; k * k];
3394        for col in 0..k {
3395            for row in 0..k {
3396                let mut v = sys.hbb[[row, col]];
3397                if row == col {
3398                    v += ridge_beta;
3399                }
3400                schur_host[col * k + row] = v;
3401            }
3402        }
3403        let mut rhs_host: Vec<f64> = sys.gb.iter().map(|v| -v).collect();
3404        for i in 0..n {
3405            // partial_S[i] stride is R_TEMPLATE × R_TEMPLATE column-major; we
3406            // only read the leading (k × k) sub-block.
3407            let s_base = i * r_template * r_template;
3408            for col in 0..k {
3409                let col_base = s_base + col * r_template;
3410                let dst_col_base = col * k;
3411                for row in 0..k {
3412                    schur_host[dst_col_base + row] -= partial_s_host[col_base + row];
3413                }
3414            }
3415            let r_base = i * r_template;
3416            for a in 0..k {
3417                rhs_host[a] += partial_r_host[r_base + a];
3418            }
3419        }
3420
3421        // ----- Factor S_β on device (cuSOLVER), solve for δβ -----
3422        let mut schur_dev = stream
3423            .clone_htod(&schur_host)
3424            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3425        let mut rhs_dev = stream
3426            .clone_htod(&rhs_host)
3427            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3428        let solver =
3429            DnHandle::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3430        let blas = CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3431        let info = potrf_single(&solver, &stream, k, &mut schur_dev)?;
3432        if info != 0 {
3433            return Err(ArrowSchurGpuFailure::SchurFactorFailed {
3434                reason: format!("fused Schur Cholesky failed at pivot {info}"),
3435            });
3436        }
3437        trsm_single(&blas, &stream, k, &schur_dev, &mut rhs_dev, false, false)?;
3438        trsm_single(&blas, &stream, k, &schur_dev, &mut rhs_dev, false, true)?;
3439        let delta_beta_host = stream
3440            .clone_dtoh(&rhs_dev)
3441            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3442        let delta_beta = Array1::from_vec(delta_beta_host.clone());
3443
3444        // ----- Layer E: launch back-sub kernel using persisted L, u, Y -----
3445        let mut delta_t_dev = stream
3446            .alloc_zeros::<f64>(n * p_max)
3447            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3448        let back_cfg = LaunchConfig {
3449            grid_dim: (plan.blocks, 1, 1),
3450            block_dim: (plan.threads_per_block, 1, 1),
3451            shared_mem_bytes: 0,
3452        };
3453        {
3454            let mut builder = stream.launch_builder(&back_sub);
3455            builder
3456                .arg(&l_out)
3457                .arg(&u_out)
3458                .arg(&y_out)
3459                .arg(&rhs_dev)
3460                .arg(&n_i32)
3461                .arg(&p_i32)
3462                .arg(&r_i32)
3463                .arg(&mut delta_t_dev);
3464            // SAFETY: kernel parameter list matches FORWARD_KERNEL_SOURCE
3465            // back-sub signature; `rhs_dev` holds δβ in the leading k entries
3466            // (R_TEMPLATE-strided indexing is column 0..k of the R-vector).
3467            unsafe { builder.launch(back_cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3468        }
3469        stream
3470            .synchronize()
3471            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3472
3473        let delta_t_host = stream
3474            .clone_dtoh(&delta_t_dev)
3475            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3476        let mut delta_t = Array1::<f64>::zeros(n * d);
3477        for i in 0..n {
3478            let src_base = i * p_max;
3479            let dst_base = i * d;
3480            for r in 0..d {
3481                delta_t[dst_base + r] = delta_t_host[src_base + r];
3482            }
3483        }
3484
3485        // ----- log|H| = 2·Σ log L_{i,jj} + 2·Σ log R_{β,aa} -----
3486        let l_local_host = stream
3487            .clone_dtoh(&l_out)
3488            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3489        let l_schur_host = stream
3490            .clone_dtoh(&schur_dev)
3491            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3492        let mut log_det = 0.0_f64;
3493        for i in 0..n {
3494            let base = i * p_max * p_max;
3495            for j in 0..d {
3496                log_det += l_local_host[base + j * p_max + j].ln();
3497            }
3498        }
3499        for j in 0..k {
3500            log_det += l_schur_host[j * k + j].ln();
3501        }
3502        log_det *= 2.0;
3503
3504        Ok(ArrowSchurGpuSolution {
3505            delta_t,
3506            delta_beta,
3507            log_det_hessian: log_det,
3508        })
3509    }
3510
3511    /// Pre-compute `Y_i = L_i^{-1} H_tβ^(i)` via the fused forward kernel and
3512    /// return a closure that evaluates the full Schur matvec
3513    /// `S·x = (H_ββ + ρ·I)·x − Σ_i Y_i^T (Y_i·x)` for each PCG iteration.
3514    ///
3515    /// The `Y_i` factors are kept in a host-side buffer after one GPU forward
3516    /// pass. Each matvec call runs O(N·d·K) host loops over the pre-computed
3517    /// buffer plus an optional `H_ββ·x` call (matrix-free or dense). This is
3518    /// the first landing of the GPU matvec; a future iteration can move the
3519    /// `Y_i·x` / `Y_i^T z_i` steps to cuBLAS batched GEMV.
3520    pub(super) fn build_schur_matvec_backend(
3521        sys: &ArrowSchurSystem,
3522        ridge_t: f64,
3523        ridge_beta: f64,
3524    ) -> Result<crate::arrow_schur::GpuSchurMatvec, super::ArrowSchurGpuFailure> {
3525        let n = sys.rows.len();
3526        let d = sys.d;
3527        let k = sys.k;
3528        let plan = crate::gpu_kernels::arrow_schur_nvrtc::plan_fused_launch(n, d, k)
3529            .ok_or(super::ArrowSchurGpuFailure::Unavailable)?;
3530        let p_max = plan.p_max;
3531        let r_template = plan.r_template;
3532
3533        let runtime = gam_gpu::linalg_dispatch::route_through_gpu(
3534            gam_gpu::linalg_dispatch::DispatchOp::SmallDenseBatchedPotrf { p: d, batch: n },
3535        )
3536        .ok_or(super::ArrowSchurGpuFailure::Unavailable)?;
3537        let ctx = gam_gpu::device_runtime::cuda_context_for(runtime.device.ordinal)
3538            .ok_or(super::ArrowSchurGpuFailure::Unavailable)?;
3539        let stream = ctx
3540            .new_stream()
3541            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3542        let cap = &runtime.device.capability;
3543        let key = crate::gpu_kernels::arrow_schur_nvrtc::FusedModuleCacheKey {
3544            cc_major: cap.compute_major,
3545            cc_minor: cap.compute_minor,
3546            p_max: p_max as u32,
3547            r_template: r_template as u32,
3548        };
3549        let module = fused_module_for(&ctx, key)?;
3550        let forward = module
3551            .load_function("arrow_schur_forward_pgroup")
3552            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3553
3554        let (d_host, b_host, g_host) = pack_fused_host(sys, ridge_t, p_max, r_template);
3555        let d_dev = stream
3556            .clone_htod(&d_host)
3557            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3558        let b_dev = stream
3559            .clone_htod(&b_host)
3560            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3561        let g_dev = stream
3562            .clone_htod(&g_host)
3563            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3564        let mut l_out = stream
3565            .alloc_zeros::<f64>(n * p_max * p_max)
3566            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3567        let mut u_out = stream
3568            .alloc_zeros::<f64>(n * p_max)
3569            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3570        let mut y_out = stream
3571            .alloc_zeros::<f64>(n * p_max * r_template)
3572            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3573        let mut partial_s = stream
3574            .alloc_zeros::<f64>(plan.partial_s_doubles)
3575            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3576        let mut partial_r = stream
3577            .alloc_zeros::<f64>(plan.partial_r_doubles)
3578            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3579        let mut status_dev = stream
3580            .alloc_zeros::<i32>(n)
3581            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3582
3583        let cfg = LaunchConfig {
3584            grid_dim: (plan.blocks, 1, 1),
3585            block_dim: (plan.threads_per_block, 1, 1),
3586            shared_mem_bytes: 0,
3587        };
3588        let n_i32 = to_i32(n).ok_or(super::ArrowSchurGpuFailure::Unavailable)?;
3589        let p_i32 = to_i32(d).ok_or(super::ArrowSchurGpuFailure::Unavailable)?;
3590        let r_i32 = to_i32(k).ok_or(super::ArrowSchurGpuFailure::Unavailable)?;
3591        let ridge_arg = ridge_t;
3592        {
3593            let mut builder = stream.launch_builder(&forward);
3594            builder
3595                .arg(&d_dev)
3596                .arg(&b_dev)
3597                .arg(&g_dev)
3598                .arg(&n_i32)
3599                .arg(&p_i32)
3600                .arg(&r_i32)
3601                .arg(&ridge_arg)
3602                .arg(&mut l_out)
3603                .arg(&mut u_out)
3604                .arg(&mut y_out)
3605                .arg(&mut partial_s)
3606                .arg(&mut partial_r)
3607                .arg(&mut status_dev);
3608            // SAFETY: all buffers were allocated on `stream` with sizes
3609            // derived from `plan`; parameter list matches FORWARD_KERNEL_SOURCE.
3610            unsafe { builder.launch(cfg) }.map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3611        }
3612        stream
3613            .synchronize()
3614            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3615
3616        let status_host = stream
3617            .clone_dtoh(&status_dev)
3618            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3619        if let Some(row) = status_host.iter().position(|s| *s != 0) {
3620            let pivot = status_host[row];
3621            let scale = sys.rows[row]
3622                .htt
3623                .diag()
3624                .iter()
3625                .map(|v| v.abs())
3626                .fold(0.0_f64, f64::max)
3627                .max(1.0);
3628            return Err(super::ArrowSchurGpuFailure::RidgeBumpRequired {
3629                row,
3630                bump: scale * (pivot.abs() as f64).max(1.0) * f64::EPSILON.sqrt() * 1024.0,
3631            });
3632        }
3633
3634        // Download Y_i factors: n × p_max × r_template column-major per block.
3635        let y_host = stream
3636            .clone_dtoh(&y_out)
3637            .map_err(|_| super::ArrowSchurGpuFailure::Unavailable)?;
3638
3639        // Capture H_ββ data for the closure. Use the matrix-free hook if present
3640        // (SAE-manifold callers), otherwise fall back to the dense matrix rows.
3641        let hbb_host: Vec<f64> = sys.hbb.iter().copied().collect();
3642        let hbb_is_kk = sys.hbb.dim() == (k, k);
3643        let hbb_matvec_opt = sys.hbb_matvec.clone();
3644
3645        let closure: crate::arrow_schur::GpuSchurMatvec =
3646            Arc::new(move |x: &Array1<f64>, out: &mut Array1<f64>| {
3647                assert_eq!(x.len(), k, "gpu_schur_matvec: x.len() != k");
3648                assert_eq!(out.len(), k, "gpu_schur_matvec: out.len() != k");
3649
3650                // (H_ββ + ρ·I)·x into out.
3651                if let Some(ref mv) = hbb_matvec_opt {
3652                    mv(x.view(), out);
3653                    for a in 0..k {
3654                        out[a] += ridge_beta * x[a];
3655                    }
3656                } else if hbb_is_kk {
3657                    // hbb_host row-major: hbb[a, b] = hbb_host[a * k + b].
3658                    for a in 0..k {
3659                        let mut acc = ridge_beta * x[a];
3660                        for b in 0..k {
3661                            acc += hbb_host[a * k + b] * x[b];
3662                        }
3663                        out[a] = acc;
3664                    }
3665                } else {
3666                    for a in 0..k {
3667                        out[a] = ridge_beta * x[a];
3668                    }
3669                }
3670
3671                // out[c] -= Σ_i (Y_i^T (Y_i·x))[c].
3672                // Y_i column-major at y_host[i·p_max·r_template + col·p_max + row].
3673                let mut z = vec![0.0_f64; d];
3674                for i in 0..n {
3675                    let y_base = i * p_max * r_template;
3676                    for r in 0..d {
3677                        let mut acc = 0.0;
3678                        for c in 0..k {
3679                            acc += y_host[y_base + c * p_max + r] * x[c];
3680                        }
3681                        z[r] = acc;
3682                    }
3683                    for c in 0..k {
3684                        let mut acc = 0.0;
3685                        for r in 0..d {
3686                            acc += y_host[y_base + c * p_max + r] * z[r];
3687                        }
3688                        out[c] -= acc;
3689                    }
3690                }
3691            });
3692
3693        Ok(closure)
3694    }
3695
3696    // ── #1017/#1026 frames-engaged device PCG ──────────────────────────────
3697
3698    struct DeviceSaeFrameBuffers {
3699        // Smooth `λ S_k ⊗ I_{r_k}`.
3700        s_off: CudaSlice<i32>,
3701        s_m: CudaSlice<i32>,
3702        s_r: CudaSlice<i32>,
3703        s_ptr: CudaSlice<i32>,
3704        s_data: CudaSlice<f64>,
3705        s_blocks: usize,
3706        // Data `G_{ij} ⊗ W_{ij}`.
3707        g_off_i: CudaSlice<i32>,
3708        g_off_j: CudaSlice<i32>,
3709        g_ri: CudaSlice<i32>,
3710        g_rj: CudaSlice<i32>,
3711        g_mi: CudaSlice<i32>,
3712        g_mj: CudaSlice<i32>,
3713        g_ptr: CudaSlice<i32>,
3714        g_data: CudaSlice<f64>,
3715        w_ptr: CudaSlice<i32>,
3716        w_data: CudaSlice<f64>,
3717        g_blocks: usize,
3718        g_max_work: usize,
3719        // Per-row dense cross-block H_tβ^(i) + row q + factored ainv.
3720        htb_ptr: CudaSlice<i32>,
3721        htb: CudaSlice<f64>,
3722        q_of: CudaSlice<i32>,
3723        ainv: CudaSlice<f64>,
3724        hvec: CudaSlice<f64>,
3725        svec: CudaSlice<f64>,
3726        n_rows: usize,
3727        k: usize,
3728        max_q: usize,
3729    }
3730
3731    fn flatten_device_sae_frame_data(
3732        sys: &ArrowSchurSystem,
3733        data: &DeviceSaePcgData,
3734        frame: &DeviceSaeFrameData,
3735        ridge_t: f64,
3736        stream: &Arc<CudaStream>,
3737    ) -> Result<DeviceSaeFrameBuffers, ArrowSchurGpuFailure> {
3738        let n_rows = sys.rows.len();
3739        let k = data.beta_dim;
3740        if frame.row_htbeta.len() != n_rows
3741            || frame.ranks.len() != frame.basis_sizes.len()
3742            || frame.border_offsets.len() != frame.ranks.len()
3743            || data.smooth_blocks.len() != frame.smooth_ranks.len()
3744        {
3745            return Err(ArrowSchurGpuFailure::Unavailable);
3746        }
3747
3748        // Smooth blocks.
3749        let mut s_off = Vec::new();
3750        let mut s_m = Vec::new();
3751        let mut s_r = Vec::new();
3752        let mut s_ptr = vec![0_i32];
3753        let mut s_data = Vec::<f64>::new();
3754        for (blk, &r) in data.smooth_blocks.iter().zip(frame.smooth_ranks.iter()) {
3755            let (m, mc) = blk.factor_a.dim();
3756            if m != mc {
3757                return Err(ArrowSchurGpuFailure::Unavailable);
3758            }
3759            s_off.push(checked_i32(blk.global_offset)?);
3760            s_m.push(checked_i32(m)?);
3761            s_r.push(checked_i32(r)?);
3762            for ri in 0..m {
3763                for ci in 0..m {
3764                    s_data.push(blk.factor_a[[ri, ci]]);
3765                }
3766            }
3767            s_ptr.push(checked_i32(s_data.len())?);
3768        }
3769
3770        // Data blocks (g + w).
3771        let mut g_off_i = Vec::new();
3772        let mut g_off_j = Vec::new();
3773        let mut g_ri = Vec::new();
3774        let mut g_rj = Vec::new();
3775        let mut g_mi = Vec::new();
3776        let mut g_mj = Vec::new();
3777        let mut g_ptr = vec![0_i32];
3778        let mut g_data = Vec::<f64>::new();
3779        let mut w_ptr = vec![0_i32];
3780        let mut w_data = Vec::<f64>::new();
3781        let mut g_max_work = 0usize;
3782        for blk in &frame.frame_blocks {
3783            let ri = frame.ranks[blk.atom_i];
3784            let rj = frame.ranks[blk.atom_j];
3785            let (mi, mj) = blk.g.dim();
3786            if blk.w.dim() != (ri, rj) {
3787                return Err(ArrowSchurGpuFailure::Unavailable);
3788            }
3789            g_off_i.push(checked_i32(frame.border_offsets[blk.atom_i])?);
3790            g_off_j.push(checked_i32(frame.border_offsets[blk.atom_j])?);
3791            g_ri.push(checked_i32(ri)?);
3792            g_rj.push(checked_i32(rj)?);
3793            g_mi.push(checked_i32(mi)?);
3794            g_mj.push(checked_i32(mj)?);
3795            for r in 0..mi {
3796                for c in 0..mj {
3797                    g_data.push(blk.g[[r, c]]);
3798                }
3799            }
3800            g_ptr.push(checked_i32(g_data.len())?);
3801            for a in 0..ri {
3802                for b in 0..rj {
3803                    w_data.push(blk.w[[a, b]]);
3804                }
3805            }
3806            w_ptr.push(checked_i32(w_data.len())?);
3807            g_max_work = g_max_work.max(mi * ri);
3808        }
3809
3810        // Per-row dense cross-block + q + ainv (factored H_tt⁻¹).
3811        let mut htb_ptr = vec![0_i32];
3812        let mut htb = Vec::<f64>::new();
3813        let mut q_of = Vec::<i32>::with_capacity(n_rows);
3814        let mut max_q = 0usize;
3815        for (i, slab) in frame.row_htbeta.iter().enumerate() {
3816            let qi = sys.row_dims[i];
3817            // A populated slab must be q_i × k row-major; an empty slab ⇒ q=0
3818            // (the row contributes no reduced-Schur term).
3819            let q_eff = if !slab.is_empty() && slab.len() == qi * k {
3820                qi
3821            } else {
3822                0
3823            };
3824            q_of.push(checked_i32(q_eff)?);
3825            max_q = max_q.max(q_eff);
3826            if q_eff > 0 {
3827                htb.extend_from_slice(slab);
3828            }
3829            htb_ptr.push(checked_i32(htb.len())?);
3830        }
3831        if max_q == 0 {
3832            // No row contributes a reduced term — the system is pure-penalty.
3833            // Still valid; give max_q=1 so the ainv buffer is non-empty.
3834            max_q = 1;
3835        }
3836
3837        let mut ainv = vec![0.0_f64; n_rows * max_q * max_q];
3838        for (i, row) in sys.rows.iter().enumerate() {
3839            let q = q_of[i] as usize;
3840            if q == 0 {
3841                continue;
3842            }
3843            if row.htt.dim() != (q, q) {
3844                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
3845                    reason: format!(
3846                        "framed SAE device PCG row {i}: H_tt shape {:?} != ({q}, {q})",
3847                        row.htt.dim()
3848                    ),
3849                });
3850            }
3851            let mut block = row.htt.clone();
3852            for d in 0..q {
3853                block[[d, d]] += ridge_t;
3854            }
3855            let factor = gam_linalg::triangular::cholesky_factor_in_place(
3856                block.view(),
3857                gam_linalg::triangular::CholeskyGuard::NonnegativePivot,
3858            )
3859            .ok_or_else(|| {
3860                let scale = row
3861                    .htt
3862                    .diag()
3863                    .iter()
3864                    .map(|v| v.abs())
3865                    .fold(0.0_f64, f64::max)
3866                    .max(1.0);
3867                ArrowSchurGpuFailure::RidgeBumpRequired {
3868                    row: i,
3869                    bump: scale * f64::EPSILON.sqrt() * super::RIDGE_BUMP_EPS_MARGIN,
3870                }
3871            })?;
3872            for col in 0..q {
3873                let mut e = Array1::<f64>::zeros(q);
3874                e[col] = 1.0;
3875                let solved =
3876                    gam_linalg::triangular::cholesky_solve_vector(factor.view(), e.view());
3877                for r in 0..q {
3878                    ainv[i * max_q * max_q + r * max_q + col] = solved[r];
3879                }
3880            }
3881        }
3882
3883        let htod_i = |v: &[i32]| {
3884            stream
3885                .clone_htod(v)
3886                .map_err(|_| ArrowSchurGpuFailure::Unavailable)
3887        };
3888        let htod_f = |v: &[f64]| {
3889            stream
3890                .clone_htod(v)
3891                .map_err(|_| ArrowSchurGpuFailure::Unavailable)
3892        };
3893        Ok(DeviceSaeFrameBuffers {
3894            s_off: htod_i(&s_off)?,
3895            s_m: htod_i(&s_m)?,
3896            s_r: htod_i(&s_r)?,
3897            s_ptr: htod_i(&s_ptr)?,
3898            s_data: htod_f(&s_data)?,
3899            s_blocks: data.smooth_blocks.len(),
3900            g_off_i: htod_i(&g_off_i)?,
3901            g_off_j: htod_i(&g_off_j)?,
3902            g_ri: htod_i(&g_ri)?,
3903            g_rj: htod_i(&g_rj)?,
3904            g_mi: htod_i(&g_mi)?,
3905            g_mj: htod_i(&g_mj)?,
3906            g_ptr: htod_i(&g_ptr)?,
3907            g_data: htod_f(&g_data)?,
3908            w_ptr: htod_i(&w_ptr)?,
3909            w_data: htod_f(&w_data)?,
3910            g_blocks: frame.frame_blocks.len(),
3911            g_max_work,
3912            htb_ptr: htod_i(&htb_ptr)?,
3913            htb: htod_f(&htb)?,
3914            q_of: htod_i(&q_of)?,
3915            ainv: htod_f(&ainv)?,
3916            hvec: stream
3917                .alloc_zeros::<f64>(n_rows * max_q)
3918                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
3919            svec: stream
3920                .alloc_zeros::<f64>(n_rows * max_q)
3921                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?,
3922            n_rows,
3923            k,
3924            max_q,
3925        })
3926    }
3927
3928    fn sae_frame_penalty_diag_host(
3929        data: &DeviceSaePcgData,
3930        frame: &DeviceSaeFrameData,
3931        ridge_beta: f64,
3932    ) -> Result<Vec<f64>, ArrowSchurGpuFailure> {
3933        let mut diag = vec![ridge_beta; data.beta_dim];
3934        // Smooth: diag[off + ia·r + ib] += S[ia,ia].
3935        for (blk, &r) in data.smooth_blocks.iter().zip(frame.smooth_ranks.iter()) {
3936            let m = blk.factor_a.nrows();
3937            for ia in 0..m {
3938                let coeff = blk.factor_a[[ia, ia]];
3939                let base = blk.global_offset + ia * r;
3940                for ib in 0..r {
3941                    if base + ib >= diag.len() {
3942                        return Err(ArrowSchurGpuFailure::Unavailable);
3943                    }
3944                    diag[base + ib] += coeff;
3945                }
3946            }
3947        }
3948        // Data: on-diagonal atom blocks contribute g[li,li]·w[a,a].
3949        for blk in &frame.frame_blocks {
3950            if blk.atom_i != blk.atom_j {
3951                continue;
3952            }
3953            let r = frame.ranks[blk.atom_i];
3954            let off = frame.border_offsets[blk.atom_i];
3955            let (mi, mj) = blk.g.dim();
3956            for li in 0..mi.min(mj) {
3957                let gii = blk.g[[li, li]];
3958                let base = off + li * r;
3959                for a in 0..r {
3960                    if base + a >= diag.len() {
3961                        return Err(ArrowSchurGpuFailure::Unavailable);
3962                    }
3963                    diag[base + a] += gii * blk.w[[a, a]];
3964                }
3965            }
3966        }
3967        Ok(diag)
3968    }
3969
3970    fn frame_grid(work: usize, n_rows: usize) -> Result<LaunchConfig, ArrowSchurGpuFailure> {
3971        Ok(LaunchConfig {
3972            grid_dim: (
3973                ((work as u32).saturating_add(255) / 256).max(1),
3974                checked_i32(n_rows)? as u32,
3975                1,
3976            ),
3977            block_dim: (256, 1, 1),
3978            shared_mem_bytes: 0,
3979        })
3980    }
3981
3982    fn launch_sae_frame_matvec(
3983        stream: &Arc<CudaStream>,
3984        module: &Arc<CudaModule>,
3985        buffers: &mut DeviceSaeFrameBuffers,
3986        x: &CudaSlice<f64>,
3987        out: &mut CudaSlice<f64>,
3988        ridge_beta: f64,
3989    ) -> Result<(), ArrowSchurGpuFailure> {
3990        launch_sae_init(stream, module, out, x, ridge_beta, buffers.k)?;
3991        // Smooth penalty.
3992        if buffers.s_blocks > 0 {
3993            let kernel = module
3994                .load_function("arrow_sae_frame_smooth_matvec")
3995                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
3996            let blocks_i32 = checked_i32(buffers.s_blocks)?;
3997            let cfg = frame_grid(buffers.k, buffers.s_blocks)?;
3998            let mut b = stream.launch_builder(&kernel);
3999            b.arg(x)
4000                .arg(&mut *out)
4001                .arg(&buffers.s_off)
4002                .arg(&buffers.s_m)
4003                .arg(&buffers.s_r)
4004                .arg(&buffers.s_ptr)
4005                .arg(&buffers.s_data)
4006                .arg(&blocks_i32);
4007            // SAFETY: smooth block metadata/data are live device buffers; the grid
4008            // covers (k channels × n_blocks) and the kernel bounds-checks m·r.
4009            unsafe { b.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4010        }
4011        // Data penalty.
4012        if buffers.g_blocks > 0 {
4013            let kernel = module
4014                .load_function("arrow_sae_frame_g_matvec")
4015                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4016            let blocks_i32 = checked_i32(buffers.g_blocks)?;
4017            let cfg = frame_grid(buffers.g_max_work.max(1), buffers.g_blocks)?;
4018            let mut b = stream.launch_builder(&kernel);
4019            b.arg(x)
4020                .arg(&mut *out)
4021                .arg(&buffers.g_off_i)
4022                .arg(&buffers.g_off_j)
4023                .arg(&buffers.g_ri)
4024                .arg(&buffers.g_rj)
4025                .arg(&buffers.g_mi)
4026                .arg(&buffers.g_mj)
4027                .arg(&buffers.g_ptr)
4028                .arg(&buffers.g_data)
4029                .arg(&buffers.w_ptr)
4030                .arg(&buffers.w_data)
4031                .arg(&blocks_i32);
4032            // SAFETY: g/w block metadata/data are live device buffers; the grid
4033            // covers (max m_i·r_i × n_blocks) and the kernel bounds-checks.
4034            unsafe { b.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4035        }
4036        // Reduced-Schur subtraction via dense per-row cross-blocks.
4037        let k_i32 = checked_i32(buffers.k)?;
4038        let max_q_i32 = checked_i32(buffers.max_q)?;
4039        let n_rows_i32 = checked_i32(buffers.n_rows)?;
4040        {
4041            let kernel = module
4042                .load_function("arrow_sae_frame_apply_h")
4043                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4044            let cfg = frame_grid(buffers.max_q, buffers.n_rows)?;
4045            let mut b = stream.launch_builder(&kernel);
4046            b.arg(x)
4047                .arg(&buffers.htb_ptr)
4048                .arg(&buffers.htb)
4049                .arg(&buffers.q_of)
4050                .arg(&mut buffers.hvec)
4051                .arg(&k_i32)
4052                .arg(&max_q_i32)
4053                .arg(&n_rows_i32);
4054            // SAFETY: dense cross-block + pointers + hvec are live buffers sized
4055            // for (n_rows × max_q) / (n_rows × k); kernel guards q_i and k.
4056            unsafe { b.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4057        }
4058        {
4059            let kernel = module
4060                .load_function("arrow_sae_frame_apply_ainv")
4061                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4062            let cfg = frame_grid(buffers.max_q, buffers.n_rows)?;
4063            let mut b = stream.launch_builder(&kernel);
4064            b.arg(&buffers.ainv)
4065                .arg(&buffers.hvec)
4066                .arg(&buffers.q_of)
4067                .arg(&mut buffers.svec)
4068                .arg(&max_q_i32)
4069                .arg(&n_rows_i32);
4070            // SAFETY: ainv/hvec/svec are live buffers sized for n_rows·max_q²
4071            // and n_rows·max_q; the kernel guards row/coord bounds.
4072            unsafe { b.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4073        }
4074        {
4075            let kernel = module
4076                .load_function("arrow_sae_frame_scatter_h")
4077                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4078            let cfg = frame_grid(buffers.k, buffers.n_rows)?;
4079            let mut b = stream.launch_builder(&kernel);
4080            b.arg(&buffers.svec)
4081                .arg(&buffers.htb_ptr)
4082                .arg(&buffers.htb)
4083                .arg(&buffers.q_of)
4084                .arg(out)
4085                .arg(&k_i32)
4086                .arg(&max_q_i32)
4087                .arg(&n_rows_i32);
4088            // SAFETY: svec/cross-block/out are live buffers; the kernel atomically
4089            // accumulates into out[a] for a<k and reads c<q_i.
4090            unsafe { b.launch(cfg) }.map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4091        }
4092        Ok(())
4093    }
4094
4095    fn launch_sae_frame_diag_sub(
4096        stream: &Arc<CudaStream>,
4097        module: &Arc<CudaModule>,
4098        buffers: &DeviceSaeFrameBuffers,
4099        diag: &mut CudaSlice<f64>,
4100    ) -> Result<(), ArrowSchurGpuFailure> {
4101        let kernel = module
4102            .load_function("arrow_sae_frame_diag_sub")
4103            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4104        let k_i32 = checked_i32(buffers.k)?;
4105        let max_q_i32 = checked_i32(buffers.max_q)?;
4106        let n_rows_i32 = checked_i32(buffers.n_rows)?;
4107        let cfg = frame_grid(buffers.k, buffers.n_rows)?;
4108        let mut b = stream.launch_builder(&kernel);
4109        b.arg(diag)
4110            .arg(&buffers.ainv)
4111            .arg(&buffers.htb_ptr)
4112            .arg(&buffers.htb)
4113            .arg(&buffers.q_of)
4114            .arg(&k_i32)
4115            .arg(&max_q_i32)
4116            .arg(&n_rows_i32);
4117        // SAFETY: diag + cross-block + ainv live buffers; kernel guards a<k, c/d<q.
4118        unsafe { b.launch(cfg) }
4119            .map(drop)
4120            .map_err(|_| ArrowSchurGpuFailure::Unavailable)
4121    }
4122
4123    pub(super) fn solve_sae_matrix_free_pcg_framed(
4124        sys: &ArrowSchurSystem,
4125        data: &DeviceSaePcgData,
4126        ridge_t: f64,
4127        ridge_beta: f64,
4128        rhs_beta: &Array1<f64>,
4129        max_iterations: usize,
4130        relative_tolerance: f64,
4131    ) -> Result<(Array1<f64>, PcgDiagnostics), ArrowSchurGpuFailure> {
4132        let k = rhs_beta.len();
4133        if k == 0 || data.beta_dim != k || sys.k != k {
4134            return Err(ArrowSchurGpuFailure::Unavailable);
4135        }
4136        let frame = data
4137            .frame
4138            .as_ref()
4139            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
4140        let runtime = gam_gpu::device_runtime::GpuRuntime::global()
4141            .filter(|rt| {
4142                rt.policy().reduced_schur_matvec_should_offload(
4143                    sys.rows.len(),
4144                    sys.k,
4145                    sys.d,
4146                    max_iterations,
4147                )
4148            })
4149            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
4150        let ctx = gam_gpu::device_runtime::cuda_context_for(runtime.selected_device().ordinal)
4151            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
4152        let stream = ctx
4153            .new_stream()
4154            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4155        let blas = CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4156        let vector_module = pcg_vector_module(&ctx)?;
4157        let mut buffers = flatten_device_sae_frame_data(sys, data, frame, ridge_t, &stream)?;
4158
4159        let rhs_norm = rhs_beta.iter().map(|v| v * v).sum::<f64>().sqrt();
4160        if rhs_norm == 0.0 {
4161            return Ok((Array1::<f64>::zeros(k), PcgDiagnostics::default()));
4162        }
4163        let tol = (relative_tolerance.max(0.0) * rhs_norm).max(1e-12);
4164        let rhs_dev = stream
4165            .clone_htod(
4166                rhs_beta
4167                    .as_slice()
4168                    .ok_or(ArrowSchurGpuFailure::Unavailable)?,
4169            )
4170            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4171        let diag_host = sae_frame_penalty_diag_host(data, frame, ridge_beta)?;
4172        let mut diag_dev = stream
4173            .clone_htod(&diag_host)
4174            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4175        launch_sae_frame_diag_sub(&stream, vector_module, &buffers, &mut diag_dev)?;
4176        let diag_host = stream
4177            .clone_dtoh(&diag_dev)
4178            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4179        let mut inv_diag = Vec::with_capacity(k);
4180        for (idx, &d) in diag_host.iter().enumerate() {
4181            if !d.is_finite() || d <= 1.0e-18 {
4182                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
4183                    reason: format!(
4184                        "framed SAE GPU PCG: non-positive Jacobi diagonal at {idx}: {d:e}"
4185                    ),
4186                });
4187            }
4188            inv_diag.push(1.0 / d);
4189        }
4190        let inv_diag_dev = stream
4191            .clone_htod(&inv_diag)
4192            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4193
4194        let mut x_dev = stream
4195            .alloc_zeros::<f64>(k)
4196            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4197        let mut r_dev = stream
4198            .alloc_zeros::<f64>(k)
4199            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4200        device_copy(&blas, &stream, k, &rhs_dev, &mut r_dev)?;
4201        let mut z_dev = stream
4202            .alloc_zeros::<f64>(k)
4203            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4204        launch_jacobi_mul(&stream, vector_module, &inv_diag_dev, &r_dev, &mut z_dev, k)?;
4205        let mut p_dev = stream
4206            .alloc_zeros::<f64>(k)
4207            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4208        device_copy(&blas, &stream, k, &z_dev, &mut p_dev)?;
4209        let mut ap_dev = stream
4210            .alloc_zeros::<f64>(k)
4211            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4212
4213        let mut rz = device_dot(&blas, &stream, k, &r_dev, &z_dev)?;
4214        if rz <= 0.0 || !rz.is_finite() {
4215            return Err(ArrowSchurGpuFailure::SchurFactorFailed {
4216                reason: format!("framed SAE GPU PCG: non-positive initial rᵀM⁻¹r={rz:e}"),
4217            });
4218        }
4219        let mut diag = PcgDiagnostics {
4220            precond_apply_calls: 1,
4221            stopping_reason: PcgStopReason::MaxIter,
4222            ..PcgDiagnostics::default()
4223        };
4224        for _ in 0..max_iterations.max(1) {
4225            launch_sae_frame_matvec(
4226                &stream,
4227                vector_module,
4228                &mut buffers,
4229                &p_dev,
4230                &mut ap_dev,
4231                ridge_beta,
4232            )?;
4233            diag.matvec_calls += 1;
4234            diag.iterations += 1;
4235            let pap = device_dot(&blas, &stream, k, &p_dev, &ap_dev)?;
4236            if pap <= 0.0 || !pap.is_finite() {
4237                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
4238                    reason: format!("framed SAE GPU PCG: non-positive curvature pᵀAp={pap:e}"),
4239                });
4240            }
4241            let alpha = rz / pap;
4242            device_axpy(&blas, &stream, k, alpha, &p_dev, &mut x_dev)?;
4243            device_axpy(&blas, &stream, k, -alpha, &ap_dev, &mut r_dev)?;
4244            let r_norm = device_nrm2(&blas, &stream, k, &r_dev)?;
4245            if r_norm <= tol {
4246                diag.final_relative_residual = r_norm / rhs_norm;
4247                diag.stopping_reason = PcgStopReason::Converged;
4248                break;
4249            }
4250            launch_jacobi_mul(&stream, vector_module, &inv_diag_dev, &r_dev, &mut z_dev, k)?;
4251            diag.precond_apply_calls += 1;
4252            let rz_new = device_dot(&blas, &stream, k, &r_dev, &z_dev)?;
4253            if rz_new <= 0.0 || !rz_new.is_finite() {
4254                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
4255                    reason: format!("framed SAE GPU PCG: non-positive rᵀM⁻¹r={rz_new:e}"),
4256                });
4257            }
4258            let beta = rz_new / rz;
4259            launch_update_p(&stream, vector_module, &z_dev, beta, &mut p_dev, k)?;
4260            rz = rz_new;
4261        }
4262        if diag.stopping_reason != PcgStopReason::Converged {
4263            let r_norm = device_nrm2(&blas, &stream, k, &r_dev)?;
4264            diag.final_relative_residual = r_norm / rhs_norm;
4265            diag.stopping_reason = PcgStopReason::MaxIter;
4266        }
4267        let x = stream
4268            .clone_dtoh(&x_dev)
4269            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4270        Ok((Array1::from_vec(x), diag))
4271    }
4272
4273    /// #1551 stage-isolating triage seam: run the framed reduced-Schur matvec
4274    /// `out = S·x` ONCE on the device (no PCG, no offload-floor gate) and return
4275    /// `out`, so a tiny hand-verifiable fixture can diff it against the CPU oracle
4276    /// `sae_framed_schur_matvec_cpu` element-by-element to localize the structural
4277    /// divergence to a single kernel stage. Returns `Unavailable` only when CUDA
4278    /// is genuinely absent (so the test skips cleanly off-device).
4279    pub(super) fn solve_sae_matrix_free_pcg(
4280        sys: &ArrowSchurSystem,
4281        data: &DeviceSaePcgData,
4282        ridge_t: f64,
4283        ridge_beta: f64,
4284        rhs_beta: &Array1<f64>,
4285        max_iterations: usize,
4286        relative_tolerance: f64,
4287    ) -> Result<(Array1<f64>, PcgDiagnostics), ArrowSchurGpuFailure> {
4288        let k = rhs_beta.len();
4289        if k == 0 || data.beta_dim != k || sys.k != k {
4290            return Err(ArrowSchurGpuFailure::Unavailable);
4291        }
4292        // #1017/#1026 GUARD: the legacy `⊗ I_p` kernel must NEVER receive framed
4293        // data (factored `G ⊗ W_{ij}` + dense per-row cross blocks); decline so a
4294        // mis-route falls back to the CPU rather than returning a wrong step.
4295        if data.frame.is_some() {
4296            return Err(ArrowSchurGpuFailure::Unavailable);
4297        }
4298        // #1017 Phase-1 dispatch re-key: this is the matrix-free SAE reduced-Schur
4299        // PCG — the production hot path, not a single dense factorization. The
4300        // dense-Direct floor `dense_hessian_work_target_is_gpu(n, k)` keys on
4301        // `2·n·k²` and is the WRONG gate here: it ignores the per-row frame depth
4302        // `d` (the M dimension that multiplies the per-apply work) and the
4303        // `1/cg_iters` staging amortisation, so it both undercounts the SAE batched
4304        // work `n·k·d` and applies a cold single-launch breakeven to an apply that
4305        // reuses device-resident frames `max_iterations` times. Key instead on the
4306        // CG-amortised total batched work — the same predicate the host injection
4307        // gate (`maybe_inject_gpu_schur_matvec`) consults — so few-row/wide-`k`/
4308        // modest-`d` LLM shapes register the real `n × k × d × cg_iters` arithmetic.
4309        // Kernels and numerics are untouched; only where the matvec runs changes,
4310        // and the host falls back to the bit-identical CPU matvec when this declines.
4311        let runtime = gam_gpu::device_runtime::GpuRuntime::global()
4312            .filter(|rt| {
4313                rt.policy().reduced_schur_matvec_should_offload(
4314                    sys.rows.len(),
4315                    sys.k,
4316                    sys.d,
4317                    max_iterations,
4318                )
4319            })
4320            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
4321        let ctx = gam_gpu::device_runtime::cuda_context_for(runtime.selected_device().ordinal)
4322            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
4323        let stream = ctx
4324            .new_stream()
4325            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4326        let blas = CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4327        let vector_module = pcg_vector_module(&ctx)?;
4328        let mut buffers = flatten_device_sae_data(sys, data, ridge_t, &stream)?;
4329
4330        let rhs_norm = rhs_beta.iter().map(|v| v * v).sum::<f64>().sqrt();
4331        if rhs_norm == 0.0 {
4332            return Ok((Array1::<f64>::zeros(k), PcgDiagnostics::default()));
4333        }
4334        let tol = (relative_tolerance.max(0.0) * rhs_norm).max(1e-12);
4335        let rhs_dev = stream
4336            .clone_htod(
4337                rhs_beta
4338                    .as_slice()
4339                    .ok_or(ArrowSchurGpuFailure::Unavailable)?,
4340            )
4341            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4342        let diag_host = sae_penalty_diag_host(data, ridge_beta)?;
4343        let mut diag_dev = stream
4344            .clone_htod(&diag_host)
4345            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4346        launch_sae_diag_sub(&stream, vector_module, &buffers, &mut diag_dev)?;
4347        let diag_host = stream
4348            .clone_dtoh(&diag_dev)
4349            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4350        let mut inv_diag = Vec::with_capacity(k);
4351        for (idx, &d) in diag_host.iter().enumerate() {
4352            if !d.is_finite() || d <= 1.0e-18 {
4353                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
4354                    reason: format!(
4355                        "SAE matrix-free GPU PCG: non-positive Schur Jacobi diagonal at {idx}: {d:e}"
4356                    ),
4357                });
4358            }
4359            inv_diag.push(1.0 / d);
4360        }
4361        let inv_diag_dev = stream
4362            .clone_htod(&inv_diag)
4363            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4364
4365        let mut x_dev = stream
4366            .alloc_zeros::<f64>(k)
4367            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4368        let mut r_dev = stream
4369            .alloc_zeros::<f64>(k)
4370            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4371        device_copy(&blas, &stream, k, &rhs_dev, &mut r_dev)?;
4372        let mut z_dev = stream
4373            .alloc_zeros::<f64>(k)
4374            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4375        launch_jacobi_mul(&stream, vector_module, &inv_diag_dev, &r_dev, &mut z_dev, k)?;
4376        let mut p_dev = stream
4377            .alloc_zeros::<f64>(k)
4378            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4379        device_copy(&blas, &stream, k, &z_dev, &mut p_dev)?;
4380        let mut ap_dev = stream
4381            .alloc_zeros::<f64>(k)
4382            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4383
4384        let mut rz = device_dot(&blas, &stream, k, &r_dev, &z_dev)?;
4385        if rz <= 0.0 || !rz.is_finite() {
4386            return Err(ArrowSchurGpuFailure::SchurFactorFailed {
4387                reason: format!("SAE matrix-free GPU PCG: non-positive initial rᵀM⁻¹r={rz:e}"),
4388            });
4389        }
4390        let mut diag = PcgDiagnostics {
4391            precond_apply_calls: 1,
4392            stopping_reason: PcgStopReason::MaxIter,
4393            ..PcgDiagnostics::default()
4394        };
4395
4396        for _ in 0..max_iterations.max(1) {
4397            launch_sae_matvec(
4398                &stream,
4399                vector_module,
4400                &mut buffers,
4401                &p_dev,
4402                &mut ap_dev,
4403                ridge_beta,
4404            )?;
4405            diag.matvec_calls += 1;
4406            diag.iterations += 1;
4407            let pap = device_dot(&blas, &stream, k, &p_dev, &ap_dev)?;
4408            if pap <= 0.0 || !pap.is_finite() {
4409                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
4410                    reason: format!("SAE matrix-free GPU PCG: non-positive curvature pᵀAp={pap:e}"),
4411                });
4412            }
4413            let alpha = rz / pap;
4414            device_axpy(&blas, &stream, k, alpha, &p_dev, &mut x_dev)?;
4415            device_axpy(&blas, &stream, k, -alpha, &ap_dev, &mut r_dev)?;
4416            let r_norm = device_nrm2(&blas, &stream, k, &r_dev)?;
4417            if r_norm <= tol {
4418                diag.final_relative_residual = r_norm / rhs_norm;
4419                diag.stopping_reason = PcgStopReason::Converged;
4420                break;
4421            }
4422            launch_jacobi_mul(&stream, vector_module, &inv_diag_dev, &r_dev, &mut z_dev, k)?;
4423            diag.precond_apply_calls += 1;
4424            let rz_new = device_dot(&blas, &stream, k, &r_dev, &z_dev)?;
4425            if rz_new <= 0.0 || !rz_new.is_finite() {
4426                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
4427                    reason: format!("SAE matrix-free GPU PCG: non-positive rᵀM⁻¹r={rz_new:e}"),
4428                });
4429            }
4430            let beta = rz_new / rz;
4431            launch_update_p(&stream, vector_module, &z_dev, beta, &mut p_dev, k)?;
4432            rz = rz_new;
4433        }
4434        if diag.stopping_reason != PcgStopReason::Converged {
4435            let r_norm = device_nrm2(&blas, &stream, k, &r_dev)?;
4436            diag.final_relative_residual = r_norm / rhs_norm;
4437            diag.stopping_reason = PcgStopReason::MaxIter;
4438        }
4439        let x = stream
4440            .clone_dtoh(&x_dev)
4441            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4442        Ok((Array1::from_vec(x), diag))
4443    }
4444
4445    pub(super) fn solve_reduced_beta_pcg_with_diagnostics(
4446        s_acc: &ndarray::Array2<f64>,
4447        rhs_beta: &Array1<f64>,
4448        max_iterations: usize,
4449        relative_tolerance: f64,
4450    ) -> Result<(Array1<f64>, PcgDiagnostics), ArrowSchurGpuFailure> {
4451        let k = rhs_beta.len();
4452        // #1017 dispatch re-key: this is an ITERATIVE device-resident PCG, not a
4453        // single GEMV. `S` (k×k) is uploaded once and reused for `max_iterations`
4454        // `S·p` GEMVs while only convergence scalars cross PCIe, so the staging
4455        // cost is amortised over the whole CG solve. Gating on the flops of ONE
4456        // `Gemv{k,k}` (`2·k²`) understates the work by the iteration count and
4457        // declines shapes (e.g. k≈512) whose total iterated arithmetic
4458        // `2·k²·iters` clears the device floor by orders of magnitude — the same
4459        // single-launch-breakeven miskey #1017 fixed for the framed reduced-Schur
4460        // matvec. Key on the CG-amortised total work via a `Gemm{k,k,iters}` whose
4461        // `flops()` is exactly `2·k²·iters`; numerics and kernels are untouched,
4462        // and the host falls back to the bit-identical CPU PCG when this declines.
4463        let cg_iters = max_iterations.max(1);
4464        let runtime = gam_gpu::linalg_dispatch::route_through_gpu(
4465            gam_gpu::linalg_dispatch::DispatchOp::Gemm {
4466                m: k,
4467                n: k,
4468                k: cg_iters,
4469            },
4470        )
4471        .ok_or(ArrowSchurGpuFailure::Unavailable)?;
4472        let stream = gam_gpu::device_runtime::cuda_context_for(runtime.device.ordinal)
4473            .and_then(|ctx| ctx.new_stream().ok())
4474            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
4475        let blas = CudaBlas::new(stream.clone()).map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4476        let ctx = gam_gpu::device_runtime::cuda_context_for(runtime.device.ordinal)
4477            .ok_or(ArrowSchurGpuFailure::Unavailable)?;
4478        let vector_module = pcg_vector_module(&ctx)?;
4479
4480        // Jacobi diagonal from S; must be strictly positive for SPD.
4481        let mut inv_diag = vec![0.0_f64; k];
4482        for j in 0..k {
4483            let djj = s_acc[[j, j]];
4484            if !(djj > 0.0) {
4485                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
4486                    reason: format!(
4487                        "reduced-β GPU PCG: Jacobi diagonal S[{j},{j}]={djj:e} not positive"
4488                    ),
4489                });
4490            }
4491            inv_diag[j] = 1.0 / djj;
4492        }
4493
4494        // Upload S column-major (S[row,col] at col*k + row).
4495        let mut s_host = vec![0.0_f64; k * k];
4496        for col in 0..k {
4497            for row in 0..k {
4498                s_host[col * k + row] = s_acc[[row, col]];
4499            }
4500        }
4501        let s_dev = stream
4502            .clone_htod(&s_host)
4503            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4504
4505        // Steihaug truncated-CG with Jacobi preconditioner, host scalar
4506        // recurrences and a device `S·p` matvec. The streaming reduced solve
4507        // uses an unbounded trust region (pure CG to tolerance).
4508        let rhs_norm = rhs_beta.iter().map(|v| v * v).sum::<f64>().sqrt();
4509        if rhs_norm == 0.0 {
4510            return Ok((Array1::<f64>::zeros(k), PcgDiagnostics::default()));
4511        }
4512        let tol = (relative_tolerance.max(0.0) * rhs_norm).max(1e-12);
4513
4514        // Device-resident PCG state. Only convergence scalars cross back during
4515        // the loop; x/r/z/p/Sp stay on CUDA until the final solution download.
4516        let mut x_dev = stream
4517            .alloc_zeros::<f64>(k)
4518            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4519        let mut r_dev = stream
4520            .clone_htod(
4521                rhs_beta
4522                    .as_slice()
4523                    .ok_or(ArrowSchurGpuFailure::Unavailable)?,
4524            )
4525            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4526        let inv_diag_dev = stream
4527            .clone_htod(&inv_diag)
4528            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4529        let mut z_dev = stream
4530            .alloc_zeros::<f64>(k)
4531            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4532        launch_jacobi_mul(&stream, vector_module, &inv_diag_dev, &r_dev, &mut z_dev, k)?;
4533        let mut p_dev = stream
4534            .alloc_zeros::<f64>(k)
4535            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4536        device_copy(&blas, &stream, k, &z_dev, &mut p_dev)?;
4537        let mut sp_dev = stream
4538            .alloc_zeros::<f64>(k)
4539            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4540        let mut rz = device_dot(&blas, &stream, k, &r_dev, &z_dev)?;
4541        let mut diag = PcgDiagnostics {
4542            precond_apply_calls: 1,
4543            stopping_reason: PcgStopReason::MaxIter,
4544            ..PcgDiagnostics::default()
4545        };
4546        if rz <= 0.0 || !rz.is_finite() {
4547            return Err(ArrowSchurGpuFailure::SchurFactorFailed {
4548                reason: format!("reduced-β GPU PCG: non-positive initial rᵀM⁻¹r={rz:e}"),
4549            });
4550        }
4551
4552        let max_iters = max_iterations.max(1);
4553        for _ in 0..max_iters {
4554            // sp = S · p (device GEMV, S column-major k×k, op = N).
4555            let gemv_cfg = GemvConfig::<f64> {
4556                trans: cublasOperation_t::CUBLAS_OP_N,
4557                m: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
4558                n: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
4559                alpha: 1.0,
4560                lda: to_i32(k).ok_or(ArrowSchurGpuFailure::Unavailable)?,
4561                incx: 1,
4562                beta: 0.0,
4563                incy: 1,
4564            };
4565            // SAFETY: s_dev is k×k column-major, p_dev / sp_dev length k.
4566            unsafe { blas.gemv(gemv_cfg, &s_dev, &p_dev, &mut sp_dev) }
4567                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4568            diag.matvec_calls += 1;
4569            diag.iterations += 1;
4570
4571            let p_sp = device_dot(&blas, &stream, k, &p_dev, &sp_dev)?;
4572            if !(p_sp > 0.0) {
4573                // Non-positive curvature on a (proximal-ridged) SPD system means
4574                // numerical breakdown; surface so the caller escalates.
4575                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
4576                    reason: format!("reduced-β GPU PCG: non-positive curvature pᵀSp={p_sp:e}"),
4577                });
4578            }
4579            let alpha = rz / p_sp;
4580            device_axpy(&blas, &stream, k, alpha, &p_dev, &mut x_dev)?;
4581            device_axpy(&blas, &stream, k, -alpha, &sp_dev, &mut r_dev)?;
4582            let r_norm = device_nrm2(&blas, &stream, k, &r_dev)?;
4583            if r_norm <= tol {
4584                diag.final_relative_residual = r_norm / rhs_norm;
4585                diag.stopping_reason = PcgStopReason::Converged;
4586                break;
4587            }
4588            launch_jacobi_mul(&stream, vector_module, &inv_diag_dev, &r_dev, &mut z_dev, k)?;
4589            diag.precond_apply_calls += 1;
4590            let rz_new = device_dot(&blas, &stream, k, &r_dev, &z_dev)?;
4591            if rz_new <= 0.0 || !rz_new.is_finite() {
4592                return Err(ArrowSchurGpuFailure::SchurFactorFailed {
4593                    reason: format!("reduced-β GPU PCG: non-positive rᵀM⁻¹r={rz_new:e}"),
4594                });
4595            }
4596            let beta = rz_new / rz;
4597            launch_update_p(&stream, vector_module, &z_dev, beta, &mut p_dev, k)?;
4598            rz = rz_new;
4599        }
4600        if diag.stopping_reason != PcgStopReason::Converged {
4601            let r_norm = device_nrm2(&blas, &stream, k, &r_dev)?;
4602            diag.final_relative_residual = r_norm / rhs_norm;
4603            diag.stopping_reason = PcgStopReason::MaxIter;
4604        }
4605
4606        let x = stream
4607            .clone_dtoh(&x_dev)
4608            .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4609        Ok((Array1::from_vec(x), diag))
4610    }
4611
4612    fn device_copy(
4613        blas: &CudaBlas,
4614        stream: &Arc<CudaStream>,
4615        n: usize,
4616        src: &CudaSlice<f64>,
4617        dst: &mut CudaSlice<f64>,
4618    ) -> Result<(), ArrowSchurGpuFailure> {
4619        let n_i = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
4620        let (src_ptr, _src_rec) = src.device_ptr(stream);
4621        let (dst_ptr, _dst_rec) = dst.device_ptr_mut(stream);
4622        // SAFETY: src and dst are live device allocations on this stream with at
4623        // least n contiguous f64 entries and unit stride.
4624        let status = unsafe {
4625            cudarc::cublas::sys::cublasDcopy_v2(
4626                *blas.handle(),
4627                n_i,
4628                src_ptr as *const f64,
4629                1,
4630                dst_ptr as *mut f64,
4631                1,
4632            )
4633        };
4634        if status == cublasStatus_t::CUBLAS_STATUS_SUCCESS {
4635            Ok(())
4636        } else {
4637            Err(ArrowSchurGpuFailure::Unavailable)
4638        }
4639    }
4640
4641    fn device_axpy(
4642        blas: &CudaBlas,
4643        stream: &Arc<CudaStream>,
4644        n: usize,
4645        alpha: f64,
4646        x: &CudaSlice<f64>,
4647        y: &mut CudaSlice<f64>,
4648    ) -> Result<(), ArrowSchurGpuFailure> {
4649        let n_i = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
4650        let (x_ptr, _x_rec) = x.device_ptr(stream);
4651        let (y_ptr, _y_rec) = y.device_ptr_mut(stream);
4652        // SAFETY: x and y are live device allocations on this stream with at
4653        // least n contiguous f64 entries and unit stride; cuBLAS only reads alpha.
4654        let status = unsafe {
4655            cudarc::cublas::sys::cublasDaxpy_v2(
4656                *blas.handle(),
4657                n_i,
4658                &alpha,
4659                x_ptr as *const f64,
4660                1,
4661                y_ptr as *mut f64,
4662                1,
4663            )
4664        };
4665        if status == cublasStatus_t::CUBLAS_STATUS_SUCCESS {
4666            Ok(())
4667        } else {
4668            Err(ArrowSchurGpuFailure::Unavailable)
4669        }
4670    }
4671
4672    fn device_dot(
4673        blas: &CudaBlas,
4674        stream: &Arc<CudaStream>,
4675        n: usize,
4676        x: &CudaSlice<f64>,
4677        y: &CudaSlice<f64>,
4678    ) -> Result<f64, ArrowSchurGpuFailure> {
4679        let n_i = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
4680        let (x_ptr, _x_rec) = x.device_ptr(stream);
4681        let (y_ptr, _y_rec) = y.device_ptr(stream);
4682        let mut result = 0.0_f64;
4683        // SAFETY: x and y are live device allocations on this stream with at
4684        // least n contiguous f64 entries and unit stride; result is a valid host
4685        // out-pointer for the cuBLAS scalar.
4686        let status = unsafe {
4687            cudarc::cublas::sys::cublasDdot_v2(
4688                *blas.handle(),
4689                n_i,
4690                x_ptr as *const f64,
4691                1,
4692                y_ptr as *const f64,
4693                1,
4694                &mut result,
4695            )
4696        };
4697        if status == cublasStatus_t::CUBLAS_STATUS_SUCCESS {
4698            Ok(result)
4699        } else {
4700            Err(ArrowSchurGpuFailure::Unavailable)
4701        }
4702    }
4703
4704    fn device_nrm2(
4705        blas: &CudaBlas,
4706        stream: &Arc<CudaStream>,
4707        n: usize,
4708        x: &CudaSlice<f64>,
4709    ) -> Result<f64, ArrowSchurGpuFailure> {
4710        let n_i = to_i32(n).ok_or(ArrowSchurGpuFailure::Unavailable)?;
4711        let (x_ptr, _x_rec) = x.device_ptr(stream);
4712        let mut result = 0.0_f64;
4713        // SAFETY: x is a live device allocation on this stream with at least n
4714        // contiguous f64 entries and unit stride; result is a valid host
4715        // out-pointer for the cuBLAS scalar.
4716        let status = unsafe {
4717            cudarc::cublas::sys::cublasDnrm2_v2(
4718                *blas.handle(),
4719                n_i,
4720                x_ptr as *const f64,
4721                1,
4722                &mut result,
4723            )
4724        };
4725        if status == cublasStatus_t::CUBLAS_STATUS_SUCCESS {
4726            Ok(result)
4727        } else {
4728            Err(ArrowSchurGpuFailure::Unavailable)
4729        }
4730    }
4731
4732    #[cfg(test)]
4733    mod tests {
4734        //! #1551 device-side framed-matvec triage. Lives inside `mod cuda` so it
4735        //! can call the private kernel launchers directly (no test-only public
4736        //! seam, which the ban-scanner forbids). A bare `#[cfg(test)] mod tests`
4737        //! is the one form the scanner permits.
4738        use super::*;
4739        use crate::arrow_schur::{
4740            ArrowSchurSystem, DeviceSaeFrameData, DeviceSaePcgData, DeviceSaeSmoothBlock,
4741            FactoredFrameGBlock,
4742        };
4743        use ndarray::Array2;
4744
4745        /// Run the framed reduced-Schur matvec `out = S·x` ONCE on the device
4746        /// (no PCG, no offload gate) and return `out`.
4747        fn device_matvec_once(
4748            sys: &ArrowSchurSystem,
4749            data: &DeviceSaePcgData,
4750            ridge_t: f64,
4751            ridge_beta: f64,
4752            x_host: &[f64],
4753        ) -> Result<Vec<f64>, ArrowSchurGpuFailure> {
4754            let k = x_host.len();
4755            let frame = data
4756                .frame
4757                .as_ref()
4758                .ok_or(ArrowSchurGpuFailure::Unavailable)?;
4759            let runtime = gam_gpu::device_runtime::GpuRuntime::global()
4760                .ok_or(ArrowSchurGpuFailure::Unavailable)?;
4761            let ctx =
4762                gam_gpu::device_runtime::cuda_context_for(runtime.selected_device().ordinal)
4763                    .ok_or(ArrowSchurGpuFailure::Unavailable)?;
4764            let stream = ctx
4765                .new_stream()
4766                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4767            let vector_module = pcg_vector_module(&ctx)?;
4768            let mut buffers = flatten_device_sae_frame_data(sys, data, frame, ridge_t, &stream)?;
4769            let x_dev = stream
4770                .clone_htod(x_host)
4771                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4772            let mut out_dev = stream
4773                .alloc_zeros::<f64>(k)
4774                .map_err(|_| ArrowSchurGpuFailure::Unavailable)?;
4775            launch_sae_frame_matvec(
4776                &stream,
4777                vector_module,
4778                &mut buffers,
4779                &x_dev,
4780                &mut out_dev,
4781                ridge_beta,
4782            )?;
4783            stream
4784                .clone_dtoh(&out_dev)
4785                .map_err(|_| ArrowSchurGpuFailure::Unavailable)
4786        }
4787
4788        /// #1551 stage-isolating matvec triage on a TINY hand-verifiable fixture:
4789        /// diff the device framed matvec `S·e_col` against the CPU oracle
4790        /// `sae_framed_schur_matvec_cpu` for every identity column, reporting the
4791        /// worst-divergent border index so the structural 91% localizes to one
4792        /// kernel stage. Skips cleanly off-device.
4793        #[test]
4794        fn framed_sae_device_matvec_stage_diff_tiny_1551() {
4795            if gam_gpu::device_runtime::GpuRuntime::global().is_none() {
4796                return;
4797            }
4798            let p = 3usize;
4799            let ranks = vec![2usize, 3usize];
4800            let basis_sizes = vec![2usize, 2usize];
4801            let mut border_offsets = Vec::new();
4802            let mut acc = 0usize;
4803            for k in 0..2 {
4804                border_offsets.push(acc);
4805                acc += basis_sizes[k] * ranks[k];
4806            }
4807            let border_dim = acc; // 2·2 + 2·3 = 10
4808            let frame_of = |k: usize| -> Array2<f64> {
4809                Array2::from_shape_fn((p, ranks[k]), |(i, j)| {
4810                    0.1 + 0.2 * ((i + 1) as f64) * ((j + 1 + 2 * k) as f64)
4811                })
4812            };
4813            let frames: Vec<Array2<f64>> = (0..2).map(frame_of).collect();
4814            let w_of = |i: usize, j: usize| -> Array2<f64> {
4815                let (ui, uj) = (&frames[i], &frames[j]);
4816                Array2::from_shape_fn((ranks[i], ranks[j]), |(a, b)| {
4817                    (0..p).map(|c| ui[[c, a]] * uj[[c, b]]).sum()
4818                })
4819            };
4820            let mut frame_blocks = Vec::new();
4821            for &(i, j) in &[(0usize, 0usize), (1usize, 1usize), (0, 1), (1, 0)] {
4822                let (mi, mj) = (basis_sizes[i], basis_sizes[j]);
4823                let mut g =
4824                    Array2::<f64>::from_shape_fn((mi, mj), |(r, c)| 0.1 * (r + 2 * c + 1) as f64);
4825                if i == j {
4826                    for r in 0..mi.min(mj) {
4827                        g[[r, r]] += mi as f64 + 2.0;
4828                    }
4829                }
4830                frame_blocks.push(FactoredFrameGBlock {
4831                    atom_i: i,
4832                    atom_j: j,
4833                    g,
4834                    w: w_of(i, j),
4835                });
4836            }
4837            let mut smooth_blocks = Vec::new();
4838            for k in 0..2 {
4839                let m = basis_sizes[k];
4840                let mut s =
4841                    Array2::<f64>::from_shape_fn((m, m), |(r, c)| 0.05 * (r + c + 1) as f64);
4842                for r in 0..m {
4843                    s[[r, r]] += 1.0;
4844                }
4845                smooth_blocks.push(DeviceSaeSmoothBlock {
4846                    global_offset: border_offsets[k],
4847                    factor_a: s,
4848                });
4849            }
4850            let smooth_ranks = ranks.clone();
4851            let n = 2usize;
4852            let q = 2usize;
4853            let mut sys = ArrowSchurSystem::new(n, q, border_dim);
4854            let mut row_htbeta = Vec::new();
4855            for i in 0..n {
4856                let mut htt =
4857                    Array2::<f64>::from_shape_fn((q, q), |(r, c)| 0.3 * (r + c + 1) as f64);
4858                for r in 0..q {
4859                    htt[[r, r]] += q as f64 + 2.0;
4860                }
4861                sys.rows[i].htt = htt;
4862                let mut slab = vec![0.0_f64; q * border_dim];
4863                for c in 0..q {
4864                    for col in 0..border_dim {
4865                        let v = 0.01 * ((c + 1) * (col + 1) + i) as f64;
4866                        slab[c * border_dim + col] = v;
4867                        sys.rows[i].htbeta[[c, col]] = v;
4868                    }
4869                }
4870                row_htbeta.push(slab);
4871            }
4872            let data = DeviceSaePcgData {
4873                p,
4874                beta_dim: border_dim,
4875                a_phi: std::sync::Arc::from(Vec::new().into_boxed_slice()),
4876                local_jac: std::sync::Arc::from(Vec::new().into_boxed_slice()),
4877                smooth_blocks,
4878                sparse_g_blocks: Vec::new(),
4879                frame: Some(DeviceSaeFrameData {
4880                    ranks,
4881                    basis_sizes,
4882                    border_offsets,
4883                    frame_blocks,
4884                    smooth_ranks,
4885                    row_htbeta,
4886                }),
4887            };
4888            let ridge_t = 1e-7;
4889            let ridge_beta = 1e-6;
4890            let mut first_bad: Option<usize> = None;
4891            let mut worst = 0.0_f64;
4892            let mut worst_at = 0usize;
4893            let mut worst_dev = 0.0_f64;
4894            let mut worst_cpu = 0.0_f64;
4895            for col in 0..border_dim {
4896                let mut x = vec![0.0_f64; border_dim];
4897                x[col] = 1.0;
4898                let dev = match device_matvec_once(&sys, &data, ridge_t, ridge_beta, &x) {
4899                    Ok(v) => v,
4900                    Err(_) => return,
4901                };
4902                let mut cpu = vec![0.0_f64; border_dim];
4903                super::super::sae_framed_schur_matvec_cpu(
4904                    &sys, &data, ridge_t, ridge_beta, &x, &mut cpu,
4905                )
4906                .expect("cpu matvec");
4907                for r in 0..border_dim {
4908                    let d = (dev[r] - cpu[r]).abs();
4909                    if d > 1e-9 && first_bad.is_none() {
4910                        first_bad = Some(r * border_dim + col);
4911                    }
4912                    if d > worst {
4913                        worst = d;
4914                        worst_at = r * border_dim + col;
4915                        worst_dev = dev[r];
4916                        worst_cpu = cpu[r];
4917                    }
4918                }
4919            }
4920            assert!(
4921                worst <= 1e-9,
4922                "[#1551 stage-diff] device framed matvec != CPU oracle: worst abs={worst:e} at \
4923                 (row*K+col)={worst_at} (dev={worst_dev:e} cpu={worst_cpu:e}), \
4924                 first_bad_idx={first_bad:?}; border layout: atom0 [0..4) rank2, atom1 [4..10) \
4925                 rank3 — which atom-range the bad row/col falls in pins the stage (smooth=diag, \
4926                 G⊗W=cross, reduced-Schur=dense per-row)",
4927            );
4928        }
4929    }
4930}
4931
4932#[cfg(test)]
4933mod tests {
4934    use super::*;
4935    use crate::arrow_schur::ArrowSchurSystem;
4936    use ndarray::{Array2, ArrayView1};
4937
4938    fn build_fixture(n: usize, d: usize, k: usize, seed: u64) -> ArrowSchurSystem {
4939        let mut sys = ArrowSchurSystem::new(n, d, k);
4940        let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15);
4941        let mut sample = || -> f64 {
4942            state = state
4943                .wrapping_mul(6364136223846793005)
4944                .wrapping_add(1442695040888963407);
4945            ((state >> 33) as f64) / ((1u64 << 31) as f64) - 1.0
4946        };
4947        for row in &mut sys.rows {
4948            let mut a = Array2::<f64>::zeros((d, d));
4949            for r in 0..d {
4950                for c in 0..d {
4951                    a[[r, c]] = sample();
4952                }
4953            }
4954            let mut htt = a.t().dot(&a);
4955            for r in 0..d {
4956                htt[[r, r]] += d as f64 + 1.0;
4957            }
4958            row.htt = htt;
4959            for r in 0..d {
4960                for c in 0..k {
4961                    row.htbeta[[r, c]] = 0.1 * sample();
4962                }
4963                row.gt[r] = sample();
4964            }
4965        }
4966        let mut hbb_a = Array2::<f64>::zeros((k, k));
4967        for r in 0..k {
4968            for c in 0..k {
4969                hbb_a[[r, c]] = sample();
4970            }
4971        }
4972        let mut hbb = hbb_a.t().dot(&hbb_a);
4973        for r in 0..k {
4974            hbb[[r, r]] += k as f64 + 1.0;
4975        }
4976        sys.hbb = hbb;
4977        for r in 0..k {
4978            sys.gb[r] = sample();
4979        }
4980        sys
4981    }
4982
4983    fn device_pcg_fixture(k: usize) -> (Array2<f64>, Array1<f64>) {
4984        let mut s = Array2::<f64>::zeros((k, k));
4985        for row in 0..k {
4986            s[[row, row]] = 2.5 + 0.001 * ((row % 17) as f64);
4987            if row + 1 < k {
4988                s[[row, row + 1]] = -0.05;
4989                s[[row + 1, row]] = -0.05;
4990            }
4991            if row + 7 < k {
4992                s[[row, row + 7]] = 0.01;
4993                s[[row + 7, row]] = 0.01;
4994            }
4995        }
4996        let rhs = Array1::from_shape_fn(k, |idx| ((idx as f64 + 1.0) * 0.013).sin());
4997        (s, rhs)
4998    }
4999
5000    fn dense_pcg_cpu_reference(
5001        s: &Array2<f64>,
5002        rhs: &Array1<f64>,
5003        max_iterations: usize,
5004        relative_tolerance: f64,
5005    ) -> Array1<f64> {
5006        let k = rhs.len();
5007        let rhs_norm = rhs.iter().map(|v| v * v).sum::<f64>().sqrt();
5008        if rhs_norm == 0.0 {
5009            return Array1::<f64>::zeros(k);
5010        }
5011        let tol = (relative_tolerance.max(0.0) * rhs_norm).max(1e-12);
5012        let inv_diag: Vec<f64> = (0..k).map(|idx| 1.0 / s[[idx, idx]]).collect();
5013        let mut x = Array1::<f64>::zeros(k);
5014        let mut r = rhs.clone();
5015        let mut z = Array1::from_shape_fn(k, |idx| inv_diag[idx] * r[idx]);
5016        let mut p = z.clone();
5017        let mut sp = Array1::<f64>::zeros(k);
5018        let mut rz = r.iter().zip(z.iter()).map(|(a, b)| a * b).sum::<f64>();
5019        for _ in 0..max_iterations.max(1) {
5020            for row in 0..k {
5021                let mut acc = 0.0;
5022                for col in 0..k {
5023                    acc += s[[row, col]] * p[col];
5024                }
5025                sp[row] = acc;
5026            }
5027            let p_sp = p.iter().zip(sp.iter()).map(|(a, b)| a * b).sum::<f64>();
5028            let alpha = rz / p_sp;
5029            for idx in 0..k {
5030                x[idx] += alpha * p[idx];
5031                r[idx] -= alpha * sp[idx];
5032            }
5033            let r_norm = r.iter().map(|v| v * v).sum::<f64>().sqrt();
5034            if r_norm <= tol {
5035                break;
5036            }
5037            for idx in 0..k {
5038                z[idx] = inv_diag[idx] * r[idx];
5039            }
5040            let rz_next = r.iter().zip(z.iter()).map(|(a, b)| a * b).sum::<f64>();
5041            let beta = rz_next / rz;
5042            for idx in 0..k {
5043                p[idx] = z[idx] + beta * p[idx];
5044            }
5045            rz = rz_next;
5046        }
5047        x
5048    }
5049
5050    #[test]
5051    fn device_resident_pcg_matches_cpu_reference_when_cuda_admits() {
5052        let (s, rhs) = device_pcg_fixture(512);
5053        let max_iterations = 200usize;
5054        let relative_tolerance = 1.0e-12;
5055        let cpu = dense_pcg_cpu_reference(&s, &rhs, max_iterations, relative_tolerance);
5056        let (device, diag) = match solve_reduced_beta_pcg_with_diagnostics(
5057            &s,
5058            &rhs,
5059            max_iterations,
5060            relative_tolerance,
5061        ) {
5062            Ok(result) => result,
5063            // #1017 — fail loud, never skip-pass: this fixture clears the device
5064            // offload floor, so a CUDA device that is PRESENT yet declines/returns
5065            // Err means the device PCG kernel does not run on GPU (a real fault that
5066            // must not masquerade as a pass via this skip). Legit skip ONLY when no
5067            // usable CUDA device exists (CPU CI). The exact `ArrowSchurGpuFailure`
5068            // variant is folded into the assert message as the diagnostic.
5069            Err(failure) => {
5070                assert!(
5071                    gam_gpu::device_runtime::GpuRuntime::global().is_none(),
5072                    "#1017: CUDA device present but the device reduced-beta PCG \
5073                     declined/faulted instead of returning a result (tag: {failure:?}) — \
5074                     the kernel does not run correctly on GPU"
5075                );
5076                return;
5077            }
5078        };
5079        let max_err = cpu
5080            .iter()
5081            .zip(device.iter())
5082            .map(|(a, b)| (a - b).abs())
5083            .fold(0.0_f64, f64::max);
5084        assert!(
5085            max_err <= 1.0e-10,
5086            "device resident PCG parity failed: max_err={max_err:e}, diag={diag:?}"
5087        );
5088        assert!(diag.matvec_calls > 0);
5089        assert_eq!(diag.matvec_calls, diag.iterations);
5090    }
5091
5092    #[test]
5093    fn dense_reference_matches_independent_solve() {
5094        let sys = build_fixture(4, 5, 3, 7);
5095        let solution = solve_arrow_newton_step_dense_reference(&sys, 0.0, 0.0).unwrap();
5096        // Re-solve by an independent matrix build and a textbook
5097        // Gaussian-elimination Cholesky to guard against typos in the
5098        // reference implementation itself.
5099        let n = sys.rows.len();
5100        let d = sys.d;
5101        let k = sys.k;
5102        let total = n * d + k;
5103        let mut h = Array2::<f64>::zeros((total, total));
5104        let mut g = ndarray::Array1::<f64>::zeros(total);
5105        for (i, row) in sys.rows.iter().enumerate() {
5106            let base = i * d;
5107            for c in 0..d {
5108                for r in 0..d {
5109                    h[[base + r, base + c]] = row.htt[[r, c]];
5110                }
5111            }
5112            for c in 0..k {
5113                for r in 0..d {
5114                    h[[base + r, n * d + c]] = row.htbeta[[r, c]];
5115                    h[[n * d + c, base + r]] = row.htbeta[[r, c]];
5116                }
5117            }
5118            for r in 0..d {
5119                g[base + r] = row.gt[r];
5120            }
5121        }
5122        for c in 0..k {
5123            for r in 0..k {
5124                h[[n * d + r, n * d + c]] += sys.hbb[[r, c]];
5125            }
5126            g[n * d + c] = sys.gb[c];
5127        }
5128        let l = cholesky_factor_in_place(h.view(), CholeskyGuard::NonnegativePivot).unwrap();
5129        let rhs = g.mapv(|v| -v);
5130        let expected = cholesky_solve_vector(l.view(), rhs.view());
5131        for i in 0..n * d {
5132            assert!(
5133                (solution.delta_t[i] - expected[i]).abs() < 1e-10 * (1.0 + expected[i].abs()),
5134                "delta_t[{i}] mismatch: got {} expected {}",
5135                solution.delta_t[i],
5136                expected[i]
5137            );
5138        }
5139        for a in 0..k {
5140            assert!(
5141                (solution.delta_beta[a] - expected[n * d + a]).abs()
5142                    < 1e-10 * (1.0 + expected[n * d + a].abs()),
5143                "delta_beta[{a}] mismatch"
5144            );
5145        }
5146    }
5147
5148    /// #1017: the row-procedural reduced-Schur matvec (the matrix-free SAE
5149    /// host backend) auto-fans its per-row point-elimination sum across rayon
5150    /// over fixed row chunks when at the top level (`n ≥
5151    /// SCHUR_MATVEC_PARALLEL_ROW_MIN`), and stays serial when already inside a
5152    /// rayon worker. The chunk-ordered fold makes the parallel result
5153    /// **deterministic** (two parallel calls are bit-identical — scheduling
5154    /// cannot change the numbers) and it agrees with the serial accumulation up
5155    /// to ULP-scale chunk reassociation (the #1017 verification gate). That
5156    /// reassociation is a genuine f64 departure from serial, so the criterion
5157    /// ranking across topology candidates is stable only up to the reassociation
5158    /// margin: a near-tie winner inside that margin can flip. This is NOT an
5159    /// exact no-move guarantee (#1211); for that, the ranking path must use the
5160    /// fixed-order serial accumulation.
5161    #[test]
5162    fn row_procedural_matvec_parallel_deterministic_and_matches_serial() {
5163        use crate::arrow_schur::SCHUR_MATVEC_PARALLEL_ROW_MIN;
5164        let n = SCHUR_MATVEC_PARALLEL_ROW_MIN + 96; // trips the parallel path
5165        let d = 3usize;
5166        let k = 24usize;
5167        let mut sys = build_fixture(n, d, k, 0xA17C_0FFE);
5168        // Install a matrix-free forward/transpose pair that reads the dense
5169        // `htbeta` slabs the fixture already populated, so the procedural
5170        // backend has a well-defined operator to apply (and exercises exactly
5171        // the sparse gather/scatter the SAE Kronecker path drives).
5172        let slabs: Vec<Array2<f64>> = sys.rows.iter().map(|row| row.htbeta.clone()).collect();
5173        let forward_slabs = slabs.clone();
5174        let transpose_slabs = slabs;
5175        sys.set_row_htbeta_operator(
5176            move |row: usize, x: ArrayView1<'_, f64>, out: &mut Array1<f64>| {
5177                let h = &forward_slabs[row];
5178                for r in 0..h.nrows() {
5179                    let mut acc = 0.0_f64;
5180                    for c in 0..h.ncols() {
5181                        acc += h[[r, c]] * x[c];
5182                    }
5183                    out[r] = acc;
5184                }
5185            },
5186            move |row: usize, v: ArrayView1<'_, f64>, out: &mut Array1<f64>| {
5187                let h = &transpose_slabs[row];
5188                for r in 0..h.nrows() {
5189                    for c in 0..h.ncols() {
5190                        out[c] += h[[r, c]] * v[r];
5191                    }
5192                }
5193            },
5194        );
5195
5196        let matvec = gpu_schur_matvec_backend(&sys, 0.0, 0.0)
5197            .expect("row-procedural matvec backend builds for matrix-free system");
5198        let x = Array1::from_shape_fn(k, |i| ((i as f64 + 1.0) * 0.37).sin());
5199
5200        // Top-level call: auto-selects the parallel chunk-fold. Run twice and
5201        // assert bit-identity — the chunk-ordered reduction must not depend on
5202        // thread scheduling.
5203        let mut out_parallel_a = Array1::<f64>::zeros(k);
5204        matvec(&x, &mut out_parallel_a);
5205        let mut out_parallel_b = Array1::<f64>::zeros(k);
5206        matvec(&x, &mut out_parallel_b);
5207        for a in 0..k {
5208            assert_eq!(
5209                out_parallel_a[a].to_bits(),
5210                out_parallel_b[a].to_bits(),
5211                "row-procedural matvec parallel reduction is non-deterministic at index {a}"
5212            );
5213        }
5214
5215        // Inside a rayon worker: auto-selects the serial path (nested-rayon
5216        // guard). `install` runs the closure on a pool thread, so
5217        // `current_thread_index()` is `Some`. The serial running sum and the
5218        // chunk-ordered parallel fold differ only by f64 reassociation.
5219        let mut out_serial = Array1::<f64>::zeros(k);
5220        rayon::ThreadPoolBuilder::new()
5221            .num_threads(2)
5222            .build()
5223            .expect("build rayon pool")
5224            .install(|| matvec(&x, &mut out_serial));
5225
5226        let max_abs = out_serial.iter().fold(0.0_f64, |m, v| m.max(v.abs()));
5227        for a in 0..k {
5228            let diff = (out_parallel_a[a] - out_serial[a]).abs();
5229            assert!(
5230                diff <= 1e-12 * (1.0 + max_abs),
5231                "row-procedural matvec parallel vs serial diverged beyond reassociation \
5232                 at index {a}: {} vs {} (diff={diff:e})",
5233                out_parallel_a[a],
5234                out_serial[a]
5235            );
5236        }
5237    }
5238
5239    /// #1017/#1026 — the frames-engaged CPU reduced-Schur matvec
5240    /// [`sae_framed_schur_matvec_cpu`] (the bit-parity oracle the GPU kernel
5241    /// mirrors) must equal the dense reduced Schur `S = (P_ββ + ρ_β I) −
5242    /// Σ_i H_βt^(i)(H_tt^(i)+ρ_t I)⁻¹ H_tβ^(i)` formed by the canonical dense
5243    /// reference, on a small framed system with mixed per-atom ranks
5244    /// (`r_k < p` framed + `r_k = p` un-framed). Size-independent gate.
5245    #[test]
5246    fn framed_sae_schur_matvec_matches_dense_reference() {
5247        use crate::arrow_schur::{
5248            BetaPenaltyOp, DeviceSaeFrameData, DeviceSaePcgData, DeviceSaeSmoothBlock,
5249            FactoredFrameGBlock, FactoredFrameKroneckerOp, IdentityRightKroneckerPenaltyOp,
5250        };
5251
5252        let p = 4usize;
5253        // Three atoms: ranks 2 (framed), 4 (un-framed), 3 (framed).
5254        let ranks = vec![2usize, 4usize, 3usize];
5255        let basis_sizes = vec![2usize, 1usize, 2usize];
5256        let n_atoms = ranks.len();
5257        let mut border_offsets = Vec::with_capacity(n_atoms);
5258        let mut acc = 0usize;
5259        for k in 0..n_atoms {
5260            border_offsets.push(acc);
5261            acc += basis_sizes[k] * ranks[k];
5262        }
5263        let border_dim = acc; // 2*2 + 1*4 + 2*3 = 14
5264
5265        let mut state = 0x1234_5678_9abc_def0u64;
5266        let mut sample = || -> f64 {
5267            state = state
5268                .wrapping_mul(6364136223846793005)
5269                .wrapping_add(1442695040888963407);
5270            ((state >> 33) as f64) / ((1u64 << 31) as f64) - 1.0
5271        };
5272
5273        // Per-atom orthonormal-ish frames U_k (p × r_k) for the W = U_iᵀU_j
5274        // factors; un-framed atom (r=p) uses U = I_p.
5275        let mut frames: Vec<Array2<f64>> = Vec::with_capacity(n_atoms);
5276        for k in 0..n_atoms {
5277            let r = ranks[k];
5278            let mut u = Array2::<f64>::zeros((p, r));
5279            for i in 0..p {
5280                for j in 0..r {
5281                    u[[i, j]] = if r == p && i == j {
5282                        1.0
5283                    } else if r == p {
5284                        0.0
5285                    } else {
5286                        sample()
5287                    };
5288                }
5289            }
5290            frames.push(u);
5291        }
5292        let w_of = |i: usize, j: usize| -> Array2<f64> {
5293            let (ui, uj) = (&frames[i], &frames[j]);
5294            let (ri, rj) = (ranks[i], ranks[j]);
5295            let mut w = Array2::<f64>::zeros((ri, rj));
5296            for a in 0..ri {
5297                for b in 0..rj {
5298                    let mut s = 0.0;
5299                    for c in 0..p {
5300                        s += ui[[c, a]] * uj[[c, b]];
5301                    }
5302                    w[[a, b]] = s;
5303                }
5304            }
5305            w
5306        };
5307
5308        // Co-occurring data-fit blocks: all diagonal pairs + one cross (0,2).
5309        let mut frame_blocks: Vec<FactoredFrameGBlock> = Vec::new();
5310        let mut pairs = vec![(0usize, 0usize), (1, 1), (2, 2), (0, 2), (2, 0)];
5311        pairs.sort();
5312        for &(i, j) in &pairs {
5313            let (mi, mj) = (basis_sizes[i], basis_sizes[j]);
5314            let mut g = Array2::<f64>::zeros((mi, mj));
5315            for r in 0..mi {
5316                for c in 0..mj {
5317                    g[[r, c]] = 0.3 * sample();
5318                }
5319            }
5320            // Make diagonal blocks SPD-leaning so S stays PD.
5321            if i == j {
5322                for r in 0..mi.min(mj) {
5323                    g[[r, r]] += mi as f64 + 2.0;
5324                }
5325            }
5326            frame_blocks.push(FactoredFrameGBlock {
5327                atom_i: i,
5328                atom_j: j,
5329                g,
5330                w: w_of(i, j),
5331            });
5332        }
5333
5334        // Smooth blocks λ S_k (M_k × M_k), SPD.
5335        let mut smooth_blocks: Vec<DeviceSaeSmoothBlock> = Vec::with_capacity(n_atoms);
5336        let mut smooth_ranks: Vec<usize> = Vec::with_capacity(n_atoms);
5337        for k in 0..n_atoms {
5338            let m = basis_sizes[k];
5339            let mut a = Array2::<f64>::zeros((m, m));
5340            for r in 0..m {
5341                for c in 0..m {
5342                    a[[r, c]] = 0.2 * sample();
5343                }
5344            }
5345            let mut s = a.t().dot(&a);
5346            for r in 0..m {
5347                s[[r, r]] += 1.0;
5348            }
5349            smooth_blocks.push(DeviceSaeSmoothBlock {
5350                global_offset: border_offsets[k],
5351                factor_a: s,
5352            });
5353            smooth_ranks.push(ranks[k]);
5354        }
5355
5356        // Build the system: n rows, dense htbeta slabs (q_i × border_dim).
5357        let n = 6usize;
5358        let q = 3usize;
5359        let mut sys = ArrowSchurSystem::new(n, q, border_dim);
5360        let mut row_htbeta: Vec<Vec<f64>> = Vec::with_capacity(n);
5361        for i in 0..n {
5362            // SPD htt.
5363            let mut a = Array2::<f64>::zeros((q, q));
5364            for r in 0..q {
5365                for c in 0..q {
5366                    a[[r, c]] = sample();
5367                }
5368            }
5369            let mut htt = a.t().dot(&a);
5370            for r in 0..q {
5371                htt[[r, r]] += q as f64 + 1.0;
5372            }
5373            sys.rows[i].htt = htt;
5374            let mut slab = vec![0.0_f64; q * border_dim];
5375            for c in 0..q {
5376                for col in 0..border_dim {
5377                    let v = 0.15 * sample();
5378                    slab[c * border_dim + col] = v;
5379                    sys.rows[i].htbeta[[c, col]] = v;
5380                }
5381            }
5382            row_htbeta.push(slab);
5383        }
5384
5385        // Dense H_ββ from the SAME penalty ops (so the dense reference's S
5386        // matches the device penalty side exactly).
5387        let data_op =
5388            FactoredFrameKroneckerOp::new(ranks.clone(), basis_sizes.clone(), frame_blocks.clone())
5389                .expect("frame op");
5390        let mut hbb = data_op.to_dense();
5391        for k in 0..n_atoms {
5392            let op = IdentityRightKroneckerPenaltyOp {
5393                factor_a: smooth_blocks[k].factor_a.clone(),
5394                p: ranks[k],
5395                global_offset: border_offsets[k],
5396                k: border_dim,
5397            };
5398            let d = op.to_dense();
5399            for r in 0..border_dim {
5400                for c in 0..border_dim {
5401                    hbb[[r, c]] += d[[r, c]];
5402                }
5403            }
5404        }
5405        sys.hbb = hbb;
5406
5407        let data = DeviceSaePcgData {
5408            p,
5409            beta_dim: border_dim,
5410            a_phi: std::sync::Arc::from(Vec::new().into_boxed_slice()),
5411            local_jac: std::sync::Arc::from(Vec::new().into_boxed_slice()),
5412            smooth_blocks,
5413            sparse_g_blocks: Vec::new(),
5414            frame: Some(DeviceSaeFrameData {
5415                ranks: ranks.clone(),
5416                basis_sizes: basis_sizes.clone(),
5417                border_offsets: border_offsets.clone(),
5418                frame_blocks,
5419                smooth_ranks,
5420                row_htbeta,
5421            }),
5422        };
5423
5424        let ridge_t = 1e-7;
5425        let ridge_beta = 1e-6;
5426
5427        // Dense reference reduced Schur S (border_dim × border_dim), formed
5428        // exactly as solve_arrow_newton_step_dense_reference assembles the
5429        // bordered Hessian and eliminates the t-block.
5430        let mut s_dense = Array2::<f64>::zeros((border_dim, border_dim));
5431        for r in 0..border_dim {
5432            for c in 0..border_dim {
5433                s_dense[[r, c]] = sys.hbb[[r, c]];
5434            }
5435            s_dense[[r, r]] += ridge_beta;
5436        }
5437        for row in &sys.rows {
5438            let mut htt = row.htt.clone();
5439            for d in 0..q {
5440                htt[[d, d]] += ridge_t;
5441            }
5442            let factor = cholesky_factor_in_place(htt.view(), CholeskyGuard::NonnegativePivot)
5443                .expect("htt PD");
5444            // Y = (htt)⁻¹ htbeta  (q × border_dim); S -= htbetaᵀ Y.
5445            let mut y = Array2::<f64>::zeros((q, border_dim));
5446            for col in 0..border_dim {
5447                let mut e = Array1::<f64>::zeros(q);
5448                for r in 0..q {
5449                    e[r] = row.htbeta[[r, col]];
5450                }
5451                let solved = cholesky_solve_vector(factor.view(), e.view());
5452                for r in 0..q {
5453                    y[[r, col]] = solved[r];
5454                }
5455            }
5456            for r in 0..border_dim {
5457                for c in 0..border_dim {
5458                    let mut acc = 0.0;
5459                    for d in 0..q {
5460                        acc += row.htbeta[[d, r]] * y[[d, c]];
5461                    }
5462                    s_dense[[r, c]] -= acc;
5463                }
5464            }
5465        }
5466
5467        // Probe vectors: compare S·x from the device-data CPU oracle vs dense S·x.
5468        let mut max_rel = 0.0_f64;
5469        for trial in 0..4 {
5470            let x: Vec<f64> = (0..border_dim)
5471                .map(|a| 0.3 * ((a as f64 + trial as f64) * 0.21).cos() - 0.1)
5472                .collect();
5473            let mut got = vec![0.0_f64; border_dim];
5474            sae_framed_schur_matvec_cpu(&sys, &data, ridge_t, ridge_beta, &x, &mut got)
5475                .expect("framed matvec");
5476            let mut want = vec![0.0_f64; border_dim];
5477            for r in 0..border_dim {
5478                let mut acc = 0.0;
5479                for c in 0..border_dim {
5480                    acc += s_dense[[r, c]] * x[c];
5481                }
5482                want[r] = acc;
5483            }
5484            let scale = want.iter().fold(0.0_f64, |m, v| m.max(v.abs())).max(1.0);
5485            for a in 0..border_dim {
5486                let rel = (got[a] - want[a]).abs() / scale;
5487                max_rel = max_rel.max(rel);
5488            }
5489        }
5490        assert!(
5491            max_rel <= 1e-10,
5492            "framed SAE Schur matvec vs dense reference diverged: max_rel={max_rel:e}"
5493        );
5494    }
5495
5496    /// #1017/#1026 GPU arm: when a CUDA device admits the framed SAE PCG, its
5497    /// solved `δβ` must match the CPU dense reduced-system solve of the SAME
5498    /// framed system (size-independent — a small device validates the kernel).
5499    /// Skips cleanly (returns) when no device is available or the policy
5500    /// declines (`solve_sae_matrix_free_pcg` → `Unavailable`).
5501    #[test]
5502    fn framed_sae_device_pcg_matches_cpu_when_cuda_admits() {
5503        use crate::arrow_schur::{
5504            BetaPenaltyOp, DeviceSaeFrameData, DeviceSaePcgData, DeviceSaeSmoothBlock,
5505            FactoredFrameGBlock, FactoredFrameKroneckerOp, IdentityRightKroneckerPenaltyOp,
5506        };
5507
5508        // Large enough to clear the device-offload policy floor (k ≥ 32 and
5509        // n·k·d·iters ≥ MATVEC_OFFLOAD_FLOPS_MIN) so the GPU kernel actually
5510        // runs on a device rather than the policy declining.
5511        let p = 6usize;
5512        let n_atoms = 8usize;
5513        let ranks: Vec<usize> = (0..n_atoms)
5514            .map(|k| if k % 2 == 0 { 3usize } else { p })
5515            .collect();
5516        let basis_sizes: Vec<usize> = (0..n_atoms).map(|_| 3usize).collect();
5517        let mut border_offsets = Vec::with_capacity(n_atoms);
5518        let mut acc = 0usize;
5519        for k in 0..n_atoms {
5520            border_offsets.push(acc);
5521            acc += basis_sizes[k] * ranks[k];
5522        }
5523        let border_dim = acc; // Σ M_k·r_k = 4·(3·3) + 4·(3·6) = 36 + 72 = 108
5524
5525        let mut state = 0xfeed_face_dead_beefu64;
5526        let mut sample = || -> f64 {
5527            state = state
5528                .wrapping_mul(6364136223846793005)
5529                .wrapping_add(1442695040888963407);
5530            ((state >> 33) as f64) / ((1u64 << 31) as f64) - 1.0
5531        };
5532        let mut frames: Vec<Array2<f64>> = Vec::new();
5533        for k in 0..n_atoms {
5534            let r = ranks[k];
5535            let mut u = Array2::<f64>::zeros((p, r));
5536            for i in 0..p {
5537                for j in 0..r {
5538                    u[[i, j]] = if r == p && i == j {
5539                        1.0
5540                    } else if r == p {
5541                        0.0
5542                    } else {
5543                        sample()
5544                    };
5545                }
5546            }
5547            frames.push(u);
5548        }
5549        let w_of = |i: usize, j: usize| {
5550            let (ui, uj) = (&frames[i], &frames[j]);
5551            let (ri, rj) = (ranks[i], ranks[j]);
5552            let mut w = Array2::<f64>::zeros((ri, rj));
5553            for a in 0..ri {
5554                for b in 0..rj {
5555                    let mut s = 0.0;
5556                    for c in 0..p {
5557                        s += ui[[c, a]] * uj[[c, b]];
5558                    }
5559                    w[[a, b]] = s;
5560                }
5561            }
5562            w
5563        };
5564        let mut pairs: Vec<(usize, usize)> = (0..n_atoms).map(|k| (k, k)).collect();
5565        // A few off-diagonal cross blocks (symmetric pairs).
5566        for &(i, j) in &[(0usize, 1usize), (2, 4), (3, 6)] {
5567            pairs.push((i, j));
5568            pairs.push((j, i));
5569        }
5570        let mut frame_blocks = Vec::new();
5571        for &(i, j) in &pairs {
5572            let (mi, mj) = (basis_sizes[i], basis_sizes[j]);
5573            let mut g = Array2::<f64>::zeros((mi, mj));
5574            for r in 0..mi {
5575                for c in 0..mj {
5576                    g[[r, c]] = 0.25 * sample();
5577                }
5578            }
5579            if i == j {
5580                for r in 0..mi.min(mj) {
5581                    g[[r, r]] += mi as f64 + 2.0;
5582                }
5583            }
5584            frame_blocks.push(FactoredFrameGBlock {
5585                atom_i: i,
5586                atom_j: j,
5587                g,
5588                w: w_of(i, j),
5589            });
5590        }
5591        let mut smooth_blocks = Vec::new();
5592        let mut smooth_ranks = Vec::new();
5593        for k in 0..n_atoms {
5594            let m = basis_sizes[k];
5595            let mut a = Array2::<f64>::zeros((m, m));
5596            for r in 0..m {
5597                for c in 0..m {
5598                    a[[r, c]] = 0.2 * sample();
5599                }
5600            }
5601            let mut s = a.t().dot(&a);
5602            for r in 0..m {
5603                s[[r, r]] += 1.0;
5604            }
5605            smooth_blocks.push(DeviceSaeSmoothBlock {
5606                global_offset: border_offsets[k],
5607                factor_a: s,
5608            });
5609            smooth_ranks.push(ranks[k]);
5610        }
5611        let n = 400usize;
5612        let q = 4usize;
5613        let mut sys = ArrowSchurSystem::new(n, q, border_dim);
5614        let mut row_htbeta = Vec::new();
5615        for i in 0..n {
5616            let mut a = Array2::<f64>::zeros((q, q));
5617            for r in 0..q {
5618                for c in 0..q {
5619                    a[[r, c]] = sample();
5620                }
5621            }
5622            let mut htt = a.t().dot(&a);
5623            for r in 0..q {
5624                htt[[r, r]] += q as f64 + 1.0;
5625            }
5626            sys.rows[i].htt = htt;
5627            let mut slab = vec![0.0_f64; q * border_dim];
5628            for c in 0..q {
5629                for col in 0..border_dim {
5630                    // Small entries: with 400 rows the reduced-Schur subtraction
5631                    // Σ_i H_βtᵀ H_tt⁻¹ H_tβ must not overwhelm the PD penalty.
5632                    let v = 0.02 * sample();
5633                    slab[c * border_dim + col] = v;
5634                    sys.rows[i].htbeta[[c, col]] = v;
5635                }
5636            }
5637            row_htbeta.push(slab);
5638        }
5639        let data_op =
5640            FactoredFrameKroneckerOp::new(ranks.clone(), basis_sizes.clone(), frame_blocks.clone())
5641                .expect("frame op");
5642        let mut hbb = data_op.to_dense();
5643        for k in 0..n_atoms {
5644            let op = IdentityRightKroneckerPenaltyOp {
5645                factor_a: smooth_blocks[k].factor_a.clone(),
5646                p: ranks[k],
5647                global_offset: border_offsets[k],
5648                k: border_dim,
5649            };
5650            let d = op.to_dense();
5651            for r in 0..border_dim {
5652                for c in 0..border_dim {
5653                    hbb[[r, c]] += d[[r, c]];
5654                }
5655            }
5656        }
5657        sys.hbb = hbb;
5658        let data = DeviceSaePcgData {
5659            p,
5660            beta_dim: border_dim,
5661            a_phi: std::sync::Arc::from(Vec::new().into_boxed_slice()),
5662            local_jac: std::sync::Arc::from(Vec::new().into_boxed_slice()),
5663            smooth_blocks,
5664            sparse_g_blocks: Vec::new(),
5665            frame: Some(DeviceSaeFrameData {
5666                ranks: ranks.clone(),
5667                basis_sizes: basis_sizes.clone(),
5668                border_offsets: border_offsets.clone(),
5669                frame_blocks,
5670                smooth_ranks,
5671                row_htbeta,
5672            }),
5673        };
5674        let ridge_t = 1e-7;
5675        let ridge_beta = 1e-6;
5676        let rhs: Array1<f64> =
5677            Array1::from_shape_fn(border_dim, |a| ((a as f64 + 1.0) * 0.17).sin());
5678
5679        let (device, diag) =
5680            match solve_sae_matrix_free_pcg(&sys, &data, ridge_t, ridge_beta, &rhs, 400, 1e-12) {
5681                Ok(result) => result,
5682                // #1017 — fail loud, never skip-pass: this fixture clears the device
5683                // offload floor, so a CUDA device that is PRESENT yet declines means the
5684                // framed device PCG kernel does not run on GPU (the fault must not pass
5685                // silently). Legit skip ONLY when no usable CUDA device exists (CPU CI).
5686                // The exact `ArrowSchurGpuFailure` variant is folded into the assert.
5687                Err(failure) => {
5688                    assert!(
5689                        gam_gpu::device_runtime::GpuRuntime::global().is_none(),
5690                        "#1017: CUDA device present but the framed device SAE PCG \
5691                     declined/faulted instead of returning a result (tag: {failure:?}) — \
5692                     the kernel does not run correctly on GPU"
5693                    );
5694                    return;
5695                }
5696            };
5697
5698        // CPU dense reduced-system solve of the SAME framed system: form S via
5699        // the CPU oracle matvec on the identity, then solve S·δβ = rhs.
5700        let mut s_dense = Array2::<f64>::zeros((border_dim, border_dim));
5701        for col in 0..border_dim {
5702            let mut e = vec![0.0_f64; border_dim];
5703            e[col] = 1.0;
5704            let mut sc = vec![0.0_f64; border_dim];
5705            sae_framed_schur_matvec_cpu(&sys, &data, ridge_t, ridge_beta, &e, &mut sc)
5706                .expect("cpu matvec");
5707            for r in 0..border_dim {
5708                s_dense[[r, col]] = sc[r];
5709            }
5710        }
5711        let factor = cholesky_factor_in_place(s_dense.view(), CholeskyGuard::NonnegativePivot)
5712            .expect("S PD");
5713        let cpu = cholesky_solve_vector(factor.view(), rhs.view());
5714
5715        let scale = cpu.iter().fold(0.0_f64, |m, v| m.max(v.abs())).max(1.0);
5716        let mut max_rel = 0.0_f64;
5717        for a in 0..border_dim {
5718            max_rel = max_rel.max((device[a] - cpu[a]).abs() / scale);
5719        }
5720        // #1551 divergence triage (max_rel=0.91 once the device actually engages):
5721        // disambiguate matvec-bug vs PCG-non-convergence vs operator-mismatch.
5722        // Residual of the DEVICE solution against the CPU operator S_cpu: if the
5723        // device solved the SAME operator and converged, ‖S_cpu·device − rhs‖ ≈ 0;
5724        // a large residual means the device matvec is a DIFFERENT operator (kernel
5725        // bug), whereas a small residual with large max_rel would indicate a
5726        // (near-)singular S where both solves are valid. Also surface what the
5727        // device PCG thought it did (stopping reason / iters / final residual).
5728        let mut s_dev_resid = 0.0_f64;
5729        {
5730            let sx = s_dense.dot(&device);
5731            for a in 0..border_dim {
5732                s_dev_resid = s_dev_resid.max((sx[a] - rhs[a]).abs());
5733            }
5734        }
5735        let s_cpu_resid = {
5736            let sc = s_dense.dot(&cpu);
5737            let mut m = 0.0_f64;
5738            for a in 0..border_dim {
5739                m = m.max((sc[a] - rhs[a]).abs());
5740            }
5741            m
5742        };
5743        assert!(
5744            max_rel <= 1e-7,
5745            "[#1551 framed-triage] max_rel={max_rel:e} | device-vs-CPU-operator residual \
5746             ‖S_cpu·device−rhs‖={s_dev_resid:e} (CPU's own ={s_cpu_resid:e}) | device PCG \
5747             stop={:?} iters={} final_rel_resid={:e} — large operator-residual ⇒ device matvec \
5748             is a different operator (kernel bug); small ⇒ PCG/precond or singular-S issue",
5749            diag.stopping_reason,
5750            diag.iterations,
5751            diag.final_relative_residual,
5752        );
5753    }
5754}