Skip to main content

gam_model_api/families/custom_family/
options.rs

1//! Fit-time configuration and cost accounting: `BlockwiseFitOptions`, the
2//! outer-derivative policy + order selection, coefficient cost models, and the
3//! argument-validation asserts shared by the solver entry points.
4
5use crate::families::custom_family::family_trait::{CustomFamily, OuterEvalContext};
6use crate::families::custom_family::psi_design::{
7    CustomFamilyBlockPsiDerivative, ExactNewtonJointHessianWorkspace,
8};
9use gam_linalg::RidgePolicy;
10use gam_problem::{ParameterBlockSpec, ParameterBlockState};
11use ndarray::Array1;
12use std::ops::Range;
13use std::sync::Arc;
14use std::sync::atomic::AtomicUsize;
15
16// Moved to `gam-problem` (#1521 CustomFamily-cone inversion): the neutral,
17// dependency-free outer-objective + exact-derivative-order capability enums now
18// live in `gam_problem::family_options` and are re-exported here so every
19// `custom_family::ExactNewtonOuterObjective` / `ExactOuterDerivativeOrder` path
20// keeps resolving byte-for-byte.
21pub use gam_problem::{ExactNewtonOuterObjective, ExactOuterDerivativeOrder};
22
23// The IRLS weight floor and block-spec consistency validator are neutral (no
24// `CustomFamily` dependency); they live in `gam-problem`. Coefficient damping
25// deliberately has no model-level default: the custom-family solver derives
26// any transient shift from the current curvature and must converge the
27// undamped score equation.
28pub use gam_problem::{CUSTOM_FAMILY_WEIGHT_FLOOR, validate_blockspec_consistency};
29
30/// Exact outer derivative order for families that expose second-order
31/// coefficient geometry.
32///
33/// This used to be a cost gate that demoted large large-scale problems to
34/// first-order BFGS. That was a policy leak into the math layer: if the family
35/// supplies analytic dense Hessian blocks or an analytic profiled-Hessian HVP,
36/// the outer optimizer should see the exact second-order objective. Runtime
37/// representation choices (dense vs operator) belong below this declaration,
38/// not in a first-order downgrade.
39/// Precondition check for the family capability / operator hooks (e.g.
40/// `batched_outer_hessian_terms`, `outer_hyper_hessian_operator`).
41///
42/// These hooks operate on whatever block geometry the caller has assembled and
43/// must validate the *consistency* of the specs they are handed — never the
44/// fit-level "at least one block" precondition, which belongs to the fit entry
45/// points (`validate_blockspecs`). An empty, self-consistent argument set is a
46/// valid no-op probe of the operator path (the operator may ignore the specs
47/// entirely), so it must not panic here.
48pub(crate) fn assert_valid_blockspecs(specs: &[ParameterBlockSpec], context: &str) {
49    assert!(
50        validate_blockspec_consistency(specs).is_ok(),
51        "{context}: inconsistent parameter block specs"
52    );
53}
54
55pub(crate) fn assert_valid_options(options: &BlockwiseFitOptions, context: &str) {
56    assert!(
57        options.inner_tol.is_finite() && options.inner_tol >= 0.0,
58        "{context}: inner_tol must be finite and non-negative"
59    );
60    assert!(
61        options.outer_tol.is_finite() && options.outer_tol >= 0.0,
62        "{context}: outer_tol must be finite and non-negative"
63    );
64    assert!(
65        options.minweight.is_finite() && options.minweight >= 0.0,
66        "{context}: minweight must be finite and non-negative"
67    );
68    assert!(
69        options.ridge_floor.is_finite() && options.ridge_floor >= 0.0,
70        "{context}: ridge_floor must be finite and non-negative"
71    );
72    if let Some(threshold) = options.early_exit_threshold {
73        assert!(
74            threshold.is_finite(),
75            "{context}: early_exit_threshold must be finite"
76        );
77    }
78}
79
80pub(crate) fn assert_states_match_specs(
81    states: &[ParameterBlockState],
82    specs: &[ParameterBlockSpec],
83    context: &str,
84) {
85    assert_eq!(
86        states.len(),
87        specs.len(),
88        "{context}: state/spec block count mismatch"
89    );
90    for (block, (state, spec)) in states.iter().zip(specs).enumerate() {
91        assert_eq!(
92            state.beta.len(),
93            spec.design.ncols(),
94            "{context}: beta length mismatch in block {block}"
95        );
96        // `state.eta` is produced from `solver_design()` (see
97        // `refresh_all_block_etas`), which is `stacked_design` when set
98        // (3·n_obs rows for survival LS time-varying blocks) and `design`
99        // (n_obs rows) otherwise. Use the same accessor here.
100        assert_eq!(
101            state.eta.len(),
102            spec.solver_design().nrows(),
103            "{context}: eta length mismatch in block {block}"
104        );
105    }
106}
107
108pub(crate) fn assert_derivative_blocks_match_specs(
109    derivative_blocks: &[Vec<CustomFamilyBlockPsiDerivative>],
110    specs: &[ParameterBlockSpec],
111    context: &str,
112) {
113    assert_eq!(
114        derivative_blocks.len(),
115        specs.len(),
116        "{context}: derivative/spec block count mismatch"
117    );
118}
119
120pub(crate) fn assert_rho_matches_specs(
121    rho: &Array1<f64>,
122    specs: &[ParameterBlockSpec],
123    context: &str,
124) {
125    let expected = specs.iter().map(|spec| spec.penalties.len()).sum::<usize>();
126    assert_eq!(
127        rho.len(),
128        expected,
129        "{context}: rho length does not match penalty count"
130    );
131}
132
133pub(crate) fn validate_hessian_workspace_ready(
134    hessian_workspace: &Option<Arc<dyn ExactNewtonJointHessianWorkspace>>,
135    context: &str,
136    eval_mode: gam_problem::EvalMode,
137) -> Result<(), String> {
138    if let Some(workspace) = hessian_workspace.as_ref() {
139        workspace
140            .warm_up_outer_caches_for_mode(eval_mode)
141            .map_err(|err| format!("{context}: failed to warm Hessian workspace caches: {err}"))?;
142    }
143    Ok(())
144}
145
146pub fn exact_outer_order_from_capability(
147    specs: &[ParameterBlockSpec],
148    coefficient_cost: u64,
149) -> ExactOuterDerivativeOrder {
150    assert_valid_blockspecs(specs, "exact outer derivative order");
151    match coefficient_cost {
152        0 => ExactOuterDerivativeOrder::Second,
153        _ => ExactOuterDerivativeOrder::Second,
154    }
155}
156
157/// Capability-aware variant of [`exact_outer_order_from_capability`].
158///
159/// Kept as the public declaration helper for existing family impls, but it no
160/// longer gates by cost. Once a caller has established dense or HVP analytic
161/// second-order support, the correct derivative order is `Second`.
162pub fn exact_outer_order_with_outer_hvp(
163    specs: &[ParameterBlockSpec],
164    coefficient_cost: u64,
165    outer_hyper_hessian_hvp_available: bool,
166) -> ExactOuterDerivativeOrder {
167    if outer_hyper_hessian_hvp_available {
168        assert_valid_blockspecs(specs, "exact outer derivative order with HVP");
169        match coefficient_cost {
170            0 => ExactOuterDerivativeOrder::Second,
171            _ => ExactOuterDerivativeOrder::Second,
172        }
173    } else {
174        exact_outer_order_from_capability(specs, coefficient_cost)
175    }
176}
177
178/// Realized outer-derivative policy at the current problem size.
179///
180/// Capability (the family can produce exact second-order calculus) controls
181/// whether the Hessian is declared. Runtime cost controls only representation
182/// and staging choices below this layer. Large problems must stay on the exact
183/// analytic Hessian path and use an operator representation when dense assembly
184/// is too expensive; they are not demoted to first-order BFGS here.
185///
186/// `OuterDerivativePolicy` records the family's *capability*, the *predicted
187/// per-eval cost* for both gradient-only and Hessian paths, and exposes the
188/// two policy queries the outer optimizer actually needs:
189///
190/// * [`order_for_evaluation`](Self::order_for_evaluation) — clamp a requested
191///   evaluation order against the policy gate.
192/// * [`declared_hessian_form`](Self::declared_hessian_form) — what shape the
193///   outer-strategy planner should declare to its plan ladder.
194/// * [`should_use_staged_kappa`](Self::should_use_staged_kappa) — auto-route
195///   the κ optimizer through the pilot/polish schedule at large `n`.
196///
197/// All thresholds are *const* — no env vars, no CLI flags. The cost model is
198/// the family's own `coefficient_gradient_cost` / `coefficient_hessian_cost`
199/// scaled by the joint outer-coordinate dimension, with `saturating_mul` so
200/// overflow rounds up to the budget ceiling rather than wrapping silently.
201#[derive(Clone, Copy, Debug)]
202pub struct OuterDerivativePolicy {
203    /// What exact calculus the family advertises in principle.
204    pub capability: ExactOuterDerivativeOrder,
205    /// Predicted per-eval work for one `ValueGradientHessian` evaluation.
206    /// Rounded conservatively *up* via `saturating_mul`. Informational for
207    /// representation and diagnostics; it does not disable Hessian capability.
208    pub predicted_hessian_work: u128,
209    /// Predicted per-eval work for one `ValueAndGradient` evaluation.
210    /// Rounded conservatively *up* via `saturating_mul`.
211    pub predicted_gradient_work: u128,
212    /// True when the family's outer-only paths consume
213    /// [`BlockwiseFitOptions::outer_score_subsample`] and produce
214    /// Horvitz-Thompson-weighted partial sums (i.e. the family overrides
215    /// `log_likelihood_only_with_options`,
216    /// `exact_newton_joint_psi_workspace_with_options`, and any other
217    /// outer-only hooks reached by `evaluate_custom_family_joint_hyper`).
218    ///
219    /// Determines whether the κ optimizer's pilot/polish staging schedule
220    /// engages: when this is `false`, [`Self::should_use_staged_kappa`]
221    /// returns `false` regardless of `n`. Engaging the schedule on a
222    /// family that ignores the subsample is strictly worse than not
223    /// engaging it — the schedule builds a `RowSet::Subsample` and the
224    /// boundary plumbing installs an `OuterScoreSubsample` on options,
225    /// but the family's default outer-only paths fall back to full-data
226    /// sums, so the pilot evaluation costs the same as the polish but
227    /// adds a Vec allocation per eval.
228    ///
229    /// Families that do **not** consume the subsample (default for new
230    /// implementations, including the GAMLSS location-scale families
231    /// today) leave this `false`. Families that do consume (today:
232    /// `BernoulliMarginalSlopeFamily`) override `outer_derivative_policy`
233    /// to set this `true`.
234    pub subsample_capable: bool,
235}
236
237impl OuterDerivativePolicy {
238    /// Per-eval gradient work ceiling above which the κ schedule switches
239    /// to the staged pilot/polish path. At large scale (n ≳ 100 k) even
240    /// the gradient sweep takes minutes per outer iter; subsampling the
241    /// pilot stage cuts that to seconds and leaves the final polish on
242    /// full data to recover the MLE.
243    pub const OUTER_GRADIENT_WORK_BUDGET: u128 = 50_000_000_000;
244
245    /// Pilot subsample auto-engages when full-data `n` exceeds this. Below
246    /// this the κ schedule collapses to a single full-data stage —
247    /// behaviour identical to the pre-P7 path.
248    pub const STAGED_KAPPA_TRIGGER_N: usize = 30_000;
249
250    /// Clamp a requested evaluation order against the policy gate.
251    ///
252    /// Returns the highest order this policy permits for the requested order:
253    /// * `ValueGradientHessian` requested → keep only if `declared_hessian_form`
254    ///   is something other than `Unavailable`.
255    /// * `ValueAndGradient` requested → always permitted (gradient-only is
256    ///   universal).
257    pub fn order_for_evaluation(&self, requested: crate::OuterEvalOrder) -> crate::OuterEvalOrder {
258        use crate::OuterEvalOrder;
259        match requested {
260            // Value-only is universal: every policy can evaluate the bare
261            // objective, so the request passes through unclamped.
262            OuterEvalOrder::Value => OuterEvalOrder::Value,
263            OuterEvalOrder::ValueAndGradient => OuterEvalOrder::ValueAndGradient,
264            OuterEvalOrder::ValueGradientHessian => {
265                if matches!(
266                    self.declared_hessian_form(),
267                    gam_problem::DeclaredHessianForm::Unavailable
268                ) {
269                    OuterEvalOrder::ValueAndGradient
270                } else {
271                    OuterEvalOrder::ValueGradientHessian
272                }
273            }
274        }
275    }
276
277    /// Outer Hessian declaration for the outer-strategy planner.
278    ///
279    /// `Either` ⇔ capability has Hessian. Work estimates select dense vs
280    /// operator assembly later; they must not erase analytic second-order
281    /// capability from the planner.
282    pub fn declared_hessian_form(&self) -> gam_problem::DeclaredHessianForm {
283        use gam_problem::DeclaredHessianForm;
284        if !self.capability.has_hessian() {
285            return DeclaredHessianForm::Unavailable;
286        }
287        DeclaredHessianForm::Either
288    }
289
290    /// True when the κ optimizer should auto-route through the staged
291    /// pilot/polish schedule. Triggers when **either** the data is big
292    /// (`n ≥ STAGED_KAPPA_TRIGGER_N`) **or** the per-eval gradient work
293    /// exceeds `OUTER_GRADIENT_WORK_BUDGET`. The second clause catches
294    /// problems with moderate `n` but very wide design (large `p_total`
295    /// or `psi_dim`) where a single full-data gradient sweep still
296    /// dominates the κ trajectory.
297    pub fn should_use_staged_kappa(&self, n: usize) -> bool {
298        if !self.subsample_capable {
299            // Family does not consume `outer_score_subsample` on its
300            // outer-only paths. Engaging the schedule would build a
301            // pilot `RowSet::Subsample` whose only effect is per-eval
302            // Vec/Arc bookkeeping — the underlying coefficient gradient
303            // would still sum every row. Gate the schedule off until
304            // the family override declares consumption.
305            return false;
306        }
307        n >= Self::STAGED_KAPPA_TRIGGER_N
308            || self.predicted_gradient_work > Self::OUTER_GRADIENT_WORK_BUDGET
309    }
310}
311
312/// Total outer-coordinate dimensionality used by the default policy work
313/// model: `rho_dim + psi_dim`. Each outer evaluation propagates one
314/// directional derivative per outer coordinate through the inner solve.
315#[inline]
316pub(crate) fn outer_coord_dim_for_policy(specs: &[ParameterBlockSpec], psi_dim: usize) -> u128 {
317    let rho_total: u128 = specs
318        .iter()
319        .map(|s| s.penalties.len() as u128)
320        .fold(0u128, |acc, k| acc.saturating_add(k));
321    rho_total.saturating_add(psi_dim as u128)
322}
323
324/// Default predicted-cost model for [`OuterDerivativePolicy`]:
325///
326/// * gradient work ≈ `coefficient_gradient_cost · (rho_dim + psi_dim)`
327/// * Hessian work  ≈ `coefficient_hessian_cost  · (rho_dim + psi_dim)`
328///
329/// Each outer coordinate triggers one analytic directional derivative
330/// through the inner solve; the dense Hessian assembly carries the extra
331/// `O(p_total)` factor already captured by `coefficient_hessian_cost`.
332///
333/// All multiplications saturate so an overflow rounds *up* to the gate
334/// ceiling: we'd rather drop one Hessian evaluation that we could have
335/// afforded than crash on a 600 s eval.
336pub fn default_outer_derivative_policy_costs(
337    specs: &[ParameterBlockSpec],
338    psi_dim: usize,
339    grad_cost: u64,
340    hess_cost: u64,
341) -> (u128, u128) {
342    let k = outer_coord_dim_for_policy(specs, psi_dim);
343    let grad = (grad_cost as u128).saturating_mul(k.max(1));
344    let hess = (hess_cost as u128).saturating_mul(k.max(1));
345    (grad, hess)
346}
347
348/// Default coefficient-space Hessian cost: `Σ_b n_b · p_b²`, summed across
349/// blocks. Represents the work to assemble or apply the dense block-diagonal
350/// inner Hessian once.
351pub fn default_coefficient_hessian_cost(specs: &[ParameterBlockSpec]) -> u64 {
352    specs
353        .iter()
354        .map(|s| {
355            let n = s.design.nrows() as u64;
356            let p = s.design.ncols() as u64;
357            n.saturating_mul(p.saturating_mul(p))
358        })
359        .fold(0u64, |acc, c| acc.saturating_add(c))
360}
361
362/// Joint-coupled coefficient-space Hessian cost: `n · (Σ_b p_b)²`. The honest
363/// per-evaluation work for any family whose row likelihood couples every block
364/// (every observation contributes a rank-`m` outer-product update to the full
365/// joint Hessian over `Σ p_b` coefficients), as opposed to the block-diagonal
366/// `default_coefficient_hessian_cost` which assumes each `X_b' W_b X_b` is
367/// assembled independently.
368///
369/// Used by all GAMLSS, marginal-slope, and joint-latent families. CTN does
370/// not delegate here — it uses its Khatri–Rao factor dimensions internally.
371pub fn joint_coupled_coefficient_hessian_cost(n: u64, specs: &[ParameterBlockSpec]) -> u64 {
372    let p_total: u64 = specs
373        .iter()
374        .map(|s| s.design.ncols() as u64)
375        .fold(0u64, |acc, p| acc.saturating_add(p));
376    n.saturating_mul(p_total.saturating_mul(p_total))
377}
378
379/// Default coefficient-space gradient cost: half the Hessian cost.
380///
381/// The first-order analytic gradient in the unified evaluator runs the same
382/// inner Newton solve as the second-order path but skips the `K`-fold
383/// pairwise Hessian assembly (`B_{j,k}` blocks) and the `K`-fold inner
384/// derivative solves; what remains is the inner solve plus a single
385/// gradient-only sweep through the data. Empirically this is roughly half
386/// the per-evaluation arithmetic of forming the dense Hessian, hence the
387/// `/2` default. Families whose gradient assembly differs structurally
388/// (e.g. matrix-free Hv operators with no dense Hessian assembly to halve)
389/// should override [`CustomFamily::coefficient_gradient_cost`] explicitly.
390pub fn default_coefficient_gradient_cost(specs: &[ParameterBlockSpec]) -> u64 {
391    default_coefficient_hessian_cost(specs) / 2
392}
393
394/// Compute β-block column ranges from a slice of `ParameterBlockSpec`s.
395///
396/// Returns one `Range<usize>` per spec, covering the spec's columns in the
397/// concatenated β vector (i.e. `offset .. offset + p_block` where `p_block =
398/// spec.design.ncols()`). The ranges are non-overlapping, sorted, and their
399/// union covers `0..Σ p_block`.
400///
401/// This is the canonical source of `block_offsets` for every
402/// [`crate::solver::arrow_schur::ArrowSchurSystem`] built for a custom family
403/// (survival, GAMLSS, transformation-normal, latent-survival, marginal-slope,
404/// …). Pass the result to
405/// [`crate::solver::arrow_schur::ArrowSchurSystem::set_block_offsets`] before
406/// calling `solve` or `solve_with_options` whenever the system will use
407/// [`crate::solver::arrow_schur::ArrowSolverMode::InexactPCG`].
408///
409/// Specs with zero columns produce a zero-width range; callers that want to
410/// skip trivial blocks may filter on `r.start < r.end` after calling this
411/// function.
412pub fn block_offsets_from_specs(specs: &[ParameterBlockSpec]) -> Arc<[Range<usize>]> {
413    let mut ranges: Vec<Range<usize>> = Vec::with_capacity(specs.len());
414    let mut cursor = 0usize;
415    for spec in specs {
416        let p = spec.design.ncols();
417        ranges.push(cursor..cursor + p);
418        cursor += p;
419    }
420    Arc::from(ranges.into_boxed_slice())
421}
422
423/// Local trust budget for first-order outer BFGS on log-smoothing parameters.
424///
425/// One unit in `rho = log(lambda)` is an `e`-fold smoothing-parameter change.
426/// Previously this cap was `1.0`, which throttled BFGS to ~1/5 of its
427/// quasi-Newton step on flat REML surfaces (the natural BFGS direction has
428/// `|d|_inf` of ~5 in log-λ for large-scale survival fits). Probes whose
429/// `step_inf > cap` are rejected for free in `OuterFirstOrderBridge::eval_cost`
430/// (returning `BFGS_LINE_SEARCH_REJECT_COST` without running an inner solve),
431/// so a larger cap costs nothing on rejection — it only lets Strong-Wolfe
432/// accept bigger steps that the inner-PIRLS divergence guard can already
433/// validate. `5.0` allows up to `e^5 ≈ 148`-fold smoothing-parameter change
434/// per accepted outer iter, which matches the typical quasi-Newton direction
435/// magnitude while still bounding pathological probes.
436pub const fn first_order_bfgs_loglambda_step_cap(has_outer_hessian: bool) -> Option<f64> {
437    if has_outer_hessian { None } else { Some(5.0) }
438}
439
440pub fn exact_newton_outer_geometry_supports_second_order_solver<F: CustomFamily + ?Sized>(
441    family: &F,
442) -> bool {
443    family.exact_newton_outerobjective() == ExactNewtonOuterObjective::StrictPseudoLaplace
444}
445
446/// Stable public API for installing outer-score subsampling.
447#[derive(Clone)]
448pub struct BlockwiseFitOptions {
449    pub inner_max_cycles: usize,
450    pub inner_tol: f64,
451    pub outer_max_iter: usize,
452    pub outer_tol: f64,
453    /// Optional override for the OUTER smoothing optimizer's
454    /// *relative-cost-decrease* convergence stop, decoupled from `outer_tol`.
455    ///
456    /// The outer convergence test derives BOTH the absolute projected-gradient
457    /// floor (`max(outer_tol, n·1e-9)`) AND the relative-cost stop
458    /// (`rel_cost = outer_tol`) from the single `outer_tol`. A caller that needs
459    /// a *tight absolute floor* to resolve λ to the genuine REML optimum at
460    /// large `n` (where the floor is `n·1e-9`) is then forced to also accept a
461    /// *tight rel-cost stop*, which on a flat REML ridge never trips and grinds
462    /// the optimizer to `outer_max_iter` — dozens of surplus O(D·p³)
463    /// Laplace-derivative outer iterations (the #1082 multinomial
464    /// smooth-by-factor wall-clock blow-up). When `Some(r)`, the rel-cost stop
465    /// uses `r` while the absolute floor keeps using `outer_tol`, so accuracy
466    /// (absolute floor) and perf (loose rel-cost) are selected independently.
467    /// `None` preserves the legacy coupling (`rel_cost = outer_tol`) for every
468    /// existing caller byte-for-byte.
469    pub outer_rel_cost_tol: Option<f64>,
470    /// Lower box bound for smoothing coordinates ρ = log λ.
471    ///
472    /// The default preserves the historical custom-family domain
473    /// `λ >= exp(-10)`. Families with known calibration failures at the
474    /// near-zero penalty boundary can raise this lower bound without changing
475    /// the upper effective-df cap or adding family-specific branches inside the
476    /// optimizer.
477    pub rho_lower_bound: f64,
478    pub minweight: f64,
479    /// Optional seed for transient solver damping. The default is zero and the
480    /// default [`RidgePolicy`] excludes every damping shift from the quadratic
481    /// objective, penalty determinant, and Laplace Hessian. A nonzero value is
482    /// therefore a numerical step-control request unless a caller explicitly
483    /// selects an objective-including policy.
484    pub ridge_floor: f64,
485    /// Shared ridge semantics used by solve/quadratic/logdet terms. Defaults to
486    /// solver-only damping so the converged estimand is the stationary point of
487    /// the undamped statistical objective.
488    pub ridge_policy: RidgePolicy,
489    /// If true, outer smoothing optimization uses a Laplace/REML-style objective:
490    ///   -loglik + penalty + 0.5(log|H| - log|S|_+)
491    /// where H is blockwise working curvature and S is blockwise penalty.
492    pub use_remlobjective: bool,
493    /// If false, the outer smoothing optimizer uses exact gradients but does
494    /// not request an analytic outer Hessian from the family.
495    pub use_outer_hessian: bool,
496    /// If false, skip post-fit joint covariance assembly.
497    pub compute_covariance: bool,
498    /// Shared cap engaged during seed screening so cost-only evaluations can
499    /// stop inner iterations early without affecting the full solve.
500    pub screening_max_inner_iterations: Option<Arc<AtomicUsize>>,
501    /// Shared cap engaged during regular outer iterations. Unlike screening,
502    /// this is only a budget: capped solves still have to earn the ordinary
503    /// KKT certificate before derivatives may be exposed.
504    pub outer_inner_max_iterations: Option<Arc<AtomicUsize>>,
505    /// Optional line-search objective ceiling for lazy log-likelihood-only
506    /// evaluations. Families whose per-row log-likelihood contributions are
507    /// non-positive may stop once the partial negative log-likelihood is already
508    /// above this ceiling, because the unvisited rows cannot improve the trial
509    /// objective enough to be accepted. Default `None` preserves exact full-sum
510    /// behavior and is the only mode used outside backtracking rejection tests.
511    pub early_exit_threshold: Option<f64>,
512    /// Stable public API for installing outer-score subsampling.
513    ///
514    /// Optional stratified row subsample used by outer-only score/gradient
515    /// passes. When `Some(s)`, outer score/gradient hot loops should iterate
516    /// only over `s.rows` and multiply each contribution by that row's
517    /// Horvitz-Thompson inverse-inclusion weight. Inner-PIRLS and final
518    /// covariance passes always run on the full data, so this field is
519    /// consulted only by outer-only call sites. Default `None` preserves the
520    /// full-data behavior. Wrapping in `Arc` keeps `Clone` cheap across the
521    /// many places `BlockwiseFitOptions` is duplicated per-eval.
522    pub outer_score_subsample: Option<Arc<crate::OuterScoreSubsample>>,
523    /// Gate for marginal-slope families to auto-derive a stratified
524    /// outer-score subsample at large scale (see
525    /// [`crate::families::marginal_slope_shared::auto_outer_score_subsample`]).
526    ///
527    /// **Default `true`.** Auto-subsampling makes the early rho-gradient
528    /// evaluations unbiased stochastic estimators with bounded relative
529    /// variance (≈ 1 % at the conservative defaults), then the family switches
530    /// back to full-data gradients for the remaining outer iterations. That
531    /// keeps large marginal-slope fits fast during the high-motion part of the
532    /// trajectory while preserving the default tight `outer_tol` polish on
533    /// exact gradients. For small datasets the auto path declines to install a
534    /// mask and the fit remains full-data throughout.
535    ///
536    /// When `outer_score_subsample` is already `Some(...)` the auto
537    /// path is bypassed entirely (caller-provided masks always win).
538    pub auto_outer_subsample: bool,
539    /// Outer-evaluation context populated by the smoothing optimizer at
540    /// the top of each real outer derivative evaluation. Used by
541    /// auto-subsample install paths to key the stratified mask on the
542    /// outer ρ rather than the inner β proxy: during the inner trust-
543    /// region / coefficient line search β changes on every trial step,
544    /// so keying on β re-fires phase prints (and re-shuffles the mask)
545    /// inside a single outer eval. Keying on (rho, eval_id) instead
546    /// keeps the mask stable across the inner Newton at one ρ, and
547    /// suppresses auto-subsample entirely on inner trial evaluations via
548    /// the [`EvalScope::InnerCoefficient`] tag set by
549    /// [`coefficient_line_search_options`].
550    ///
551    /// `None` preserves legacy behavior (no context — install paths fall
552    /// back to "no auto-subsample"). Default `None`.
553    pub outer_eval_context: Option<OuterEvalContext>,
554    /// Optional persistent warm-start cache session. When `Some`, the
555    /// outer smoothing optimizer consults the on-disk cache before
556    /// starting (to seed θ from the last accepted iterate) and writes
557    /// checkpoints + a final entry on completion. When `None`, the fit
558    /// runs cold and writes nothing — the default for unit tests and
559    /// any caller that pinned a deterministic optimum.
560    ///
561    /// Callers that need cross-process reuse must supply the session
562    /// explicitly; ordinary workflow fits leave this empty so refit-heavy
563    /// loops do not touch the shared on-disk store.
564    pub cache_session: Option<Arc<gam_runtime::warm_start::Session>>,
565    /// Optional mirror sessions that receive a copy of the final-result
566    /// finalize() write. Callers can use this to broadcast a converged ρ to
567    /// additional keyspace(s) so future fits with related structure can
568    /// warm-start from this run. Writes still pass through the session rate
569    /// limiter, so mirroring checkpoints does not add unbounded I/O.
570    pub cache_mirror_sessions: Vec<Arc<gam_runtime::warm_start::Session>>,
571    /// Optional bundle of cross-block (full-width) penalties, paired with
572    /// their current `log λ` values from the outer ρ vector. When `Some`,
573    /// the inner joint-Newton primitives add the contributions
574    ///
575    /// * objective: `½ Σ_j exp(ρ_j) βᵀ S_j β`
576    /// * gradient:  `Σ_j exp(ρ_j) S_j β`
577    /// * Hessian:   `Σ_j exp(ρ_j) S_j`
578    ///
579    /// in addition to the per-block penalty stack assembled from
580    /// `ParameterBlockSpec.penalties`. The per-block path is unchanged.
581    /// `None` preserves legacy behaviour for every existing caller.
582    pub joint_penalties: Option<Arc<crate::JointPenaltyBundle>>,
583    /// Precision labels whose per-block penalty components are INDEPENDENT
584    /// Gaussian prior factors (the hierarchical coefficient-group priors from
585    /// `realize_coefficient_groups_for_custom_family`; copy its
586    /// `independent_prior_factor_labels` here), as opposed to additive pieces
587    /// of one Gaussian smooth prior.
588    ///
589    /// The distinction matters only for the evidence normalizer. A
590    /// multi-penalty smooth is ONE Gaussian with precision `Σ_k λ_k S_k`, so
591    /// its normalizer is the coalesced `½ log|Σ_k λ_k S_k|₊`. A product of
592    /// independent group factors `∏_k N(0, (λ_k S_k)⁻¹)` instead contributes
593    /// `Σ_k ½ (rank S_k · log λ_k + log|S_k|₊)` — and the two disagree
594    /// exactly when factors overlap (two factors with precision λ on one
595    /// scalar coefficient carry `λ^{1/2}·λ^{1/2} = λ`, but the coalesced form
596    /// `½ log(2λ)` loses `½ log λ` up to constants), which biases the outer
597    /// ρ-posterior and the hierarchical Gamma precision exponent. Labels
598    /// listed here get the per-factor normalizer in the outer objective.
599    ///
600    /// **Default empty** — every penalty coalesces per block, the correct
601    /// convention for ordinary (tensor/multi-penalty) smooths.
602    pub independent_prior_factor_labels: Vec<String>,
603    /// Whether the outer smoothing optimizer screens the explicit
604    /// `initial_rho` seed through the seed-screening cascade before the
605    /// solver starts.
606    ///
607    /// **Default `true`** — the general path benefits from ranking the
608    /// initial seed against the generated exploration seeds via cheap
609    /// capped proxy fits.
610    ///
611    /// A caller sets this `false` when `initial_rho` is already the correct,
612    /// identified optimum for its regime so that re-screening it adds only
613    /// cost. The survival location-scale constant-scale (parametric-AFT)
614    /// path uses this: its time-warp ρ seed is pinned AT the inner ρ box
615    /// bound (the affine-baseline limit), where the REML/LAML profile is a
616    /// dead-flat unidentified ridge. Running the screening cascade there
617    /// drives each proxy fit (and, when every capped stage collapses to
618    /// non-finite cost, the uncapped final stage) into a full inner solve on
619    /// the near-singular flat Hessian — the source of the multi-minute
620    /// no-iteration-log stall (#736, #735, #721). Skipping screening lets the
621    /// already-correct seed flow straight to the outer solver, which certifies
622    /// box-constraint stationarity at iteration 0. Genuinely flexible regimes
623    /// (smooth scale / spatial) leave this `true` and keep full screening.
624    pub screen_initial_rho: bool,
625    /// Set ONLY while the inner solve is invoked from the seed-screening proxy
626    /// (`custom_family_seed_screening_proxy_labeled`), which RANKS candidate
627    /// seeds by their penalized objective and never produces the final fit.
628    ///
629    /// When `true`, the inner joint-Newton skips the full per-axis
630    /// Jeffreys/Firth curvature (`custom_family_joint_jeffreys_term`'s
631    /// `for k in 0..p` directional-derivative loop, O(p · per-axis-Hdot) per
632    /// cycle), keeping ONLY the cheap value-only Jeffreys term
633    /// (`custom_family_joint_jeffreys_value`, one reduced-info eigendecomposition)
634    /// in the screening score. The per-axis gradient/curvature is what the inner
635    /// Newton step needs to *converge* a near-separating fit; the screening proxy
636    /// is capped and only ranks, so it does not need step convergence — it needs
637    /// a finite, separation-aware score cheaply. For a K-block coupled family
638    /// (Dirichlet/multinomial) each per-axis directional derivative is itself
639    /// O(K²·n·p), so running the full term for every cascade candidate over the
640    /// joint width `p` is the wrong cost class and made the coupled fit
641    /// non-completing during screening alone (gam#729/#808). The actual fit
642    /// (after a seed is selected) runs with this `false`, so the load-bearing
643    /// Firth curvature is fully present where it matters.
644    ///
645    /// **Default `false`** — only the screening proxy sets it `true`.
646    pub seed_screening: bool,
647}
648
649pub const DEFAULT_CUSTOM_FAMILY_INNER_MAX_CYCLES: usize = 1200;
650
651impl Default for BlockwiseFitOptions {
652    fn default() -> Self {
653        Self {
654            // Large-scale custom-family marginal-slope fits can have a
655            // long, monotone joint-Newton tail: objective and step size keep
656            // shrinking, but the exact KKT residual may need several hundred
657            // additional cycles after the old 300-cycle cap. The outer
658            // REML/LAML derivative path is correct only at a stationary inner
659            // mode, so a merely descended iterate must not be accepted as
660            // converged. Use a production-sized cap by default and rely on the
661            // KKT/objective certificates to exit early for well-conditioned
662            // Gaussian, logistic, and small-n fits.
663            inner_max_cycles: DEFAULT_CUSTOM_FAMILY_INNER_MAX_CYCLES,
664            inner_tol: 1e-6,
665            outer_max_iter: 60,
666            outer_tol: 1e-5,
667            outer_rel_cost_tol: None,
668            rho_lower_bound: -10.0,
669            minweight: CUSTOM_FAMILY_WEIGHT_FLOOR,
670            // Conditioning is solver state, not a coefficient prior. Start at
671            // the exact Hessian (zero shift); rank/curvature-aware damping may
672            // regularize rejected Newton steps, but none of it enters the
673            // objective or its derivatives and convergence is certified on the
674            // undamped KKT residual.
675            ridge_floor: 0.0,
676            ridge_policy: RidgePolicy::solver_only(),
677            use_remlobjective: true,
678            // Default ON: families expose exact outer Hessians whenever their
679            // analytic dense or operator representation is implemented.
680            use_outer_hessian: true,
681            compute_covariance: false,
682            screening_max_inner_iterations: None,
683            outer_inner_max_iterations: None,
684            seed_screening: false,
685            early_exit_threshold: None,
686            outer_score_subsample: None,
687            auto_outer_subsample: true,
688            outer_eval_context: None,
689            cache_session: None,
690            cache_mirror_sessions: Vec::new(),
691            joint_penalties: None,
692            independent_prior_factor_labels: Vec::new(),
693            screen_initial_rho: true,
694        }
695    }
696}
697
698#[cfg(test)]
699mod tests {
700    use super::*;
701    use gam_linalg::matrix::DesignMatrix;
702    use ndarray::Array2;
703
704    fn make_spec(nrows: usize, ncols: usize) -> ParameterBlockSpec {
705        ParameterBlockSpec {
706            design: DesignMatrix::from(Array2::<f64>::zeros((nrows, ncols))),
707            ..ParameterBlockSpec::defaults()
708        }
709    }
710
711    // -----------------------------------------------------------------------
712    // default_coefficient_hessian_cost
713    // -----------------------------------------------------------------------
714
715    #[test]
716    fn hessian_cost_empty_specs_is_zero() {
717        assert_eq!(default_coefficient_hessian_cost(&[]), 0);
718    }
719
720    #[test]
721    fn hessian_cost_single_block() {
722        // n=10, p=3 → 10 * 3^2 = 90
723        let spec = make_spec(10, 3);
724        assert_eq!(default_coefficient_hessian_cost(&[spec]), 90);
725    }
726
727    #[test]
728    fn hessian_cost_two_blocks_sum() {
729        // n=10, p=3 → 90; n=5, p=4 → 5*16=80; total=170
730        let specs = [make_spec(10, 3), make_spec(5, 4)];
731        assert_eq!(default_coefficient_hessian_cost(&specs), 170);
732    }
733
734    // -----------------------------------------------------------------------
735    // default_coefficient_gradient_cost
736    // -----------------------------------------------------------------------
737
738    #[test]
739    fn gradient_cost_is_half_hessian_cost() {
740        let specs = [make_spec(10, 3)];
741        let hess = default_coefficient_hessian_cost(&specs);
742        assert_eq!(default_coefficient_gradient_cost(&specs), hess / 2);
743    }
744
745    // -----------------------------------------------------------------------
746    // joint_coupled_coefficient_hessian_cost
747    // -----------------------------------------------------------------------
748
749    #[test]
750    fn joint_coupled_cost_empty_specs_is_zero() {
751        assert_eq!(joint_coupled_coefficient_hessian_cost(100, &[]), 0);
752    }
753
754    #[test]
755    fn joint_coupled_cost_two_blocks() {
756        // n=10, p_total = 3+4=7 → 10 * 49 = 490
757        let specs = [make_spec(99, 3), make_spec(99, 4)];
758        assert_eq!(joint_coupled_coefficient_hessian_cost(10, &specs), 490);
759    }
760
761    // -----------------------------------------------------------------------
762    // block_offsets_from_specs
763    // -----------------------------------------------------------------------
764
765    #[test]
766    fn block_offsets_empty_is_empty() {
767        let offsets = block_offsets_from_specs(&[]);
768        assert_eq!(offsets.len(), 0);
769    }
770
771    #[test]
772    fn block_offsets_three_blocks() {
773        // p = [2, 3, 1] → [0..2, 2..5, 5..6]
774        let specs = [make_spec(1, 2), make_spec(1, 3), make_spec(1, 1)];
775        let offsets = block_offsets_from_specs(&specs);
776        assert_eq!(&offsets[0], &(0..2));
777        assert_eq!(&offsets[1], &(2..5));
778        assert_eq!(&offsets[2], &(5..6));
779    }
780
781    #[test]
782    fn block_offsets_zero_width_block() {
783        // p = [2, 0, 1] → [0..2, 2..2, 2..3]
784        let specs = [make_spec(1, 2), make_spec(1, 0), make_spec(1, 1)];
785        let offsets = block_offsets_from_specs(&specs);
786        assert_eq!(&offsets[0], &(0..2));
787        assert_eq!(&offsets[1], &(2..2));
788        assert_eq!(&offsets[2], &(2..3));
789    }
790
791    // -----------------------------------------------------------------------
792    // first_order_bfgs_loglambda_step_cap
793    // -----------------------------------------------------------------------
794
795    #[test]
796    fn step_cap_without_outer_hessian_is_some_five() {
797        assert_eq!(first_order_bfgs_loglambda_step_cap(false), Some(5.0));
798    }
799
800    #[test]
801    fn step_cap_with_outer_hessian_is_none() {
802        assert_eq!(first_order_bfgs_loglambda_step_cap(true), None);
803    }
804
805    #[test]
806    fn default_custom_family_objective_is_coefficient_ridge_free() {
807        let options = BlockwiseFitOptions::default();
808        assert_eq!(options.ridge_floor, 0.0);
809        assert!(options.ridge_policy.rho_independent);
810        assert!(!options.ridge_policy.include_quadratic_penalty);
811        assert!(!options.ridge_policy.include_penalty_logdet);
812        assert!(!options.ridge_policy.include_laplacehessian);
813    }
814}