Loading...
Searching...
No Matches
StableBasis.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4//
5// Hilbert-Schmidt SVD (HS-SVD) stable basis for the squared-exponential /
6// Gaussian kernel -- the conditioning fix that makes the working interpolation
7// matrix O(1)-conditioned INDEPENDENT of the nugget (the nugget only floors
8// cond at 1/eps ~ 1e4; the stable basis removes the ill-conditioning at the
9// representation level).
10//
11// Algorithm (validated numerically in scripts/hssvd_prototype.py: cond(K)
12// 1.8e18 -> cond(Psi) 1.000, interpolant identical to 5e-9):
13// K(X,X) = Phi Lambda Phi^T = A A^T, A = Phi diag(sqrt(lambda)) (M x N)
14// thin SVD A = U S V^T
15// stable basis Psi(x) = A(x) V S^{-1} (= U at the nodes, orthonormal)
16// The nearest orthonormal polar factor of the retained columns is computed
17// only in StableBasisND::factorize. The dual-kernel paths and
18// factorizeGPCartesian keep the SVD factor.
19// drop the Mercer tail S_i <= sv_rtol * S_0 (else 1/S reinjects cond)
20// The eigenfunctions phi_n / eigenvalues lambda_n are the Fasshauer-McCourt
21// Gaussian Mercer pair (symbolically verified in scripts/derive_hssvd_gradient
22// .py), evaluated via a stably-scaled Hermite recurrence (numpy hermval
23// overflows for the large n the flat regime needs).
24//
25// References:
26// Fasshauer & McCourt, "Stable Evaluation of Gaussian RBF Interpolants",
27// SIAM J. Sci. Comput. 34(2):A737-A762, 2012. doi:10.1137/110824784
28// Fornberg, Larsson & Flyer, "Stable Computations with Gaussian RBF",
29// SIAM J. Sci. Comput. 33(2):869-892, 2011. doi:10.1137/09076756X
30// Fasshauer & McCourt, "Kernel-based Approximation Methods using MATLAB",
31// World Scientific, 2015. doi:10.1142/9335
32
33#ifndef GPR_ML_GP_STABLE_BASIS_H_
34#define GPR_ML_GP_STABLE_BASIS_H_
35
36#include <Eigen/Core>
37#include <algorithm>
38#include <cmath>
39#include <cstdlib>
40#include <limits>
41#include <memory>
42#include <mutex>
43#include <stdexcept>
44#include <string>
45#include <vector>
46
50
51namespace gpr {
52namespace linalg {
53class BackendContext;
54}
55
56namespace detail {
57
58[[nodiscard]] bool useGpuEigensolverForProcessCount(int process_count) noexcept;
59[[nodiscard]] bool useRankBlockKernelAppend(
60 bool gpu_full_eigensolver_available) noexcept;
61[[nodiscard]] bool gpuFullKernelEigensolverAvailable() noexcept;
62[[nodiscard]] bool gpuFullKernelEigensolverAvailable(
63 const linalg::MpiContext& process_group) noexcept;
64
65} // namespace detail
66
68 Eigen::VectorXd alpha;
69 Eigen::VectorXd reduced;
70};
71
73 double lower = 0.0;
74 double upper = 0.0;
75};
76
82
94 double requested = 0.0;
95 double floored = 0.0;
96 double certificate_gap = 0.0;
97 double interval = 0.0;
98 bool floor_active = false;
99 bool certified = false;
100};
101
102// 1D HS-SVD stable basis for K(x,z) = exp(-eps^2 (x-z)^2). The d-dimensional
103// separable SE kernel composes these per descriptor dimension via the
104// tensor-product eigenfunctions (build-out); this 1D core is the validated
105// kernel of the algorithm.
107public:
108 // Factorize on training nodes x (length M). eps = shape parameter
109 // (eps^2 = inv_l2 / 2 for the SexpatCF per-pairtype length scale); alpha =
110 // global scale of the Gaussian weight (a tuning knob, O(1)); n_extra =
111 // eigenfunctions beyond M (N = M + n_extra); sv_rtol drops the Mercer tail.
112 void factorize(const Eigen::VectorXd& x, double eps, double alpha,
113 int n_extra = 20, double sv_rtol = 1e-13);
114
115 // Solve Psi_X b = y in least-squares sense (Psi_X is M x rank, consistent
116 // to Mercer-truncation accuracy). Returns the stable-basis coefficients b.
117 Eigen::VectorXd solve(const Eigen::VectorXd& y) const;
118
119 // Evaluate the stable basis at new points: Psi(x*) = A(x*) V S^{-1}.
120 Eigen::MatrixXd evalBasis(const Eigen::VectorXd& xstar) const;
121
122 // Predict s(x*) = Psi(x*) b.
123 Eigen::VectorXd predict(const Eigen::VectorXd& xstar,
124 const Eigen::VectorXd& b) const;
125
126 double conditionNumber() const; // cond(Psi_X); ~1 when stable
127 int rank() const
128 {
129 return rank_;
130 }
131
132 // Eigenfunctions phi_n(x) and their shape-parameter (hyperparameter)
133 // derivative d phi_n/d eps, evaluated together via the normalized
134 // recurrence carried in parallel. Closed forms verified in
135 // scripts/derive_hssvd_eps_gradient.py. Needed for the tensor dA path:
136 // dA = dPhi diag(sqrt_lam) + Phi diag(d sqrt_lam/d eps).
137 void eigenfunctionsWithEpsDerivative(const Eigen::VectorXd& x,
138 Eigen::MatrixXd& Phi,
139 Eigen::MatrixXd& dPhi_deps) const;
140 // d sqrt(lambda_n)/d eps, length N.
141 Eigen::VectorXd sqrtLambdaEpsDerivative() const;
142 const Eigen::VectorXd& sqrtLambda() const
143 {
144 return sqrt_lam_;
145 }
146
147private:
148 // Hermite-Gaussian eigenfunctions phi_n(x), n=0..N-1, at the points x.
149 // Stably-scaled three-term recurrence (avoids 2^n n! overflow).
150 Eigen::MatrixXd eigenfunctions(const Eigen::VectorXd& x) const;
151
152 double eps_ = 0.0;
153 double alpha_ = 1.0;
154 double beta_ = 1.0;
155 double delta2_ = 0.0;
156 int N_ = 0;
157 int M_ = 0;
158 int rank_ = 0;
159 Eigen::VectorXd sqrt_lam_; // sqrt(lambda_n), length N
160 Eigen::MatrixXd W_; // V S^{-1}, N x rank
161 Eigen::MatrixXd Psi_X_; // A(X) W, M x rank (= U[:, kept])
162};
163
164// d-dimensional, GRADIENT-ENHANCED HS-SVD stable basis for the separable SE
165// kernel K(x,z) = prod_k exp(-eps_k^2 (x_k - z_k)^2) over d descriptor
166// dimensions (per-dimension shape eps_k = the per-pairtype length scale of
167// SexpatCF). The Mercer pair is the tensor product of the 1D pairs; gradient
168// observations contribute design rows d/dx_j Phi_alpha(x) sqrt(lambda_alpha)
169// stacked with the energy rows Phi_alpha(x) sqrt(lambda_alpha), so the SAME
170// thin-SVD stable basis conditions the whole [[K_EE,K_Eg],[K_gE,K_gg]] system.
171// Validated in scripts/hssvd_gradient_prototype.py (cond 6.4e13 -> 1.0,
172// off-node energy 1.5e-6 / gradient 4.4e-6) and symbolically in
173// scripts/derive_hssvd_gradient.py (A_full A_full^T == K_full to 2.2e-16).
178double looVarianceCalibrationFactor(const Eigen::VectorXd& alpha,
179 const Eigen::VectorXd& inv_diag);
180
183bool looCalibrationIsUnityFromCholeskyDiagonal(const Eigen::VectorXd& alpha,
184 const Eigen::VectorXd& diagonal);
185
193[[nodiscard]] bool stabilizePosteriorCovariance(Eigen::MatrixXd& covariance);
194
196public:
198 explicit StableBasisND(std::shared_ptr<linalg::BackendContext> context);
202 void setChopNoiseVariance(double sigma2) noexcept
203 {
204 chop_sigma2_ = sigma2;
205 }
206 [[nodiscard]] double chopNoiseVariance() const noexcept
207 {
208 return chop_sigma2_;
209 }
210
211 [[nodiscard]] double droppedEigenvalueMax() const noexcept
212 {
213 return dropped_s2_max_;
214 }
215
220 [[nodiscard]] double covarianceComplementEigenvalue() const noexcept
221 {
222 return dropped_s2_max_;
223 }
224
226 [[nodiscard]] double complementWeight(double sigma2) const noexcept
227 {
228 // A full orthogonal basis has no complement. Its rounded projector
229 // residual must not be amplified by the inverse noise variance.
230 if (Psi_.cols() == Psi_.rows()) return 0.0;
231 // The exact weight of a dropped component in (K + sigma2 I)^-1 lies
232 // in [1/(s2_drop_max + sigma2), 1/sigma2]; the lower end never
233 // overshoots the explicit posterior and is exact to
234 // s2_drop_max/sigma2 relative. It applies to the targets too: the
235 // observation noise lives in the null directions of K, and the
236 // weights carry y_null/sigma2 exactly as the dense factor does.
237 // Callers form the complement from residual vectors, never from a
238 // difference of squared norms, so rounding in a null direction
239 // enters as norm(r)^2 ~ eps^2 and not as eps/sigma2.
240 const double d = dropped_s2_max_ + sigma2;
241 return (d > 0.0 && std::isfinite(d)) ? 1.0 / d : 0.0;
242 }
243
258 [[nodiscard]] double covarianceComplementWeight(
259 double sigma2) const noexcept
260 {
261 if (Psi_.cols() == Psi_.rows()) return 0.0;
262 // maxCoeff rather than Sr_(0): the bound must not depend on every
263 // factorization path storing the spectrum in descending order.
264 const double s_max = Sr_.size() > 0 ? Sr_.cwiseAbs().maxCoeff() : 0.0;
265 const double s2_max = std::isfinite(s_max) ? s_max * s_max : 0.0;
266 const double resolution =
267 static_cast<double>(std::max<Eigen::Index>(1, Psi_.rows())) *
268 std::numeric_limits<double>::epsilon() * s2_max;
269 const double d = std::max(dropped_s2_max_, resolution) + sigma2;
270 return (d > 0.0 && std::isfinite(d)) ? 1.0 / d : 0.0;
271 }
272 void recordDroppedSpectrum(const Eigen::VectorXd& S);
276 static std::size_t factorizationCount() noexcept;
277 // Factorize on training points X (M x d). eps = per-dimension shape (length
278 // d); alpha = Gaussian-weight global scale (O(1)); max_degree = graded
279 // total-degree truncation of the tensor multi-index set (abs(alpha) <=
280 // max_degree); gradient_enhanced stacks the d gradient rows per point;
281 // sv_rtol drops the Mercer tail. Observation order: M energy rows, then for
282 // each point its d gradient-component rows (matches a [E ; G] target).
283 // The nearest orthonormal polar factor of the retained columns is
284 // computed only in this function. factorizeGPCartesian and the dual
285 // kernel paths keep the SVD factor.
286 void factorize(const Eigen::MatrixXd& X, const Eigen::VectorXd& eps,
287 double alpha, int max_degree, bool gradient_enhanced,
288 double sv_rtol = 1e-13);
289
290 // Factorize for the PRODUCTION gradient-enhanced GP, whose gradient
291 // observations are CARTESIAN forces, not descriptor-space gradients. The
292 // separable SE kernel K = overall_scale * prod_k exp(-eps_k^2 (q_k-q'_k)^2)
293 // over the inverse-distance descriptors q matches SexpatCF exactly
294 // (eps_k = 1/l_pairtype(k), overall_scale = magnSigma2; proven in
295 // scripts/derive_hssvd_sexpat_equiv.py). The energy design row is
296 // Phi(q_i) diag(sqrt(lambda)); a Cartesian-force row (config i, component
297 // c) is the descriptor-gradient feature contracted with the descriptor
298 // Jacobian column:
299 // sum_k (d/dq_k Phi(q_i)) sqrt(lambda) * J_i(k, c), J_i = dq/dx.
300 // X = descriptor matrix (M x d); jacobians[i] = (d x C). Every
301 // observation must provide the same positive number C of complete
302 // gradient channels.
303 //
304 // Gradient-row order:
305 // component_major=false (default): M energy rows, then per config its
306 // C_i gradient rows -- [E ; (G_0 of cfg0..), (G_1 of cfg0..), ...].
307 // component_major=true: M energy rows, then per component across all
308 // configs -- [E ; G_{*,0} ; G_{*,1} ; ...], matching the production GP
309 // target (assembleVectorFromEnergyAndGradient ships G column-major) and
310 // the a_unpermuted layout. Requires every jacobians[i] to share the
311 // same column count C.
312 // sketch_size > 0 selects the randomized range finder (Halko-Martinsson-
313 // Tropp, SIAM Review 2011, Alg 4.4 + 5.1) instead of the dense BDCSVD: it
314 // sketches the N-mode design to an nobs x sketch_size range basis (one pass
315 // + n_power_iter subspace iterations), giving the same top-rank Psi/Sr/W to
316 // the truncation tolerance WITHOUT forming the Gram A A^T (conditioning
317 // preserved). Cheaper when the numerical rank << min(nobs, N); the sketched
318 // GEMMs (A*Omega, Q^T A) are the distribution surface for the ScaLAPACK
319 // path. sketch_size auto-expands (doubling, capped at nobs) if the
320 // recovered rank saturates the sketch. sketch_size <= 0 keeps the
321 // deterministic SVD. mode_prune_rtol > 0 applies the Mercer /
322 // Karhunen-Loeve truncation up front: graded multi-indices whose
323 // sqrt(lambda) falls below mode_prune_rtol * max_k sqrt(lambda_k) are
324 // dropped before the eigenfunction-tensor build, since their design columns
325 // (scaled by sqrt(lambda)) sit below the SVD tail and cannot yield a
326 // retained singular vector. This cuts the build (the dominant decompose
327 // cost) and the SVD from N modes to the numerically significant few (e.g.
328 // 79/2925 on 01_hcn) without changing the retained rank / singular values.
329 // 0 disables.
330 void factorizeGPCartesian(const Eigen::MatrixXd& X,
331 const Eigen::VectorXd& eps, double alpha,
332 double overall_scale, int max_degree,
333 const std::vector<Eigen::MatrixXd>& jacobians,
334 bool component_major = false,
335 double sv_rtol = 1e-13, int sketch_size = 0,
336 int n_power_iter = 2,
337 double mode_prune_rtol = 0.0,
338 double sv_abs_tol = 0.0);
339
340 // Factorize a high-dimensional descriptor kernel whose training descriptors
341 // lie in a low-dimensional affine span. U is the coordinate matrix in that
342 // span (M x r). jac_tangent[i] is B^T dq_i/dx and jac_normal[i] is
343 // (I-BB^T)dq_i/dx in the original descriptor coordinates. The design uses
344 // the r-dimensional Mercer tensor basis for the affine span plus explicit
345 // first normal-derivative columns, preserving the full descriptor-space
346 // Gaussian energy/force covariance without enumerating a d-dimensional
347 // tensor product.
348 void factorizeGPCartesianAffine(
349 const Eigen::MatrixXd& U, const Eigen::VectorXd& eps, double alpha,
350 double overall_scale, int max_degree,
351 const std::vector<Eigen::MatrixXd>& jac_tangent,
352 const std::vector<Eigen::MatrixXd>& jac_normal,
353 bool component_major = false, double sv_rtol = 1e-13,
354 int sketch_size = 0, int n_power_iter = 2, double mode_prune_rtol = 0.0,
355 double sv_abs_tol = 0.0);
356
357 // Dual-kernel HS-SVD factorization. sv_chop_tol > 0 enables an
358 // Aurentz-Trefethen standardChop plateau cutoff (doi:10.1145/2998442) on
359 // the singular spectrum as an experimental rank policy; sv_rtol/sv_abs_tol
360 // remain the exact-path truncation controls.
361 void factorizeKernel(const Eigen::MatrixXd& kernel, double sv_rtol = 1e-13,
362 double sv_abs_tol = 0.0, double sv_chop_tol = 0.0);
363 // Exact dual-kernel factorization: the full spectrum (cuSOLVER when a GPU
364 // is usable, else the host Eigen eigensolver), with the arrowhead border
365 // extension and the value-range cut. The name is the configuration key's;
366 // the host path no longer calls LAPACK DSYEVR, whose OpenBLAS kernels
367 // changed the eigenvectors with OPENBLAS_CORETYPE. Returns false when the
368 // eigensolver fails; callers keep factorizeKernel as the fallback.
369 bool factorizeKernelLapackRrr(const Eigen::MatrixXd& kernel,
370 double sv_rtol = 1e-13,
371 double sv_abs_tol = 0.0,
372 double sv_chop_tol = 0.0,
373 bool allow_value_range = false);
374 // Objective factorization from the ALREADY-noisy kernel C = K + sigma2 I.
375 // Eigendecomposes C directly and retains the full noisy spectrum
376 // mu_i = eig(C)_i (>= sigma2 for a PSD signal kernel). The signal singular
377 // values Sr_(i) = sqrt(max(0, mu_i - sigma2)) and Psi columns are stored
378 // for the shrink/predict paths, but logDetNoisy / noisyPosteriorWeights /
379 // solveNoisy use mu_i directly so the marginal-likelihood logdet and
380 // quadratic form never form the cancelling difference mu_i - sigma2. This
381 // is the precision-preserving path the hyperparameter objective needs to
382 // match the Cholesky reference on ill-conditioned (near-duplicate) C.
383 // No mode is dropped: the full orthonormal eigenbasis of C is retained, so
384 // the quadratic form and logdet are exact eigen-contractions.
385 void factorizeNoisyKernel(const Eigen::MatrixXd& noisy_kernel,
386 double sigma2);
387 // Same host eigensolver as factorizeKernelLapackRrr (Eigen's
388 // self-adjoint solver, or cuSOLVER at one rank when a GPU is present).
389 // The name is historical. Returns false when the eigensolver fails.
390 bool factorizeNoisyKernelLapackRrr(const Eigen::MatrixXd& noisy_kernel,
391 double sigma2);
392#ifdef GPR_LINALG_SCALAPACK
393 // Distributed exact dual-kernel factorization. The order threshold is
394 // kMinDistributedSymmetricEigenOrder (1). At or above that order, with
395 // more than one rank and unconstrained library reductions enabled, the
396 // eigensolve is PDSYEV, then PDSYEVR or PDSYEVD, or SLATE heev. Otherwise
397 // the host path is Eigen's self-adjoint solver.
398 bool factorizeKernelDistributed(const Eigen::MatrixXd& kernel,
399 double sv_rtol = 1e-13,
400 double sv_abs_tol = 0.0,
401 double sv_chop_tol = 0.0);
402#endif
403 // Randomized Rayleigh-Ritz dual-kernel factorization for PSD K
404 // (Halko-Martinsson-Tropp randomized range finding, doi:10.1137/090771806):
405 // draw an observation-space range Q, diagonalize T=Q^T K Q, and lift the
406 // kept Ritz vectors as Psi=QZ. When the range contains the retained
407 // eigenspace, K Psi = Psi diag(S^2) and Psi^T Psi = I, so the HS-SVD noisy
408 // solve keeps the same cond(Psi)=1 invariant as the exact dual path.
409 void factorizeKernelRandomized(const Eigen::MatrixXd& kernel,
410 int sketch_size, int n_power_iter = 2,
411 double sv_rtol = 1e-13,
412 double sv_abs_tol = 0.0,
413 double sv_chop_tol = 0.0);
414 // Lift a deflated dual-kernel factorization back into full N-row
415 // observation space while keeping Sr_, rank_, and the deflated N_r x N_r
416 // bordered kernel K_r from the deflated solve, along with the orthogonal
417 // projector needed to project query cross-covariances for certification.
418 void liftFromDeflatedSubspace(Eigen::Index full_rows,
419 Eigen::MatrixXd lifted_psi,
420 const detail::RigidDeflationState& deflation,
421 double extra_assembly_error = 0.0);
422 // Rank-block update of a dual-kernel HS-SVD factorization. The appended
423 // kernel is K_+ = [[K_old, cross_old_new], [cross_old_new^T, new_kernel]],
424 // where K_old is represented by old_basis. The update diagonalizes only the
425 // small projected block while preserving an orthonormal observation basis.
426 bool factorizeKernelAppend(const StableBasisND& old_basis,
427 const Eigen::MatrixXd& cross_old_new,
428 const Eigen::MatrixXd& new_kernel,
429 double sv_rtol = 1e-13, double sv_abs_tol = 0.0,
430 double sv_chop_tol = 0.0);
431
432#ifdef GPR_LINALG_SCALAPACK
433 // Mode-distributed factorizeGPCartesian (#89 strong scaling). Each rank
434 // builds ONLY the contiguous block of Mercer mode-columns it owns
435 // (DistributedState::col_block_range), so the (~60%) eigenfunction-tensor +
436 // Cartesian-force-contraction design build never assembles the full
437 // nobs x N design on one rank. The local column block feeds
438 // distributed_thin_svd_colblock; the gathered U/S/V set Psi_/Sr_/W_/rank_
439 // exactly as the serial path. A_train_ stays empty (the production
440 // reduced-coefficient predict uses A_E*W_*p, never A_train_); the explicit
441 // alpha-K form and reconstructKernel are unavailable on this path. Bitwise
442 // arguments match factorizeGPCartesian. Returns false if the distributed
443 // SVD fails (caller falls back to the serial path).
444 bool factorizeGPCartesianDistributed(
445 const Eigen::MatrixXd& X, const Eigen::VectorXd& eps, double alpha,
446 double overall_scale, int max_degree,
447 const std::vector<Eigen::MatrixXd>& jacobians,
448 bool component_major = false, double sv_rtol = 1e-13,
449 double mode_prune_rtol = 0.0);
450#endif
451
452 // Least-squares solve Psi b = y (column-pivoted Householder QR; the
453 // orthonormality shortcut loses the threshold mode in float64 -- see
454 // StableBasis1D::solve). y length matches the complete joint design:
455 // M energy rows followed by every gradient row.
456 Eigen::VectorXd solve(const Eigen::VectorXd& y) const;
457
458 // Predict energy s(x*) and gradient grad s(x*) at new points Xstar (m x d)
459 // for the NOISELESS interpolant (b from solve()).
460 Eigen::VectorXd predictEnergy(const Eigen::MatrixXd& Xstar,
461 const Eigen::VectorXd& b) const;
462 Eigen::MatrixXd predictGradient(const Eigen::MatrixXd& Xstar,
463 const Eigen::VectorXd& b) const;
464
465 // --- Noisy GP API (the integration surface that replaces Cholesky) ---
466 // The stable basis gives an exact eigendecomposition of the training kernel
467 // K_obs = A A^T = Psi diag(S^2) Psi^T (Psi = U[:,kept], orthonormal),
468 // so the regularized GP linear algebra is explicit and stable, WITHOUT ever
469 // forming or Cholesky-factoring the ill-conditioned K:
470 // (K + sigma2 I)^{-1} y = Psi diag(1/(S^2+sigma2)) Psi^T y
471 // + (1/sigma2)(y - Psi Psi^T y),
472 // log det(K + sigma2 I) = sum_i log(S_i^2+sigma2) + (n-rank) log(sigma2).
473 // sigma2 is the Gaussian likelihood variance + jitter (the nugget).
474
475 // Posterior weights alpha = (K + sigma2 I)^{-1} y (length nobs).
476 Eigen::VectorXd solveNoisy(const Eigen::VectorXd& y, double sigma2) const;
477 // Diagonal quadratic forms for many right-hand sides:
478 // q_j = y_j^T (Psi diag(S^2) Psi^T + sigma2 I)^-1 y_j.
479 // With z = Psi^T Y and orthonormal Psi, the HS-SVD decomposition gives
480 // q_j = sum_i z_ij^2/(S_i^2+sigma2)
481 // + (||y_j||^2 - ||z_j||^2)/sigma2,
482 // avoiding one dense solve per query while preserving cond(Psi)=1.
483 Eigen::VectorXd noisySelfQuadratic(const Eigen::MatrixXd& rhs,
484 double sigma2) const;
485 // Range-only diagonal quadratic forms:
486 // q_j = z_j^T diag(1/(S^2+sigma2)) z_j, z_j = Psi^T y_j.
487 // Cross-covariance columns k(X,x*) are range vectors of the kernel
488 // operator represented by Psi diag(S^2) Psi^T; this contraction is the
489 // Schur-complement term for posterior covariance. It avoids treating
490 // floating-point range residual as an independent noise-space target.
491 Eigen::VectorXd noisyRangeSelfQuadratic(const Eigen::MatrixXd& rhs,
492 double sigma2) const;
505 Eigen::VectorXd stableRangePosteriorDiagonal(
506 const Eigen::MatrixXd& rhs, const Eigen::VectorXd& prior,
507 const Eigen::VectorXd& signal, double sigma2,
508 bool check_variance = true) const;
519 std::vector<BorderedVarianceInterval> noisyBorderedVarianceIntervals(
520 const Eigen::MatrixXd& rhs, const Eigen::VectorXd& prior_diag,
521 double sigma2) const;
523 std::vector<BorderedVarianceInterval> noisyBorderedVarianceIntervals(
524 const Eigen::MatrixXd& rhs, const Eigen::VectorXd& prior_diag,
525 double sigma2, BorderedSchurSign sign) const;
530 BorderedNoiseReport borderedNoiseReport(double sigma2) const;
540 BorderedNoiseReport borderedNoiseReport(double sigma2,
541 double output_variance_scale) const;
550 BorderedNoiseReport borderedNoiseReport(double sigma2, double y_scale,
551 double calibration) const;
552
558 Eigen::Index floored = 0;
561 Eigen::Index proven_negative = 0;
565 Eigen::Index uncertified = 0;
569 Eigen::Index raised = 0;
570 };
571
572 [[nodiscard]] static SchurFloorReport schurFloorTotals() noexcept;
573 static void resetSchurFloorTotals() noexcept;
589 const Eigen::MatrixXd& cross, const Eigen::VectorXd& prior,
590 double sigma2, Eigen::VectorXd& value,
591 const std::vector<char>* skip = nullptr) const;
597 [[nodiscard]] double trainingRowLatentErrorBound(Eigen::Index row,
598 double sigma2) const;
605 static double floorLatentVariance(double latent, double error_bound,
606 SchurFloorReport* report) noexcept;
607 [[nodiscard]] Eigen::Index borderedKernelOrder() const noexcept
608 {
609 return bordered_deflation_ ? bordered_deflation_->deflated_rows
610 : Psi_.rows();
611 }
612
616 [[nodiscard]] bool supportsBorderedVarianceInterval() const noexcept
617 {
618 const Eigen::Index expected = borderedKernelOrder();
619 return bordered_kernel_.rows() == expected &&
620 bordered_kernel_.cols() == expected;
621 }
622 // Diagonal of (K + sigma2 I)^-1 in the HS-SVD observation basis:
623 // inv_diag_i = sigma2^-1 * (1 - sum_j Psi_ij^2 S_j^2/(S_j^2+sigma2)).
624 // This is the exact inverse diagonal for the retained eigenspace plus
625 // orthogonal noise solve, and is the primitive needed for Gaussian LOO
626 // predictive scoring without a dense inverse.
627 Eigen::VectorXd noisyInverseDiagonal(double sigma2) const;
628 // Same quantity as noisyInverseDiagonal restricted to selected rows.
629 // Each entry costs one pass over the Psi row rather than a pass over
630 // the whole basis, so a caller that reads a handful of training
631 // channels per query does not form the full observation-length
632 // diagonal. Rows outside [0, numObs) yield NaN, which the callers
633 // already treat as an unusable channel.
634 Eigen::VectorXd noisyInverseDiagonalEntries(const Eigen::VectorXi& rows,
635 double sigma2) const;
636 // Exact Gaussian leave-one-out negative log predictive density for the
637 // joint observation model. With alpha=(K+sigma2 I)^-1 y and
638 // q_i=((K+sigma2 I)^-1)_ii,
639 // -log p(y_i|y_-i)=0.5*(log(2*pi)-log(q_i)+alpha_i^2/q_i).
640 double leaveOneOutNegativeLogPredictiveDensity(const Eigen::VectorXd& y,
641 double sigma2) const;
642 // Leave-one-out variance calibration factor c >= 1 (Bastos & O'Hagan
643 // 2009, "Diagnostics for Gaussian Process Emulators", Technometrics
644 // 51(4)): for a calibrated model the standardized LOO residuals
645 // z_i = alpha_i/sqrt(q_i) satisfy z_i^2 ~ chi-square(1), so
646 // median(z_i^2) should equal the chi-square(1) population median. c is
647 // the ratio of the observed median to that reference, floored at 1 (an
648 // under-confident or calibrated model is left untouched; only measured
649 // overconfidence is corrected). Multiply REPORTED posterior variance by
650 // c; never the fitted amplitude or the variance gates compared against
651 // it. Returns 1.0 when the basis or inputs cannot support the estimate
652 // (fewer than 2 rows, size mismatch, or a non-finite/non-positive q_i).
653 double computeVarianceCalibrationFactor(const Eigen::VectorXd& y,
654 double sigma2) const;
655 // Diagonal of A dK A, A=(K+sigma2 I)^-1, using the HS-SVD inverse
656 // representation. This is the trace-local term needed for analytic
657 // directional derivatives of the Gaussian LOO score.
658 Eigen::VectorXd noisyInverseSandwichDiagonal(const Eigen::MatrixXd& dK,
659 double sigma2) const;
660 double leaveOneOutNegativeLogPredictiveDensityDirectionalDerivative(
661 const Eigen::VectorXd& y, double sigma2,
662 const Eigen::MatrixXd& dK) const;
663
664 // Full dense noisy inverse (K+sigma2 I)^-1 from the HS-SVD representation.
665 Eigen::MatrixXd noisyInverse(double sigma2) const;
666 // PER-GEOMETRY-BLOCK Gaussian leave-one-out: each `group` holds the row
667 // indices of one geometry's joint observations (its energy AND all its
668 // gradient rows). Leaving out a whole geometry (not a single row) is the
669 // correct derivative-GP LOO -- a per-row LOO leaves out one gradient
670 // component while keeping the same geometry's energy + other components,
671 // which trivially predict the held-out row, so the per-row score is blind
672 // to a collapsing length scale (the energy fit is fine, the force/curvature
673 // is not). The block score penalizes the collapse that blows up 1/ls^4 in
674 // the dimer Hessian. NLPD_B = 0.5[size(B) * log2pi - logdet(Cinv_BB)
675 // + alpha_B^T (Cinv_BB)^-1 alpha_B], alpha=(K+sigma2 I)^-1 y.
676 double leaveOneOutNegativeLogPredictiveDensityGrouped(
677 const Eigen::VectorXd& y, double sigma2,
678 const std::vector<std::vector<Eigen::Index>>& groups) const;
679 double leaveOneOutNegativeLogPredictiveDensityGroupedDirectionalDerivative(
680 const Eigen::VectorXd& y, double sigma2, const Eigen::MatrixXd& dK,
681 const std::vector<std::vector<Eigen::Index>>& groups) const;
682
683 // CANCELLATION-FREE posterior mean. The standard mu(x*) = k*(x*)^T alpha
684 // sums ~nobs terms scaled by alpha = (K+sigma2 I)^{-1} y, whose entries
685 // reach ~1e5-1e7 for the ill-conditioned gradient-enhanced kernel -> ~6
686 // digit cancellation, the source of the 1-ULP force fragility. Collapsing
687 // A_train^T (K+sigma2 I)^{-1} y = V diag(S/(S^2+sigma2)) (Psi^T y)
688 // analytically (A_train = U S V^T, Psi=U) removes alpha entirely: the
689 // reduced rank-r coefficient
690 // p_i = S_i^2/(S_i^2+sigma2) * (Psi^T y)_i (O(1), no cancellation)
691 // feeds the EXISTING predictEnergy(x*, p) = A_E(x*) W p = A_E(x*) A_train^T
692 // (K+sigma2 I)^{-1} y and predictGradient(x*, p) (descriptor-space
693 // gradient). Verified vs the direct alpha-form to ~1e-10 (scripts/derive
694 // math). This is what lets the HS-SVD path run with NO output normalization
695 // (cond=1 solve + cancellation-free predict). y in natural [E ; G] order;
696 // length numObs().
697 Eigen::VectorXd posteriorMeanReducedCoeffs(const Eigen::VectorXd& y,
698 double sigma2) const;
699 StableBasisPosteriorWeights noisyPosteriorWeights(const Eigen::VectorXd& y,
700 double sigma2) const;
701 // log det(K + sigma2 I) for the marginal likelihood.
702 double logDetNoisy(double sigma2) const;
703 // Weights that, applied to a query's cross-covariance, give the posterior
704 // mean whose variance posteriorVarianceDiagonal reports. With the stable
705 // variance off, or a resolved discarded complement, they are alpha
706 // itself; with it on and a null complement they are alpha restricted to
707 // the retained basis.
708 Eigen::VectorXd posteriorMeanWeights(const Eigen::VectorXd& alpha) const;
709 // Posterior mean energy / gradient at Xstar from alpha = solveNoisy(...).
710 Eigen::VectorXd posteriorMeanEnergy(const Eigen::MatrixXd& Xstar,
711 const Eigen::VectorXd& alpha) const;
712 Eigen::MatrixXd posteriorMeanGradient(const Eigen::MatrixXd& Xstar,
713 const Eigen::VectorXd& alpha) const;
714 // Posterior predictive variance of the ENERGY at Xstar (length m):
715 // var(x*) = k(x*,x*) - k*(x*)^T (K + sigma2 I)^{-1} k*(x*).
716 Eigen::VectorXd posteriorVarianceEnergy(const Eigen::MatrixXd& Xstar,
717 double sigma2) const;
729 Eigen::VectorXd posteriorVarianceDiagonal(const Eigen::MatrixXd& cross,
730 const Eigen::VectorXd& prior,
731 double sigma2) const;
740 Eigen::MatrixXd posteriorCovariance(const Eigen::MatrixXd& cross,
741 const Eigen::MatrixXd& prior,
742 double sigma2) const;
749 double posteriorVarianceAction(const Eigen::MatrixXd& cross,
750 const Eigen::MatrixXd& prior,
751 const Eigen::VectorXd& weights,
752 double sigma2) const;
753 Eigen::VectorXd predictEnergyAffine(const Eigen::MatrixXd& Ustar,
754 const Eigen::MatrixXd& residuals,
755 const Eigen::VectorXd& b) const;
756 // One row of A_E W. The standardized energy is this row dotted with b.
757 Eigen::VectorXd energyAffineDesignRow(
758 const Eigen::MatrixXd& Ustar, const Eigen::MatrixXd& residuals) const;
759 Eigen::MatrixXd predictGradientAffine(const Eigen::MatrixXd& Ustar,
760 const Eigen::MatrixXd& residuals,
761 const Eigen::MatrixXd& basis,
762 const Eigen::VectorXd& b) const;
763 Eigen::MatrixXd predictGradientHessianVectorAffine(
764 const Eigen::MatrixXd& Ustar, const Eigen::MatrixXd& residuals,
765 const Eigen::MatrixXd& basis, const Eigen::MatrixXd& tangent_directions,
766 const Eigen::MatrixXd& residual_directions,
767 const Eigen::VectorXd& b) const;
768 Eigen::VectorXd posteriorVarianceEnergyAffine(
769 const Eigen::MatrixXd& Ustar, const Eigen::MatrixXd& residuals,
770 double sigma2) const;
771
772 // Aurentz-Trefethen standardChop ("Chopping a Chebyshev series",
773 // doi:10.1145/2998442): given a decaying coefficient magnitude
774 // sequence and a target relative tolerance tol in (0,1), return the cutoff
775 // index = number of leading entries to retain, by detecting the plateau /
776 // noise floor rather than a fixed threshold. Returns coeffs.size() when no
777 // plateau is found. Used here to select the Mercer expansion degree
778 // adaptively from the eigenvalue decay (autoMaxDegree).
779 static Eigen::Index standardChop(const Eigen::VectorXd& coeffs, double tol);
780 // Smallest graded total degree whose per-degree Mercer envelope
781 // E_D = prod_k sqrt(lambda_0k) * (max_k sqrt(r_k))^D resolves the kernel
782 // to target_tol, then applies standardChop (doi:10.1145/2998442).
783 static int autoMaxDegree(const Eigen::VectorXd& eps, double alpha, int dim,
784 double target_tol, int max_degree_cap = 40);
785 // True when the graded total-degree tensor set
786 // C(dim + max_degree, max_degree) exceeds a caller-provided matrix-size
787 // limit. This lets callers reject expansions that cannot be represented
788 // without enumerating the multi-indices.
789 static bool gradedModeCountExceedsLimit(int dim, int max_degree,
790 Eigen::Index limit);
791 static int capMaxDegreeByModeCount(int dim, int requested_degree,
792 Eigen::Index mode_limit);
793 // Orthonormal basis for the column span of already-centred descriptor rows.
794 // The numerical-rank tolerance follows the SVD backward-error scale.
795 static Eigen::MatrixXd affineSpanBasis(const Eigen::MatrixXd& centered_X);
796 static void projectToAffineSpan(const Eigen::MatrixXd& centered_X,
797 const Eigen::MatrixXd& basis,
798 Eigen::MatrixXd& coords,
799 Eigen::MatrixXd& residuals);
800
801 double conditionNumber() const; // cond(Psi); ~1 when stable
806 [[nodiscard]] double conditionFlooredNoise(double sigma2) const;
817 [[nodiscard]] double varianceFlooredNoise(double sigma2) const;
820 [[nodiscard]] static double conditionFlooredSigma2ForTesting(
821 const Eigen::VectorXd& singular_values, double sigma2,
822 Eigen::Index nobs);
823
824 int rank() const
825 {
826 return rank_;
827 }
828 bool usedLapackRrrValueRange() const noexcept
829 {
830 return lapack_rrr_value_range_used_;
831 }
832 [[nodiscard]] const char* lastKernelFactorizeDriver() const noexcept
833 {
834 return last_kernel_factorize_driver_;
835 }
836
838 [[nodiscard]] int lapackRrrFullSolvesForTesting() const noexcept
839 {
840 return lapack_rrr_full_solves_;
841 }
842 [[nodiscard]] int lapackRrrExtensionsForTesting() const noexcept
843 {
844 return lapack_rrr_extensions_;
845 }
847 {
849 }
851 {
852 return fast_kernel_eigensolver_used_;
853 }
854 [[nodiscard]] int borderedFactorBuildsForTesting() const noexcept
855 {
856 std::lock_guard<std::mutex> lock(bordered_cache_.mutex);
857 return bordered_cache_.builds;
858 }
859
862 void assumeExtendedCertificationForTesting(bool available);
867 void setRetainedSpectrumForTesting(Eigen::MatrixXd psi,
868 Eigen::VectorXd singular_values)
869 {
870 if (psi.cols() != singular_values.size())
871 throw std::invalid_argument(
872 "retained basis and spectrum must have the same rank");
873 Psi_ = std::move(psi);
874 Sr_ = std::move(singular_values);
875 rank_ = static_cast<int>(Sr_.size());
876 dropped_s2_max_ = 0.0;
877 noisy_eigvals_.resize(0);
878 clearBorderedCache();
879 }
880 // The design matrices that define the represented kernel, so that a test
881 // can build a dense reference posterior from the same finite feature map:
882 // K = A A^T, k* = A_E A^T, and k** = |A_E row|^2 (energy) or the exact
883 // span norm kself (affine).
884 Eigen::MatrixXd energyDesignForTesting(const Eigen::MatrixXd& Xstar) const
885 {
886 Eigen::MatrixXd energy;
887 std::vector<Eigen::MatrixXd> gradient;
888 designAt(Xstar, energy, gradient);
889 return energy;
890 }
892 const Eigen::MatrixXd& Ustar, const Eigen::MatrixXd& residuals,
893 Eigen::VectorXd& kself) const
894 {
895 Eigen::MatrixXd energy;
896 AffineVariancePrior exact;
897 designAtAffineEnergy(Ustar, residuals, energy, &exact);
898 kself.resize(exact.diagonal.size());
899 // The variance path keeps this diagonal unrounded. Callers that
900 // rebuild a reference in binary64 get an upper bound on it.
901 for (Eigen::Index i = 0; i < exact.diagonal.size(); ++i)
902 kself(i) = gpr::extended::roundUpToDouble(exact.diagonal(i));
903 return energy;
904 }
905
907 [[nodiscard]] static int designVarianceWorkingDigitsForTesting() noexcept;
910 [[nodiscard]] static long long latentVarianceOperationDepthForTesting(
911 Eigen::Index rank) noexcept;
914 [[nodiscard]] Eigen::VectorXd rangeVarianceFromDesignForTesting(
915 const Eigen::MatrixXd& A_E, double sigma2) const;
916 [[nodiscard]] const Eigen::MatrixXd& trainingDesignForTesting() const
917 {
918 return A_train_;
919 }
920
922 void borderedEpsKForTesting(double& hi, double& lo, int& operations) const;
925 [[nodiscard]] const Eigen::MatrixXd& borderedKernelForTesting() const
926 {
927 return bordered_kernel_;
928 }
929 [[nodiscard]] double borderedAssemblyErrorForTesting() const
930 {
931 return bordered_assembly_error_;
932 }
933 // True when the training cross-covariance A_train is retained (serial
934 // factorize). The distributed path leaves it empty, so posteriorVariance*
935 // and reconstructKernel are unavailable there; callers must check this.
937 {
938 return A_train_.size() > 0;
939 }
940 int numBasis() const
941 {
942 return static_cast<int>(midx_.rows());
943 }
944 // Number of observations the basis was factorized for (energy + gradient
945 // rows). The caller must pass solveNoisy a y of exactly this length.
946 Eigen::Index numObs() const
947 {
948 return Psi_.rows();
949 }
950 const Eigen::MatrixXd& leftSingularVectors() const
951 {
952 return Psi_;
953 }
954 const Eigen::VectorXd& singularValues() const
955 {
956 return Sr_;
957 }
958 // Noisy eigenvalues mu_i = eig(K + sigma2 I) when factorized via
959 // factorizeNoisyKernel; empty otherwise. Aligned with Psi_ columns / Sr_.
960 const Eigen::VectorXd& noisyEigenvalues() const
961 {
962 return noisy_eigvals_;
963 }
965 {
966 return noisy_eigvals_.size() == Sr_.size() && noisy_eigvals_.size() > 0;
967 }
968 // Reorder observation rows after an algebraic update. source_for_target[i]
969 // gives the source row copied into target row i.
970 bool permuteObservationRows(const Eigen::VectorXi& source_for_target);
971
972 // Reconstruct the training kernel K_obs (nobs x nobs) for diagnostics.
973 // truncated=false: the full design Gram A_full A_full^T -- the Mercer
974 // kernel at this max_degree, which must match the assembled SexpatCF block.
975 // truncated=true: the rank-kept Psi diag(S^2) Psi^T -- the kernel
976 // solveNoisy actually inverts. Comparing K_exact vs the production kernel
977 // isolates a kernel-form error; K_trunc vs K_exact isolates SVD-truncation
978 // loss.
979 Eigen::MatrixXd reconstructKernel(bool truncated) const;
980
981 // Energy tensor eigenfunctions Phi (m x N) and their derivative w.r.t. the
982 // j-th descriptor dimension's shape parameter, d Phi/d eps_j (tensor-dA
983 // step 2): the same product as eigenTensor with dim j's 1D table swapped
984 // for its eps-derivative. The building block for dA = dPhi diag(sqrt_lam) +
985 // Phi diag(d sqrt_lam/d eps).
986 void eigenTensorEpsDerivative(const Eigen::MatrixXd& X, int j,
987 Eigen::MatrixXd& Phi,
988 Eigen::MatrixXd& dPhi_eps) const;
989
990private:
991 std::shared_ptr<linalg::BackendContext> backend_context_;
992 [[nodiscard]] linalg::BackendContext& backend() const
993 {
994 return *backend_context_;
995 }
996
997 // The noise report in training units, before any output scale.
998 struct TrainingNoiseReport {
999 double requested = 0.0;
1000 double floored = 0.0;
1001 double gap = std::numeric_limits<double>::infinity();
1002 bool floor_active = false;
1003 bool certifiable = false;
1004 };
1005 TrainingNoiseReport borderedTrainingNoiseReport(double sigma2) const;
1006
1007 // Per-dimension 1D eigenfunction values phi_n(x_k) and derivatives
1008 // phi_n'(x_k) at a single coordinate, n=0..max_degree, via the stably
1009 // scaled Hermite recurrence (avoids 2^n n! overflow).
1010 void eigen1d(double xk, int dim, Eigen::VectorXd& val,
1011 Eigen::VectorXd& deriv) const;
1012 void eigen1dSecond(double xk, int dim, Eigen::VectorXd& val,
1013 Eigen::VectorXd& deriv, Eigen::VectorXd& second) const;
1014 // phi_n(x_k) and its shape-parameter derivative d phi_n/d eps_k (tensor-dA
1015 // step 2). Same verified closed forms as StableBasis1D (see
1016 // scripts/derive_hssvd_eps_gradient.py), per descriptor dimension.
1017 void eigen1dEpsDerivative(double xk, int dim, Eigen::VectorXd& val,
1018 Eigen::VectorXd& dval_eps) const;
1019 // Tensor eigenfunctions Phi (m x N) and, if want_grad, per-dimension
1020 // gradients dPhi[j] (m x N) for all points X over the multi-index set.
1021 void eigenTensor(const Eigen::MatrixXd& X, bool want_grad,
1022 Eigen::MatrixXd& Phi,
1023 std::vector<Eigen::MatrixXd>& dPhi) const;
1024 // Column-restricted eigenTensor: builds only mode columns [c0, c0+count) of
1025 // Phi (m x count) and, if want_grad, dPhi[j] (m x count). The per-(point,
1026 // dim) 1D Hermite tables are shared; only the tensor product over the
1027 // requested multi-indices is computed -- the per-rank work of the
1028 // mode-distributed design build.
1029 void eigenTensorCols(const Eigen::MatrixXd& X, bool want_grad,
1030 Eigen::Index c0, Eigen::Index count,
1031 Eigen::MatrixXd& Phi,
1032 std::vector<Eigen::MatrixXd>& dPhi) const;
1033 // Fill sqrt_lam_ = scl * prod_k sqrt(lam0_k) sqrt(r_k)^midx for the current
1034 // midx_, then (if prune_rtol > 0) drop modes with sqrt_lam below
1035 // prune_rtol * max sqrt_lam, shrinking midx_ and sqrt_lam_ together (the
1036 // Mercer / Karhunen-Loeve truncation).
1037 void buildSqrtLamAndPrune(const Eigen::VectorXd& r,
1038 const Eigen::VectorXd& lam0, double scl,
1039 double prune_rtol);
1040 // Stacked design rows A(Xstar) for energy + (enhanced) gradient prediction.
1041 void designAt(const Eigen::MatrixXd& Xstar, Eigen::MatrixXd& A_E,
1042 std::vector<Eigen::MatrixXd>& A_g) const;
1043 struct AffineVariancePrior {
1044 Eigen::Matrix<gpr::extended::WorkingReal, Eigen::Dynamic, 1> diagonal;
1045 bool stable = false;
1046 };
1047 void designAtAffineEnergy(const Eigen::MatrixXd& Ustar,
1048 const Eigen::MatrixXd& residuals,
1049 Eigen::MatrixXd& A_E,
1050 AffineVariancePrior* prior = nullptr) const;
1051 // RKHS-range predictive variance from an already-built energy design A_E
1052 // (shared by posteriorVarianceEnergy / posteriorVarianceEnergyAffine).
1053 // The affine diagonal holds omitted mass in stable mode and the total
1054 // prior in legacy mode.
1055 Eigen::VectorXd rangeVarianceFromDesign(
1056 const Eigen::MatrixXd& A_E, double sigma2,
1057 const AffineVariancePrior* affine_prior = nullptr) const;
1058 // Set Psi_/Sr_/W_/rank_/A_train_ from the assembled design A via the
1059 // randomized range finder (HMT). sketch is the initial range dimension;
1060 // n_power subspace iterations sharpen the spectrum capture.
1061 void factorizeFromDesignRandomized(const Eigen::MatrixXd& A, int sketch,
1062 int n_power, double sv_rtol,
1063 double sv_abs_tol);
1064 void clearBorderedCache() noexcept;
1065
1066 struct BorderedFactorCache;
1067 struct BorderedRmCache;
1068
1069 struct BorderedCacheState {
1070 mutable std::mutex mutex;
1071 std::shared_ptr<const BorderedFactorCache> factor;
1072 std::string error;
1073 std::shared_ptr<const BorderedRmCache> rm;
1074 int builds = 0;
1075 // -1 follows the platform, 0 forces the certificate off, 1 requests
1076 // it. A request cannot enable a platform that has no working type.
1077 int extended_override = -1;
1078
1079 BorderedCacheState() = default;
1080 BorderedCacheState(const BorderedCacheState& other)
1081 {
1082 std::lock_guard<std::mutex> lock(other.mutex);
1083 factor = other.factor;
1084 error = other.error;
1085 rm = other.rm;
1086 builds = other.builds;
1087 extended_override = other.extended_override;
1088 }
1089 BorderedCacheState& operator=(const BorderedCacheState& other)
1090 {
1091 if (this == &other) return *this;
1092 std::scoped_lock lock(mutex, other.mutex);
1093 factor = other.factor;
1094 error = other.error;
1095 rm = other.rm;
1096 builds = other.builds;
1097 extended_override = other.extended_override;
1098 return *this;
1099 }
1100 BorderedCacheState(BorderedCacheState&& other) noexcept
1101 {
1102 std::lock_guard<std::mutex> lock(other.mutex);
1103 factor = std::move(other.factor);
1104 error = std::move(other.error);
1105 rm = std::move(other.rm);
1106 builds = other.builds;
1107 extended_override = other.extended_override;
1108 }
1109 BorderedCacheState& operator=(BorderedCacheState&& other) noexcept
1110 {
1111 if (this == &other) return *this;
1112 std::scoped_lock lock(mutex, other.mutex);
1113 factor = std::move(other.factor);
1114 error = std::move(other.error);
1115 rm = std::move(other.rm);
1116 builds = other.builds;
1117 extended_override = other.extended_override;
1118 return *this;
1119 }
1120 };
1121
1122 bool extendedCertificationEnabledLocked() const;
1123 void buildBorderedFactorLocked() const;
1124 std::pair<std::shared_ptr<const BorderedFactorCache>,
1125 std::shared_ptr<const BorderedRmCache>>
1126 ensureBorderedFactorAndRm(double sigma2) const;
1127
1128 int dim_ = 0;
1129 int M_ = 0;
1130 int max_degree_ = 0;
1131 double chop_sigma2_ = 0.0;
1132 double dropped_s2_max_ = 0.0;
1133 int rank_ = 0;
1134 bool gradient_enhanced_ = false;
1135 double alpha_ = 1.0;
1136 Eigen::VectorXd eps_; // per-dim shape, length d
1137 Eigen::VectorXd beta_; // per-dim beta_k
1138 Eigen::VectorXd delta2_; // per-dim delta_k^2
1139 Eigen::MatrixXi midx_; // N x d graded multi-indices
1140 Eigen::VectorXd sqrt_lam_; // sqrt(lambda_alpha), length N
1141 Eigen::MatrixXd W_; // V S^{-1}, N x rank
1142 Eigen::MatrixXd Psi_; // A_full W, nobs x rank (= U[:, kept])
1143 Eigen::VectorXd Sr_; // retained singular values of A_full, length rank
1144 // Noisy eigenvalues mu_i = eig(K + sigma2 I), populated only by
1145 // factorizeNoisyKernel. When set, logDetNoisy / noisyPosteriorWeights /
1146 // solveNoisy contract with mu_i directly (no sigma2 re-addition), avoiding
1147 // the cancelling subtraction mu_i - sigma2 in the objective.
1148 Eigen::VectorXd noisy_eigvals_;
1149 Eigen::MatrixXd A_train_; // training design A_full, nobs x N (for k*)
1150 Eigen::Index affine_full_dim_ = 0;
1151 double overall_scale_ = 1.0;
1152 bool lapack_rrr_value_range_used_ = false;
1153 bool fast_kernel_eigensolver_used_ = false;
1154 const char* last_kernel_factorize_driver_ = "unset";
1155 int lapack_rrr_full_solves_ = 0;
1156 int lapack_rrr_extensions_ = 0;
1157 Eigen::MatrixXd cached_spectrum_matrix_;
1158 Eigen::VectorXd cached_spectrum_evals_;
1159 Eigen::MatrixXd cached_spectrum_evecs_;
1160 Eigen::MatrixXd bordered_kernel_;
1161 double bordered_assembly_error_ = 0.0;
1162 std::shared_ptr<const detail::RigidDeflationState> bordered_deflation_;
1163 mutable BorderedCacheState bordered_cache_;
1164 double condition_number_ = 0.0;
1165};
1166
1180 const StableBasisND& basis, const Eigen::MatrixXd& Kstar,
1181 const Eigen::MatrixXd& Kright, const Eigen::MatrixXd& prior,
1182 double total_sigma2, Eigen::MatrixXd& K_post, bool contracted_mean = false,
1183 Eigen::Index left_queries = 1, Eigen::Index right_queries = 1);
1184
1185} // namespace gpr
1186
1187#endif // GPR_ML_GP_STABLE_BASIS_H_
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
Tiny value type describing the MPI dispatch context for a probe loop.
void factorize(const Eigen::VectorXd &x, double eps, double alpha, int n_extra=20, double sv_rtol=1e-13)
Eigen::VectorXd predict(const Eigen::VectorXd &xstar, const Eigen::VectorXd &b) const
double conditionNumber() const
const Eigen::VectorXd & sqrtLambda() const
Eigen::VectorXd solve(const Eigen::VectorXd &y) const
Eigen::MatrixXd evalBasis(const Eigen::VectorXd &xstar) const
static void resetSchurFloorTotals() noexcept
int borderedFactorBuildsForTesting() const noexcept
int lapackRrrExtensionsForTesting() const noexcept
bool hasNoisyEigenvalues() const
double droppedEigenvalueMax() const noexcept
Largest eigenvalue discarded by the last truncation (0 when none).
bool usedLapackRrrValueRangeForTesting() const noexcept
double covarianceComplementEigenvalue() const noexcept
Largest signal eigenvalue represented by the discarded covariance complement.
static SchurFloorReport schurFloorTotals() noexcept
Process-wide totals of SchurFloorReport over every call.
int lapackRrrFullSolvesForTesting() const noexcept
const Eigen::VectorXd & noisyEigenvalues() const
Eigen::MatrixXd affineEnergyDesignForTesting(const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, Eigen::VectorXd &kself) const
static double floorLatentVariance(double latent, double error_bound, SchurFloorReport *report) noexcept
double covarianceComplementWeight(double sigma2) const noexcept
const Eigen::MatrixXd & borderedKernelForTesting() const
SchurFloorReport floorCertifiedSchurDiagonal(const Eigen::MatrixXd &cross, const Eigen::VectorXd &prior, double sigma2, Eigen::VectorXd &value, const std::vector< char > *skip=nullptr) const
Eigen::Index borderedKernelOrder() const noexcept
bool hasCrossCovariance() const
double borderedAssemblyErrorForTesting() const
double trainingRowLatentErrorBound(Eigen::Index row, double sigma2) const
Eigen::MatrixXd energyDesignForTesting(const Eigen::MatrixXd &Xstar) const
bool usedLapackRrrValueRange() const noexcept
bool supportsBorderedVarianceInterval() const noexcept
double complementWeight(double sigma2) const noexcept
const Eigen::MatrixXd & leftSingularVectors() const
int numBasis() const
const char * lastKernelFactorizeDriver() const noexcept
void setChopNoiseVariance(double sigma2) noexcept
bool usedFastKernelEigensolverForTesting() const noexcept
const Eigen::VectorXd & singularValues() const
void setRetainedSpectrumForTesting(Eigen::MatrixXd psi, Eigen::VectorXd singular_values)
Eigen::Index numObs() const
double chopNoiseVariance() const noexcept
const Eigen::MatrixXd & trainingDesignForTesting() const
double roundUpToDouble(Work value)
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
bool looCalibrationIsUnityFromCholeskyDiagonal(const Eigen::VectorXd &alpha, const Eigen::VectorXd &diagonal)
BorderedSchurSign
Definition StableBasis.h:81
double looVarianceCalibrationFactor(const Eigen::VectorXd &alpha, const Eigen::VectorXd &inv_diag)
bool stabilizePosteriorCovariance(Eigen::MatrixXd &covariance)
Project a rounded covariance onto the positive-semidefinite cone while preserving its nonnegative dia...
bool subtractStableBasisProjectedCrossCovariance(const StableBasisND &basis, const Eigen::MatrixXd &Kstar, const Eigen::MatrixXd &Kright, const Eigen::MatrixXd &prior, double total_sigma2, Eigen::MatrixXd &K_post, bool contracted_mean=false, Eigen::Index left_queries=1, Eigen::Index right_queries=1)
STL namespace.
What floorCertifiedSchurDiagonal did to a diagonal.