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 pub fn new(n: usize, p: usize, _: usize, _: usize) -> Self {
59 // Default implementation ignores this parameter.
60 // Default implementation ignores this parameter.
61 // Stage buffers are allocated lazily: historically these were pre-sized to
62 // worst-case dimensions, which inflates memory when many PIRLS workspaces
63 // exist concurrently (e.g. parallel REML evals).
64 // The active code paths resize-on-demand where needed.
65
66 PirlsWorkspace {
67 wz: Array1::zeros(n),
68 eta_buf: Array1::zeros(n),
69 scaled_matrix: Array2::zeros((0, 0).f()),
70 final_aug_matrix: Array2::zeros((0, 0).f()),
71 rhs_full: Array1::zeros(0),
72 weighted_residual: Array1::zeros(n),
73 delta_eta: Array1::zeros(n),
74 vec_buf_p: Array1::zeros(p),
75 sparse_penalized_system_cache: None,
76 // Keep scratch minimal at init; grow only if/when a factorization path
77 // needs it.
78 factorization_scratch: {
79 let par = faer::Par::Seq;
80 let req = faer::linalg::cholesky::llt::factor::cholesky_in_place_scratch::<f64>(
81 1,
82 par,
83 Spec::new(<LltParams as Auto<f64>>::auto()),
84 );
85 MemBuffer::new(req)
86 },
87 perm: vec![0; p],
88 perm_inv: vec![0; p],
89 factorization_matrix: Array2::zeros((0, 0)),
90 weighted_xvalues: Vec::new(),
91 weighted_x_chunk: Array2::zeros((0, 0).f()),
92 hessian_buf: Array2::zeros((0, 0).f()),
93 matvec_buf: Array1::zeros(n),
94 resident_design_gram: None,
95 }
96 }
97
98 pub(super) fn add_dense_xtwx_signed(
99 weights: &Array1<f64>,
100 weighted_x_scratch: &mut Array2<f64>,
101 x: &Array2<f64>,
102 out: &mut Array2<f64>,
103 ) {
104 *out =
105 crate::estimate::reml::assembly::xt_diag_x_dense_into(x, weights, weighted_x_scratch);
106 }
107
108 /// Ensure the sparse penalty cache is populated and consistent with `x` and `s_lambda`.
109 pub(crate) fn ensure_sparse_penalty_cache(
110 &mut self,
111 x: &SparseColMat<usize, f64>,
112 s_lambda: &Array2<f64>,
113 ) -> Result<(), EstimationError> {
114 let penalty_pattern = SparsePenaltyPattern::from_dense_upper(s_lambda, 1e-12);
115 let rebuild = match self.sparse_penalized_system_cache.as_ref() {
116 Some(cache) => !cache.matches(x, &penalty_pattern),
117 None => true,
118 };
119 if rebuild {
120 self.sparse_penalized_system_cache =
121 Some(SparsePenalizedSystemCache::new(x, penalty_pattern)?);
122 }
123 Ok(())
124 }
125
126 pub(crate) fn sparse_penalized_system_stats(
127 &mut self,
128 x: &SparseColMat<usize, f64>,
129 s_lambda: &Array2<f64>,
130 ) -> Result<SparsePenalizedSystemStats, EstimationError> {
131 self.ensure_sparse_penalty_cache(x, s_lambda)?;
132 Ok(self.sparse_penalized_system_cache.as_ref().unwrap().stats())
133 }
134
135 // Phase 2 hook: numeric sparse penalized-system assembly in original coordinates.
136 pub(super) fn assemble_sparse_penalized_hessian(
137 &mut self,
138 x: &SparseColMat<usize, f64>,
139 weights: &Array1<f64>,
140 s_lambda: &Array2<f64>,
141 ridge: f64,
142 precomputed_xtwx: Option<&SparseXtwxPrecomputed>,
143 ) -> Result<SparseColMat<usize, f64>, EstimationError> {
144 self.ensure_sparse_penalty_cache(x, s_lambda)?;
145 self.sparse_penalized_system_cache
146 .as_mut()
147 .unwrap()
148 .assemble_upper(x, weights, ridge, precomputed_xtwx)
149 }
150}
151
152#[derive(Clone, Debug)]
153pub struct WorkingModelPirlsOptions {
154 pub max_iterations: usize,
155 pub convergence_tolerance: f64,
156 pub adaptive_kkt_tolerance: Option<AdaptiveKktTolerance>,
157 pub max_step_halving: usize,
158 pub min_step_size: f64,
159 pub firth_bias_reduction: bool,
160 /// Optional lower bounds on coefficients (same coordinate system as `beta`).
161 /// Use `-inf` for unconstrained entries.
162 pub coefficient_lower_bounds: Option<Array1<f64>>,
163 /// Optional linear inequality constraints in current coefficient coordinates:
164 /// A * beta >= b.
165 pub linear_constraints: Option<LinearInequalityConstraints>,
166 /// Optional warm-start hint for the Levenberg-Marquardt damping
167 /// coefficient. When set, the inner solver seeds `λ_LM` to this
168 /// value instead of the default `1e-6`. Clamped on consumption to
169 /// `[1e-6, 1e-3]` so a stale or pathological hint cannot poison the
170 /// solve: the upper bound costs at most three damping halvings
171 /// versus the cold default, which is dwarfed by the savings when
172 /// the hint is informative.
173 ///
174 /// Used by `execute_pirls_if_needed` (in `solver::reml::outer_eval`)
175 /// to persist the converged λ across consecutive PIRLS calls in a
176 /// single REML outer optimization, so the inner Newton does not
177 /// have to rediscover problem-specific damping at every accepted
178 /// outer iterate.
179 pub initial_lm_lambda: Option<f64>,
180 /// Optional arrow-Schur structured-inner-solve descriptor.
181 ///
182 /// When `Some`, every accepted LM Newton step inside the inner loop
183 /// is computed by the per-observation arrow-Schur path
184 /// ([`crate::arrow_schur::ArrowSchurSystem`]) instead of the
185 /// β-only `solve_newton_direction_dense`. When `None`, the existing
186 /// β-only path is used unchanged (back-compat: every existing call
187 /// site that does not opt in is unaffected).
188 ///
189 /// **Scope note.** This wires the *inner* Gauss–Newton step. The REML
190 /// outer-loop gradient w.r.t. `t` (which carries a shared `Schur⁻¹`
191 /// factor) is a separate plumbing change owned by the REML driver and is
192 /// **not** handled here.
193 pub arrow_schur: Option<ArrowSchurInnerConfig>,
194}
195
196/// Per-iteration arrow-Schur builder hook.
197///
198/// The driver supplies a closure that, given the current `β` iterate,
199/// returns a freshly-populated [`crate::arrow_schur::ArrowSchurSystem`]
200/// — i.e. the per-row `H_tt^(i)`, `H_tβ^(i)`, `g_t^(i)` blocks and the
201/// β-block `H_ββ`, `g_β`. The driver owns the assembly because the
202/// per-row Jacobians depend on the latent-coord term's basis (Duchon,
203/// Sphere, …) and the analytic-penalty contributions depend on the
204/// registry the outer-fit configuration owns. PIRLS only knows how to
205/// *solve* the bordered system once it has been assembled.
206#[derive(Clone)]
207pub struct ArrowSchurInnerConfig {
208 /// Number of latent rows `N`.
209 pub n_rows: usize,
210 /// Latent dimensionality `d`.
211 pub latent_dim: usize,
212 /// β dimensionality `K` (must match the inner Hessian dimension).
213 pub n_beta: usize,
214 /// Closure that builds the bordered system at the current `β` and
215 /// current latent `t` (the latter held externally by the driver, e.g.
216 /// in a `LatentCoordValues` registered alongside the working model).
217 /// Returning `None` signals "fall back to the β-only path for this
218 /// iteration" — useful for the seeding sweep before `t` has been
219 /// initialized.
220 pub build: std::sync::Arc<
221 dyn Fn(&Array1<f64>) -> Option<crate::arrow_schur::ArrowSchurSystem> + Send + Sync,
222 >,
223 /// BA Schur solve mode. `None` selects Direct for `K <= 2000` and
224 /// InexactPCG above, following "Bundle Adjustment in the Large".
225 pub solver_mode: Option<crate::arrow_schur::ArrowSolverMode>,
226 /// When set, assemble the reduced dense Schur block in row chunks.
227 pub streaming_chunk_size: Option<usize>,
228 /// Steihaug trust-region radius for the reduced shared step. This ports
229 /// the Ceres/BA trust-region guard while retaining PIRLS's LM damping.
230 pub trust_region_radius: f64,
231 /// Optional β-block column ranges for the block-Jacobi Schur preconditioner.
232 ///
233 /// When `Some`, the PIRLS driver calls
234 /// [`crate::arrow_schur::ArrowSchurSystem::set_block_offsets`] on
235 /// every system returned by the `build` closure, wiring the block-Jacobi
236 /// path without requiring each family's closure to call it manually.
237 ///
238 /// Derive from `ParameterBlockSpec` slices via
239 /// `gam_custom_family::block_offsets_from_specs`. When
240 /// `None`, the preconditioner falls back to scalar-diagonal Jacobi (the
241 /// pre-#287 behaviour); when `Some([])` (empty slice), the same fallback
242 /// applies.
243 pub block_offsets: Option<Arc<[std::ops::Range<usize>]>>,
244 /// Callback that the inner solver invokes after each LM-attempted
245 /// joint step to write the latent tangent increment back into the
246 /// driver's `LatentCoordValues` via that latent's update rule
247 /// (`retract_flat_delta` for manifold latents). `delta_t` is the flat
248 /// row-major increment of length `n_rows * latent_dim`.
249 pub apply_delta_t: std::sync::Arc<dyn Fn(&Array1<f64>) + Send + Sync>,
250 /// Snapshot the driver's latent field before an LM trial step mutates it.
251 pub snapshot_t: std::sync::Arc<dyn Fn() -> Array1<f64> + Send + Sync>,
252 /// Restore a snapshot produced by [`Self::snapshot_t`] after any rejected
253 /// LM trial. Accepted trials deliberately do not call this hook: β and t
254 /// commit together.
255 pub restore_t: std::sync::Arc<dyn Fn(&Array1<f64>) + Send + Sync>,
256}
257
258impl std::fmt::Debug for ArrowSchurInnerConfig {
259 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260 f.debug_struct("ArrowSchurInnerConfig")
261 .field("n_rows", &self.n_rows)
262 .field("latent_dim", &self.latent_dim)
263 .field("n_beta", &self.n_beta)
264 .field("solver_mode", &self.solver_mode)
265 .field("streaming_chunk_size", &self.streaming_chunk_size)
266 .field("trust_region_radius", &self.trust_region_radius)
267 .field(
268 "block_offsets",
269 &self.block_offsets.as_ref().map(|o| o.len()),
270 )
271 .finish_non_exhaustive()
272 }
273}
274
275pub(crate) fn restore_arrow_latent_if_needed(
276 options: &WorkingModelPirlsOptions,
277 snapshot: Option<Array1<f64>>,
278) {
279 if let (Some(arrow_cfg), Some(snapshot)) = (options.arrow_schur.as_ref(), snapshot) {
280 arrow_cfg.restore_t.as_ref()(&snapshot);
281 }
282}
283
284pub(super) fn restore_pending_arrow_latent_if_needed(
285 options: &WorkingModelPirlsOptions,
286 pending_snapshot: &mut Option<Array1<f64>>,
287) {
288 restore_arrow_latent_if_needed(options, pending_snapshot.take());
289}
290
291pub(super) fn commit_pending_arrow_latent(pending_snapshot: &mut Option<Array1<f64>>) {
292 drop(pending_snapshot.take());
293}