gam_solve/pirls/workspace.rs
1//! Reusable inner-loop scratch (`PirlsWorkspace`), the P-IRLS options bundle
2//! (`WorkingModelPirlsOptions`), the arrow-Schur structured-inner-solve
3//! descriptor, and the arrow-latent snapshot/restore/commit helpers.
4
5use super::*;
6
7pub struct PirlsWorkspace {
8 // Common IRLS buffers. Only O(n) state is kept persistently; any
9 // design-weighted n x p scratch must be streamed through bounded chunks.
10 pub wz: Array1<f64>,
11 pub eta_buf: Array1<f64>,
12 // Stage 2/4 assembly (use max needed sizes)
13 pub scaled_matrix: Array2<f64>, // (<= p + ebrows) x p
14 pub final_aug_matrix: Array2<f64>, // (<= p + erows) x p
15 // Stage 5 RHS buffers
16 pub rhs_full: Array1<f64>, // length <= p + erows
17 // Gradient helper
18 pub weighted_residual: Array1<f64>,
19 // Step-halving direction (XΔβ)
20 pub delta_eta: Array1<f64>,
21 // Preallocated buffer for GEMV results (length p)
22 pub vec_buf_p: Array1<f64>,
23 // Cached sparse penalized-system workspace for sparse-native solve eligibility/assembly.
24 pub(crate) sparse_penalized_system_cache: Option<SparsePenalizedSystemCache>,
25 // Factorization scratch (avoid per-iteration allocation)
26 pub factorization_scratch: MemBuffer,
27 // Permutation buffers for LDLT
28 pub perm: Vec<usize>,
29 pub perm_inv: Vec<usize>,
30 // Buffer for in-place factorization (preserves original Hessian in WorkingState)
31 pub factorization_matrix: Array2<f64>,
32 // Buffer for sparse matrix scaling (avoid per-iteration allocation)
33 pub weighted_xvalues: Vec<f64>,
34 // Dense chunk buffer for streaming X'WX assembly on very large n.
35 pub weighted_x_chunk: Array2<f64>,
36 // Reusable p×p buffer for Hessian assembly (avoids per-iteration allocation).
37 pub hessian_buf: Array2<f64>,
38 // Reusable n-length buffer for X*β matvec (avoids per-iteration allocation in update).
39 pub matvec_buf: Array1<f64>,
40 // #1412: device-resident design `X` for the GPU `XᵀWX` Gram. The inner P-IRLS
41 // loop rebuilds the Gram once per Newton/LM iterate with the SAME design `X`
42 // (only the working weights `w` move), so re-uploading the full n×p `X` on
43 // every iterate starves the device on H2D staging (measured ~98% of the
44 // pipeline at <20% utilisation). This caches the device-resident `X` keyed on
45 // its host data pointer + shape, so the first Gram of an inner solve uploads
46 // `X` and every later iterate crosses only the n-vector `w` H2D and the p×p
47 // Gram D2H. `None` whenever CUDA is unavailable / the shape is below the GPU
48 // Gram threshold / the upload failed — the caller keeps its per-call path.
49 pub(crate) resident_design_gram: Option<(
50 usize,
51 usize,
52 usize,
53 gam_gpu::linalg_dispatch::ResidentDesignGram,
54 )>,
55}
56
57impl PirlsWorkspace {
58 /// Coefficient-space scratch for an exact sufficient-statistic solve.
59 ///
60 /// The Gaussian value-only rho lane has already reduced every data-row
61 /// contribution into `XᵀWX`, `XᵀW(y-offset)`, and the centered response
62 /// norm. It never enters an IRLS iteration, so allocating the general
63 /// workspace's five observation-length vectors would reintroduce O(n)
64 /// work before the zero-iteration branch can consume those statistics.
65 pub fn coefficient_only(p: usize) -> Self {
66 Self::new(0, p, 0, 0)
67 }
68
69 pub fn new(n: usize, p: usize, _: usize, _: usize) -> Self {
70 // Default implementation ignores this parameter.
71 // Default implementation ignores this parameter.
72 // Stage buffers are allocated lazily: historically these were pre-sized to
73 // worst-case dimensions, which inflates memory when many PIRLS workspaces
74 // exist concurrently (e.g. parallel REML evals).
75 // The active code paths resize-on-demand where needed.
76
77 PirlsWorkspace {
78 wz: Array1::zeros(n),
79 eta_buf: Array1::zeros(n),
80 scaled_matrix: Array2::zeros((0, 0).f()),
81 final_aug_matrix: Array2::zeros((0, 0).f()),
82 rhs_full: Array1::zeros(0),
83 weighted_residual: Array1::zeros(n),
84 delta_eta: Array1::zeros(n),
85 vec_buf_p: Array1::zeros(p),
86 sparse_penalized_system_cache: None,
87 // Keep scratch minimal at init; grow only if/when a factorization path
88 // needs it.
89 factorization_scratch: {
90 let par = faer::Par::Seq;
91 let req = faer::linalg::cholesky::llt::factor::cholesky_in_place_scratch::<f64>(
92 1,
93 par,
94 Spec::new(<LltParams as Auto<f64>>::auto()),
95 );
96 MemBuffer::new(req)
97 },
98 perm: vec![0; p],
99 perm_inv: vec![0; p],
100 factorization_matrix: Array2::zeros((0, 0)),
101 weighted_xvalues: Vec::new(),
102 weighted_x_chunk: Array2::zeros((0, 0).f()),
103 hessian_buf: Array2::zeros((0, 0).f()),
104 matvec_buf: Array1::zeros(n),
105 resident_design_gram: None,
106 }
107 }
108
109 pub(super) fn add_dense_xtwx_signed(
110 weights: &Array1<f64>,
111 weighted_x_scratch: &mut Array2<f64>,
112 x: &Array2<f64>,
113 out: &mut Array2<f64>,
114 ) {
115 *out =
116 crate::estimate::reml::assembly::xt_diag_x_dense_into(x, weights, weighted_x_scratch);
117 }
118
119 /// Ensure the sparse penalty cache is populated and consistent with `x` and `s_lambda`.
120 pub(crate) fn ensure_sparse_penalty_cache(
121 &mut self,
122 x: &SparseColMat<usize, f64>,
123 s_lambda: &Array2<f64>,
124 ) -> Result<(), EstimationError> {
125 let penalty_pattern = SparsePenaltyPattern::from_dense_upper(s_lambda, 1e-12);
126 let rebuild = match self.sparse_penalized_system_cache.as_ref() {
127 Some(cache) => !cache.matches(x, &penalty_pattern),
128 None => true,
129 };
130 if rebuild {
131 self.sparse_penalized_system_cache =
132 Some(SparsePenalizedSystemCache::new(x, penalty_pattern)?);
133 }
134 Ok(())
135 }
136
137 pub(crate) fn sparse_penalized_system_stats(
138 &mut self,
139 x: &SparseColMat<usize, f64>,
140 s_lambda: &Array2<f64>,
141 ) -> Result<SparsePenalizedSystemStats, EstimationError> {
142 self.ensure_sparse_penalty_cache(x, s_lambda)?;
143 Ok(self.sparse_penalized_system_cache.as_ref().unwrap().stats())
144 }
145
146 // Phase 2 hook: numeric sparse penalized-system assembly in original coordinates.
147 pub(super) fn assemble_sparse_penalized_hessian(
148 &mut self,
149 x: &SparseColMat<usize, f64>,
150 weights: &Array1<f64>,
151 s_lambda: &Array2<f64>,
152 ridge: f64,
153 precomputed_xtwx: Option<&SparseXtwxPrecomputed>,
154 ) -> Result<SparseColMat<usize, f64>, EstimationError> {
155 self.ensure_sparse_penalty_cache(x, s_lambda)?;
156 self.sparse_penalized_system_cache
157 .as_mut()
158 .unwrap()
159 .assemble_upper(x, weights, ridge, precomputed_xtwx)
160 }
161}
162
163#[derive(Clone, Debug)]
164pub struct WorkingModelPirlsOptions {
165 pub max_iterations: usize,
166 pub convergence_tolerance: f64,
167 pub adaptive_kkt_tolerance: Option<AdaptiveKktTolerance>,
168 pub max_step_halving: usize,
169 pub min_step_size: f64,
170 pub firth_bias_reduction: bool,
171 /// Optional lower bounds on coefficients (same coordinate system as `beta`).
172 /// Use `-inf` for unconstrained entries.
173 pub coefficient_lower_bounds: Option<Array1<f64>>,
174 /// Optional linear inequality constraints in current coefficient coordinates:
175 /// A * beta >= b.
176 pub linear_constraints: Option<LinearInequalityConstraints>,
177 /// Optional warm-start hint for the Levenberg-Marquardt damping
178 /// coefficient. When set, the inner solver seeds `λ_LM` to this
179 /// value instead of the default `1e-6`. Clamped on consumption to
180 /// `[1e-6, 1e-3]` so a stale or pathological hint cannot poison the
181 /// solve: the upper bound costs at most three damping halvings
182 /// versus the cold default, which is dwarfed by the savings when
183 /// the hint is informative.
184 ///
185 /// Used by `execute_pirls_if_needed` (in `solver::reml::outer_eval`)
186 /// to persist the converged λ across consecutive PIRLS calls in a
187 /// single REML outer optimization, so the inner Newton does not
188 /// have to rediscover problem-specific damping at every accepted
189 /// outer iterate.
190 pub initial_lm_lambda: Option<f64>,
191 /// Optional arrow-Schur structured-inner-solve descriptor.
192 ///
193 /// When `Some`, every accepted LM Newton step inside the inner loop
194 /// is computed by the per-observation arrow-Schur path
195 /// ([`crate::arrow_schur::ArrowSchurSystem`]) instead of the
196 /// β-only `solve_newton_direction_dense`. When `None`, the existing
197 /// β-only path is used unchanged (back-compat: every existing call
198 /// site that does not opt in is unaffected).
199 ///
200 /// **Scope note.** This wires the *inner* Gauss–Newton step. The REML
201 /// outer-loop gradient w.r.t. `t` (which carries a shared `Schur⁻¹`
202 /// factor) is a separate plumbing change owned by the REML driver and is
203 /// **not** handled here.
204 pub arrow_schur: Option<ArrowSchurInnerConfig>,
205}
206
207/// Per-iteration arrow-Schur builder hook.
208///
209/// The driver supplies a closure that, given the current `β` iterate,
210/// returns a freshly-populated [`crate::arrow_schur::ArrowSchurSystem`]
211/// — i.e. the per-row `H_tt^(i)`, `H_tβ^(i)`, `g_t^(i)` blocks and the
212/// β-block `H_ββ`, `g_β`. The driver owns the assembly because the
213/// per-row Jacobians depend on the latent-coord term's basis (Duchon,
214/// Sphere, …) and the analytic-penalty contributions depend on the
215/// registry the outer-fit configuration owns. PIRLS only knows how to
216/// *solve* the bordered system once it has been assembled.
217#[derive(Clone)]
218pub struct ArrowSchurInnerConfig {
219 /// Number of latent rows `N`.
220 pub n_rows: usize,
221 /// Latent dimensionality `d`.
222 pub latent_dim: usize,
223 /// β dimensionality `K` (must match the inner Hessian dimension).
224 pub n_beta: usize,
225 /// Closure that builds the bordered system at the current `β` and
226 /// current latent `t` (the latter held externally by the driver, e.g.
227 /// in a `LatentCoordValues` registered alongside the working model).
228 /// Returning `None` signals "fall back to the β-only path for this
229 /// iteration" — useful for the seeding sweep before `t` has been
230 /// initialized.
231 pub build: std::sync::Arc<
232 dyn Fn(&Array1<f64>) -> Option<crate::arrow_schur::ArrowSchurSystem> + Send + Sync,
233 >,
234 /// BA Schur solve mode. `None` selects Direct for `K <= 2000` and
235 /// InexactPCG above, following "Bundle Adjustment in the Large".
236 pub solver_mode: Option<crate::arrow_schur::ArrowSolverMode>,
237 /// When set, assemble the reduced dense Schur block in row chunks.
238 pub streaming_chunk_size: Option<usize>,
239 /// Steihaug trust-region radius for the reduced shared step. This ports
240 /// the Ceres/BA trust-region guard while retaining PIRLS's LM damping.
241 pub trust_region_radius: f64,
242 /// Optional β-block column ranges for the block-Jacobi Schur preconditioner.
243 ///
244 /// When `Some`, the PIRLS driver calls
245 /// [`crate::arrow_schur::ArrowSchurSystem::set_block_offsets`] on
246 /// every system returned by the `build` closure, wiring the block-Jacobi
247 /// path without requiring each family's closure to call it manually.
248 ///
249 /// Derive from `ParameterBlockSpec` slices via
250 /// `gam_custom_family::block_offsets_from_specs`. When
251 /// `None`, the preconditioner falls back to scalar-diagonal Jacobi (the
252 /// pre-#287 behaviour); when `Some([])` (empty slice), the same fallback
253 /// applies.
254 pub block_offsets: Option<Arc<[std::ops::Range<usize>]>>,
255 /// Callback that the inner solver invokes after each LM-attempted
256 /// joint step to write the latent tangent increment back into the
257 /// driver's `LatentCoordValues` via that latent's update rule
258 /// (`retract_flat_delta` for manifold latents). `delta_t` is the flat
259 /// row-major increment of length `n_rows * latent_dim`.
260 pub apply_delta_t: std::sync::Arc<dyn Fn(&Array1<f64>) + Send + Sync>,
261 /// Snapshot the driver's latent field before an LM trial step mutates it.
262 pub snapshot_t: std::sync::Arc<dyn Fn() -> Array1<f64> + Send + Sync>,
263 /// Restore a snapshot produced by [`Self::snapshot_t`] after any rejected
264 /// LM trial. Accepted trials deliberately do not call this hook: β and t
265 /// commit together.
266 pub restore_t: std::sync::Arc<dyn Fn(&Array1<f64>) + Send + Sync>,
267}
268
269impl std::fmt::Debug for ArrowSchurInnerConfig {
270 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
271 f.debug_struct("ArrowSchurInnerConfig")
272 .field("n_rows", &self.n_rows)
273 .field("latent_dim", &self.latent_dim)
274 .field("n_beta", &self.n_beta)
275 .field("solver_mode", &self.solver_mode)
276 .field("streaming_chunk_size", &self.streaming_chunk_size)
277 .field("trust_region_radius", &self.trust_region_radius)
278 .field(
279 "block_offsets",
280 &self.block_offsets.as_ref().map(|o| o.len()),
281 )
282 .finish_non_exhaustive()
283 }
284}
285
286pub(crate) fn restore_arrow_latent_if_needed(
287 options: &WorkingModelPirlsOptions,
288 snapshot: Option<Array1<f64>>,
289) {
290 if let (Some(arrow_cfg), Some(snapshot)) = (options.arrow_schur.as_ref(), snapshot) {
291 arrow_cfg.restore_t.as_ref()(&snapshot);
292 }
293}
294
295pub(super) fn restore_pending_arrow_latent_if_needed(
296 options: &WorkingModelPirlsOptions,
297 pending_snapshot: &mut Option<Array1<f64>>,
298) {
299 restore_arrow_latent_if_needed(options, pending_snapshot.take());
300}
301
302pub(super) fn commit_pending_arrow_latent(pending_snapshot: &mut Option<Array1<f64>>) {
303 drop(pending_snapshot.take());
304}