Loading...
Searching...
No Matches
StableBasis.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4//
5// HS-SVD stable basis -- C++ port of the algorithm validated in
6// scripts/hssvd_prototype.py (cond(K) 1.8e18 -> cond(Psi) 1.000, identical
7// interpolant). See StableBasis.h for the references / DOIs.
8
9#include "StableBasis.h"
10
11#include <Eigen/Eigenvalues>
12#include <Eigen/QR>
13#include <Eigen/SVD>
14#include <algorithm>
15#include <atomic>
16#include <chrono>
17#include <cmath>
18#include <cstdlib>
19#include <limits>
20#include <random>
21#include <stdexcept>
22#include <vector>
23
32#include "../PhaseTimers.h"
33#include "ArrowheadSpectrum.h"
34#include "ExtendedReal.h"
35
36// Eigen 3.4's lapacke.h does not declare the Fortran dsyevr_ entry. Keep
37// the declaration when EIGEN_USE_LAPACKE selects that header.
38extern "C" {
39void dsyevr_(char*, char*, char*, int*, double*, int*, double*, double*, int*,
40 int*, double*, int*, double*, double*, int*, int*, double*, int*,
41 int*, int*, int*);
42}
43
44namespace {
45
46Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> timedSymmetricEigen(
47 const Eigen::MatrixXd& matrix)
48{
49 const auto start = std::chrono::steady_clock::now();
50 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(matrix);
52 std::chrono::duration<double>(std::chrono::steady_clock::now() - start)
53 .count();
54 return solver;
55}
56
57} // namespace
58
59#ifdef GPR_LINALG_SCALAPACK
60#include "../../linalg/DistributedState.h" // col_block_range
61#include "../../linalg/ScalapackBackend.h" // distributed_symmetric_eigen
62#endif
63
64namespace gpr {
65
66namespace detail {
67
68bool useGpuEigensolverForProcessCount(int process_count) noexcept
69{
70 return process_count == 1;
71}
72
73bool useRankBlockKernelAppend(bool gpu_full_eigensolver_available) noexcept
74{
75 return !gpu_full_eigensolver_available;
76}
77
78} // namespace detail
79
80namespace {
81
82class BorderedVarianceError : public std::runtime_error {
83public:
84 using std::runtime_error::runtime_error;
85};
86
87template <typename T>
88T workingSqrt(T value)
89{
90 using std::sqrt;
91 return sqrt(value);
92}
93
94template <typename T>
95T workingAbs(T value)
96{
97 using std::abs;
98 return abs(value);
99}
100
101template <typename T>
102bool workingIsFinite(T value)
103{
104 using std::isfinite;
105 return isfinite(value);
106}
107
108// Operation counts for the directed Higham scale. Each constant is the
109// number of arithmetic operations in that nonnegative expression; the scale
110// itself adds kDirectedScaleOps inside directedGamma.
111constexpr int kAssemblyPairOps = 1;
112// eps_K is the sum of six nonnegative contributions: the assembly error, the
113// symmetry and scale residuals, eps_pos, eps_qr and eps_bb. The sum is five
114// additions. Each contribution adds the operations it is formed with, and the
115// deepest of them decides the relative error of the whole sum, since all are
116// nonnegative:
117// eps_pos max_d * max_d, 1 + orth, the product with neg_eval, the sum with
118// es_residual and the product by max_d2: 5.
119// eps_qr the Frobenius norm of B (one square per entry, entries - 1
120// additions, a square root: entries + 1), the sum with qr_residual
121// and the product with qr_residual: entries + 3.
122// eps_bb the squared norm of B (entries) and the product with the
123// rounding factor of B's own entries: entries + 1.
124// When an entry of B is near underflow, formScaledFactor returns eps_bb and
125// the norm of B in eps_qr already rounded up, so these counts still cover the
126// sum. The doubling of the norm is exact and is not counted. The symmetry,
127// scale, eigen and QR residuals are bounds from frobeniusResidualUpperBound,
128// which already carries the operation depth of their own sums.
129constexpr int kEpsKSumAdditions = 5;
130constexpr int kEpsPosOps = 5;
131constexpr int kEpsQrExtraOps = 3;
132constexpr int kEpsBbExtraOps = 1;
133// B_ij = d_i v_ij sqrt(lambda_j): two products and the square root.
134constexpr int kFormedFactorEntryOps = 3;
135constexpr int kLambdaCertMulOps = 4;
136constexpr int kMuMinOps = 3;
137constexpr int kESplitQOps = 10;
138constexpr int kESolveQOps = 7;
139constexpr int kQtVErrOps = 3;
140constexpr int kEOrthQOps = 12;
141constexpr int kESumOps = 4;
142constexpr int kEKernelOps = 1;
143constexpr int kEQHiSumOps = 4;
144constexpr int kRNormOps = 13;
145constexpr int kSquareOps = 1;
146constexpr int kResDivOps = 1;
147constexpr int kELowerAddOps = 1;
148
149template <typename Extended>
150Extended directedGamma(long long expression_ops)
151{
152 using Prec = gpr::extended::WorkingPrecision<Extended>;
153 const long long total = expression_ops + gpr::extended::kDirectedScaleOps;
154 // 2^53 is the last integer that is exact in binary64, the leading limb
155 // of both working types. Past it the scale is not a faithful integer,
156 // and k*u >= 1 makes gamma infinite.
157 if (total <= 0 || total > (1LL << 53))
158 throw BorderedVarianceError(
159 "the directed margin exceeds working-precision resolution");
160 const Extended k(static_cast<double>(total));
161 const Extended u = Prec::unitRoundoff();
162 if (!(k * u < Extended(1)))
163 throw BorderedVarianceError(
164 "the directed margin exceeds working-precision resolution");
165 return (k * u) / (Extended(1) - k * u);
166}
167
168// Next working number above value*(1+gamma). An exact zero stays zero:
169// nextUp(0) would be a subnormal and is not an error term.
170template <typename Extended>
171Extended directedUpper(Extended value, long long expression_ops)
172{
173 using Prec = gpr::extended::WorkingPrecision<Extended>;
174 if (!workingIsFinite(value))
175 throw BorderedVarianceError(
176 "the bordered variance error bound is not finite");
177 if (!(value > Extended(0))) return Extended(0);
178 const Extended gamma = directedGamma<Extended>(expression_ops);
179 return Prec::nextUp(value * (Extended(1) + gamma));
180}
181
182// Next working number below value*(1-gamma), clamped at 0 because every
183// caller is a quantity already known to be nonnegative.
184template <typename Extended>
185Extended directedLower(Extended value, long long expression_ops)
186{
187 using Prec = gpr::extended::WorkingPrecision<Extended>;
188 if (!workingIsFinite(value) || !(value > Extended(0))) return Extended(0);
189 const Extended gamma = directedGamma<Extended>(expression_ops);
190 Extended scaled = value * (Extended(1) - gamma);
191 if (!(scaled > Extended(0))) return Extended(0);
192 scaled = Prec::nextDown(scaled);
193 return (scaled > Extended(0)) ? scaled : Extended(0);
194}
195
196// One entry of R R^T + sigma2 I - Rm^T Rm adds 2 rank products and sigma2, in
197// whatever order the product kernel uses: one rounded product and at most
198// 2 rank additions on any term.
199long long gramResidualEntryOps(Eigen::Index rank)
200{
201 const long long width = static_cast<long long>(rank);
202 if (width > (1LL << 26))
203 throw BorderedVarianceError(
204 "the bordered factor order exceeds the residual operation count");
205 return 2 * width + 1;
206}
207
208double kernelAssemblyErrorBound(const Eigen::MatrixXd& kernel,
209 const Eigen::MatrixXd& symmetric)
210{
211 using Extended = gpr::extended::WorkingReal;
212 const Extended unit =
213 gpr::extended::WorkingPrecision<Extended>::unitRoundoff();
214 const Extended order = static_cast<Extended>(kernel.cols());
215 if (!(order * unit < Extended(1)))
216 throw BorderedVarianceError(
217 "the kernel order exceeds assembly-bound resolution");
218 const Extended inflation = Extended(1) / (Extended(1) - order * unit);
219 Extended bound = 0;
220 for (Eigen::Index row = 0; row < kernel.rows(); ++row) {
221 Extended row_sum = 0;
222 for (Eigen::Index col = 0; col < kernel.cols(); ++col) {
223 row_sum += workingAbs(static_cast<Extended>(symmetric(row, col)) -
224 static_cast<Extended>(kernel(row, col)));
225 }
226 const Extended row_bound = inflation * row_sum;
227 if (row_bound > bound) bound = row_bound;
228 }
229 return gpr::extended::roundUpToDouble(bound);
230}
231
232// Bound on the exact Frobenius residual of a matrix identity from the
233// residual the working type computed and the entrywise sum of absolute values
234// of the terms that formed it; see gpr::extended::frobeniusResidualUpperBound.
235// A computed residual that cancels to zero still gets a positive bound.
236template <typename Computed, typename AbsTerms>
237gpr::extended::WorkingReal certifiedResidual(const Computed& computed,
238 const AbsTerms& abs_terms,
239 long long entry_ops)
240{
241 using Extended = gpr::extended::WorkingReal;
243 computed, abs_terms, entry_ops);
244 if (!workingIsFinite(bound)) {
245 throw BorderedVarianceError(
246 "the bordered residual bound exceeds working-precision "
247 "resolution");
248 }
249 return bound;
250}
251
252void validateJointJacobians(const Eigen::MatrixXd& points,
253 const std::vector<Eigen::MatrixXd>& jacobians)
254{
255 if (points.rows() <= 0 ||
256 jacobians.size() != static_cast<std::size_t>(points.rows())) {
257 throw std::invalid_argument(
258 "joint factorization requires one Jacobian per observation");
259 }
260 Eigen::Index gradient_components = -1;
261 for (const Eigen::MatrixXd& jacobian: jacobians) {
262 if (jacobian.rows() != points.cols() || jacobian.cols() <= 0) {
263 throw std::invalid_argument(
264 "joint factorization requires complete gradient channels");
265 }
266 if (gradient_components < 0) {
267 gradient_components = jacobian.cols();
268 } else if (jacobian.cols() != gradient_components) {
269 throw std::invalid_argument(
270 "joint observations require a common gradient dimension");
271 }
272 }
273}
274
275void validateJointAffineJacobians(
276 const Eigen::MatrixXd& coordinates,
277 const std::vector<Eigen::MatrixXd>& tangent_jacobians,
278 const std::vector<Eigen::MatrixXd>& normal_jacobians)
279{
280 validateJointJacobians(coordinates, tangent_jacobians);
281 if (normal_jacobians.size() != tangent_jacobians.size()) {
282 throw std::invalid_argument(
283 "affine joint factorization requires tangent and normal "
284 "Jacobians");
285 }
286 const Eigen::Index gradient_components = tangent_jacobians[0].cols();
287 const Eigen::Index normal_dimension = normal_jacobians[0].rows();
288 for (const Eigen::MatrixXd& jacobian: normal_jacobians) {
289 if (jacobian.rows() != normal_dimension ||
290 jacobian.cols() != gradient_components) {
291 throw std::invalid_argument(
292 "affine joint Jacobians must share observation dimensions");
293 }
294 }
295}
296
297} // namespace
298
299namespace {
300
301double singularCutoff(const Eigen::VectorXd& S, double sv_rtol,
302 double sv_abs_tol)
303{
304 if (S.size() == 0) return 0.0;
305 return std::max(sv_rtol * S(0), sv_abs_tol);
306}
307
308double dualKernelSingularCutoff(const Eigen::VectorXd& S, double sv_rtol,
309 double sv_abs_tol)
310{
311 double cutoff = singularCutoff(S, sv_rtol, sv_abs_tol);
312 if (S.size() == 0) return cutoff;
313
314 const double s0 = std::abs(S(0));
315 const double neps =
316 static_cast<double>(S.size()) * std::numeric_limits<double>::epsilon();
317 if (std::isfinite(s0) && s0 > 0.0 && neps > 0.0 && neps < 1.0) {
318 // Symmetric eigensolvers are backward stable: the returned eigensystem
319 // is exact for K + E with ||E|| bounded by the Higham gamma_n model
320 // (doi:10.1137/1.9780898718027). A PSD-kernel eigenvalue below that
321 // perturbation scale is numerical nullspace; retaining sqrt(lambda)
322 // from it changes variance projectors without adding resolvable signal.
323 const double gamma_n = neps / (1.0 - neps);
324 cutoff = std::max(cutoff, std::sqrt(gamma_n) * s0);
325 }
326 return cutoff;
327}
328
329Eigen::Index keptSingularRank(const Eigen::VectorXd& S, double cutoff)
330{
331 return gpr::linalg::resolvedSingularRank(S, cutoff);
332}
333
334Eigen::Index keptSingularRankWithChop(const Eigen::VectorXd& S, double cutoff,
335 double chop_tol, double sigma2)
336{
337 Eigen::Index rank = keptSingularRank(S, cutoff);
338 if (rank <= 0 || !(chop_tol > 0.0 && chop_tol < 1.0)) return rank;
339 const Eigen::Index chopped = StableBasisND::standardChop(S, chop_tol);
340 if (chopped <= 0) return rank;
341 Eigen::Index kept = std::min(rank, chopped);
342 // The chop is a plateau test on the spectrum alone. A dropped component
343 // with signal eigenvalue s^2 is treated as s^2 = 0 by every posterior
344 // formula (its shrinkage s^2/(s^2 + sigma2) becomes 0), which perturbs
345 // (K + sigma2 I)^-1 by s^2 / (sigma2 (s^2 + sigma2)) <= s^2 / sigma2^2,
346 // i.e. by a relative s^2 / sigma2 of the noise-dominated inverse. So a
347 // component may leave the basis only when s^2 <= chop_tol * sigma2;
348 // everything above that stays, whatever the plateau says.
349 if (sigma2 > 0.0 && std::isfinite(sigma2)) {
350 const double keep_below = chop_tol * sigma2;
351 while (kept < rank && S(kept) * S(kept) > keep_below)
352 ++kept;
353 }
354 return kept;
355}
356
357Eigen::ArrayXd stablePosteriorShrinkage(const Eigen::ArrayXd& signal_eigvals,
358 double sigma2, Eigen::Index nobs)
359{
360 Eigen::ArrayXd shrink = signal_eigvals / (signal_eigvals + sigma2);
361 if (shrink.size() <= 1 || !(sigma2 > 0.0)) return shrink;
362
363 const double neps = static_cast<double>(std::max<Eigen::Index>(1, nobs)) *
364 std::numeric_limits<double>::epsilon();
365 if (!(neps > 0.0 && neps < 1.0)) return shrink;
366 const double gamma_n = neps / (1.0 - neps);
367 const double eigengap_tol = std::sqrt(gamma_n);
368
369 Eigen::Index first = 0;
370 while (first < shrink.size()) {
371 Eigen::Index last = first + 1;
372 double lo = signal_eigvals(first);
373 double hi = signal_eigvals(first);
374 while (last < shrink.size()) {
375 const double candidate = signal_eigvals(last);
376 const double next_lo = std::min(lo, candidate);
377 const double next_hi = std::max(hi, candidate);
378 const double scale = std::max(std::abs(next_lo), std::abs(next_hi));
379 if (scale <= 0.0 || next_hi - next_lo > eigengap_tol * scale) break;
380 lo = next_lo;
381 hi = next_hi;
382 ++last;
383 }
384 if (last - first > 1) {
385 const double block = shrink.segment(first, last - first).mean();
386 shrink.segment(first, last - first).setConstant(block);
387 }
388 first = last;
389 }
390 return shrink;
391}
392
393double symmetricEigenUpperBound(const Eigen::MatrixXd& sym)
394{
395 if (sym.rows() != sym.cols())
396 return std::numeric_limits<double>::quiet_NaN();
397 if (sym.rows() == 0) return 0.0;
398
399 double upper = -std::numeric_limits<double>::infinity();
400 for (Eigen::Index i = 0; i < sym.rows(); ++i) {
401 double radius = 0.0;
402 for (Eigen::Index j = 0; j < sym.cols(); ++j) {
403 if (i == j) continue;
404 radius += std::abs(sym(i, j));
405 }
406 upper = std::max(upper, sym(i, i) + radius);
407 }
408 if (!std::isfinite(upper)) return upper;
409 return std::nextafter(std::max(0.0, upper),
410 std::numeric_limits<double>::infinity());
411}
412
413// Host eigenpairs of the dual kernel: Eigen's tridiagonalization and
414// implicit QR, compiled without EIGEN_USE_BLAS. LAPACK dsyevr reduces and
415// back-transforms on the OpenBLAS kernel the CPU selects at load, so its
416// eigenvectors, and the GP-NEB trajectory that follows them, moved with
417// OPENBLAS_CORETYPE. Canonical sign and tie order as for every driver.
418bool hostSymmetricEigenpairs(const Eigen::MatrixXd& sym, Eigen::VectorXd& evals,
419 Eigen::MatrixXd& evecs)
420{
421 if (!gpr::linalg::teamDivideConquerEigen(sym, evals, evecs)) return false;
422 if (evals.size() > 0) gpr::linalg::canonicalizeEigenpairs(evals, evecs);
423 return true;
424}
425
426// Eigenpairs with lambda > min_eval, ascending: the (vl, vu] value range of
427// the full spectrum with vu the Gershgorin bound.
428bool hostSymmetricEigenpairsAbove(const Eigen::MatrixXd& sym, double min_eval,
429 Eigen::VectorXd& evals,
430 Eigen::MatrixXd& evecs)
431{
432 if (sym.rows() != sym.cols()) return false;
433 if (!(min_eval >= 0.0) || !std::isfinite(min_eval)) return false;
434 if (sym.rows() == 0) {
435 evals.resize(0);
436 evecs.resize(0, 0);
437 return true;
438 }
439 const double upper = symmetricEigenUpperBound(sym);
440 if (!(std::isfinite(upper) && upper > min_eval)) return false;
441 Eigen::VectorXd all_evals;
442 Eigen::MatrixXd all_evecs;
443 if (!hostSymmetricEigenpairs(sym, all_evals, all_evecs)) return false;
444 Eigen::Index keep = 0;
445 for (Eigen::Index i = 0; i < all_evals.size(); ++i)
446 if (all_evals(i) > min_eval) ++keep;
447 evals = all_evals.tail(keep);
448 evecs = all_evecs.rightCols(keep);
449 return true;
450}
451
452// Full ascending eigendecomposition for the rank-N dual-kernel eigensolve --
453// the per-outer HS-SVD bottleneck. Tries the dlopen'd cuSOLVER
454// syevd first (GPU, present in build-gpu-scalapack on A100 nodes), then the
455// host solver. Both return the same ascending all-eigenpairs decomposition.
456// The host solver canonicalizes the sign and the near-tie order, so a
457// reconstruction and a mode that follows one column do not depend on the
458// CPU.
459
460namespace {
461// Every rank owns the replicated dual-kernel solve. Sharing one visible GPU
462// across ranks adds CUDA-context contention without distributing the work.
466bool reproducibleBasis() noexcept
467{
470}
471
472bool gpuEighUsableInProcess(const linalg::MpiContext& process_group) noexcept
473{
474 return detail::useGpuEigensolverForProcessCount(process_group.nprocs);
475}
476
477linalg::CusolverEighLib* availableGpuEigensolver(
478 const linalg::MpiContext& process_group)
479{
480 if (reproducibleBasis() || !gpuEighUsableInProcess(process_group))
481 return nullptr;
482 auto& cusolver = linalg::CusolverEighLib::instance();
483 return cusolver.available() ? &cusolver : nullptr;
484}
485} // namespace
486
491
514bool dispatchAllEigenpairs(linalg::BackendContext& context,
515 const Eigen::MatrixXd& sym,
516 Eigen::VectorXd& evals_asc,
517 Eigen::MatrixXd& evecs_asc, const char** driver_name)
518{
519#ifdef GPR_LINALG_SCALAPACK
520 auto& st = context.distributed();
521 st.initialize();
522 if (!reproducibleBasis() && linalg::unconstrainedLibraryReductions() &&
523 st.nprocs() > 1 &&
525 context.distributed_symmetric_eigen(sym, evals_asc, evecs_asc,
526 driver_name)) {
527 return true;
528 }
529#endif
530 if (driver_name != nullptr) *driver_name = "serial_floor";
531 return false;
532}
533
534bool fastAllEigenpairs(const linalg::MpiContext& process_group,
535 const Eigen::MatrixXd& sym, Eigen::VectorXd& evals,
536 Eigen::MatrixXd& evecs,
537 const char** driver_name = nullptr)
538{
539 const auto eigen_start = std::chrono::steady_clock::now();
540 const auto note_eigen = [&]() {
542 std::chrono::duration<double>(std::chrono::steady_clock::now() -
543 eigen_start)
544 .count();
545 };
546 if (reproducibleBasis()) {
547 const bool solved = hostSymmetricEigenpairs(sym, evals, evecs);
548 if (solved && driver_name != nullptr)
549 *driver_name = "eigen_selfadjoint";
550 note_eigen();
551 return solved;
552 }
553 auto* cusolver = availableGpuEigensolver(process_group);
554 if (cusolver && cusolver->allEigenpairs(sym, evals, evecs)) {
555 if (driver_name != nullptr) *driver_name = "cusolver_syevd";
556 note_eigen();
557 return true;
558 }
559 const bool valid = hostSymmetricEigenpairs(sym, evals, evecs);
560 if (valid && driver_name != nullptr) *driver_name = "eigen_selfadjoint";
561 note_eigen();
562 return valid;
563}
564
565// Eigenpairs with eigenvalue > min_eval, ascending. cuSOLVER syevd computes the
566// full spectrum, so this matches the LAPACK dsyevr range='V' half-open (vl, vu]
567// semantics by filtering the full ascending decomposition with the same strict
568// lower bound. The host solver filters its full spectrum the same way.
569bool fastEigenpairsAbove(const linalg::MpiContext& process_group,
570 const Eigen::MatrixXd& sym, double min_eval,
571 Eigen::VectorXd& evals, Eigen::MatrixXd& evecs,
572 const char** driver_name = nullptr)
573{
574 if (reproducibleBasis()) {
575 const bool valid =
576 hostSymmetricEigenpairsAbove(sym, min_eval, evals, evecs);
577 if (valid && driver_name != nullptr) *driver_name = "eigen_selfadjoint";
578 return valid;
579 }
580 auto* cusolver = availableGpuEigensolver(process_group);
581 if (cusolver) {
582 Eigen::VectorXd all_evals;
583 Eigen::MatrixXd all_evecs;
584 if (cusolver->allEigenpairs(sym, all_evals, all_evecs)) {
585 Eigen::Index keep = 0;
586 for (Eigen::Index i = 0; i < all_evals.size(); ++i)
587 if (all_evals(i) > min_eval) ++keep;
588 evals.resize(keep);
589 evecs.resize(all_evecs.rows(), keep);
590 Eigen::Index c = 0;
591 for (Eigen::Index i = 0; i < all_evals.size(); ++i) {
592 if (all_evals(i) > min_eval) {
593 evals(c) = all_evals(i);
594 evecs.col(c) = all_evecs.col(i);
595 ++c;
596 }
597 }
598 if (driver_name != nullptr) *driver_name = "cusolver_syevd";
599 return true;
600 }
601 }
602 const bool valid =
603 hostSymmetricEigenpairsAbove(sym, min_eval, evals, evecs);
604 if (valid && driver_name != nullptr) *driver_name = "eigen_selfadjoint";
605 return valid;
606}
607
608} // namespace
609
610namespace linalg {
611bool covarianceDsyevr(const Eigen::MatrixXd& sym, Eigen::VectorXd& evals,
612 Eigen::MatrixXd& evecs)
613{
614 return hostSymmetricEigenpairs(sym, evals, evecs);
615}
616} // namespace linalg
617
618bool detail::gpuFullKernelEigensolverAvailable() noexcept
619{
620 return gpuFullKernelEigensolverAvailable(linalg::BackendContext{}.mpi());
621}
622
623bool detail::gpuFullKernelEigensolverAvailable(
624 const linalg::MpiContext& process_group) noexcept
625{
626 return availableGpuEigensolver(process_group) != nullptr;
627}
628
630 : backend_context_(std::make_shared<linalg::BackendContext>())
631{
632}
633
634StableBasisND::StableBasisND(std::shared_ptr<linalg::BackendContext> context)
635 : backend_context_(std::move(context))
636{
637 if (!backend_context_)
638 throw std::invalid_argument("stable basis requires a backend context");
639}
640
641Eigen::MatrixXd StableBasis1D::eigenfunctions(const Eigen::VectorXd& x) const
642{
643 // phi_n(x) = sqrt(beta/(2^n n!)) exp(-delta2 x^2) H_n(alpha beta x), H_n
644 // the physicists' Hermite polynomial. Evaluated via the NORMALIZED
645 // recurrence
646 // psi_n(u) = sqrt(beta/(2^n n!)) H_n(u),
647 // psi_0 = sqrt(beta), psi_1 = sqrt(2 beta) u,
648 // psi_{n+1} = sqrt(2/(n+1)) u psi_n - sqrt(n/(n+1)) psi_{n-1},
649 // whose O(1) coefficients avoid the 2^n n! overflow of the direct form
650 // (numpy hermval overflowed for the large n the flat regime needs).
651 const Eigen::Index m = x.size();
652 Eigen::MatrixXd Phi(m, N_);
653 if (N_ <= 0) return Phi;
654 const Eigen::ArrayXd u = (alpha_ * beta_) * x.array();
655 const Eigen::ArrayXd env = (-delta2_ * x.array().square()).exp();
656 const double sb = std::sqrt(beta_);
657
658 Eigen::ArrayXd psi_prev = Eigen::ArrayXd::Constant(m, sb); // psi_0
659 Phi.col(0) = (env * psi_prev).matrix();
660 if (N_ >= 2) {
661 Eigen::ArrayXd psi_cur = std::sqrt(2.0) * sb * u; // psi_1
662 Phi.col(1) = (env * psi_cur).matrix();
663 for (int n = 1; n + 1 < N_; ++n) {
664 const double a = std::sqrt(2.0 / (n + 1));
665 const double b = std::sqrt(static_cast<double>(n) / (n + 1));
666 Eigen::ArrayXd psi_next = a * (u * psi_cur) - b * psi_prev;
667 Phi.col(n + 1) = (env * psi_next).matrix();
668 psi_prev = psi_cur;
669 psi_cur = psi_next;
670 }
671 }
672 return Phi;
673}
674
676 const Eigen::VectorXd& x, Eigen::MatrixXd& Phi,
677 Eigen::MatrixXd& dPhi_deps) const
678{
679 // Carries the normalized psi recurrence and its d/d(eps) in parallel; the
680 // env/u/beta eps-derivatives are the closed forms verified in
681 // scripts/derive_hssvd_eps_gradient.py.
682 const Eigen::Index m = x.size();
683 Phi.resize(m, N_);
684 dPhi_deps.resize(m, N_);
685 if (N_ <= 0) return;
686 const double dbeta = 2.0 * eps_ / (alpha_ * alpha_ * beta_ * beta_ * beta_);
687 const double ddelta2 = alpha_ * alpha_ * beta_ * dbeta;
688 const Eigen::ArrayXd u = (alpha_ * beta_) * x.array();
689 const Eigen::ArrayXd du = (alpha_ * dbeta) * x.array(); // d u/d eps
690 const Eigen::ArrayXd env = (-delta2_ * x.array().square()).exp();
691 const Eigen::ArrayXd denv =
692 env * (-x.array().square() * ddelta2); // d env/d eps
693 const double sb = std::sqrt(beta_);
694 const double dsb = dbeta / (2.0 * sb); // d sqrt(beta)/d eps
695
696 Eigen::ArrayXd psi_prev = Eigen::ArrayXd::Constant(m, sb); // psi_0
697 Eigen::ArrayXd dpsi_prev = Eigen::ArrayXd::Constant(m, dsb);
698 Phi.col(0) = (env * psi_prev).matrix();
699 dPhi_deps.col(0) = (denv * psi_prev + env * dpsi_prev).matrix();
700 if (N_ >= 2) {
701 Eigen::ArrayXd psi_cur = std::sqrt(2.0) * sb * u; // psi_1
702 Eigen::ArrayXd dpsi_cur = std::sqrt(2.0) * (dsb * u + sb * du);
703 Phi.col(1) = (env * psi_cur).matrix();
704 dPhi_deps.col(1) = (denv * psi_cur + env * dpsi_cur).matrix();
705 for (int n = 1; n + 1 < N_; ++n) {
706 const double a = std::sqrt(2.0 / (n + 1));
707 const double b = std::sqrt(static_cast<double>(n) / (n + 1));
708 Eigen::ArrayXd psi_next = a * (u * psi_cur) - b * psi_prev;
709 Eigen::ArrayXd dpsi_next =
710 a * (du * psi_cur + u * dpsi_cur) - b * dpsi_prev;
711 Phi.col(n + 1) = (env * psi_next).matrix();
712 dPhi_deps.col(n + 1) = (denv * psi_next + env * dpsi_next).matrix();
713 psi_prev = psi_cur;
714 psi_cur = psi_next;
715 dpsi_prev = dpsi_cur;
716 dpsi_cur = dpsi_next;
717 }
718 }
719}
720
722{
723 Eigen::VectorXd out(N_);
724 if (N_ <= 0) return out;
725 const double dbeta = 2.0 * eps_ / (alpha_ * alpha_ * beta_ * beta_ * beta_);
726 const double ddelta2 = alpha_ * alpha_ * beta_ * dbeta;
727 const double denom = alpha_ * alpha_ + delta2_ + eps_ * eps_;
728 const double ddenom = ddelta2 + 2.0 * eps_;
729 const double lam0 = std::sqrt(alpha_ * alpha_ / denom);
730 const double r = eps_ * eps_ / denom;
731 const double dlam0 = -alpha_ * ddenom / (2.0 * std::pow(denom, 1.5));
732 const double dr =
733 (2.0 * eps_ * denom - eps_ * eps_ * ddenom) / (denom * denom);
734 for (int n = 0; n < N_; ++n) {
735 out(n) = sqrt_lam_(n) * (dlam0 / (2.0 * lam0) +
736 static_cast<double>(n) * dr / (2.0 * r));
737 }
738 return out;
739}
740
741void StableBasis1D::factorize(const Eigen::VectorXd& x, double eps,
742 double alpha, int n_extra, double sv_rtol)
743{
744 eps_ = eps;
745 alpha_ = alpha;
746 M_ = static_cast<int>(x.size());
747 N_ = M_ + n_extra;
748 // Fasshauer-McCourt Gaussian-eigenpair constants (verified in
749 // scripts/derive_hssvd_gradient.py).
750 beta_ = std::pow(1.0 + std::pow(2.0 * eps / alpha, 2), 0.25);
751 delta2_ = alpha * alpha / 2.0 * (beta_ * beta_ - 1.0);
752 const double denom = alpha * alpha + delta2_ + eps * eps;
753 const double r = eps * eps / denom; // eigenvalue ratio < 1
754 const double lam0 = std::sqrt(alpha * alpha / denom);
755 // sqrt(lambda_n) = sqrt(lam0) * r^{n/2}
756 sqrt_lam_.resize(N_);
757 const double sqrt_lam0 = std::sqrt(lam0);
758 const double sqrt_r = std::sqrt(r);
759 double s = sqrt_lam0;
760 for (int n = 0; n < N_; ++n) {
761 sqrt_lam_(n) = s;
762 s *= sqrt_r;
763 }
764
765 // A = Phi diag(sqrt(lambda)) (M x N), so K = A A^T.
766 const Eigen::MatrixXd Phi = eigenfunctions(x); // M x N
767 Eigen::MatrixXd A = Phi;
768 A.array().rowwise() *= sqrt_lam_.transpose().array();
769
770 // Thin SVD: A = U S V^T. Stable basis Psi(x) = A(x) V S^{-1}; at the nodes
771 // Psi(X) = U (orthonormal) -> cond 1. Drop the Mercer tail (S <= rtol*S0)
772 // so 1/S does not reinject conditioning.
773 Eigen::BDCSVD<Eigen::MatrixXd> svd(
774 A, Eigen::ComputeThinU | Eigen::ComputeThinV);
775 const Eigen::VectorXd& S = svd.singularValues();
776 const double thresh = sv_rtol * S(0);
777 rank_ = 0;
778 while (rank_ < S.size() && S(rank_) > thresh)
779 ++rank_;
780
781 const Eigen::MatrixXd Vr = svd.matrixV().leftCols(rank_); // N x rank
782 const Eigen::VectorXd Sr = S.head(rank_);
783 W_ = Vr.array().rowwise() / Sr.transpose().array(); // N x rank
784 Psi_X_ = A * W_; // M x rank (= U[:,kept])
785}
786
787Eigen::VectorXd StableBasis1D::solve(const Eigen::VectorXd& y) const
788{
789 // Solve the interpolation system Psi_X b = y in least-squares sense.
790 //
791 // In exact arithmetic Psi_X = A V S^{-1} = U[:,kept] has orthonormal
792 // columns, which would make b = Psi_X^T y. In float64 that orthonormality
793 // is LOST at the threshold mode: the last retained singular value sits at
794 // ~sv_rtol*S0 ~ 1e-13*S0, so forming A (V/S) divides by ~1e-13 and the
795 // rounding in that column drifts Psi_X^T Psi_X from I by ~3e-6. The
796 // transpose shortcut then carries that ~3e-6 error into b, which inflates
797 // the train residual to ~1e-9 and the off-node error to ~1e-3. A
798 // column-pivoted Householder QR solves the actual least-squares problem and
799 // restores train RMSE ~1e-16 and off-node accuracy ~1e-10 at the same rank
800 // (matching numpy.linalg.lstsq in the prototype).
801 return Psi_X_.colPivHouseholderQr().solve(y);
802}
803
804Eigen::MatrixXd StableBasis1D::evalBasis(const Eigen::VectorXd& xstar) const
805{
806 Eigen::MatrixXd A = eigenfunctions(xstar); // m x N
807 A.array().rowwise() *= sqrt_lam_.transpose().array();
808 return A * W_; // m x rank
809}
810
811Eigen::VectorXd StableBasis1D::predict(const Eigen::VectorXd& xstar,
812 const Eigen::VectorXd& b) const
813{
814 return evalBasis(xstar) * b;
815}
816
818{
819 if (Psi_X_.size() == 0) return 0.0;
820 Eigen::BDCSVD<Eigen::MatrixXd> svd(Psi_X_);
821 const Eigen::VectorXd& S = svd.singularValues();
822 if (S.size() == 0 || S(S.size() - 1) == 0.0) return 0.0;
823 return S(0) / S(S.size() - 1);
824}
825
826// ---------------------------------------------------------------------------
827// StableBasisND: d-dimensional, gradient-enhanced stable basis.
828// ---------------------------------------------------------------------------
829
830namespace {
831
832// All multi-indices alpha in N^dim with sum(alpha) <= max_degree, graded order
833// (by total degree, then lexicographic) -- the tensor truncation set.
834Eigen::MatrixXi gradedMultiIndices(int dim, int max_degree)
835{
836 std::vector<std::vector<int>> idx;
837 std::vector<int> a(dim, 0);
838 // odometer over {0..max_degree}^dim, keep sum <= max_degree
839 while (true) {
840 int s = 0;
841 for (int k = 0; k < dim; ++k)
842 s += a[k];
843 if (s <= max_degree) idx.push_back(a);
844 int k = dim - 1;
845 while (k >= 0) {
846 if (++a[k] <= max_degree) break;
847 a[k] = 0;
848 --k;
849 }
850 if (k < 0) break;
851 }
852 std::sort(idx.begin(), idx.end(),
853 [](const std::vector<int>& p, const std::vector<int>& q) {
854 int sp = 0, sq = 0;
855 for (int v: p)
856 sp += v;
857 for (int v: q)
858 sq += v;
859 if (sp != sq) return sp < sq;
860 return p < q;
861 });
862 Eigen::MatrixXi M(static_cast<Eigen::Index>(idx.size()), dim);
863 for (Eigen::Index i = 0; i < M.rows(); ++i)
864 for (int k = 0; k < dim; ++k)
865 M(i, k) = idx[i][k];
866 return M;
867}
868
869} // namespace
870
871Eigen::Index StableBasisND::standardChop(const Eigen::VectorXd& coeffs,
872 double tol)
873{
874 // Port of the Aurentz-Trefethen standardChop algorithm
875 // (doi:10.1145/2998442). Indices are kept 1-based to match the paper;
876 // returns the count of leading entries to retain, or coeffs.size() when no
877 // plateau is found.
878 const int n = static_cast<int>(coeffs.size());
879 if (tol >= 1.0) return 1;
880 if (n < 17) return n;
881 // Step 1: monotone-nonincreasing envelope, normalized to begin at 1.
882 std::vector<double> m(n + 1, 0.0);
883 m[n] = std::abs(coeffs(n - 1));
884 for (int j = n - 1; j >= 1; --j)
885 m[j] = std::max(std::abs(coeffs(j - 1)), m[j + 1]);
886 if (m[1] == 0.0) return 1;
887 std::vector<double> env(n + 1, 0.0);
888 for (int j = 1; j <= n; ++j)
889 env[j] = m[j] / m[1];
890 // Step 2: scan for a plateau point.
891 int plateauPoint = 0, j2 = 0;
892 bool found = false;
893 for (int j = 2; j <= n; ++j) {
894 j2 = static_cast<int>(std::round(1.25 * j + 5.0));
895 if (j2 > n) return n; // no plateau -> not happy
896 const double e1 = env[j], e2 = env[j2];
897 const double r = 3.0 * (1.0 - std::log(e1) / std::log(tol));
898 if (e1 == 0.0 || e2 / e1 > r) {
899 plateauPoint = j - 1;
900 found = true;
901 break;
902 }
903 }
904 if (!found) return n;
905 // Step 3: refine the cutoff with a left-biasing linear tilt.
906 if (env[plateauPoint] == 0.0) return std::max(plateauPoint, 1);
907 const double t76 = std::pow(tol, 7.0 / 6.0);
908 int j3 = 0;
909 for (int j = 1; j <= n; ++j)
910 if (env[j] >= t76) ++j3;
911 if (j3 < j2) {
912 j2 = j3 + 1;
913 if (j2 <= n) env[j2] = t76;
914 }
915 const double slope = (-1.0 / 3.0) * std::log10(tol);
916 int dmin = 1;
917 double best = std::numeric_limits<double>::infinity();
918 for (int j = 1; j <= j2; ++j) {
919 const double lin = (j2 > 1) ? slope * static_cast<double>(j - 1) /
920 static_cast<double>(j2 - 1)
921 : 0.0;
922 const double cc = std::log10(env[j]) + lin;
923 if (cc < best) {
924 best = cc;
925 dmin = j;
926 }
927 }
928 return std::max(dmin - 1, 1);
929}
930
931int StableBasisND::autoMaxDegree(const Eigen::VectorXd& eps, double alpha,
932 int dim, double target_tol, int max_degree_cap)
933{
934 // The largest sqrt(lambda) at total degree D concentrates the degree in the
935 // slowest-decaying dimension: env(D) = prod_k sqrt(lam0_k) (max_k
936 // sqrt(r_k))^D, a geometric series. standardChop on this per-degree
937 // envelope returns where the Mercer expansion resolves the kernel to
938 // target_tol, giving an eps-adaptive degree in place of a fixed constant.
939 double prod_lam0 = 1.0, max_sqrt_r = 0.0;
940 for (int k = 0; k < dim; ++k) {
941 const double e = eps(k);
942 const double beta = std::pow(1.0 + std::pow(2.0 * e / alpha, 2), 0.25);
943 const double delta2 = alpha * alpha / 2.0 * (beta * beta - 1.0);
944 const double denom = alpha * alpha + delta2 + e * e;
945 const double rr = e * e / denom;
946 const double lam0 = std::sqrt(alpha * alpha / denom);
947 prod_lam0 *= std::sqrt(lam0);
948 max_sqrt_r = std::max(max_sqrt_r, std::sqrt(rr));
949 }
950 Eigen::VectorXd env(max_degree_cap + 1);
951 for (int D = 0; D <= max_degree_cap; ++D)
952 env(D) = prod_lam0 * std::pow(max_sqrt_r, static_cast<double>(D));
953 const int cut = static_cast<int>(standardChop(env, target_tol));
954 int deg = cut - 1; // degrees 0..cut-1 retained
955 if (deg < 1) deg = 1;
956 if (deg > max_degree_cap) deg = max_degree_cap;
957 return deg;
958}
959
961 Eigen::Index limit)
962{
963 if (dim < 0 || max_degree < 0 || limit < 0) return true;
964 if (dim == 0 || max_degree == 0) return 1 > limit;
965
966 const int k = std::min(dim, max_degree);
967 const int n = dim + max_degree;
968 long double count = 1.0L;
969 const long double cap = static_cast<long double>(limit);
970 for (int i = 1; i <= k; ++i) {
971 count *= static_cast<long double>(n - k + i);
972 count /= static_cast<long double>(i);
973 if (count > cap) return true;
974 }
975 return count > cap;
976}
977
978int StableBasisND::capMaxDegreeByModeCount(int dim, int requested_degree,
979 Eigen::Index mode_limit)
980{
981 if (requested_degree <= 0) return 0;
982 if (mode_limit <= 0) return 0;
983 int degree = requested_degree;
984 while (degree > 0 && gradedModeCountExceedsLimit(dim, degree, mode_limit))
985 --degree;
986 return degree;
987}
988
989namespace {
990std::atomic<std::size_t> g_stable_basis_factorizations{0};
991}
993{
994 return g_stable_basis_factorizations.load(std::memory_order_relaxed);
995}
996void StableBasisND::recordDroppedSpectrum(const Eigen::VectorXd& S)
997{
998 // Largest eigenvalue s^2 the truncation discarded: the exact weight of a
999 // discarded component in (K + sigma2 I)^-1 lies in
1000 // [1/(dropped_s2_max_ + sigma2), 1/sigma2]; the posterior formulas use
1001 // the lower end, which never overshoots the explicit posterior and is
1002 // exact to dropped_s2_max_/sigma2 relative (eps s2_max/sigma2 for the
1003 // resolution cutoff).
1004 //
1005 // A dropped eigenvalue below the eigensolver's backward error n eps s2_max
1006 // is rounding, not spectrum: its size and sign change with the solver,
1007 // and a weight 1/(s2 + sigma2) built on it moves every posterior
1008 // quantity by s2/sigma2 relative from one evaluation to the next. Such a
1009 // direction is null, and its weight is 1/sigma2.
1010 dropped_s2_max_ = 0.0;
1011 if (rank_ >= 0 && rank_ < S.size()) {
1012 const double s = S(rank_);
1013 const double s2 = std::isfinite(s) ? s * s : 0.0;
1014 const double s2_max =
1015 S.size() > 0 && std::isfinite(S(0)) ? S(0) * S(0) : 0.0;
1016 const double resolution =
1017 static_cast<double>(std::max<Eigen::Index>(1, S.size())) *
1018 std::numeric_limits<double>::epsilon() * s2_max;
1019 dropped_s2_max_ = s2 > resolution ? s2 : 0.0;
1020 }
1021}
1022
1023void StableBasisND::factorizeKernel(const Eigen::MatrixXd& kernel,
1024 double sv_rtol, double sv_abs_tol,
1025 double sv_chop_tol)
1026{
1027 bordered_kernel_.resize(0, 0);
1028 bordered_assembly_error_ = 0.0;
1029 clearBorderedCache();
1032 PhaseTimers::factorization_rows += kernel.rows();
1033 g_stable_basis_factorizations.fetch_add(1, std::memory_order_relaxed);
1034 lapack_rrr_value_range_used_ = false;
1035 fast_kernel_eigensolver_used_ = false;
1036 last_kernel_factorize_driver_ = "eigen";
1037 condition_number_ = 0.0;
1038 dim_ = 0;
1039 M_ = static_cast<int>(kernel.rows());
1040 max_degree_ = 0;
1041 gradient_enhanced_ = true;
1042 affine_full_dim_ = 0;
1043 midx_.resize(0, 0);
1044 sqrt_lam_.resize(0);
1045 W_.resize(0, 0);
1046 A_train_.resize(0, 0);
1047 noisy_eigvals_.resize(0);
1048
1049 if (kernel.rows() == 0 || kernel.rows() != kernel.cols()) {
1050 rank_ = 0;
1051 Psi_.resize(kernel.rows(), 0);
1052 Sr_.resize(0);
1053 return;
1054 }
1055
1056 Eigen::MatrixXd sym = 0.5 * (kernel + kernel.transpose());
1057 bordered_assembly_error_ = kernelAssemblyErrorBound(kernel, sym);
1058 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1059 timedSymmetricEigen(sym);
1060 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0) {
1061 rank_ = 0;
1062 Psi_.resize(kernel.rows(), 0);
1063 Sr_.resize(0);
1064 return;
1065 }
1066
1067 Eigen::VectorXd evals_asc = es.eigenvalues();
1068 Eigen::MatrixXd evecs_asc = es.eigenvectors();
1069 gpr::linalg::canonicalizeEigenpairs(evals_asc, evecs_asc);
1070 const Eigen::Index n = evals_asc.size();
1071 Eigen::VectorXd S(n);
1072 for (Eigen::Index i = 0; i < n; ++i) {
1073 const Eigen::Index src = n - 1 - i;
1074 S(i) = std::sqrt(std::max(0.0, evals_asc(src)));
1075 }
1076
1077 rank_ = static_cast<int>(keptSingularRankWithChop(
1078 S, dualKernelSingularCutoff(S, sv_rtol, sv_abs_tol), sv_chop_tol,
1079 chop_sigma2_));
1081 Sr_ = S.head(rank_);
1082 Psi_.resize(kernel.rows(), rank_);
1083 for (Eigen::Index i = 0; i < rank_; ++i) {
1084 const Eigen::Index src = n - 1 - i;
1085 Psi_.col(i) = evecs_asc.col(src);
1086 }
1087 bordered_kernel_ = std::move(sym);
1088 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1089}
1090
1091#ifdef GPR_LINALG_SCALAPACK
1092bool StableBasisND::factorizeKernelDistributed(const Eigen::MatrixXd& kernel,
1093 double sv_rtol,
1094 double sv_abs_tol,
1095 double sv_chop_tol)
1096{
1097 bordered_kernel_.resize(0, 0);
1098 bordered_assembly_error_ = 0.0;
1099 clearBorderedCache();
1102 PhaseTimers::factorization_rows += kernel.rows();
1103 lapack_rrr_value_range_used_ = false;
1104 last_kernel_factorize_driver_ = "serial_floor";
1105 condition_number_ = 0.0;
1106 dim_ = 0;
1107 M_ = static_cast<int>(kernel.rows());
1108 max_degree_ = 0;
1109 gradient_enhanced_ = true;
1110 affine_full_dim_ = 0;
1111 midx_.resize(0, 0);
1112 sqrt_lam_.resize(0);
1113 W_.resize(0, 0);
1114 A_train_.resize(0, 0);
1115 noisy_eigvals_.resize(0);
1116
1117 if (kernel.rows() == 0 || kernel.rows() != kernel.cols()) {
1118 rank_ = 0;
1119 Psi_.resize(kernel.rows(), 0);
1120 Sr_.resize(0);
1121 return kernel.rows() == kernel.cols();
1122 }
1123
1124 Eigen::MatrixXd sym = 0.5 * (kernel + kernel.transpose());
1125 bordered_assembly_error_ = kernelAssemblyErrorBound(kernel, sym);
1126 Eigen::MatrixXd evecs_asc;
1127 Eigen::VectorXd evals_asc;
1128 if (kernel.rows() >
1129 static_cast<Eigen::Index>(std::numeric_limits<int>::max())) {
1130 rank_ = 0;
1131 Psi_.resize(kernel.rows(), 0);
1132 Sr_.resize(0);
1133 return false;
1134 }
1135 auto& st = backend().distributed();
1136 st.initialize();
1137 int eigensystem_ok = 0;
1138 const char* full_driver = "serial_floor";
1139 last_kernel_factorize_driver_ = full_driver;
1140 if (dispatchAllEigenpairs(backend(), sym, evals_asc, evecs_asc,
1141 &full_driver)) {
1142 eigensystem_ok = 1;
1143 last_kernel_factorize_driver_ = full_driver;
1144 }
1145 if (eigensystem_ok == 0) {
1146 if (st.is_root()) {
1147 eigensystem_ok =
1148 fastAllEigenpairs(backend().mpi(), sym, evals_asc, evecs_asc)
1149 ? 1
1150 : 0;
1151 if (eigensystem_ok == 0) {
1152 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1153 timedSymmetricEigen(sym);
1154 if (es.info() == Eigen::Success &&
1155 es.eigenvalues().size() > 0) {
1156 evals_asc = es.eigenvalues();
1157 evecs_asc = es.eigenvectors();
1158 gpr::linalg::canonicalizeEigenpairs(evals_asc, evecs_asc);
1159 eigensystem_ok = 1;
1160 }
1161 }
1162 }
1163 MPI_Bcast(&eigensystem_ok, 1, MPI_INT, 0, st.world_comm());
1164 const int n_int = static_cast<int>(kernel.rows());
1165 if (eigensystem_ok != 0) {
1166 if (!st.is_root()) {
1167 evals_asc.resize(n_int);
1168 evecs_asc.resize(n_int, n_int);
1169 }
1170 MPI_Bcast(evals_asc.data(), n_int, MPI_DOUBLE, 0, st.world_comm());
1171 MPI_Bcast(evecs_asc.data(), n_int * n_int, MPI_DOUBLE, 0,
1172 st.world_comm());
1173 }
1174 }
1175 if (eigensystem_ok == 0 || evals_asc.size() == 0 ||
1176 evecs_asc.rows() != kernel.rows()) {
1177 rank_ = 0;
1178 Psi_.resize(kernel.rows(), 0);
1179 Sr_.resize(0);
1180 return false;
1181 }
1182
1183 const Eigen::Index n = evals_asc.size();
1184 Eigen::VectorXd S(n);
1185 for (Eigen::Index i = 0; i < n; ++i) {
1186 const Eigen::Index src = n - 1 - i;
1187 S(i) = std::sqrt(std::max(0.0, evals_asc(src)));
1188 }
1189
1190 rank_ = static_cast<int>(keptSingularRankWithChop(
1191 S, dualKernelSingularCutoff(S, sv_rtol, sv_abs_tol), sv_chop_tol,
1192 chop_sigma2_));
1194 Sr_ = S.head(rank_);
1195 Psi_.resize(kernel.rows(), rank_);
1196 for (Eigen::Index i = 0; i < rank_; ++i) {
1197 const Eigen::Index src = n - 1 - i;
1198 Psi_.col(i) = evecs_asc.col(src);
1199 }
1200 bordered_kernel_ = std::move(sym);
1201 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1202 return true;
1203}
1204#endif
1205
1206bool StableBasisND::factorizeKernelLapackRrr(const Eigen::MatrixXd& kernel,
1207 double sv_rtol, double sv_abs_tol,
1208 double sv_chop_tol,
1209 bool allow_value_range)
1210{
1211 bordered_kernel_.resize(0, 0);
1212 bordered_assembly_error_ = 0.0;
1213 clearBorderedCache();
1216 PhaseTimers::factorization_rows += kernel.rows();
1217 lapack_rrr_value_range_used_ = false;
1218 last_kernel_factorize_driver_ = "unset";
1219 condition_number_ = 0.0;
1220 dim_ = 0;
1221 M_ = static_cast<int>(kernel.rows());
1222 max_degree_ = 0;
1223 gradient_enhanced_ = true;
1224 affine_full_dim_ = 0;
1225 midx_.resize(0, 0);
1226 sqrt_lam_.resize(0);
1227 W_.resize(0, 0);
1228 A_train_.resize(0, 0);
1229 noisy_eigvals_.resize(0);
1230
1231 if (kernel.rows() == 0 || kernel.rows() != kernel.cols()) {
1232 rank_ = 0;
1233 Psi_.resize(kernel.rows(), 0);
1234 Sr_.resize(0);
1235 return kernel.rows() == kernel.cols();
1236 }
1237
1238 Eigen::MatrixXd sym = 0.5 * (kernel + kernel.transpose());
1239 bordered_assembly_error_ = kernelAssemblyErrorBound(kernel, sym);
1240 Eigen::VectorXd evals_asc;
1241 Eigen::MatrixXd evecs_asc;
1242 bool used_cached_spectrum = false;
1243 const Eigen::Index cached_n = cached_spectrum_matrix_.rows();
1244 if (cached_n > 0 && cached_n < sym.rows() &&
1245 cached_spectrum_evals_.size() == cached_n &&
1246 cached_spectrum_evecs_.rows() == cached_n &&
1247 cached_spectrum_evecs_.cols() == cached_n &&
1248 sym.topLeftCorner(cached_n, cached_n) == cached_spectrum_matrix_ &&
1249 extendSymmetricSpectrum(sym, cached_spectrum_evals_,
1250 cached_spectrum_evecs_, evals_asc, evecs_asc)) {
1251 used_cached_spectrum = true;
1252 ++lapack_rrr_extensions_;
1253 last_kernel_factorize_driver_ = "lapack_rrr_arrowhead";
1254 } else if (cached_n == sym.rows() && cached_spectrum_matrix_ == sym &&
1255 cached_spectrum_evals_.size() == cached_n &&
1256 cached_spectrum_evecs_.cols() == cached_n) {
1257 evals_asc = cached_spectrum_evals_;
1258 evecs_asc = cached_spectrum_evecs_;
1259 used_cached_spectrum = true;
1260 last_kernel_factorize_driver_ = "lapack_rrr_cache";
1261 }
1262 bool used_value_range = false;
1263 // DSYEVR range='V' returns eigenpairs with lambda in (vl, vu]. The HS-SVD
1264 // cutoff keeps singular values S > max(sv_rtol*S0, sv_abs_tol). A
1265 // Gershgorin upper bound S0 <= sqrt(upper_eval) proves that sv_abs_tol is
1266 // the active cutoff here, so vl=sv_abs_tol^2 removes exactly the same tail
1267 // as the full-spectrum path. standardChop needs the tail shape and keeps
1268 // the full-spectrum driver.
1269 if (!used_cached_spectrum && allow_value_range && sv_chop_tol <= 0.0 &&
1270 sv_abs_tol > 0.0) {
1271 const double upper_eval = symmetricEigenUpperBound(sym);
1272 const double upper_singular = std::sqrt(std::max(0.0, upper_eval));
1273 if (std::isfinite(upper_singular) &&
1274 sv_abs_tol >= sv_rtol * upper_singular &&
1275 fastEigenpairsAbove(backend().mpi(), sym, sv_abs_tol * sv_abs_tol,
1276 evals_asc, evecs_asc,
1277 &last_kernel_factorize_driver_)) {
1278 used_value_range = true;
1279 }
1280 }
1281 if (!used_cached_spectrum && !used_value_range &&
1282 !fastAllEigenpairs(backend().mpi(), sym, evals_asc, evecs_asc,
1283 &last_kernel_factorize_driver_)) {
1284 rank_ = 0;
1285 Psi_.resize(kernel.rows(), 0);
1286 Sr_.resize(0);
1287 return false;
1288 }
1289 if (evals_asc.size() == 0) {
1290 rank_ = 0;
1291 Psi_.resize(kernel.rows(), 0);
1292 Sr_.resize(0);
1293 lapack_rrr_value_range_used_ = used_value_range;
1294 return true;
1295 }
1296 if (!used_cached_spectrum && !used_value_range) ++lapack_rrr_full_solves_;
1297 // A partial value-range spectrum is not a basis the next border can
1298 // extend. The full spectrum is the one DSYEVR would return again.
1299 if (!used_value_range && evals_asc.size() == sym.rows() &&
1300 evecs_asc.cols() >= sym.rows()) {
1301 cached_spectrum_matrix_ = sym;
1302 cached_spectrum_evals_ = evals_asc;
1303 cached_spectrum_evecs_ = evecs_asc.leftCols(sym.rows());
1304 }
1305
1306 const Eigen::Index n = evals_asc.size();
1307 Eigen::VectorXd S(n);
1308 for (Eigen::Index i = 0; i < n; ++i) {
1309 const Eigen::Index src = n - 1 - i;
1310 S(i) = std::sqrt(std::max(0.0, evals_asc(src)));
1311 }
1312
1313 rank_ = static_cast<int>(keptSingularRankWithChop(
1314 S, dualKernelSingularCutoff(S, sv_rtol, sv_abs_tol), sv_chop_tol,
1315 chop_sigma2_));
1317 Sr_ = S.head(rank_);
1318 Psi_.resize(kernel.rows(), rank_);
1319 for (Eigen::Index i = 0; i < rank_; ++i) {
1320 const Eigen::Index src = n - 1 - i;
1321 Psi_.col(i) = evecs_asc.col(src);
1322 }
1323 bordered_kernel_ = std::move(sym);
1324 lapack_rrr_value_range_used_ = used_value_range;
1325 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1326 return true;
1327}
1328
1329namespace {
1330
1331// Shared finalization for the noisy-objective factorizations. evals_asc /
1332// evecs_asc hold the ascending eigensystem of C = K + sigma2 I; this stores
1333// the descending noisy eigenvalues mu_i, the orthonormal eigenbasis Psi, and
1334// the signal singular values Sr_(i) = sqrt(max(0, mu_i - sigma2)) used only by
1335// the shrink / predict paths. No eigenpair is dropped: the objective needs the
1336// full spectrum so the logdet and quadratic form are exact eigen-contractions.
1337void finalizeNoisyKernel(const Eigen::VectorXd& evals_asc,
1338 const Eigen::MatrixXd& evecs_asc, double sigma2,
1339 int& rank_out, Eigen::MatrixXd& Psi_out,
1340 Eigen::VectorXd& Sr_out, Eigen::VectorXd& mu_out,
1341 double& condition_number_out)
1342{
1343 const Eigen::Index n = evals_asc.size();
1344 Psi_out.resize(evecs_asc.rows(), n);
1345 Sr_out.resize(n);
1346 mu_out.resize(n);
1347 for (Eigen::Index i = 0; i < n; ++i) {
1348 const Eigen::Index src = n - 1 - i; // descending
1349 const double mu = std::max(sigma2, evals_asc(src));
1350 mu_out(i) = mu;
1351 Sr_out(i) = std::sqrt(std::max(0.0, mu - sigma2));
1352 Psi_out.col(i) = evecs_asc.col(src);
1353 }
1354 rank_out = static_cast<int>(n);
1355 condition_number_out = n > 0 ? 1.0 : 0.0;
1356}
1357
1358} // namespace
1359
1360void StableBasisND::factorizeNoisyKernel(const Eigen::MatrixXd& noisy_kernel,
1361 double sigma2)
1362{
1363 bordered_kernel_.resize(0, 0);
1364 bordered_assembly_error_ = 0.0;
1365 clearBorderedCache();
1368 PhaseTimers::factorization_rows += noisy_kernel.rows();
1369 lapack_rrr_value_range_used_ = false;
1370 condition_number_ = 0.0;
1371 dim_ = 0;
1372 M_ = static_cast<int>(noisy_kernel.rows());
1373 max_degree_ = 0;
1374 gradient_enhanced_ = true;
1375 affine_full_dim_ = 0;
1376 midx_.resize(0, 0);
1377 sqrt_lam_.resize(0);
1378 W_.resize(0, 0);
1379 A_train_.resize(0, 0);
1380 noisy_eigvals_.resize(0);
1381
1382 if (noisy_kernel.rows() == 0 ||
1383 noisy_kernel.rows() != noisy_kernel.cols()) {
1384 rank_ = 0;
1385 Psi_.resize(noisy_kernel.rows(), 0);
1386 Sr_.resize(0);
1387 return;
1388 }
1389
1390 const Eigen::MatrixXd sym = 0.5 * (noisy_kernel + noisy_kernel.transpose());
1391 // cuSOLVER syevd is divide-and-conquer -- the GPU equivalent of Eigen's
1392 // SelfAdjointEigenSolver -- so it is the faithful accelerator for this
1393 // (non-RRR) path. The flag's MRRR algorithm choice is preserved on the
1394 // CPU fallback below.
1395 auto* cusolver = availableGpuEigensolver(backend().mpi());
1396 Eigen::VectorXd evals_gpu;
1397 Eigen::MatrixXd evecs_gpu;
1398 if (cusolver && cusolver->allEigenpairs(sym, evals_gpu, evecs_gpu) &&
1399 evals_gpu.size() > 0) {
1400 finalizeNoisyKernel(evals_gpu, evecs_gpu, sigma2, rank_, Psi_, Sr_,
1401 noisy_eigvals_, condition_number_);
1402 return;
1403 }
1404 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1405 timedSymmetricEigen(sym);
1406 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0) {
1407 rank_ = 0;
1408 Psi_.resize(noisy_kernel.rows(), 0);
1409 Sr_.resize(0);
1410 return;
1411 }
1412 finalizeNoisyKernel(es.eigenvalues(), es.eigenvectors(), sigma2, rank_,
1413 Psi_, Sr_, noisy_eigvals_, condition_number_);
1414}
1415
1417 const Eigen::MatrixXd& noisy_kernel, double sigma2)
1418{
1419 bordered_kernel_.resize(0, 0);
1420 bordered_assembly_error_ = 0.0;
1421 clearBorderedCache();
1424 PhaseTimers::factorization_rows += noisy_kernel.rows();
1425 lapack_rrr_value_range_used_ = false;
1426 condition_number_ = 0.0;
1427 dim_ = 0;
1428 M_ = static_cast<int>(noisy_kernel.rows());
1429 max_degree_ = 0;
1430 gradient_enhanced_ = true;
1431 affine_full_dim_ = 0;
1432 midx_.resize(0, 0);
1433 sqrt_lam_.resize(0);
1434 W_.resize(0, 0);
1435 A_train_.resize(0, 0);
1436 noisy_eigvals_.resize(0);
1437
1438 if (noisy_kernel.rows() == 0 ||
1439 noisy_kernel.rows() != noisy_kernel.cols()) {
1440 rank_ = 0;
1441 Psi_.resize(noisy_kernel.rows(), 0);
1442 Sr_.resize(0);
1443 return noisy_kernel.rows() == noisy_kernel.cols();
1444 }
1445
1446 const Eigen::MatrixXd sym = 0.5 * (noisy_kernel + noisy_kernel.transpose());
1447 Eigen::VectorXd evals_asc;
1448 Eigen::MatrixXd evecs_asc;
1449 if (!fastAllEigenpairs(backend().mpi(), sym, evals_asc, evecs_asc)) {
1450 rank_ = 0;
1451 Psi_.resize(noisy_kernel.rows(), 0);
1452 Sr_.resize(0);
1453 return false;
1454 }
1455 if (evals_asc.size() == 0) {
1456 rank_ = 0;
1457 Psi_.resize(noisy_kernel.rows(), 0);
1458 Sr_.resize(0);
1459 return true;
1460 }
1461 finalizeNoisyKernel(evals_asc, evecs_asc, sigma2, rank_, Psi_, Sr_,
1462 noisy_eigvals_, condition_number_);
1463 return true;
1464}
1465
1466void StableBasisND::factorizeKernelRandomized(const Eigen::MatrixXd& kernel,
1467 int sketch_size, int n_power_iter,
1468 double sv_rtol, double sv_abs_tol,
1469 double sv_chop_tol)
1470{
1471 bordered_kernel_.resize(0, 0);
1472 bordered_assembly_error_ = 0.0;
1473 clearBorderedCache();
1474 lapack_rrr_value_range_used_ = false;
1475 condition_number_ = 0.0;
1476 if (sketch_size <= 0) {
1477 factorizeKernel(kernel, sv_rtol, sv_abs_tol, sv_chop_tol);
1478 return;
1479 }
1480
1481 dim_ = 0;
1482 M_ = static_cast<int>(kernel.rows());
1483 max_degree_ = 0;
1484 gradient_enhanced_ = true;
1485 affine_full_dim_ = 0;
1486 midx_.resize(0, 0);
1487 sqrt_lam_.resize(0);
1488 W_.resize(0, 0);
1489 A_train_.resize(0, 0);
1490
1491 if (kernel.rows() == 0 || kernel.rows() != kernel.cols()) {
1492 rank_ = 0;
1493 Psi_.resize(kernel.rows(), 0);
1494 Sr_.resize(0);
1495 return;
1496 }
1497
1498 Eigen::MatrixXd sym = 0.5 * (kernel + kernel.transpose());
1499 bordered_assembly_error_ = kernelAssemblyErrorBound(kernel, sym);
1500 const Eigen::Index n = sym.rows();
1501 Eigen::Index l = std::min<Eigen::Index>(
1502 std::max<Eigen::Index>(1, static_cast<Eigen::Index>(sketch_size)), n);
1503 const int n_power = std::max(0, n_power_iter);
1504
1505 for (;;) {
1506 std::mt19937_64 gen(0x5EED1234ULL);
1507 std::normal_distribution<double> nd(0.0, 1.0);
1508 Eigen::MatrixXd Omega(n, l);
1509 for (Eigen::Index j = 0; j < l; ++j)
1510 for (Eigen::Index i = 0; i < n; ++i)
1511 Omega(i, j) = nd(gen);
1512
1513 Eigen::MatrixXd Y = sym * Omega;
1514 for (int p = 0; p < n_power; ++p) {
1515 const Eigen::MatrixXd Qp =
1516 Eigen::HouseholderQR<Eigen::MatrixXd>(Y).householderQ() *
1517 Eigen::MatrixXd::Identity(n, l);
1518 Y = sym * Qp;
1519 }
1520 const Eigen::MatrixXd Q =
1521 Eigen::HouseholderQR<Eigen::MatrixXd>(Y).householderQ() *
1522 Eigen::MatrixXd::Identity(n, l);
1523 Eigen::MatrixXd T = Q.transpose() * sym * Q;
1524 T = 0.5 * (T + T.transpose()).eval();
1525
1526 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1527 timedSymmetricEigen(T);
1528 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0) {
1529 rank_ = 0;
1530 Psi_.resize(n, 0);
1531 Sr_.resize(0);
1532 return;
1533 }
1534
1535 const Eigen::VectorXd evals_asc = es.eigenvalues();
1536 const Eigen::MatrixXd evecs_asc = es.eigenvectors();
1537 Eigen::VectorXd S(l);
1538 Eigen::MatrixXd Z(l, l);
1539 for (Eigen::Index i = 0; i < l; ++i) {
1540 const Eigen::Index src = l - 1 - i;
1541 S(i) = std::sqrt(std::max(0.0, evals_asc(src)));
1542 Z.col(i) = evecs_asc.col(src);
1543 }
1544
1545 const Eigen::Index rk = keptSingularRankWithChop(
1546 S, dualKernelSingularCutoff(S, sv_rtol, sv_abs_tol), sv_chop_tol,
1547 chop_sigma2_);
1548 if (rk == l && l < n) {
1549 l = std::min<Eigen::Index>(2 * l, n);
1550 continue;
1551 }
1552
1553 rank_ = static_cast<int>(rk);
1554
1556 Sr_ = S.head(rk);
1557 Psi_ = Q * Z.leftCols(rk);
1558 bordered_kernel_ = std::move(sym);
1559 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1560 return;
1561 }
1562}
1563
1565 Eigen::Index full_rows, Eigen::MatrixXd lifted_psi,
1566 const detail::RigidDeflationState& deflation, double extra_assembly_error)
1567{
1568 M_ = static_cast<int>(full_rows);
1569 Psi_ = std::move(lifted_psi);
1570 const Eigen::Index expected_deflated = deflation.deflated_rows;
1571 const bool has_deflated_bordered =
1572 deflation.active && deflation.full_rows == full_rows &&
1573 bordered_kernel_.rows() == expected_deflated &&
1574 bordered_kernel_.cols() == expected_deflated;
1575 clearBorderedCache();
1576 if (has_deflated_bordered) {
1577 if (extra_assembly_error > 0.0 && std::isfinite(extra_assembly_error)) {
1578 bordered_assembly_error_ += extra_assembly_error;
1579 }
1580 bordered_deflation_ =
1581 std::make_shared<detail::RigidDeflationState>(deflation);
1582 } else {
1583 bordered_kernel_.resize(0, 0);
1584 bordered_assembly_error_ = 0.0;
1585 }
1586}
1587
1589 const Eigen::MatrixXd& cross_old_new,
1590 const Eigen::MatrixXd& new_kernel,
1591 double sv_rtol, double sv_abs_tol,
1592 double sv_chop_tol)
1593{
1594 const Eigen::MatrixXd& old_bordered = old_basis.bordered_kernel_;
1595 const double old_asm_error = old_basis.bordered_assembly_error_;
1596 bordered_kernel_.resize(0, 0);
1597 bordered_assembly_error_ = 0.0;
1598 clearBorderedCache();
1599 g_stable_basis_factorizations.fetch_add(1, std::memory_order_relaxed);
1600 lapack_rrr_value_range_used_ = false;
1601 fast_kernel_eigensolver_used_ = false;
1602 condition_number_ = 0.0;
1603 dim_ = 0;
1604 M_ = static_cast<int>(old_basis.numObs() + new_kernel.rows());
1605 max_degree_ = 0;
1606 gradient_enhanced_ = true;
1607 affine_full_dim_ = 0;
1608 overall_scale_ = 1.0;
1609 eps_.resize(0);
1610 beta_.resize(0);
1611 delta2_.resize(0);
1612 midx_.resize(0, 0);
1613 sqrt_lam_.resize(0);
1614 W_.resize(0, 0);
1615 A_train_.resize(0, 0);
1616
1617 const Eigen::Index n_old = old_basis.numObs();
1618 const Eigen::Index n_new = new_kernel.rows();
1619 const Eigen::Index r_old = old_basis.rank();
1620 if (n_old <= 0 || n_new <= 0 || new_kernel.cols() != n_new ||
1621 cross_old_new.rows() != n_old || cross_old_new.cols() != n_new ||
1622 old_basis.leftSingularVectors().rows() != n_old ||
1623 old_basis.leftSingularVectors().cols() != r_old ||
1624 old_basis.singularValues().size() != r_old || r_old <= 0) {
1625 rank_ = 0;
1626 Psi_.resize(std::max<Eigen::Index>(0, n_old + n_new), 0);
1627 Sr_.resize(0);
1628 return false;
1629 }
1630
1631 const Eigen::MatrixXd& U = old_basis.leftSingularVectors();
1632 const Eigen::VectorXd& S = old_basis.singularValues();
1633 const Eigen::MatrixXd C = cross_old_new;
1634 const Eigen::MatrixXd D = 0.5 * (new_kernel + new_kernel.transpose());
1635
1636 Eigen::MatrixXd UtC;
1638 UtC = linalg::trainingProduct(U, C, true);
1639 else
1640 UtC.noalias() = U.transpose() * C;
1641 const Eigen::MatrixXd residual = C - U * UtC;
1642
1643 Eigen::MatrixXd Q(n_old, 0);
1644 if (residual.size() > 0) {
1645 Eigen::BDCSVD<Eigen::MatrixXd> rsvd(residual, Eigen::ComputeThinU);
1646 const Eigen::VectorXd& Rsv = rsvd.singularValues();
1647 Eigen::Index q_rank = 0;
1648 if (Rsv.size() > 0 && Rsv(0) > 0.0) {
1649 const double kernel_scale =
1650 std::max(C.norm(), S.array().square().matrix().norm());
1651 const double tol = std::numeric_limits<double>::epsilon() *
1652 static_cast<double>(
1653 std::max(residual.rows(), residual.cols())) *
1654 kernel_scale;
1655 while (q_rank < Rsv.size() && Rsv(q_rank) > tol)
1656 ++q_rank;
1657 }
1658 if (q_rank > 0) {
1659 Q = rsvd.matrixU().leftCols(q_rank);
1660 Q -= U * (U.transpose() * Q);
1661 Q = Eigen::HouseholderQR<Eigen::MatrixXd>(Q).householderQ() *
1662 Eigen::MatrixXd::Identity(n_old, q_rank);
1663 }
1664 }
1665
1666 const Eigen::Index q = Q.cols();
1667 const Eigen::Index m_small = r_old + q + n_new;
1668 Eigen::MatrixXd projected = Eigen::MatrixXd::Zero(m_small, m_small);
1669 projected.topLeftCorner(r_old, r_old).diagonal() =
1670 S.array().square().matrix();
1671 projected.block(0, r_old + q, r_old, n_new) = UtC;
1672 projected.block(r_old + q, 0, n_new, r_old) = UtC.transpose();
1673 if (q > 0) {
1674 Eigen::MatrixXd QtC;
1676 QtC = linalg::trainingProduct(Q, C, true);
1677 else
1678 QtC.noalias() = Q.transpose() * C;
1679 projected.block(r_old, r_old + q, q, n_new) = QtC;
1680 projected.block(r_old + q, r_old, n_new, q) = QtC.transpose();
1681 }
1682 projected.bottomRightCorner(n_new, n_new) = D;
1683 projected = 0.5 * (projected + projected.transpose()).eval();
1684
1685 Eigen::VectorXd evals_asc;
1686 Eigen::MatrixXd evecs_asc;
1687 // Same dispatch as the full-refactorize paths: distributed across ranks
1688 // when there is more than one, else cuSOLVER above the size floor and
1689 // LAPACK below it. The projected block is near-full-size on
1690 // flat-spectrum kernels, so this eigensolve dominates the per-append
1691 // cost and is the one worth spreading.
1692 // This block is a diagonal bordered by the appended rows, because U
1693 // already diagonalises the old kernel, and an arrowhead has an
1694 // O(k m^2) solver where this dense call is O(m^3). It is not used,
1695 // and the reason is the width: an acquisition appends
1696 // delta_images * (1 + 3 natoms) rows, so k is thirty to sixty rather
1697 // than one or two. gpr::linalg::arrowheadEigen absorbs one border
1698 // column per pass and accumulates the basis with a dense product each
1699 // time, which is O(k m^3) in total and loses to one dense solve as
1700 // soon as k passes a handful: measured at m = 800, 4.84x faster at
1701 // k = 1, 0.56x at k = 8, 0.09x at k = 62.
1702 //
1703 // The structure is still there to be used; successive bordering is
1704 // just the wrong way to use it at this width, and a block
1705 // divide-and-conquer that never forms the accumulated basis densely
1706 // is the right one.
1707 const char* append_driver = "serial_floor";
1708 if (dispatchAllEigenpairs(backend(), projected, evals_asc, evecs_asc,
1709 &append_driver)) {
1710 last_kernel_factorize_driver_ = append_driver;
1711 } else if (fastAllEigenpairs(backend().mpi(), projected, evals_asc,
1712 evecs_asc)) {
1713 fast_kernel_eigensolver_used_ = true;
1714 } else {
1715 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
1716 timedSymmetricEigen(projected);
1717 if (es.info() != Eigen::Success || es.eigenvalues().size() == 0) {
1718 rank_ = 0;
1719 Psi_.resize(n_old + n_new, 0);
1720 Sr_.resize(0);
1721 return false;
1722 }
1723 evals_asc = es.eigenvalues();
1724 evecs_asc = es.eigenvectors();
1725 gpr::linalg::canonicalizeEigenpairs(evals_asc, evecs_asc);
1726 }
1727 Eigen::VectorXd Snew(m_small);
1728 Eigen::MatrixXd Z(m_small, m_small);
1729 for (Eigen::Index i = 0; i < m_small; ++i) {
1730 const Eigen::Index src = m_small - 1 - i;
1731 Snew(i) = std::sqrt(std::max(0.0, evals_asc(src)));
1732 Z.col(i) = evecs_asc.col(src);
1733 }
1734
1735 rank_ = static_cast<int>(keptSingularRankWithChop(
1736 Snew, dualKernelSingularCutoff(Snew, sv_rtol, sv_abs_tol), sv_chop_tol,
1737 chop_sigma2_));
1739 Sr_ = Snew.head(rank_);
1740
1741 Eigen::MatrixXd P = Eigen::MatrixXd::Zero(n_old + n_new, m_small);
1742 P.block(0, 0, n_old, r_old) = U;
1743 if (q > 0) P.block(0, r_old, n_old, q) = Q;
1744 P.block(n_old, r_old + q, n_new, n_new).setIdentity();
1745 // Near-full rank makes this an O(n^3) product every append. Disjoint
1746 // output columns distribute the work while retaining a replicated basis.
1747 {
1748 const Eigen::MatrixXd Zr = Z.leftCols(rank_);
1749 bool multiplied = false;
1750#ifdef GPR_LINALG_SCALAPACK
1751 auto& state = backend().distributed();
1752 state.initialize();
1753 if (!reproducibleBasis() && state.nprocs() > 1 &&
1754 std::min({P.rows(), P.cols(), Zr.cols()}) >=
1756 multiplied = backend().distributed_gemm_nn(P, Zr, Psi_);
1757 }
1758#endif
1759 if (!multiplied) {
1760 Psi_.resize(P.rows(), Zr.cols());
1761 if (!linalg::tryTrainingProduct(P, Zr, Psi_)) {
1762 auto* gpu = availableGpuEigensolver(backend().mpi());
1763 if (!(gpu != nullptr && gpu->gemmNN(P, Zr, Psi_))) {
1764 Psi_.noalias() = P * Zr;
1765 }
1766 }
1767 }
1768 }
1769 if (rank_ > 0 && old_bordered.rows() == n_old &&
1770 old_bordered.cols() == n_old) {
1771 bordered_kernel_.resize(n_old + n_new, n_old + n_new);
1772 bordered_kernel_.topLeftCorner(n_old, n_old) = old_bordered;
1773 bordered_kernel_.topRightCorner(n_old, n_new) = C;
1774 bordered_kernel_.bottomLeftCorner(n_new, n_old) = C.transpose();
1775 bordered_kernel_.bottomRightCorner(n_new, n_new) = D;
1776 bordered_assembly_error_ = old_asm_error;
1777 }
1778 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
1779 return rank_ > 0;
1780}
1781
1783 const Eigen::VectorXi& source_for_target)
1784{
1785 const Eigen::Index n = Psi_.rows();
1786 if (source_for_target.size() != n) return false;
1787 std::vector<unsigned char> seen(static_cast<std::size_t>(n), 0);
1788 Eigen::MatrixXd Psi_next(Psi_.rows(), Psi_.cols());
1789 Eigen::MatrixXd A_next;
1790 const bool permute_design = A_train_.rows() == n;
1791 if (A_train_.size() > 0 && !permute_design) return false;
1792 if (permute_design) A_next.resize(A_train_.rows(), A_train_.cols());
1793
1794 for (Eigen::Index target = 0; target < n; ++target) {
1795 const Eigen::Index src = source_for_target(target);
1796 if (src < 0 || src >= n) return false;
1797 auto& visited = seen[static_cast<std::size_t>(src)];
1798 if (visited != 0) return false;
1799 visited = 1;
1800 Psi_next.row(target) = Psi_.row(src);
1801 if (permute_design) A_next.row(target) = A_train_.row(src);
1802 }
1803
1804 Psi_ = std::move(Psi_next);
1805 if (permute_design) A_train_ = std::move(A_next);
1806 if (bordered_kernel_.rows() == n && bordered_kernel_.cols() == n) {
1807 Eigen::MatrixXd K_next(n, n);
1808 for (Eigen::Index r = 0; r < n; ++r) {
1809 const Eigen::Index sr = source_for_target(r);
1810 for (Eigen::Index c = 0; c < n; ++c) {
1811 K_next(r, c) = bordered_kernel_(sr, source_for_target(c));
1812 }
1813 }
1814 bordered_kernel_ = std::move(K_next);
1815 } else {
1816 bordered_kernel_.resize(0, 0);
1817 bordered_assembly_error_ = 0.0;
1818 }
1819 clearBorderedCache();
1820 return true;
1821}
1822
1824 const Eigen::MatrixXd& centered_X)
1825{
1826 const Eigen::Index d = centered_X.cols();
1827 if (centered_X.rows() == 0 || d == 0) return Eigen::MatrixXd(d, 0);
1828
1829 Eigen::BDCSVD<Eigen::MatrixXd> svd(centered_X, Eigen::ComputeThinV);
1830 const Eigen::VectorXd& S = svd.singularValues();
1831 if (S.size() == 0 || S(0) == 0.0) return Eigen::MatrixXd(d, 0);
1832
1833 const double tol = std::numeric_limits<double>::epsilon() *
1834 static_cast<double>(std::max(centered_X.rows(), d)) *
1835 S(0);
1836 Eigen::Index rank = 0;
1837 while (rank < S.size() && S(rank) > tol)
1838 ++rank;
1839 return svd.matrixV().leftCols(rank);
1840}
1841
1842void StableBasisND::projectToAffineSpan(const Eigen::MatrixXd& centered_X,
1843 const Eigen::MatrixXd& basis,
1844 Eigen::MatrixXd& coords,
1845 Eigen::MatrixXd& residuals)
1846{
1847 coords = centered_X * basis;
1848 residuals = centered_X - coords * basis.transpose();
1849}
1850
1851void StableBasisND::eigen1d(double xk, int dim, Eigen::VectorXd& val,
1852 Eigen::VectorXd& deriv) const
1853{
1854 Eigen::VectorXd second;
1855 eigen1dSecond(xk, dim, val, deriv, second);
1856}
1857
1858void StableBasisND::eigen1dSecond(double xk, int dim, Eigen::VectorXd& val,
1859 Eigen::VectorXd& deriv,
1860 Eigen::VectorXd& second) const
1861{
1862 // Normalized Hermite recurrence (see StableBasis1D::eigenfunctions):
1863 // psi_0 = sqrt(beta), psi_1 = sqrt(2 beta) u,
1864 // psi_{n+1} = sqrt(2/(n+1)) u psi_n - sqrt(n/(n+1)) psi_{n-1},
1865 // u=alpha*beta*x.
1866 // phi_n(x) = exp(-delta2 x^2) psi_n. The derivative uses dpsi_n/du =
1867 // sqrt(2n) psi_{n-1}, so phi_n'(x) = exp(-delta2 x^2)[ alpha*beta*sqrt(2n)
1868 // psi_{n-1} - 2 delta2 x psi_n ].
1869 const int P = max_degree_;
1870 const double beta = beta_(dim);
1871 const double delta2 = delta2_(dim);
1872 const double u = alpha_ * beta * xk;
1873 const double env = std::exp(-delta2 * xk * xk);
1874 val.resize(P + 1);
1875 deriv.resize(P + 1);
1876 second.resize(P + 1);
1877 Eigen::VectorXd psi(P + 1);
1878 psi(0) = std::sqrt(beta);
1879 if (P >= 1) psi(1) = std::sqrt(2.0) * std::sqrt(beta) * u;
1880 for (int n = 1; n < P; ++n)
1881 psi(n + 1) = std::sqrt(2.0 / (n + 1)) * u * psi(n) -
1882 std::sqrt(static_cast<double>(n) / (n + 1)) * psi(n - 1);
1883 for (int n = 0; n <= P; ++n) {
1884 val(n) = env * psi(n);
1885 const double dpsi =
1886 (n > 0) ? alpha_ * beta * std::sqrt(2.0 * n) * psi(n - 1) : 0.0;
1887 const double ddpsi =
1888 (n > 1)
1889 ? alpha_ * alpha_ * beta * beta * 2.0 *
1890 std::sqrt(static_cast<double>(n) * (n - 1)) * psi(n - 2)
1891 : 0.0;
1892 deriv(n) = env * (dpsi - 2.0 * delta2 * xk * psi(n));
1893 second(n) =
1894 env * (ddpsi - 4.0 * delta2 * xk * dpsi +
1895 (4.0 * delta2 * delta2 * xk * xk - 2.0 * delta2) * psi(n));
1896 }
1897}
1898
1899void StableBasisND::eigen1dEpsDerivative(double xk, int dim,
1900 Eigen::VectorXd& val,
1901 Eigen::VectorXd& dval_eps) const
1902{
1903 // phi_n and d phi_n/d eps_k via the normalized psi recurrence carried in
1904 // parallel with its eps-derivative; closed forms verified in
1905 // scripts/derive_hssvd_eps_gradient.py and StableBasis1D's finite-diff
1906 // test.
1907 const int P = max_degree_;
1908 const double beta = beta_(dim);
1909 const double delta2 = delta2_(dim);
1910 const double eps = eps_(dim);
1911 const double u = alpha_ * beta * xk;
1912 const double env = std::exp(-delta2 * xk * xk);
1913 const double dbeta = 2.0 * eps / (alpha_ * alpha_ * beta * beta * beta);
1914 const double ddelta2 = alpha_ * alpha_ * beta * dbeta;
1915 const double du = alpha_ * dbeta * xk;
1916 const double denv = env * (-(xk * xk) * ddelta2);
1917 const double sb = std::sqrt(beta);
1918 const double dsb = dbeta / (2.0 * sb);
1919 val.resize(P + 1);
1920 dval_eps.resize(P + 1);
1921 Eigen::VectorXd psi(P + 1), dpsi(P + 1);
1922 psi(0) = sb;
1923 dpsi(0) = dsb;
1924 if (P >= 1) {
1925 psi(1) = std::sqrt(2.0) * sb * u;
1926 dpsi(1) = std::sqrt(2.0) * (dsb * u + sb * du);
1927 }
1928 for (int n = 1; n < P; ++n) {
1929 const double a = std::sqrt(2.0 / (n + 1));
1930 const double b = std::sqrt(static_cast<double>(n) / (n + 1));
1931 psi(n + 1) = a * u * psi(n) - b * psi(n - 1);
1932 dpsi(n + 1) = a * (du * psi(n) + u * dpsi(n)) - b * dpsi(n - 1);
1933 }
1934 for (int n = 0; n <= P; ++n) {
1935 val(n) = env * psi(n);
1936 dval_eps(n) = denv * psi(n) + env * dpsi(n);
1937 }
1938}
1939
1940void StableBasisND::eigenTensor(const Eigen::MatrixXd& X, bool want_grad,
1941 Eigen::MatrixXd& Phi,
1942 std::vector<Eigen::MatrixXd>& dPhi) const
1943{
1944 const Eigen::Index m = X.rows();
1945 const Eigen::Index N = midx_.rows();
1946 // Per-(point,dim) 1D tables: V[i][k] = phi_n(x_ik), D[i][k] = phi_n'(x_ik).
1947 std::vector<std::vector<Eigen::VectorXd>> V(m), D(m);
1948 for (Eigen::Index i = 0; i < m; ++i) {
1949 V[i].resize(dim_);
1950 D[i].resize(dim_);
1951 for (int k = 0; k < dim_; ++k)
1952 eigen1d(X(i, k), k, V[i][k], D[i][k]);
1953 }
1954 Phi.setOnes(m, N);
1955 for (Eigen::Index c = 0; c < N; ++c)
1956 for (Eigen::Index i = 0; i < m; ++i) {
1957 double p = 1.0;
1958 for (int k = 0; k < dim_; ++k)
1959 p *= V[i][k](midx_(c, k));
1960 Phi(i, c) = p;
1961 }
1962 if (!want_grad) return;
1963 dPhi.assign(dim_, Eigen::MatrixXd::Zero(m, N));
1964 for (int j = 0; j < dim_; ++j)
1965 for (Eigen::Index c = 0; c < N; ++c)
1966 for (Eigen::Index i = 0; i < m; ++i) {
1967 double p = 1.0;
1968 for (int k = 0; k < dim_; ++k)
1969 p *= (k == j) ? D[i][k](midx_(c, k)) : V[i][k](midx_(c, k));
1970 dPhi[j](i, c) = p;
1971 }
1972}
1973
1974void StableBasisND::eigenTensorEpsDerivative(const Eigen::MatrixXd& X, int j,
1975 Eigen::MatrixXd& Phi,
1976 Eigen::MatrixXd& dPhi_eps) const
1977{
1978 const Eigen::Index m = X.rows();
1979 const Eigen::Index N = midx_.rows();
1980 // Per-(point,dim) 1D tables; dim j also carries d phi_n/d eps_j.
1981 std::vector<std::vector<Eigen::VectorXd>> V(m);
1982 std::vector<Eigen::VectorXd> dVj(m);
1983 for (Eigen::Index i = 0; i < m; ++i) {
1984 V[i].resize(dim_);
1985 for (int k = 0; k < dim_; ++k) {
1986 if (k == j) {
1987 eigen1dEpsDerivative(X(i, k), k, V[i][k], dVj[i]);
1988 } else {
1989 Eigen::VectorXd d;
1990 eigen1d(X(i, k), k, V[i][k], d);
1991 }
1992 }
1993 }
1994 Phi.setOnes(m, N);
1995 dPhi_eps.setZero(m, N);
1996 for (Eigen::Index c = 0; c < N; ++c)
1997 for (Eigen::Index i = 0; i < m; ++i) {
1998 double p = 1.0, dp = 1.0; // product rule: dim j uses d phi/d eps_j
1999 for (int k = 0; k < dim_; ++k) {
2000 p *= V[i][k](midx_(c, k));
2001 dp *= (k == j) ? dVj[i](midx_(c, k)) : V[i][k](midx_(c, k));
2002 }
2003 Phi(i, c) = p;
2004 dPhi_eps(i, c) = dp;
2005 }
2006}
2007
2008void StableBasisND::buildSqrtLamAndPrune(const Eigen::VectorXd& r,
2009 const Eigen::VectorXd& lam0,
2010 double scl, double prune_rtol)
2011{
2012 const Eigen::Index Nfull = midx_.rows();
2013 Eigen::VectorXd lamfull(Nfull);
2014 for (Eigen::Index c = 0; c < Nfull; ++c) {
2015 double s = 1.0;
2016 for (int k = 0; k < dim_; ++k)
2017 s *= std::sqrt(lam0(k)) * std::pow(std::sqrt(r(k)), midx_(c, k));
2018 lamfull(c) = scl * s;
2019 }
2020 if (prune_rtol <= 0.0 || Nfull == 0) {
2021 sqrt_lam_ = std::move(lamfull);
2022 return;
2023 }
2024 // Mercer / Karhunen-Loeve truncation: a mode whose sqrt(lambda) is below
2025 // prune_rtol * max sqrt(lambda) scales its design column below the SVD
2026 // tail, so it cannot contribute a retained singular vector. Dropping it up
2027 // front shrinks the eigenfunction-tensor build and the SVD without changing
2028 // the retained rank or singular values.
2029 const double thresh = prune_rtol * lamfull.maxCoeff();
2030 std::vector<Eigen::Index> keep;
2031 keep.reserve(static_cast<size_t>(Nfull));
2032 for (Eigen::Index c = 0; c < Nfull; ++c)
2033 if (lamfull(c) >= thresh) keep.push_back(c);
2034 const Eigen::Index Nk = static_cast<Eigen::Index>(keep.size());
2035 Eigen::MatrixXi midx_keep(Nk, dim_);
2036 Eigen::VectorXd lam_keep(Nk);
2037 for (Eigen::Index j = 0; j < Nk; ++j) {
2038 midx_keep.row(j) = midx_.row(keep[static_cast<size_t>(j)]);
2039 lam_keep(j) = lamfull(keep[static_cast<size_t>(j)]);
2040 }
2041 midx_ = std::move(midx_keep);
2042 sqrt_lam_ = std::move(lam_keep);
2043}
2044
2045void StableBasisND::eigenTensorCols(const Eigen::MatrixXd& X, bool want_grad,
2046 Eigen::Index c0, Eigen::Index count,
2047 Eigen::MatrixXd& Phi,
2048 std::vector<Eigen::MatrixXd>& dPhi) const
2049{
2050 const Eigen::Index m = X.rows();
2051 // Per-(point,dim) 1D tables shared across all requested columns.
2052 std::vector<std::vector<Eigen::VectorXd>> V(m), D(m);
2053 for (Eigen::Index i = 0; i < m; ++i) {
2054 V[i].resize(dim_);
2055 D[i].resize(dim_);
2056 for (int k = 0; k < dim_; ++k)
2057 eigen1d(X(i, k), k, V[i][k], D[i][k]);
2058 }
2059 Phi.setOnes(m, count);
2060 for (Eigen::Index cc = 0; cc < count; ++cc) {
2061 const Eigen::Index c = c0 + cc;
2062 for (Eigen::Index i = 0; i < m; ++i) {
2063 double p = 1.0;
2064 for (int k = 0; k < dim_; ++k)
2065 p *= V[i][k](midx_(c, k));
2066 Phi(i, cc) = p;
2067 }
2068 }
2069 if (!want_grad) return;
2070 dPhi.assign(dim_, Eigen::MatrixXd::Zero(m, count));
2071 for (int j = 0; j < dim_; ++j)
2072 for (Eigen::Index cc = 0; cc < count; ++cc) {
2073 const Eigen::Index c = c0 + cc;
2074 for (Eigen::Index i = 0; i < m; ++i) {
2075 double p = 1.0;
2076 for (int k = 0; k < dim_; ++k)
2077 p *= (k == j) ? D[i][k](midx_(c, k)) : V[i][k](midx_(c, k));
2078 dPhi[j](i, cc) = p;
2079 }
2080 }
2081}
2082
2083void StableBasisND::factorize(const Eigen::MatrixXd& X,
2084 const Eigen::VectorXd& eps, double alpha,
2085 int max_degree, bool gradient_enhanced,
2086 double sv_rtol)
2087{
2088 bordered_kernel_.resize(0, 0);
2089 bordered_assembly_error_ = 0.0;
2090 clearBorderedCache();
2091 lapack_rrr_value_range_used_ = false;
2092 condition_number_ = 0.0;
2093 dim_ = static_cast<int>(X.cols());
2094 M_ = static_cast<int>(X.rows());
2095 alpha_ = alpha;
2096 max_degree_ = max_degree;
2097 gradient_enhanced_ = gradient_enhanced;
2098 affine_full_dim_ = 0;
2099 overall_scale_ = 1.0;
2100 eps_ = eps;
2101 // Per-dimension Fasshauer-McCourt constants.
2102 beta_.resize(dim_);
2103 delta2_.resize(dim_);
2104 Eigen::VectorXd r(dim_), lam0(dim_);
2105 for (int k = 0; k < dim_; ++k) {
2106 const double e = eps_(k);
2107 beta_(k) = std::pow(1.0 + std::pow(2.0 * e / alpha, 2), 0.25);
2108 delta2_(k) = alpha * alpha / 2.0 * (beta_(k) * beta_(k) - 1.0);
2109 const double denom = alpha * alpha + delta2_(k) + e * e;
2110 r(k) = e * e / denom;
2111 lam0(k) = std::sqrt(alpha * alpha / denom);
2112 }
2113 midx_ = gradedMultiIndices(dim_, max_degree);
2114 const Eigen::Index N = midx_.rows();
2115 // sqrt(lambda_alpha) = prod_k sqrt(lam0_k) * sqrt(r_k)^{alpha_k}.
2116 sqrt_lam_.resize(N);
2117 for (Eigen::Index c = 0; c < N; ++c) {
2118 double s = 1.0;
2119 for (int k = 0; k < dim_; ++k)
2120 s *= std::sqrt(lam0(k)) * std::pow(std::sqrt(r(k)), midx_(c, k));
2121 sqrt_lam_(c) = s;
2122 }
2123
2124 // Stacked design A_full = [Phi ; dPhi rows] diag(sqrt_lam).
2125 Eigen::MatrixXd Phi;
2126 std::vector<Eigen::MatrixXd> dPhi;
2127 eigenTensor(X, gradient_enhanced_, Phi, dPhi);
2128 const Eigen::Index nobs = gradient_enhanced_ ? M_ * (1 + dim_) : M_;
2129 Eigen::MatrixXd A(nobs, N);
2130 A.topRows(M_) = Phi;
2131 if (gradient_enhanced_)
2132 for (int i = 0; i < M_; ++i)
2133 for (int j = 0; j < dim_; ++j)
2134 A.row(M_ + i * dim_ + j) = dPhi[j].row(i);
2135 A.array().rowwise() *= sqrt_lam_.transpose().array();
2136
2137 // Thin SVD + Mercer-tail truncation (cf. StableBasis1D::factorize).
2138 Eigen::BDCSVD<Eigen::MatrixXd> svd(
2139 A, Eigen::ComputeThinU | Eigen::ComputeThinV);
2140 const Eigen::VectorXd& S = svd.singularValues();
2141 const double thresh = sv_rtol * S(0);
2142 rank_ = 0;
2143 while (rank_ < S.size() && S(rank_) > thresh)
2144 ++rank_;
2146 const Eigen::MatrixXd Vr = svd.matrixV().leftCols(rank_);
2147 Sr_ = S.head(rank_);
2148 W_ = Vr.array().rowwise() / Sr_.transpose().array();
2149 // Psi = U[:,kept] taken DIRECTLY from the SVD: A W = A (V/S) = U exactly,
2150 // so svd.matrixU() avoids the A*W GEMM (~37% of the decompose, the largest
2151 // single cost) AND is strictly more orthonormal -- A*W divides by the
2152 // ~1e-13 threshold singular value, drifting Psi^T Psi from I by ~3e-6,
2153 // which the solveNoisy projector (1/sigma2)(y - Psi Psi^T y) then
2154 // amplifies. W_ is still kept for the prediction path (predictEnergy = A_E
2155 // W b).
2156 Psi_ = svd.matrixU().leftCols(rank_);
2157 // Thin U is orthonormal only to a few ulps. Off-diagonal gram entries,
2158 // divided by a small retained singular value, push an in-range
2159 // cancellation past the local roundoff. The nearest orthonormal factor
2160 // of those columns, applied to W as well, leaves the diagonal at the
2161 // column-norm residue and keeps A W aligned with Psi.
2162 if (rank_ > 0) {
2163 const Eigen::MatrixXd gram = Psi_.transpose() * Psi_;
2164 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> gram_solver(gram);
2165 if (gram_solver.info() == Eigen::Success &&
2166 gram_solver.eigenvalues()(0) > 0.0) {
2167 const Eigen::VectorXd inv_sqrt =
2168 gram_solver.eigenvalues().cwiseSqrt().cwiseInverse();
2169 const Eigen::MatrixXd polar =
2170 gram_solver.eigenvectors() * inv_sqrt.asDiagonal() *
2171 gram_solver.eigenvectors().transpose();
2172 Psi_ = Psi_ * polar;
2173 W_ = W_ * polar;
2174 }
2175 }
2176 A_train_ =
2177 A; // retained for the noisy-GP cross-covariance k*(x*) = A(x*) A^T
2178 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2179}
2180
2182 const Eigen::MatrixXd& X, const Eigen::VectorXd& eps, double alpha,
2183 double overall_scale, int max_degree,
2184 const std::vector<Eigen::MatrixXd>& jacobians, bool component_major,
2185 double sv_rtol, int sketch_size, int n_power_iter, double mode_prune_rtol,
2186 double sv_abs_tol)
2187{
2188 validateJointJacobians(X, jacobians);
2189 bordered_kernel_.resize(0, 0);
2190 bordered_assembly_error_ = 0.0;
2191 clearBorderedCache();
2192 lapack_rrr_value_range_used_ = false;
2193 condition_number_ = 0.0;
2194 dim_ = static_cast<int>(X.cols());
2195 M_ = static_cast<int>(X.rows());
2196 alpha_ = alpha;
2197 max_degree_ = max_degree;
2198 gradient_enhanced_ = true;
2199 affine_full_dim_ = 0;
2200 overall_scale_ = overall_scale;
2201 eps_ = eps;
2202 beta_.resize(dim_);
2203 delta2_.resize(dim_);
2204 Eigen::VectorXd r(dim_), lam0(dim_);
2205 for (int k = 0; k < dim_; ++k) {
2206 const double e = eps_(k);
2207 beta_(k) = std::pow(1.0 + std::pow(2.0 * e / alpha, 2), 0.25);
2208 delta2_(k) = alpha * alpha / 2.0 * (beta_(k) * beta_(k) - 1.0);
2209 const double denom = alpha * alpha + delta2_(k) + e * e;
2210 r(k) = e * e / denom;
2211 lam0(k) = std::sqrt(alpha * alpha / denom);
2212 }
2213 midx_ = gradedMultiIndices(dim_, max_degree);
2214 // sqrt(lambda_alpha), with the overall kernel scale magnSigma2 folded in:
2215 // K = A A^T scales by overall_scale when sqrt_lam *= sqrt(overall_scale).
2216 const double scl = std::sqrt(overall_scale);
2217 buildSqrtLamAndPrune(r, lam0, scl, mode_prune_rtol);
2218 const Eigen::Index N = midx_.rows();
2219
2220 // Eigenfunctions Phi (M x N) and descriptor gradients dPhi[k] (M x N).
2221 Eigen::MatrixXd Phi;
2222 std::vector<Eigen::MatrixXd> dPhi;
2223 eigenTensor(X, /*want_grad=*/true, Phi, dPhi);
2224
2225 Eigen::Index ngrad = 0;
2226 for (const auto& J: jacobians)
2227 ngrad += J.cols();
2228 const Eigen::Index nobs = static_cast<Eigen::Index>(M_) + ngrad;
2229 Eigen::MatrixXd A(nobs, N);
2230 A.topRows(M_) = Phi; // energy rows (sqrt_lam applied below)
2231 // Cartesian-force rows: contract the descriptor-gradient features with the
2232 // descriptor Jacobian column. config i, component c ->
2233 // row = sum_k dPhi[k](i,:) * J_i(k,c).
2234 // component_major: rows ordered [comp 0 across configs, comp 1 across
2235 // configs, ...] to match the GP's G-column-major target; else config-major.
2236 // Cartesian-force row (config i, component c): contract the descriptor-
2237 // gradient features with the descriptor Jacobian column. The per-(i,c) AXPY
2238 // here beats a per-config GEMM because the contraction dim (dim_, ~3) is
2239 // too small for BLAS GEMM to amortize its overhead + the dPhi gather
2240 // (cachegrind: GEMM 330M vs AXPY 326M/solve, measured at 47c88ac7).
2241 auto force_row = [&](int i, Eigen::Index c) {
2242 Eigen::RowVectorXd g = Eigen::RowVectorXd::Zero(N);
2243 for (int k = 0; k < dim_; ++k)
2244 g += jacobians[i](k, c) * dPhi[k].row(i);
2245 return g;
2246 };
2247 Eigen::Index row = M_;
2248 if (component_major) {
2249 const Eigen::Index C = jacobians.empty() ? 0 : jacobians[0].cols();
2250 for (Eigen::Index c = 0; c < C; ++c)
2251 for (int i = 0; i < M_; ++i)
2252 A.row(row++) = force_row(i, c);
2253 } else {
2254 for (int i = 0; i < M_; ++i)
2255 for (Eigen::Index c = 0; c < jacobians[i].cols(); ++c)
2256 A.row(row++) = force_row(i, c);
2257 }
2258 A.array().rowwise() *= sqrt_lam_.transpose().array();
2259
2260 if (sketch_size > 0 && sketch_size < nobs) {
2261 factorizeFromDesignRandomized(A, sketch_size, n_power_iter, sv_rtol,
2262 sv_abs_tol);
2263 return;
2264 }
2265
2266 Eigen::BDCSVD<Eigen::MatrixXd> svd(
2267 A, Eigen::ComputeThinU | Eigen::ComputeThinV);
2268 const Eigen::VectorXd& S = svd.singularValues();
2269 rank_ = static_cast<int>(
2270 keptSingularRank(S, singularCutoff(S, sv_rtol, sv_abs_tol)));
2272 const Eigen::MatrixXd Vr = svd.matrixV().leftCols(rank_);
2273 Sr_ = S.head(rank_);
2274 W_ = Vr.array().rowwise() / Sr_.transpose().array();
2275 // Psi = U[:,kept] taken DIRECTLY from the SVD: A W = A (V/S) = U exactly,
2276 // so svd.matrixU() avoids the A*W GEMM (~37% of the decompose, the largest
2277 // single cost) AND is strictly more orthonormal -- A*W divides by the
2278 // ~1e-13 threshold singular value, drifting Psi^T Psi from I by ~3e-6,
2279 // which the solveNoisy projector (1/sigma2)(y - Psi Psi^T y) then
2280 // amplifies. W_ is still kept for the prediction path (predictEnergy = A_E
2281 // W b).
2282 Psi_ = svd.matrixU().leftCols(rank_);
2283 A_train_ = A;
2284 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2285}
2286
2288 const Eigen::MatrixXd& U, const Eigen::VectorXd& eps, double alpha,
2289 double overall_scale, int max_degree,
2290 const std::vector<Eigen::MatrixXd>& jac_tangent,
2291 const std::vector<Eigen::MatrixXd>& jac_normal, bool component_major,
2292 double sv_rtol, int sketch_size, int n_power_iter, double mode_prune_rtol,
2293 double sv_abs_tol)
2294{
2295 validateJointAffineJacobians(U, jac_tangent, jac_normal);
2296 bordered_kernel_.resize(0, 0);
2297 bordered_assembly_error_ = 0.0;
2298 clearBorderedCache();
2299 lapack_rrr_value_range_used_ = false;
2300 condition_number_ = 0.0;
2301 dim_ = static_cast<int>(U.cols());
2302 M_ = static_cast<int>(U.rows());
2303 alpha_ = alpha;
2304 max_degree_ = max_degree;
2305 gradient_enhanced_ = true;
2306 affine_full_dim_ = jac_normal.empty() ? 0 : jac_normal[0].rows();
2307 overall_scale_ = overall_scale;
2308 eps_ = eps;
2309 beta_.resize(dim_);
2310 delta2_.resize(dim_);
2311 Eigen::VectorXd r(dim_), lam0(dim_);
2312 for (int k = 0; k < dim_; ++k) {
2313 const double e = eps_(k);
2314 beta_(k) = std::pow(1.0 + std::pow(2.0 * e / alpha, 2), 0.25);
2315 delta2_(k) = alpha * alpha / 2.0 * (beta_(k) * beta_(k) - 1.0);
2316 const double denom = alpha * alpha + delta2_(k) + e * e;
2317 r(k) = e * e / denom;
2318 lam0(k) = std::sqrt(alpha * alpha / denom);
2319 }
2320 midx_ = gradedMultiIndices(dim_, max_degree);
2321 const double scl = std::sqrt(overall_scale);
2322 buildSqrtLamAndPrune(r, lam0, scl, mode_prune_rtol);
2323 const Eigen::Index N = midx_.rows();
2324 const Eigen::Index ncols = N * (1 + affine_full_dim_);
2325
2326 Eigen::MatrixXd Phi;
2327 std::vector<Eigen::MatrixXd> dPhi;
2328 eigenTensor(U, /*want_grad=*/true, Phi, dPhi);
2329 Eigen::MatrixXd Phi_s =
2330 Phi.array().rowwise() * sqrt_lam_.transpose().array();
2331 std::vector<Eigen::MatrixXd> dPhi_s(dim_);
2332 for (int k = 0; k < dim_; ++k)
2333 dPhi_s[k] = dPhi[k].array().rowwise() * sqrt_lam_.transpose().array();
2334
2335 Eigen::Index ngrad = 0;
2336 for (const auto& J: jac_tangent)
2337 ngrad += J.cols();
2338 const Eigen::Index nobs = static_cast<Eigen::Index>(M_) + ngrad;
2339 Eigen::MatrixXd A = Eigen::MatrixXd::Zero(nobs, ncols);
2340 A.block(0, 0, M_, N) = Phi_s;
2341
2342 const double sqrt2 = std::sqrt(2.0);
2343 auto fill_force_row = [&](Eigen::Index row, int i, Eigen::Index comp) {
2344 Eigen::RowVectorXd tangent = Eigen::RowVectorXd::Zero(N);
2345 for (int k = 0; k < dim_; ++k)
2346 tangent += jac_tangent[i](k, comp) * dPhi_s[k].row(i);
2347 A.block(row, 0, 1, N) = tangent;
2348 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2349 A.block(row, (p + 1) * N, 1, N) =
2350 sqrt2 * jac_normal[i](p, comp) * Phi_s.row(i);
2351 }
2352 };
2353
2354 Eigen::Index row = M_;
2355 if (component_major) {
2356 const Eigen::Index C = jac_tangent.empty() ? 0 : jac_tangent[0].cols();
2357 for (Eigen::Index comp = 0; comp < C; ++comp)
2358 for (int i = 0; i < M_; ++i)
2359 fill_force_row(row++, i, comp);
2360 } else {
2361 for (int i = 0; i < M_; ++i)
2362 for (Eigen::Index comp = 0; comp < jac_tangent[i].cols(); ++comp)
2363 fill_force_row(row++, i, comp);
2364 }
2365
2366 if (sketch_size > 0 && sketch_size < nobs) {
2367 factorizeFromDesignRandomized(A, sketch_size, n_power_iter, sv_rtol,
2368 sv_abs_tol);
2369 return;
2370 }
2371
2372 Eigen::BDCSVD<Eigen::MatrixXd> svd(
2373 A, Eigen::ComputeThinU | Eigen::ComputeThinV);
2374 const Eigen::VectorXd& S = svd.singularValues();
2375 rank_ = static_cast<int>(
2376 keptSingularRank(S, singularCutoff(S, sv_rtol, sv_abs_tol)));
2378 const Eigen::MatrixXd Vr = svd.matrixV().leftCols(rank_);
2379 Sr_ = S.head(rank_);
2380 W_ = Vr.array().rowwise() / Sr_.transpose().array();
2381 Psi_ = svd.matrixU().leftCols(rank_);
2382 A_train_ = A;
2383 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2384}
2385
2386#ifdef GPR_LINALG_SCALAPACK
2387bool StableBasisND::factorizeGPCartesianDistributed(
2388 const Eigen::MatrixXd& X, const Eigen::VectorXd& eps, double alpha,
2389 double overall_scale, int max_degree,
2390 const std::vector<Eigen::MatrixXd>& jacobians, bool component_major,
2391 double sv_rtol, double mode_prune_rtol)
2392{
2393 validateJointJacobians(X, jacobians);
2394 bordered_kernel_.resize(0, 0);
2395 bordered_assembly_error_ = 0.0;
2396 clearBorderedCache();
2397 lapack_rrr_value_range_used_ = false;
2398 condition_number_ = 0.0;
2399 // Mercer/eigen setup is identical to factorizeGPCartesian (cheap, O(N));
2400 // every rank computes it so midx_/sqrt_lam_ are replicated for prediction.
2401 dim_ = static_cast<int>(X.cols());
2402 M_ = static_cast<int>(X.rows());
2403 alpha_ = alpha;
2404 max_degree_ = max_degree;
2405 gradient_enhanced_ = true;
2406 eps_ = eps;
2407 beta_.resize(dim_);
2408 delta2_.resize(dim_);
2409 Eigen::VectorXd r(dim_), lam0(dim_);
2410 for (int k = 0; k < dim_; ++k) {
2411 const double e = eps_(k);
2412 beta_(k) = std::pow(1.0 + std::pow(2.0 * e / alpha, 2), 0.25);
2413 delta2_(k) = alpha * alpha / 2.0 * (beta_(k) * beta_(k) - 1.0);
2414 const double denom = alpha * alpha + delta2_(k) + e * e;
2415 r(k) = e * e / denom;
2416 lam0(k) = std::sqrt(alpha * alpha / denom);
2417 }
2418 midx_ = gradedMultiIndices(dim_, max_degree);
2419 const double scl = std::sqrt(overall_scale);
2420 buildSqrtLamAndPrune(r, lam0, scl, mode_prune_rtol);
2421 const Eigen::Index N = midx_.rows();
2422
2423 // This rank owns a contiguous block [c0, c0+count) of the N mode columns.
2424 auto& st = backend().distributed();
2425 st.initialize();
2426 int c0i = 0, cnt = 0;
2427 st.col_block_range(static_cast<int>(N), c0i, cnt);
2428 const Eigen::Index c0 = c0i;
2429 const Eigen::Index count = cnt;
2430
2431 // Build ONLY the local eigenfunction columns (the per-rank design work).
2432 Eigen::MatrixXd Phi;
2433 std::vector<Eigen::MatrixXd> dPhi;
2434 eigenTensorCols(X, /*want_grad=*/true, c0, count, Phi, dPhi);
2435
2436 Eigen::Index ngrad = 0;
2437 for (const auto& J: jacobians)
2438 ngrad += J.cols();
2439 const Eigen::Index nobs = static_cast<Eigen::Index>(M_) + ngrad;
2440 Eigen::MatrixXd Aloc(nobs, count);
2441 if (count > 0) {
2442 Aloc.topRows(M_) = Phi; // energy rows (sqrt_lam applied below)
2443 // Cartesian-force row (config i, component c): contract local
2444 // descriptor-gradient columns with the descriptor Jacobian column.
2445 auto force_row = [&](int i, Eigen::Index comp) {
2446 Eigen::RowVectorXd g = Eigen::RowVectorXd::Zero(count);
2447 for (int k = 0; k < dim_; ++k)
2448 g += jacobians[i](k, comp) * dPhi[k].row(i);
2449 return g;
2450 };
2451 Eigen::Index row = M_;
2452 if (component_major) {
2453 const Eigen::Index C = jacobians.empty() ? 0 : jacobians[0].cols();
2454 for (Eigen::Index comp = 0; comp < C; ++comp)
2455 for (int i = 0; i < M_; ++i)
2456 Aloc.row(row++) = force_row(i, comp);
2457 } else {
2458 for (int i = 0; i < M_; ++i)
2459 for (Eigen::Index comp = 0; comp < jacobians[i].cols(); ++comp)
2460 Aloc.row(row++) = force_row(i, comp);
2461 }
2462 Aloc.array().rowwise() *=
2463 sqrt_lam_.segment(c0, count).transpose().array();
2464 }
2465
2466 // Thin SVD of the mode-distributed design via TSQR (#90): local QR of each
2467 // rank's A_local^T block, gather/refactor the tiny R, dense SVD of R, then
2468 // V = A^T U S^{-1}. Pure MPI + Eigen -- no pdgesvd, no Gram, conditioning
2469 // preserved. U/S/V are gathered to replicated (nobs x k, k, N x k).
2470 Eigen::MatrixXd U, V;
2471 Eigen::VectorXd S;
2472 if (!backend().distributed_thin_svd_tsqr(Aloc, static_cast<int>(nobs),
2473 static_cast<int>(N), U, S, V))
2474 return false;
2475
2476 const double thresh = sv_rtol * S(0);
2477 rank_ = 0;
2478 while (rank_ < S.size() && S(rank_) > thresh)
2479 ++rank_;
2481 const Eigen::MatrixXd Vr = V.leftCols(rank_); // N x rank
2482 Sr_ = S.head(rank_);
2483 W_ = Vr.array().rowwise() / Sr_.transpose().array();
2484 Psi_ = U.leftCols(rank_); // nobs x rank (= the kept left singular vectors)
2485 // The production reduced-coefficient predict path uses A_E*W_*p only; the
2486 // full nobs x N design is never assembled on one rank, so A_train_ (the
2487 // explicit alpha-K cross-covariance and reconstructKernel) stays empty.
2488 A_train_.resize(0, 0);
2489 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2490 return true;
2491}
2492#endif // GPR_LINALG_SCALAPACK
2493
2494// Randomized range finder (HMT, SIAM Review 2011, Alg 4.4 subspace iteration +
2495// 5.1). Recovers the same top-rank left singular vectors Psi = U[:,kept],
2496// singular values Sr, and W = V/Sr as the dense BDCSVD -- to the truncation
2497// tolerance -- but via sketched GEMMs, never the Gram A A^T (so cond(Psi) stays
2498// O(1)). The two GEMMs A*Omega (nobs x l) and Q^T A (l x N) are the surface the
2499// ScaLAPACK path distributes block-cyclically over the N modes; the QR is the
2500// TSQR target. A fixed-seed PRNG keeps the factorization deterministic.
2501void StableBasisND::factorizeFromDesignRandomized(const Eigen::MatrixXd& A,
2502 int sketch, int n_power,
2503 double sv_rtol,
2504 double sv_abs_tol)
2505{
2506 bordered_kernel_.resize(0, 0);
2507 bordered_assembly_error_ = 0.0;
2508 clearBorderedCache();
2509 condition_number_ = 0.0;
2510 const Eigen::Index nobs = A.rows();
2511 const Eigen::Index N = A.cols();
2512 std::mt19937_64 gen(0xC0FFEEULL); // fixed seed -> reproducible
2513 std::normal_distribution<double> nd(0.0, 1.0);
2514 Eigen::Index l = std::min<Eigen::Index>(sketch, nobs);
2515
2516 for (;;) {
2517 Eigen::MatrixXd Omega(N, l);
2518 for (Eigen::Index j = 0; j < l; ++j)
2519 for (Eigen::Index i = 0; i < N; ++i)
2520 Omega(i, j) = nd(gen);
2521
2522 // Y = A Omega, then n_power subspace iterations Y <- A (A^T Y) with a
2523 // QR reorthonormalization each half-step to fight round-off (HMT 4.4).
2524 Eigen::MatrixXd Y = A * Omega; // nobs x l
2525 for (int p = 0; p < n_power; ++p) {
2526 const Eigen::MatrixXd Q1 =
2527 Eigen::HouseholderQR<Eigen::MatrixXd>(Y).householderQ() *
2528 Eigen::MatrixXd::Identity(nobs, l);
2529 const Eigen::MatrixXd Z = A.transpose() * Q1; // N x l
2530 const Eigen::MatrixXd Q2 =
2531 Eigen::HouseholderQR<Eigen::MatrixXd>(Z).householderQ() *
2532 Eigen::MatrixXd::Identity(N, l);
2533 Y = A * Q2; // nobs x l
2534 }
2535 const Eigen::MatrixXd Q =
2536 Eigen::HouseholderQR<Eigen::MatrixXd>(Y).householderQ() *
2537 Eigen::MatrixXd::Identity(nobs, l); // nobs x l, orthonormal
2538
2539 const Eigen::MatrixXd B = Q.transpose() * A; // l x N
2540 Eigen::BDCSVD<Eigen::MatrixXd> svdB(
2541 B, Eigen::ComputeThinU | Eigen::ComputeThinV);
2542 const Eigen::VectorXd& S = svdB.singularValues();
2543 const double thresh = singularCutoff(S, sv_rtol, sv_abs_tol);
2544 const Eigen::Index rk = keptSingularRank(S, thresh);
2545
2546 // If the kept rank saturates the sketch (and room remains), the range
2547 // dimension was too small to capture the spectrum down to the
2548 // threshold -- grow it and retry (bounded by nobs, the exact rank cap).
2549 if (rk == l && l < nobs) {
2550 l = std::min<Eigen::Index>(2 * l, nobs);
2551 continue;
2552 }
2553
2554 rank_ = static_cast<int>(rk);
2555
2557 // A = Q B = Q (U_b S V_b^T) = (Q U_b) S V_b^T, so U = Q U_b, V = V_b.
2558 Psi_ = Q * svdB.matrixU().leftCols(rk); // nobs x rank
2559 Sr_ = S.head(rk);
2560 const Eigen::MatrixXd Vr = svdB.matrixV().leftCols(rk); // N x rank
2561 W_ = Vr.array().rowwise() / Sr_.transpose().array();
2562 A_train_ = A;
2563 condition_number_ = rank_ > 0 ? 1.0 : 0.0;
2564 return;
2565 }
2566}
2567
2568void StableBasisND::designAt(const Eigen::MatrixXd& Xstar, Eigen::MatrixXd& A_E,
2569 std::vector<Eigen::MatrixXd>& A_g) const
2570{
2571 Eigen::MatrixXd Phi;
2572 std::vector<Eigen::MatrixXd> dPhi;
2573 eigenTensor(Xstar, true, Phi, dPhi);
2574 A_E = Phi.array().rowwise() * sqrt_lam_.transpose().array();
2575 A_g.resize(dim_);
2576 for (int j = 0; j < dim_; ++j)
2577 A_g[j] = dPhi[j].array().rowwise() * sqrt_lam_.transpose().array();
2578}
2579
2580void StableBasisND::designAtAffineEnergy(const Eigen::MatrixXd& Ustar,
2581 const Eigen::MatrixXd& residuals,
2582 Eigen::MatrixXd& A_E,
2583 AffineVariancePrior* prior) const
2584{
2585 Eigen::MatrixXd Phi;
2586 std::vector<Eigen::MatrixXd> dPhi;
2587 eigenTensor(Ustar, false, Phi, dPhi);
2588 const Eigen::Index m = Ustar.rows();
2589 const Eigen::Index N = midx_.rows();
2590 Eigen::MatrixXd Phi_s =
2591 Phi.array().rowwise() * sqrt_lam_.transpose().array();
2592 if (prior) {
2593 // The residual kernel is one on the diagonal. The prior diagonal
2594 // therefore equals the span feature norm in the working type.
2596 prior->diagonal.resize(m);
2597 using Work = gpr::extended::WorkingReal;
2598 if (prior->stable) {
2599 for (Eigen::Index i = 0; i < m; ++i)
2600 prior->diagonal(i) = Phi_s.row(i).cast<Work>().squaredNorm();
2601 } else {
2602 for (Eigen::Index i = 0; i < m; ++i)
2603 prior->diagonal(i) =
2604 static_cast<Work>(Phi_s.row(i).squaredNorm());
2605 }
2606 }
2607 A_E = Eigen::MatrixXd::Zero(m, N * (1 + affine_full_dim_));
2608 const double sqrt2 = std::sqrt(2.0);
2609 for (Eigen::Index i = 0; i < m; ++i) {
2610 const double scale = std::exp(-residuals.row(i).squaredNorm());
2611 A_E.block(i, 0, 1, N) = scale * Phi_s.row(i);
2612 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2613 A_E.block(i, (p + 1) * N, 1, N) =
2614 scale * sqrt2 * residuals(i, p) * Phi_s.row(i);
2615 }
2616 }
2617}
2618
2619Eigen::VectorXd StableBasisND::solve(const Eigen::VectorXd& y) const
2620{
2621 return Psi_.colPivHouseholderQr().solve(y);
2622}
2623
2624Eigen::VectorXd StableBasisND::predictEnergy(const Eigen::MatrixXd& Xstar,
2625 const Eigen::VectorXd& b) const
2626{
2627 Eigen::MatrixXd A_E;
2628 std::vector<Eigen::MatrixXd> A_g;
2629 designAt(Xstar, A_E, A_g);
2630 return (A_E * W_) * b;
2631}
2632
2633Eigen::MatrixXd StableBasisND::predictGradient(const Eigen::MatrixXd& Xstar,
2634 const Eigen::VectorXd& b) const
2635{
2636 Eigen::MatrixXd A_E;
2637 std::vector<Eigen::MatrixXd> A_g;
2638 designAt(Xstar, A_E, A_g);
2639 Eigen::MatrixXd G(Xstar.rows(), dim_);
2640 for (int j = 0; j < dim_; ++j)
2641 G.col(j) = (A_g[j] * W_) * b;
2642 return G;
2643}
2644
2646 const Eigen::MatrixXd& Ustar, const Eigen::MatrixXd& residuals,
2647 const Eigen::VectorXd& b) const
2648{
2649 Eigen::MatrixXd A_E;
2650 designAtAffineEnergy(Ustar, residuals, A_E);
2651 return (A_E * W_) * b;
2652}
2653
2655 const Eigen::MatrixXd& Ustar, const Eigen::MatrixXd& residuals) const
2656{
2657 Eigen::MatrixXd A_E;
2658 designAtAffineEnergy(Ustar, residuals, A_E);
2659 if (A_E.rows() < 1) return {};
2660 return (A_E * W_).row(0).transpose();
2661}
2662
2664 const Eigen::MatrixXd& Ustar, const Eigen::MatrixXd& residuals,
2665 const Eigen::MatrixXd& basis, const Eigen::VectorXd& b) const
2666{
2667 Eigen::MatrixXd Phi;
2668 std::vector<Eigen::MatrixXd> dPhi;
2669 eigenTensor(Ustar, true, Phi, dPhi);
2670 const Eigen::Index m = Ustar.rows();
2671 const Eigen::Index N = midx_.rows();
2672 Eigen::MatrixXd Phi_s =
2673 Phi.array().rowwise() * sqrt_lam_.transpose().array();
2674 std::vector<Eigen::MatrixXd> dPhi_s(dim_);
2675 for (int k = 0; k < dim_; ++k)
2676 dPhi_s[k] = dPhi[k].array().rowwise() * sqrt_lam_.transpose().array();
2677
2678 const Eigen::VectorXd coeff = W_ * b;
2679 const Eigen::VectorXd base_coeff = coeff.head(N);
2680 const double sqrt2 = std::sqrt(2.0);
2681 const Eigen::MatrixXd projector =
2682 Eigen::MatrixXd::Identity(affine_full_dim_, affine_full_dim_) -
2683 basis * basis.transpose();
2684 Eigen::MatrixXd G(m, affine_full_dim_);
2685
2686 for (Eigen::Index i = 0; i < m; ++i) {
2687 const Eigen::RowVectorXd ri = residuals.row(i);
2688 const double scale = std::exp(-ri.squaredNorm());
2689 const double base_value = Phi_s.row(i).dot(base_coeff);
2690 Eigen::VectorXd normal_values(affine_full_dim_);
2691 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2692 normal_values(p) = Phi_s.row(i).dot(coeff.segment((p + 1) * N, N));
2693 }
2694 const double normal_dot = ri.dot(normal_values);
2695
2696 Eigen::RowVectorXd gu = Eigen::RowVectorXd::Zero(dim_);
2697 for (int k = 0; k < dim_; ++k) {
2698 double val = dPhi_s[k].row(i).dot(base_coeff);
2699 for (Eigen::Index p = 0; p < affine_full_dim_; ++p)
2700 val += sqrt2 * ri(p) *
2701 dPhi_s[k].row(i).dot(coeff.segment((p + 1) * N, N));
2702 gu(k) = scale * val;
2703 }
2704
2705 Eigen::RowVectorXd gr(affine_full_dim_);
2706 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2707 gr(p) =
2708 scale * (-2.0 * ri(p) * base_value +
2709 sqrt2 * (normal_values(p) - 2.0 * ri(p) * normal_dot));
2710 }
2711 G.row(i) = gu * basis.transpose() + gr * projector;
2712 }
2713 return G;
2714}
2715
2717 const Eigen::MatrixXd& Ustar, const Eigen::MatrixXd& residuals,
2718 const Eigen::MatrixXd& basis, const Eigen::MatrixXd& tangent_directions,
2719 const Eigen::MatrixXd& residual_directions, const Eigen::VectorXd& b) const
2720{
2721 const Eigen::Index m = Ustar.rows();
2722 const Eigen::Index N = midx_.rows();
2723
2724 std::vector<std::vector<Eigen::VectorXd>> V(m), D(m), DD(m);
2725 for (Eigen::Index i = 0; i < m; ++i) {
2726 V[i].resize(dim_);
2727 D[i].resize(dim_);
2728 DD[i].resize(dim_);
2729 for (int k = 0; k < dim_; ++k)
2730 eigen1dSecond(Ustar(i, k), k, V[i][k], D[i][k], DD[i][k]);
2731 }
2732
2733 Eigen::MatrixXd Phi(m, N);
2734 std::vector<Eigen::MatrixXd> dPhi(dim_, Eigen::MatrixXd::Zero(m, N));
2735 std::vector<Eigen::MatrixXd> d2PhiDirection(dim_,
2736 Eigen::MatrixXd::Zero(m, N));
2737
2738 for (Eigen::Index c = 0; c < N; ++c) {
2739 for (Eigen::Index i = 0; i < m; ++i) {
2740 double p = 1.0;
2741 for (int k = 0; k < dim_; ++k)
2742 p *= V[i][k](midx_(c, k));
2743 Phi(i, c) = p;
2744
2745 for (int j = 0; j < dim_; ++j) {
2746 double gp = 1.0;
2747 for (int k = 0; k < dim_; ++k)
2748 gp *=
2749 (k == j) ? D[i][k](midx_(c, k)) : V[i][k](midx_(c, k));
2750 dPhi[j](i, c) = gp;
2751
2752 double hp = 0.0;
2753 for (int l = 0; l < dim_; ++l) {
2754 double term = tangent_directions(i, l);
2755 for (int k = 0; k < dim_; ++k) {
2756 if (k == j && k == l)
2757 term *= DD[i][k](midx_(c, k));
2758 else if (k == j || k == l)
2759 term *= D[i][k](midx_(c, k));
2760 else
2761 term *= V[i][k](midx_(c, k));
2762 }
2763 hp += term;
2764 }
2765 d2PhiDirection[j](i, c) = hp;
2766 }
2767 }
2768 }
2769
2770 const Eigen::MatrixXd Phi_s =
2771 Phi.array().rowwise() * sqrt_lam_.transpose().array();
2772 std::vector<Eigen::MatrixXd> dPhi_s(dim_), d2PhiDirection_s(dim_);
2773 for (int k = 0; k < dim_; ++k) {
2774 dPhi_s[k] = dPhi[k].array().rowwise() * sqrt_lam_.transpose().array();
2775 d2PhiDirection_s[k] =
2776 d2PhiDirection[k].array().rowwise() * sqrt_lam_.transpose().array();
2777 }
2778
2779 const Eigen::VectorXd coeff = W_ * b;
2780 const Eigen::VectorXd base_coeff = coeff.head(N);
2781 const double sqrt2 = std::sqrt(2.0);
2782 const Eigen::MatrixXd projector =
2783 Eigen::MatrixXd::Identity(affine_full_dim_, affine_full_dim_) -
2784 basis * basis.transpose();
2785 Eigen::MatrixXd HV(m, affine_full_dim_);
2786
2787 for (Eigen::Index i = 0; i < m; ++i) {
2788 const Eigen::RowVectorXd ri = residuals.row(i);
2789 const Eigen::RowVectorXd dri = residual_directions.row(i);
2790 const double scale = std::exp(-ri.squaredNorm());
2791 const double dscale = -2.0 * scale * ri.dot(dri);
2792
2793 const double base_value = Phi_s.row(i).dot(base_coeff);
2794 Eigen::RowVectorXd base_grad = Eigen::RowVectorXd::Zero(dim_);
2795 Eigen::RowVectorXd base_hv = Eigen::RowVectorXd::Zero(dim_);
2796 for (int k = 0; k < dim_; ++k) {
2797 base_grad(k) = dPhi_s[k].row(i).dot(base_coeff);
2798 base_hv(k) = d2PhiDirection_s[k].row(i).dot(base_coeff);
2799 }
2800 const double dbase_value = base_grad.dot(tangent_directions.row(i));
2801
2802 Eigen::VectorXd normal_values(affine_full_dim_);
2803 Eigen::VectorXd dnormal_values(affine_full_dim_);
2804 Eigen::MatrixXd normal_grad =
2805 Eigen::MatrixXd::Zero(affine_full_dim_, dim_);
2806 Eigen::MatrixXd normal_hv =
2807 Eigen::MatrixXd::Zero(affine_full_dim_, dim_);
2808 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2809 const Eigen::VectorXd normal_coeff = coeff.segment((p + 1) * N, N);
2810 normal_values(p) = Phi_s.row(i).dot(normal_coeff);
2811 for (int k = 0; k < dim_; ++k) {
2812 normal_grad(p, k) = dPhi_s[k].row(i).dot(normal_coeff);
2813 normal_hv(p, k) = d2PhiDirection_s[k].row(i).dot(normal_coeff);
2814 }
2815 dnormal_values(p) =
2816 normal_grad.row(p).dot(tangent_directions.row(i));
2817 }
2818
2819 Eigen::RowVectorXd gu_arg = base_grad;
2820 Eigen::RowVectorXd dgu_arg = base_hv;
2821 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2822 gu_arg += sqrt2 * ri(p) * normal_grad.row(p);
2823 dgu_arg += sqrt2 *
2824 (dri(p) * normal_grad.row(p) + ri(p) * normal_hv.row(p));
2825 }
2826 const Eigen::RowVectorXd dgu = dscale * gu_arg + scale * dgu_arg;
2827
2828 const double normal_dot = ri.dot(normal_values);
2829 const double dnormal_dot =
2830 dri.dot(normal_values) + ri.dot(dnormal_values);
2831 const double h = base_value + sqrt2 * normal_dot;
2832 const double dh = dbase_value + sqrt2 * dnormal_dot;
2833
2834 Eigen::RowVectorXd gr_arg(affine_full_dim_);
2835 Eigen::RowVectorXd dgr_arg(affine_full_dim_);
2836 for (Eigen::Index p = 0; p < affine_full_dim_; ++p) {
2837 gr_arg(p) = -2.0 * ri(p) * h + sqrt2 * normal_values(p);
2838 dgr_arg(p) = -2.0 * dri(p) * h - 2.0 * ri(p) * dh +
2839 sqrt2 * dnormal_values(p);
2840 }
2841 const Eigen::RowVectorXd dgr = dscale * gr_arg + scale * dgr_arg;
2842 HV.row(i) = dgu * basis.transpose() + dgr * projector;
2843 }
2844 return HV;
2845}
2846
2848 const Eigen::VectorXd& y, double sigma2) const
2849{
2850 // p_i = S_i^2/(S_i^2+sigma2) * (Psi^T y)_i. predictEnergy(x*, p) then
2851 // yields A_E(x*) W p = A_E(x*) A_train^T (K+sigma2 I)^{-1} y without
2852 // forming alpha.
2853 const Eigen::ArrayXd s2 = Sr_.array().square();
2854 const Eigen::ArrayXd shrink =
2855 stablePosteriorShrinkage(s2, sigma2, Psi_.rows());
2856 return (shrink * (Psi_.transpose() * y).array()).matrix();
2857}
2858
2859namespace {
2860// Resolution floor for the likelihood variance in the stable basis.
2861//
2862// The retained eigenvalues s^2 of the kernel Gram matrix carry the backward
2863// error of a symmetric eigensolver, |delta s^2| <= c n eps ||K||_2, so a
2864// noisy eigenvalue s^2 + sigma2 is resolvable only when sigma2 (or s^2)
2865// exceeds n eps s2_max. Below that, every dropped or near-null component
2866// would be weighted 1/sigma2 against a spectrum that cannot represent it;
2867// the floor is the smallest noise the double-precision spectrum resolves.
2868// Written as a condition bound on the SQUARED spectrum,
2869// (s2_max + f)/(s2_min + f) <= kappa, kappa = 1/(n eps),
2870// so f >= (s2_max - kappa s2_min)/(kappa - 1). The earlier version applied
2871// the singular-value bound 1/sqrt(eps) to the eigenvalues, i.e. it raised
2872// sigma2 to sqrt(eps) s2_max whenever the kernel had any near-null
2873// direction: on the two-geometry CuH2 fixture (s2_max ~ 1, sigma2 = 1e-8)
2874// that put the dual training-row latent variance at 1.66x the exact
2875// posterior and the LOO calibration at 2.15 against 1.0 on the dense
2876// factor. The test LatentEnergyVarianceMatchesExplicitDenseReference pins
2877// both backends to the explicit posterior.
2878inline double spectralFloorSigma2(const Eigen::VectorXd& Sr, double sigma2,
2879 Eigen::Index nobs, double resolution_factor)
2880{
2881 if (Sr.size() == 0) return sigma2;
2882 if (!(resolution_factor > 0.0 && resolution_factor < 1.0)) return sigma2;
2883 namespace dir = gpr::extended::directed;
2884 // f = (s2_max - kappa s2_min)/(kappa - 1) with kappa = 1/r, r the
2885 // resolution factor, is
2886 // f = (r s2_max - s2_min)/(1 - r).
2887 // r is n eps or eps, both exact in binary64. The floor is a lower limit on
2888 // the noise, so the stored value must not fall below f: s2_max, the
2889 // product with r and the quotient round up, s2_min and the divisor round
2890 // down, and the difference rounds up. Round-to-nearest here could store a
2891 // floor below the exact value by an ulp.
2892 const double s2_max = dir::mulUp(Sr(0), Sr(0)); // Sr is descending
2893 // The discarded observation-space complement has zero signal in the
2894 // retained model. Its minimum eigenvalue controls inverse conditioning.
2895 const double s2_min =
2896 Sr.size() < nobs ? 0.0
2897 : dir::mulDown(Sr(Sr.size() - 1), Sr(Sr.size() - 1));
2898 const double numerator =
2899 dir::subUp(dir::mulUp(resolution_factor, s2_max), s2_min);
2900 const double denominator = dir::subDown(1.0, resolution_factor);
2901 const double floor = dir::divUp(numerator, denominator);
2902 return (std::isfinite(floor) && floor > sigma2) ? floor : sigma2;
2903}
2904
2905inline double conditionFlooredSigma2(const Eigen::VectorXd& Sr, double sigma2,
2906 Eigen::Index nobs)
2907{
2908 const double neps = static_cast<double>(std::max<Eigen::Index>(1, nobs)) *
2909 std::numeric_limits<double>::epsilon();
2910 return spectralFloorSigma2(Sr, sigma2, nobs, neps);
2911}
2912
2913// The stable posterior variance is instead a sum of a nonnegative feature
2914// tail and terms sigma2/(s_i^2 + sigma2) c_i^2. ExactSum rounds that local
2915// Schur reduction once, so resolving one squared eigenvalue needs eps*s2_max
2916// rather than the n-row projector bound:
2917// (s2_max + f)/(s2_min + f) <= 1/eps.
2918// The legacy variance reductions keep the n*eps floor bit for bit.
2919inline double varianceFlooredSigma2(const Eigen::VectorXd& Sr, double sigma2,
2920 Eigen::Index nobs)
2921{
2923 return conditionFlooredSigma2(Sr, sigma2, nobs);
2924 return spectralFloorSigma2(Sr, sigma2, nobs,
2925 std::numeric_limits<double>::epsilon());
2926}
2927
2928double nonnegativeEigenmodeVariance(const Eigen::VectorXd& projected,
2929 const Eigen::VectorXd& residual,
2930 const Eigen::VectorXd& singular_values,
2931 double sigma2, double complement_eigenvalue,
2932 bool use_complement, linalg::ExactSum prior)
2933{
2934 const double prior_value = prior.value();
2935 const linalg::ExactSum original_prior = prior;
2936 Eigen::VectorXd retained_coordinates(singular_values.size());
2937 for (Eigen::Index mode = 0; mode < singular_values.size(); ++mode) {
2938 const double singular = singular_values(mode);
2939 if (!(singular > 0.0) || !std::isfinite(singular))
2940 return std::numeric_limits<double>::quiet_NaN();
2941 const double coordinate = projected(mode) / singular;
2942 retained_coordinates(mode) = coordinate;
2943 prior.addProduct(-coordinate, coordinate);
2944 }
2945
2946 Eigen::VectorXd complement_coordinates;
2947 if (use_complement) {
2948 if (!(complement_eigenvalue > 0.0) ||
2949 !std::isfinite(complement_eigenvalue))
2950 return std::numeric_limits<double>::quiet_NaN();
2951 complement_coordinates = residual / std::sqrt(complement_eigenvalue);
2952 for (Eigen::Index row = 0; row < complement_coordinates.size(); ++row)
2953 prior.addProduct(-complement_coordinates(row),
2954 complement_coordinates(row));
2955 }
2956
2957 double unresolved_tail = prior.value();
2958 // ExactSum itself cannot change the sign: it rounds the exact reduction
2959 // once. A one-ulp negative tail can only come from the rounded basis
2960 // projection. Its backward-error allowance is eps times this query's
2961 // local prior, not the number of training observations times a global
2962 // spectral scale.
2963 const double tail_roundoff =
2964 std::numeric_limits<double>::epsilon() * std::abs(prior_value);
2965 if (unresolved_tail < 0.0) {
2966 if (std::abs(unresolved_tail) <= tail_roundoff)
2967 unresolved_tail = 0.0;
2968 else {
2969 // A few low-level callers provide a noisy self-covariance that is
2970 // positive semidefinite only after conditioning, rather than a
2971 // latent joint covariance. Such an input has no nonnegative
2972 // unresolved latent tail. Preserve that algebraic API with one
2973 // exact Schur reduction; production kernel queries take the
2974 // nonnegative branch below.
2975 linalg::ExactSum direct = original_prior;
2976 for (Eigen::Index mode = 0; mode < singular_values.size(); ++mode) {
2977 const double s2 = singular_values(mode) * singular_values(mode);
2978 direct.addTripleProduct(-retained_coordinates(mode),
2979 retained_coordinates(mode),
2980 s2 / (s2 + sigma2));
2981 }
2982 if (use_complement) {
2983 const double explained =
2984 complement_eigenvalue / (complement_eigenvalue + sigma2);
2985 for (Eigen::Index row = 0; row < complement_coordinates.size();
2986 ++row)
2987 direct.addTripleProduct(-complement_coordinates(row),
2988 complement_coordinates(row),
2989 explained);
2990 }
2991 double value = direct.value();
2992 if (value < 0.0 && std::abs(value) <= tail_roundoff) value = 0.0;
2993 return value >= 0.0 ? value
2994 : std::numeric_limits<double>::quiet_NaN();
2995 }
2996 }
2997
2999 variance.add(unresolved_tail);
3000 for (Eigen::Index mode = 0; mode < singular_values.size(); ++mode) {
3001 const double s2 = singular_values(mode) * singular_values(mode);
3002 const double attenuation = sigma2 / (s2 + sigma2);
3003 variance.addTripleProduct(retained_coordinates(mode),
3004 retained_coordinates(mode), attenuation);
3005 }
3006 if (use_complement) {
3007 const double attenuation = sigma2 / (complement_eigenvalue + sigma2);
3008 for (Eigen::Index row = 0; row < complement_coordinates.size(); ++row)
3009 variance.addTripleProduct(complement_coordinates(row),
3010 complement_coordinates(row), attenuation);
3011 }
3012 return variance.value();
3013}
3014
3015// Second projection of the query cross covariance onto the retained basis,
3016// so a retained-range query enters the unresolved tail quadratically in the
3017// orthogonality error.
3018void projectOntoStableBasis(const Eigen::MatrixXd& psi,
3019 const Eigen::MatrixXd& cross,
3020 Eigen::MatrixXd& projected,
3021 Eigen::MatrixXd& residual)
3022{
3023 projected = psi.transpose() * cross;
3024 residual = cross - psi * projected;
3025 const Eigen::MatrixXd correction = psi.transpose() * residual;
3026 residual.noalias() -= psi * correction;
3027 projected += correction;
3028}
3029
3030} // namespace
3031
3032double StableBasisND::conditionFlooredNoise(double sigma2) const
3033{
3034 return conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3035}
3036
3037double StableBasisND::varianceFlooredNoise(double sigma2) const
3038{
3039 return varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
3040}
3041
3043 const Eigen::VectorXd& singular_values, double sigma2, Eigen::Index nobs)
3044{
3045 return conditionFlooredSigma2(singular_values, sigma2, nobs);
3046}
3047
3049 const Eigen::VectorXd& y, double sigma2) const
3050{
3051 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3052 const Eigen::VectorXd z = Psi_.transpose() * y;
3053 // mu_i = S_i^2 + sigma2, the eigenvalues of K + sigma2 I. When the basis
3054 // was built from the noisy kernel directly (factorizeNoisyKernel), use the
3055 // stored mu_i so the inverse never re-forms the cancelling sum S_i^2 +
3056 // sigma2 (the signal S_i^2 = mu_i - sigma2 lost digits at assembly).
3057 const Eigen::ArrayXd mu =
3058 hasNoisyEigenvalues() ? Eigen::ArrayXd(noisy_eigvals_.array())
3059 : Eigen::ArrayXd(Sr_.array().square() + sigma2);
3060 const Eigen::ArrayXd s2 = mu - sigma2;
3061 const Eigen::ArrayXd shrink =
3062 stablePosteriorShrinkage(s2, sigma2, Psi_.rows());
3063 Eigen::ArrayXd projected_inverse = mu.inverse();
3064 for (Eigen::Index i = 0; i < projected_inverse.size(); ++i) {
3065 if (s2(i) > 0.0) projected_inverse(i) = shrink(i) / s2(i);
3066 }
3067 const Eigen::VectorXd noisy_projected =
3068 Psi_ * (projected_inverse * z.array()).matrix();
3070 weights.alpha = noisy_projected;
3071 const double complement = complementWeight(sigma2);
3072 if (complement > 0.0) {
3073 weights.alpha += complement * (y - Psi_ * z);
3074 }
3075 weights.reduced = (shrink * z.array()).matrix();
3076 return weights;
3077}
3078
3079Eigen::VectorXd StableBasisND::solveNoisy(const Eigen::VectorXd& y,
3080 double sigma2) const
3081{
3082 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3083 // (K + sigma2 I)^{-1} y with K = Psi diag(S^2) Psi^T (Psi orthonormal):
3084 // = Psi diag(1/(S^2+sigma2)) (Psi^T y) + (1/sigma2)(y - Psi (Psi^T y)).
3085 // mu_i = S_i^2 + sigma2; the noisy-objective path stores mu_i directly so
3086 // the inverse avoids the cancelling sum S_i^2 + sigma2.
3087 const Eigen::VectorXd p = Psi_.transpose() * y; // rank
3088 const Eigen::ArrayXd mu =
3089 hasNoisyEigenvalues() ? Eigen::ArrayXd(noisy_eigvals_.array())
3090 : Eigen::ArrayXd(Sr_.array().square() + sigma2);
3091 const Eigen::ArrayXd d = mu.inverse();
3092 Eigen::VectorXd solved = Psi_ * (d.matrix().asDiagonal() * p);
3093 const double complement = complementWeight(sigma2);
3094 if (complement > 0.0) {
3095 solved += complement * (y - Psi_ * p);
3096 }
3097 return solved;
3098}
3099
3100Eigen::VectorXd StableBasisND::noisySelfQuadratic(const Eigen::MatrixXd& rhs,
3101 double sigma2) const
3102{
3103 if (rhs.rows() != Psi_.rows() || Psi_.cols() != Sr_.size() ||
3104 !(sigma2 > 0.0)) {
3105 return Eigen::VectorXd();
3106 }
3107 if (rhs.cols() == 0) return Eigen::VectorXd();
3108
3109 const Eigen::MatrixXd z = Psi_.transpose() * rhs;
3110 const Eigen::ArrayXd inv_projected =
3111 (Sr_.array().square() + sigma2).inverse();
3112 Eigen::VectorXd quad(rhs.cols());
3113 for (Eigen::Index j = 0; j < rhs.cols(); ++j) {
3114 const double projected =
3115 (z.col(j).array().square() * inv_projected).sum();
3116 const double residual2 = (rhs.col(j) - Psi_ * z.col(j)).squaredNorm();
3117 // y^T (K + sigma2 I)^-1 y with the inverse solveNoisy applies to the
3118 // targets, so the complement keeps the mean-path weight; posterior
3119 // covariance subtractions use covarianceComplementWeight instead.
3120 quad(j) = projected + residual2 * complementWeight(sigma2);
3121 }
3122 return quad;
3123}
3124
3126 const Eigen::MatrixXd& rhs, double sigma2) const
3127{
3128 // Same regularized operator as the mean path: every mean, logdet,
3129 // and LOO route floors sigma2 through conditionFlooredSigma2; a raw
3130 // sigma2 here yields moments of a DIFFERENT posterior (systematic
3131 // overconfidence exactly when the floor is active).
3132 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3133 if (rhs.rows() != Psi_.rows() || Psi_.cols() != Sr_.size() ||
3134 !(sigma2 > 0.0)) {
3135 return Eigen::VectorXd();
3136 }
3137 if (rhs.cols() == 0) return Eigen::VectorXd();
3138
3139 const Eigen::MatrixXd z = Psi_.transpose() * rhs;
3140 const Eigen::ArrayXd inv_projected =
3141 (Sr_.array().square() + sigma2).inverse();
3142 Eigen::VectorXd quad(rhs.cols());
3143 for (Eigen::Index j = 0; j < rhs.cols(); ++j) {
3144 quad(j) = (z.col(j).array().square() * inv_projected).sum();
3145 }
3146 return quad;
3147}
3148
3150 const Eigen::MatrixXd& rhs, const Eigen::VectorXd& prior,
3151 const Eigen::VectorXd& signal, double sigma2, bool check_variance) const
3152{
3153 if (prior.size() != rhs.cols() || signal.size() != prior.size())
3155 "stable range posterior variance: prior, signal and query "
3156 "columns disagree");
3157 if (rhs.rows() != Psi_.rows() || Psi_.cols() != Sr_.size())
3159 "stable range posterior variance: cross covariance does not match "
3160 "the stable basis");
3161 sigma2 = varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
3162 if (!(sigma2 > 0.0) || !std::isfinite(sigma2))
3164 "stable range posterior variance: noise floor is not finite and "
3165 "positive");
3166 Eigen::VectorXd variance(rhs.cols());
3167 if (rhs.cols() == 0) return variance;
3168 Eigen::MatrixXd projected, residual;
3169 projectOntoStableBasis(Psi_, rhs, projected, residual);
3170 const Eigen::VectorXd no_residual;
3171 for (Eigen::Index column = 0; column < rhs.cols(); ++column) {
3172 linalg::ExactSum local_prior;
3173 local_prior.add(prior(column));
3174 variance(column) = nonnegativeEigenmodeVariance(
3175 projected.col(column), no_residual, Sr_, sigma2, 0.0,
3176 /*use_complement=*/false, local_prior);
3177 if (check_variance)
3179 signal(column));
3180 }
3181 return variance;
3182}
3183
3187 Eigen::Matrix<Extended, Eigen::Dynamic, Eigen::Dynamic>;
3188 using ExtendedVector = Eigen::Matrix<Extended, Eigen::Dynamic, 1>;
3189
3190 Eigen::Index n = 0;
3191 Eigen::Index rk = 0;
3192 bool is_kernel_path = false;
3196 int eps_k_ops = 0;
3202};
3203
3207 Eigen::Matrix<Extended, Eigen::Dynamic, Eigen::Dynamic>;
3208
3209 double sigma2 = -1.0;
3214};
3215
3216void StableBasisND::clearBorderedCache() noexcept
3217{
3218 bordered_deflation_.reset();
3219 std::lock_guard<std::mutex> lock(bordered_cache_.mutex);
3220 bordered_cache_.factor.reset();
3221 bordered_cache_.error.clear();
3222 bordered_cache_.rm.reset();
3223}
3224
3225bool StableBasisND::extendedCertificationEnabledLocked() const
3226{
3227 if (bordered_cache_.extended_override == 0) return false;
3229}
3230
3232{
3233 if (available && !gpr::extended::certificationAvailable()) {
3234 throw std::invalid_argument(
3235 "extended certification cannot be enabled on this platform");
3236 }
3237 std::lock_guard<std::mutex> lock(bordered_cache_.mutex);
3238 bordered_cache_.factor.reset();
3239 bordered_cache_.error.clear();
3240 bordered_cache_.rm.reset();
3241 bordered_cache_.extended_override = available ? 1 : 0;
3242}
3243
3244void StableBasisND::buildBorderedFactorLocked() const
3245{
3246 if (!extendedCertificationEnabledLocked()) {
3247 throw BorderedVarianceError(
3248 "this platform cannot certify the bordered variance");
3249 }
3250 using Extended = gpr::extended::WorkingReal;
3251 using ExtendedMatrix =
3252 Eigen::Matrix<Extended, Eigen::Dynamic, Eigen::Dynamic>;
3253 using ExtendedVector = Eigen::Matrix<Extended, Eigen::Dynamic, 1>;
3254
3255 if (!bordered_cache_.error.empty()) {
3256 throw BorderedVarianceError(bordered_cache_.error);
3257 }
3258
3259 if (!bordered_cache_.factor) {
3260 try {
3261 auto factor = std::make_shared<BorderedFactorCache>();
3262 const Eigen::Index n = borderedKernelOrder();
3263 factor->n = n;
3264 if (bordered_kernel_.rows() == n && bordered_kernel_.cols() == n) {
3265 factor->is_kernel_path = true;
3266 if (n == 0) {
3267 factor->rk = 0;
3268 factor->Q.resize(0, 0);
3269 factor->R.resize(0, 0);
3270 } else {
3271 if (!bordered_kernel_.allFinite()) {
3272 throw BorderedVarianceError(
3273 "the kernel matrix is not positive semidefinite");
3274 }
3275 const ExtendedMatrix raw =
3276 bordered_kernel_.cast<Extended>();
3277 const ExtendedMatrix sym =
3278 Extended(0.5L) * (raw + raw.transpose());
3279 // Entry: raw_ij + raw_ji, the half and the subtraction.
3280 const Extended sym_residual = certifiedResidual(
3281 sym - raw,
3282 Extended(0.5L) *
3283 (raw.cwiseAbs() + raw.transpose().cwiseAbs()) +
3284 raw.cwiseAbs(),
3285 3);
3286
3287 ExtendedVector diag_scale(n);
3288 ExtendedVector inv_scale(n);
3289 bool any_positive_diag = false;
3290 Extended min_pos_d = 0.0L;
3291 Extended max_d = 0.0L;
3292 for (Eigen::Index i = 0; i < n; ++i) {
3293 const Extended v = sym(i, i);
3294 if (!(v >= Extended(0)) || !workingIsFinite(v)) {
3295 throw BorderedVarianceError(
3296 "the kernel matrix is not positive "
3297 "semidefinite");
3298 }
3299 if (v > 0.0L) {
3300 any_positive_diag = true;
3301 const Extended d = workingSqrt(v);
3302 diag_scale(i) = d;
3303 inv_scale(i) = 1.0L / d;
3304 if (min_pos_d == 0.0L || d < min_pos_d)
3305 min_pos_d = d;
3306 if (d > max_d) max_d = d;
3307 } else {
3308 for (Eigen::Index j = 0; j < n; ++j) {
3309 if (sym(i, j) != 0.0L || sym(j, i) != 0.0L) {
3310 throw BorderedVarianceError(
3311 "the kernel matrix is not positive "
3312 "semidefinite");
3313 }
3314 }
3315 diag_scale(i) = 0.0L;
3316 inv_scale(i) = 0.0L;
3317 }
3318 }
3319
3320 if (!any_positive_diag) {
3321 factor->rk = 0;
3322 factor->Q.resize(n, 0);
3323 factor->R.resize(0, 0);
3324 factor->eps_k = directedUpper(
3325 static_cast<Extended>(bordered_assembly_error_) +
3326 sym_residual,
3327 kAssemblyPairOps);
3328 factor->eps_k_ops = kAssemblyPairOps;
3329 } else {
3330 ExtendedMatrix equilibrated = sym;
3331 for (Eigen::Index i = 0; i < n; ++i) {
3332 for (Eigen::Index j = 0; j < n; ++j) {
3333 equilibrated(i, j) *=
3334 inv_scale(i) * inv_scale(j);
3335 }
3336 }
3337 equilibrated =
3338 Extended(0.5L) *
3339 (equilibrated + equilibrated.transpose());
3340 ExtendedMatrix rescaled = equilibrated;
3341 for (Eigen::Index i = 0; i < n; ++i) {
3342 for (Eigen::Index j = 0; j < n; ++j) {
3343 rescaled(i, j) *= diag_scale(i) * diag_scale(j);
3344 }
3345 }
3346 // Entry: d_i d_j, the product with the entry and the
3347 // subtraction.
3348 ExtendedMatrix rescaled_abs = equilibrated.cwiseAbs();
3349 for (Eigen::Index i = 0; i < n; ++i) {
3350 for (Eigen::Index j = 0; j < n; ++j) {
3351 rescaled_abs(i, j) *=
3352 workingAbs(diag_scale(i) * diag_scale(j));
3353 }
3354 }
3355 const Extended scale_residual = certifiedResidual(
3356 sym - rescaled, sym.cwiseAbs() + rescaled_abs, 3);
3357
3358 Eigen::MatrixXd eq_double = equilibrated.cast<double>();
3359 eq_double = 0.5 * (eq_double + eq_double.transpose());
3360 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es =
3361 timedSymmetricEigen(eq_double);
3362 if (es.info() != Eigen::Success ||
3363 es.eigenvalues().size() != n ||
3364 !es.eigenvalues().allFinite() ||
3365 !es.eigenvectors().allFinite()) {
3366 throw BorderedVarianceError(
3367 "the bordered kernel eigendecomposition "
3368 "failed");
3369 }
3370
3371 const ExtendedVector evals_asc =
3372 es.eigenvalues().cast<Extended>();
3373 const ExtendedMatrix evecs_asc =
3374 es.eigenvectors().cast<Extended>();
3375 const Extended lambda_max = evals_asc(n - 1);
3376 const Extended lambda_min = evals_asc(0);
3377 if (!(lambda_max > Extended(0)) ||
3378 !workingIsFinite(lambda_max) ||
3379 !workingIsFinite(lambda_min)) {
3380 throw BorderedVarianceError(
3381 "the kernel matrix is not positive "
3382 "semidefinite");
3383 }
3384
3385 // Entry: V Lambda, the n products of the sum, the
3386 // subtraction. n + 2 operations in any order.
3387 const Extended es_residual = certifiedResidual(
3388 equilibrated - evecs_asc * evals_asc.asDiagonal() *
3389 evecs_asc.transpose(),
3390 equilibrated.cwiseAbs() +
3391 evecs_asc.cwiseAbs() *
3392 evals_asc.cwiseAbs().asDiagonal() *
3393 evecs_asc.transpose().cwiseAbs(),
3394 static_cast<long long>(n) + 2);
3395 // Entry: the n products, the sum and the subtraction
3396 // from the identity.
3397 const Extended orth_residual = certifiedResidual(
3398 ExtendedMatrix::Identity(n, n) -
3399 evecs_asc.transpose() * evecs_asc,
3400 ExtendedMatrix::Identity(n, n) +
3401 evecs_asc.transpose().cwiseAbs() *
3402 evecs_asc.cwiseAbs(),
3403 static_cast<long long>(n) + 1);
3404 if (!(orth_residual < Extended(1)) ||
3405 !workingIsFinite(es_residual) ||
3406 !workingIsFinite(orth_residual)) {
3407 throw BorderedVarianceError(
3408 "the bordered kernel eigenbasis is not "
3409 "orthonormal");
3410 }
3411
3412 Eigen::Index rk = 0;
3413 while (rk < n && evals_asc(n - 1 - rk) > 0.0L)
3414 ++rk;
3415 if (rk == 0) {
3416 throw BorderedVarianceError(
3417 "the kernel matrix has no positive "
3418 "eigenvalues");
3419 }
3420
3421 const gpr::extended::FormedFactor<Extended> formed =
3423 diag_scale, evecs_asc, evals_asc, rk,
3424 kFormedFactorEntryOps);
3425 if (!workingIsFinite(formed.gram_error)) {
3426 throw BorderedVarianceError(
3427 "the bordered factor entries exceed "
3428 "working-precision resolution");
3429 }
3430 const ExtendedMatrix& B = formed.B;
3431 Eigen::HouseholderQR<ExtendedMatrix> qr(B);
3432 factor->Q =
3433 qr.householderQ() * ExtendedMatrix::Identity(n, rk);
3434 factor->R =
3435 qr.matrixQR()
3436 .topLeftCorner(rk, rk)
3437 .template triangularView<Eigen::Upper>();
3438 factor->rk = rk;
3439 const Extended qr_residual = certifiedResidual(
3440 B - factor->Q * factor->R,
3441 B.cwiseAbs() +
3442 factor->Q.cwiseAbs() * factor->R.cwiseAbs(),
3443 static_cast<long long>(rk) + 1);
3444 factor->q_orth_res = certifiedResidual(
3445 ExtendedMatrix::Identity(rk, rk) -
3446 factor->Q.transpose() * factor->Q,
3447 ExtendedMatrix::Identity(rk, rk) +
3448 factor->Q.transpose().cwiseAbs() *
3449 factor->Q.cwiseAbs(),
3450 static_cast<long long>(n) + 1);
3451 if (!(factor->q_orth_res < Extended(1)) ||
3452 !workingIsFinite(qr_residual) ||
3453 !workingIsFinite(factor->q_orth_res)) {
3454 throw BorderedVarianceError(
3455 "the bordered QR factor is ill-conditioned");
3456 }
3457 factor->q_norm_f = factor->Q.norm();
3458 factor->q_norm_2 =
3459 workingSqrt(Extended(1) + factor->q_orth_res);
3460 const Extended r_norm_f = factor->R.norm();
3461 factor->r_norm_f2 = r_norm_f * r_norm_f;
3462
3463 const Extended max_d2 = max_d * max_d;
3464 const Extended neg_eval =
3465 lambda_min < 0.0L ? -lambda_min : 0.0L;
3466 const Extended eps_pos =
3467 max_d2 *
3468 (es_residual + (1.0L + orth_residual) * neg_eval);
3469 const long long b_entries =
3470 static_cast<long long>(B.size());
3471 if (b_entries > (1LL << 26)) {
3472 throw BorderedVarianceError(
3473 "the bordered factor exceeds the eps_K "
3474 "operation count");
3475 }
3476 const Extended eps_qr =
3477 qr_residual * (2.0L * formed.norm + qr_residual);
3478 // ||Bh Bh^T - B B^T||_F for the factor formed in
3479 // the working type, with an absolute allowance for
3480 // entries near underflow (see formScaledFactor).
3481 const Extended eps_bb = formed.gram_error;
3482 const long long eps_k_ops =
3483 kEpsKSumAdditions +
3484 std::max<long long>(
3485 kEpsPosOps,
3486 b_entries +
3487 std::max(kEpsQrExtraOps, kEpsBbExtraOps));
3488 factor->eps_k = directedUpper(
3489 static_cast<Extended>(bordered_assembly_error_) +
3490 sym_residual + scale_residual + eps_pos +
3491 eps_qr + eps_bb,
3492 eps_k_ops);
3493 factor->eps_k_ops = static_cast<int>(eps_k_ops);
3494 factor->lambda_min_cert = directedLower(
3495 (rk == n && min_pos_d > Extended(0) &&
3496 lambda_min > Extended(0))
3497 ? lambda_min * (Extended(1) - orth_residual) *
3498 min_pos_d * min_pos_d
3499 : Extended(0),
3500 kLambdaCertMulOps);
3501 }
3502 }
3503 } else {
3504 throw BorderedVarianceError(
3505 "bordered variance requires an exact stored kernel");
3506 }
3507 bordered_cache_.factor = std::move(factor);
3508 ++bordered_cache_.builds;
3509 } catch (const BorderedVarianceError& err) {
3510 bordered_cache_.error = err.what();
3511 throw;
3512 } catch (const std::exception& err) {
3513 bordered_cache_.error = err.what();
3514 throw BorderedVarianceError(err.what());
3515 }
3516 }
3517}
3518
3519std::pair<std::shared_ptr<const StableBasisND::BorderedFactorCache>,
3520 std::shared_ptr<const StableBasisND::BorderedRmCache>>
3521StableBasisND::ensureBorderedFactorAndRm(double sigma2) const
3522{
3523 using Extended = gpr::extended::WorkingReal;
3524 using ExtendedMatrix =
3525 Eigen::Matrix<Extended, Eigen::Dynamic, Eigen::Dynamic>;
3526
3527 if (!(sigma2 >= 0.0) || !std::isfinite(sigma2)) {
3528 throw BorderedVarianceError(
3529 "bordered variance inputs do not match the stable basis");
3530 }
3531
3532 std::lock_guard<std::mutex> lock(bordered_cache_.mutex);
3533 buildBorderedFactorLocked();
3534
3535 const auto factor = bordered_cache_.factor;
3536 if (!factor->is_kernel_path) {
3537 throw BorderedVarianceError(
3538 "bordered variance requires an exact stored kernel");
3539 }
3540 // sigma2 is the condition-floored requested noise. Replacing it with a
3541 // larger certificate noise raises the posterior, so the lower endpoint
3542 // would no longer bound the requested value.
3543 const Extended sigma2_ext(sigma2);
3544 const Extended mu_raw =
3545 sigma2_ext + factor->lambda_min_cert - factor->eps_k;
3546 const Extended mu_min = directedLower(mu_raw, kMuMinOps);
3547 if (!(mu_min > Extended(0)) || !workingIsFinite(mu_min)) {
3548 throw BorderedVarianceError(
3549 "the bordered covariance is not certified positive definite at "
3550 "this noise level");
3551 }
3552
3553 if (!bordered_cache_.rm || bordered_cache_.rm->sigma2 != sigma2) {
3554 auto rm_cache = std::make_shared<BorderedRmCache>();
3555 rm_cache->sigma2 = sigma2;
3556 rm_cache->mu_min = mu_min;
3557 const Eigen::Index rk = factor->rk;
3558 if (rk > 0) {
3559 Extended residual = 0;
3560 if (sigma2 > 0.0) {
3561 ExtendedMatrix stacked = ExtendedMatrix::Zero(2 * rk, rk);
3562 stacked.topRows(rk) = factor->R.transpose();
3563 const Extended s_sig = workingSqrt(sigma2_ext);
3564 for (Eigen::Index i = 0; i < rk; ++i)
3565 stacked(rk + i, i) = s_sig;
3566 Eigen::HouseholderQR<ExtendedMatrix> stacked_qr(stacked);
3567 rm_cache->Rm = stacked_qr.matrixQR()
3568 .topLeftCorner(rk, rk)
3569 .template triangularView<Eigen::Upper>();
3570 residual = certifiedResidual(
3571 factor->R * factor->R.transpose() +
3572 sigma2_ext * ExtendedMatrix::Identity(rk, rk) -
3573 rm_cache->Rm.transpose() * rm_cache->Rm,
3574 factor->R.cwiseAbs() * factor->R.transpose().cwiseAbs() +
3575 sigma2_ext * ExtendedMatrix::Identity(rk, rk) +
3576 rm_cache->Rm.transpose().cwiseAbs() *
3577 rm_cache->Rm.cwiseAbs(),
3578 gramResidualEntryOps(rk));
3579 } else {
3580 // Householder QR of R^T is the LQ factorization of R:
3581 // R^T = Q Rm, so Rm^T Rm = R R^T and R = Rm^T Q^T.
3582 // Rm = R would certify the different product R^T R.
3583 // R is not normal, so the residual is measured.
3584 Eigen::HouseholderQR<ExtendedMatrix> transpose_qr(
3585 factor->R.transpose());
3586 rm_cache->Rm = transpose_qr.matrixQR()
3587 .topLeftCorner(rk, rk)
3588 .template triangularView<Eigen::Upper>();
3589 residual = certifiedResidual(
3590 factor->R * factor->R.transpose() -
3591 rm_cache->Rm.transpose() * rm_cache->Rm,
3592 factor->R.cwiseAbs() * factor->R.transpose().cwiseAbs() +
3593 rm_cache->Rm.transpose().cwiseAbs() *
3594 rm_cache->Rm.cwiseAbs(),
3595 gramResidualEntryOps(rk));
3596 }
3597 rm_cache->rm_residual = residual;
3598 rm_cache->rm_norm_2 = rm_cache->Rm.norm();
3599 }
3600 bordered_cache_.rm = std::move(rm_cache);
3601 }
3602
3603 return {factor, bordered_cache_.rm};
3604}
3605
3606StableBasisND::TrainingNoiseReport StableBasisND::borderedTrainingNoiseReport(
3607 double sigma2) const
3608{
3609 if (!(sigma2 >= 0.0) || !std::isfinite(sigma2)) {
3610 throw BorderedVarianceError(
3611 "bordered variance inputs do not match the stable basis");
3612 }
3613 TrainingNoiseReport out;
3614 out.requested = sigma2;
3615 out.floored = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3616 out.floor_active = out.floored > sigma2;
3617
3618 std::lock_guard<std::mutex> lock(bordered_cache_.mutex);
3619 if (!extendedCertificationEnabledLocked()) return out;
3620 buildBorderedFactorLocked();
3621 const auto factor = bordered_cache_.factor;
3622 using Extended = gpr::extended::WorkingReal;
3623 const Extended gap_raw = factor->eps_k - factor->lambda_min_cert;
3624 const Extended gap_hi =
3625 gpr::extended::WorkingPrecision<Extended>::nextUp(gap_raw);
3626 out.gap = gpr::extended::roundUpToDouble(gap_hi);
3627 out.certifiable = true;
3628 return out;
3629}
3630
3632{
3633 return borderedNoiseReport(sigma2, 1.0);
3634}
3635
3637 double sigma2, double output_variance_scale) const
3638{
3639 if (!(output_variance_scale > 0.0) ||
3640 !std::isfinite(output_variance_scale)) {
3641 throw BorderedVarianceError(
3642 "bordered variance inputs do not match the stable basis");
3643 }
3644 const TrainingNoiseReport training = borderedTrainingNoiseReport(sigma2);
3645 BorderedNoiseReport report;
3646 // requested and floored round the same way, so the floor never lowers the
3647 // reported noise.
3648 double up = 0.0;
3649 gpr::extended::outwardProduct(training.requested, output_variance_scale,
3650 report.requested, up);
3651 gpr::extended::outwardProduct(training.floored, output_variance_scale,
3652 report.floored, up);
3653 report.floor_active = training.floor_active;
3654 // The enclosure is computed at the floored noise, not at a larger one.
3655 report.interval = report.floored;
3656 if (!training.certifiable) {
3657 report.certificate_gap = std::numeric_limits<double>::infinity();
3658 report.certified = false;
3659 return report;
3660 }
3661 // The certificate is decided from the scaled endpoints: floored rounded
3662 // down and the gap rounded up, so a one-unit gap in training units that
3663 // collapses under the multiply is not certified.
3664 double gap_down = 0.0;
3665 gpr::extended::outwardProduct(training.gap, output_variance_scale, gap_down,
3666 report.certificate_gap);
3667 report.certified = report.floored > report.certificate_gap;
3668 return report;
3669}
3670
3672 double y_scale,
3673 double calibration) const
3674{
3675 using Work = gpr::extended::WorkingReal;
3676 const auto scale =
3677 gpr::extended::varianceScaleEnclosure<Work>(y_scale, calibration);
3678 if (!scale.valid) {
3679 throw BorderedVarianceError(
3680 "bordered variance inputs do not match the stable basis");
3681 }
3682 const TrainingNoiseReport training = borderedTrainingNoiseReport(sigma2);
3683 BorderedNoiseReport report;
3684 report.requested =
3685 gpr::extended::scaledLowerBound(training.requested, scale);
3686 report.floored = gpr::extended::scaledLowerBound(training.floored, scale);
3687 report.floor_active = training.floor_active;
3688 report.interval = report.floored;
3689 if (!training.certifiable) {
3690 report.certificate_gap = std::numeric_limits<double>::infinity();
3691 report.certified = false;
3692 return report;
3693 }
3694 report.certificate_gap =
3695 gpr::extended::scaledUpperBound(training.gap, scale);
3696 report.certified = report.floored > report.certificate_gap;
3697 return report;
3698}
3699
3700std::vector<BorderedVarianceInterval>
3702 const Eigen::VectorXd& prior_diag,
3703 double sigma2) const
3704{
3705 return noisyBorderedVarianceIntervals(rhs, prior_diag, sigma2,
3707}
3708
3709std::vector<BorderedVarianceInterval>
3711 const Eigen::VectorXd& prior_diag,
3712 double sigma2,
3713 BorderedSchurSign sign) const
3714{
3715 if (rhs.rows() != Psi_.rows() || rhs.cols() != prior_diag.size() ||
3716 Psi_.cols() != Sr_.size() || !(sigma2 >= 0.0) ||
3717 !std::isfinite(sigma2) || !rhs.allFinite() || !prior_diag.allFinite()) {
3718 throw BorderedVarianceError(
3719 "bordered variance inputs do not match the stable basis");
3720 }
3721 // The interval encloses the posterior of the operator the trained factor
3722 // inverts: mean, logdet and LOO all floor sigma2 through
3723 // conditionFlooredSigma2, so a raw sigma2 below the floor would certify
3724 // (or refuse) a different matrix K + sigma2 I than the one trained on.
3725 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3726 for (Eigen::Index i = 0; i < prior_diag.size(); ++i) {
3727 if (!(prior_diag(i) >= 0.0)) {
3728 throw BorderedVarianceError(
3729 "the bordered covariance is not positive semidefinite");
3730 }
3731 }
3732 std::vector<BorderedVarianceInterval> intervals(
3733 static_cast<std::size_t>(rhs.cols()));
3734 if (rhs.cols() == 0) return intervals;
3735
3736 const auto [factor, rm_cache] = ensureBorderedFactorAndRm(sigma2);
3737 sigma2 = rm_cache->sigma2;
3738
3739 using Extended = gpr::extended::WorkingReal;
3740 using ExtendedVector = Eigen::Matrix<Extended, Eigen::Dynamic, 1>;
3741 const Eigen::Index n = factor->n;
3742 const Eigen::Index rk = factor->rk;
3743 const Extended sigma2_ext(sigma2);
3744 const Extended unit_work =
3746 const Extended n_ext = static_cast<Extended>(n);
3747 const Extended r_ext = static_cast<Extended>(rk);
3748 const Extended nr_order = n_ext + r_ext + 4.0L;
3749 const Extended sum_order = n_ext + r_ext + 4.0L;
3750 if (!(nr_order * unit_work < 1.0L) || !(sum_order * unit_work < 1.0L)) {
3751 throw BorderedVarianceError(
3752 "the bordered covariance order exceeds unit roundoff resolution");
3753 }
3754 const Extended gamma_r_work =
3755 (rk > 0) ? (r_ext * unit_work) / (1.0L - r_ext * unit_work) : 0.0L;
3756 const Extended gamma_nr_work =
3757 (nr_order * unit_work) / (1.0L - nr_order * unit_work);
3758 const Extended gamma_sum_work =
3759 (sum_order * unit_work) / (1.0L - sum_order * unit_work);
3760
3761 const Extended w_lo =
3762 (sigma2 > 0.0) ? (Extended(1) / sigma2_ext) : Extended(0);
3763
3764 Eigen::MatrixXd rhs_projected;
3765 const Eigen::MatrixXd* rhs_effective = &rhs;
3766 if (bordered_deflation_) {
3767 rhs_projected = bordered_deflation_->projectRows(rhs);
3768 rhs_effective = &rhs_projected;
3769 }
3770
3771 for (Eigen::Index column = 0; column < rhs.cols(); ++column) {
3772 const Extended prior = static_cast<Extended>(prior_diag(column));
3773 const ExtendedVector k_vec =
3774 rhs_effective->col(column).cast<Extended>();
3775 const Extended k_norm = k_vec.norm();
3776
3777 ExtendedVector y_q(rk), w_q(rk), alpha(rk);
3778 ExtendedVector k_perp = k_vec;
3779 Extended q_k_perp = 0.0L;
3780 ExtendedVector v_q = ExtendedVector::Zero(n);
3781 if (rk > 0) {
3782 y_q = factor->Q.transpose() * k_vec;
3783 k_perp.noalias() -= factor->Q * y_q;
3784 const ExtendedVector dy = factor->Q.transpose() * k_perp;
3785 k_perp.noalias() -= factor->Q * dy;
3786 y_q += dy;
3787 q_k_perp = (factor->Q.transpose() * k_perp).norm();
3788
3789 w_q = y_q;
3790 rm_cache->Rm.transpose()
3791 .template triangularView<Eigen::Lower>()
3792 .solveInPlace(w_q);
3793 alpha = w_q;
3794 rm_cache->Rm.template triangularView<Eigen::Upper>().solveInPlace(
3795 alpha);
3796 v_q = -(factor->Q * alpha);
3797 }
3798
3799 const Extended k_perp_norm2 = k_perp.squaredNorm();
3800 const Extended k_perp_norm = workingSqrt(k_perp_norm2);
3801 const ExtendedVector v_perp = -w_lo * k_perp;
3802 const Extended w_perp2 = w_lo * k_perp_norm2;
3803 const ExtendedVector v = v_q + v_perp;
3804
3805 Extended schur = prior;
3806 Extended correction = 0.0L;
3807 auto neumaier_add = [&](const Extended term) {
3808 const Extended next = schur + term;
3809 correction += workingAbs(schur) >= workingAbs(term)
3810 ? (schur - next) + term
3811 : (term - next) + schur;
3812 schur = next;
3813 };
3814 if (rk > 0) {
3815 for (Eigen::Index row = 0; row < rk; ++row)
3816 neumaier_add(-w_q(row) * w_q(row));
3817 }
3818 if (w_perp2 > 0.0L) neumaier_add(-w_perp2);
3819 schur += correction;
3820 if (!workingIsFinite(schur)) {
3821 throw BorderedVarianceError(
3822 "the bordered covariance is not positive semidefinite");
3823 }
3824
3825 const Extended y_q_norm = (rk > 0) ? y_q.norm() : 0.0L;
3826 const Extended w_q_norm = (rk > 0) ? w_q.norm() : 0.0L;
3827 const Extended alpha_norm = (rk > 0) ? alpha.norm() : 0.0L;
3828 const Extended v_norm2 = v.squaredNorm();
3829 const Extended v_norm = workingSqrt(v_norm2);
3830
3831 const Extended rho_split =
3832 2.0L * gamma_nr_work * (k_norm + factor->q_norm_f * y_q_norm);
3833 const Extended delta_y =
3834 (rk > 0) ? gamma_r_work * (rm_cache->Rm.transpose().cwiseAbs() *
3835 w_q.cwiseAbs())
3836 .norm()
3837 : 0.0L;
3838 const Extended delta_w =
3839 (rk > 0) ? gamma_r_work *
3840 (rm_cache->Rm.cwiseAbs() * alpha.cwiseAbs()).norm()
3841 : 0.0L;
3842 const Extended rho_solve = rm_cache->rm_norm_2 * delta_w + delta_y;
3843
3844 const Extended e_split_q = directedUpper(
3845 Extended(2) *
3846 (gamma_nr_work * factor->q_norm_f * k_norm * alpha_norm +
3847 rho_split * (alpha_norm + w_lo * k_perp_norm) +
3848 w_lo * y_q_norm * q_k_perp),
3849 kESplitQOps);
3850 const Extended e_solve_q = directedUpper(
3851 Extended(2) * delta_y * alpha_norm + delta_w * delta_w +
3852 rm_cache->rm_residual * alpha_norm * alpha_norm,
3853 kESolveQOps);
3854 const Extended qt_v_err = directedUpper(
3855 factor->q_orth_res * alpha_norm + w_lo * q_k_perp, kQtVErrOps);
3856 const Extended e_orth_q = directedUpper(
3857 factor->r_norm_f2 * qt_v_err *
3858 (Extended(2) * alpha_norm + qt_v_err) +
3859 sigma2_ext * (factor->q_orth_res * alpha_norm * alpha_norm +
3860 Extended(2) * w_lo * alpha_norm * q_k_perp),
3861 kEOrthQOps);
3862 const Extended e_sum = directedUpper(
3863 gamma_sum_work * (prior + w_q_norm * w_q_norm + w_perp2), kESumOps);
3864 const Extended e_kernel =
3865 directedUpper(factor->eps_k * v_norm2, kEKernelOps);
3866 const Extended e_q_hi = directedUpper(
3867 e_split_q + e_solve_q + e_orth_q + e_sum + e_kernel, kEQHiSumOps);
3868
3869 // sigma^2 > 0 absorbs the complement into Rm. At sigma^2 = 0 the
3870 // complement is the exact null component and stays in the residual.
3871 const Extended r_perp = (sigma2 > 0.0) ? Extended(0) : k_perp_norm;
3872 const Extended r_norm = directedUpper(
3873 rho_split +
3874 factor->q_norm_2 *
3875 (rho_solve + rm_cache->rm_residual * alpha_norm +
3876 factor->r_norm_f2 *
3877 (factor->q_orth_res * alpha_norm + w_lo * q_k_perp)) +
3878 r_perp + factor->eps_k * v_norm,
3879 kRNormOps);
3880 const Extended r2 = directedUpper(r_norm * r_norm, kSquareOps);
3881 const Extended e_res = directedUpper(r2 / rm_cache->mu_min, kResDivOps);
3882 const Extended e_lower = directedUpper(e_q_hi + e_res, kELowerAddOps);
3883 const Extended e_upper = e_q_hi;
3884 if (!workingIsFinite(e_lower) || !workingIsFinite(e_upper)) {
3885 throw BorderedVarianceError(
3886 "the bordered variance error bound is not finite");
3887 }
3888
3889 Extended raw_lo = schur - e_lower;
3890 Extended raw_hi = schur + e_upper;
3891 if (!workingIsFinite(raw_lo) || !workingIsFinite(raw_hi)) {
3892 throw BorderedVarianceError(
3893 "the bordered variance interval is not finite");
3894 }
3896 if (!(raw_hi >= Extended(0))) {
3897 throw BorderedVarianceError(
3898 "the bordered variance upper bound is negative");
3899 }
3900 if (raw_lo < Extended(0)) raw_lo = Extended(0);
3901 }
3902 const double lo = gpr::extended::roundDownToDouble(raw_lo);
3903 const double hi = gpr::extended::roundUpToDouble(raw_hi);
3904 if (!(hi >= lo)) {
3905 throw BorderedVarianceError(
3906 "bordered variance interval endpoints are inconsistent");
3907 }
3908 intervals[static_cast<std::size_t>(column)] = {lo, hi};
3909 }
3910 return intervals;
3911}
3912
3913Eigen::VectorXd StableBasisND::noisyInverseDiagonal(double sigma2) const
3914{
3915 // Same regularized operator as the mean path: every mean, logdet,
3916 // and LOO route floors sigma2 through conditionFlooredSigma2; a raw
3917 // sigma2 here yields moments of a DIFFERENT posterior (systematic
3918 // overconfidence exactly when the floor is active).
3919 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3920 if (Psi_.rows() == 0 || Psi_.cols() != Sr_.size() || !(sigma2 > 0.0)) {
3921 return Eigen::VectorXd();
3922 }
3923
3924 const Eigen::ArrayXd shrink =
3925 Sr_.array().square() / (Sr_.array().square() + sigma2);
3926 // diag_i = sum_j psi_ij^2/(s_j^2 + sigma2) + w_c (1 - sum_j psi_ij^2),
3927 // w_c the complement weight (1/sigma2 when nothing above the resolution
3928 // cutoff was dropped). Leave-one-out scores and the variance
3929 // calibration pair this diagonal with alpha from solveNoisy, so both
3930 // carry the mean-path weight of one (K + sigma2 I)^-1; joint posterior
3931 // covariance uses covarianceComplementWeight.
3932 const double w_c = complementWeight(sigma2);
3933 Eigen::VectorXd diag = Eigen::VectorXd::Constant(Psi_.rows(), w_c);
3934 for (Eigen::Index j = 0; j < Psi_.cols(); ++j) {
3935 const double inv_noisy = 1.0 / (Sr_(j) * Sr_(j) + sigma2);
3936 diag.array() += (inv_noisy - w_c) * Psi_.col(j).array().square();
3937 }
3938 return diag;
3939}
3940
3942 const Eigen::VectorXi& rows, double sigma2) const
3943{
3944 // Floored identically to noisyInverseDiagonal; the two must describe
3945 // the same posterior or a caller mixing them sees two noise models.
3946 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
3947 if (Psi_.rows() == 0 || Psi_.cols() != Sr_.size() || !(sigma2 > 0.0)) {
3948 return Eigen::VectorXd();
3949 }
3950
3951 const Eigen::ArrayXd shrink =
3952 Sr_.array().square() / (Sr_.array().square() + sigma2);
3953 const double inv_sigma2 = 1.0 / sigma2;
3954 Eigen::VectorXd out(rows.size());
3955 for (Eigen::Index r = 0; r < rows.size(); ++r) {
3956 const Eigen::Index row = rows(r);
3957 if (row < 0 || row >= Psi_.rows()) {
3958 out(r) = std::numeric_limits<double>::quiet_NaN();
3959 continue;
3960 }
3961 double value = complementWeight(sigma2);
3962 for (Eigen::Index j = 0; j < Psi_.cols(); ++j) {
3963 const double inv_noisy = 1.0 / (Sr_(j) * Sr_(j) + sigma2);
3964 value += (inv_noisy - complementWeight(sigma2)) * Psi_(row, j) *
3965 Psi_(row, j);
3966 }
3967 (void)inv_sigma2;
3968 (void)shrink;
3969 out(r) = value;
3970 }
3971 return out;
3972}
3973
3975 const Eigen::VectorXd& y, double sigma2) const
3976{
3977 if (y.size() != Psi_.rows() || !(sigma2 > 0.0)) {
3978 return std::numeric_limits<double>::quiet_NaN();
3979 }
3980
3981 const Eigen::VectorXd alpha = solveNoisy(y, sigma2);
3982 const Eigen::VectorXd inv_diag = noisyInverseDiagonal(sigma2);
3983 if (alpha.size() != y.size() || inv_diag.size() != y.size()) {
3984 return std::numeric_limits<double>::quiet_NaN();
3985 }
3986
3987 double nlp = 0.0;
3988 const double log_two_pi = std::log(2.0 * std::acos(-1.0));
3989 for (Eigen::Index i = 0; i < y.size(); ++i) {
3990 const double q = inv_diag(i);
3991 if (!(q > 0.0) || !std::isfinite(q) || !std::isfinite(alpha(i))) {
3992 return std::numeric_limits<double>::quiet_NaN();
3993 }
3994 nlp += 0.5 * (log_two_pi - std::log(q) + alpha(i) * alpha(i) / q);
3995 }
3996 return nlp;
3997}
3998
3999bool looCalibrationIsUnityFromCholeskyDiagonal(const Eigen::VectorXd& alpha,
4000 const Eigen::VectorXd& diagonal)
4001{
4002 if (alpha.size() < 2 || alpha.size() != diagonal.size()) return false;
4003 // q_i = ||L^-1 e_i||^2 >= 1 / L_ii^2 gives
4004 // alpha_i^2 / q_i <= (alpha_i L_ii)^2. A strict majority below the
4005 // chi-square median bounds both middle entries for an even sample.
4006 // The margin keeps a rounded score at the boundary inconclusive.
4007 constexpr double kChiSquare1Median = 0.4549364231195727;
4008 const double limit = std::sqrt(kChiSquare1Median) *
4009 (1.0 - 128.0 * std::numeric_limits<double>::epsilon());
4010 Eigen::Index below = 0;
4011 for (Eigen::Index i = 0; i < alpha.size(); ++i) {
4012 if (!std::isfinite(alpha(i)) || !std::isfinite(diagonal(i)) ||
4013 !(diagonal(i) > 0.0))
4014 return false;
4015 if (std::abs(alpha(i)) * diagonal(i) < limit) ++below;
4016 }
4017 return below > alpha.size() / 2;
4018}
4019
4020double looVarianceCalibrationFactor(const Eigen::VectorXd& alpha,
4021 const Eigen::VectorXd& inv_diag)
4022{
4023 // z_i^2 = alpha_i^2 / q_i with alpha = (K + sigma2 I)^-1 y and
4024 // q_i = [(K + sigma2 I)^-1]_ii is the squared leave-one-out z-score of
4025 // row i (Sundararajan-Keerthi). A calibrated posterior has z_i marginally
4026 // standard normal, so z_i^2 ~ chi-square(1) with population median
4027 // Phi^-1(0.75)^2 = 0.4549364231195727 (a distributional constant). The
4028 // factor is the median z^2 over that reference; calibrated or
4029 // under-confident models (c <= 1) are left untouched. Backend-independent
4030 // on purpose: the dense Cholesky and the HS-SVD dual basis must report
4031 // the same calibrated variance for the same data.
4032 if (alpha.size() < 2 || alpha.size() != inv_diag.size()) return 1.0;
4033 std::vector<double> z2;
4034 z2.reserve(static_cast<std::size_t>(alpha.size()));
4035 for (Eigen::Index i = 0; i < alpha.size(); ++i) {
4036 const double q = inv_diag(i);
4037 if (!(q > 0.0) || !std::isfinite(q) || !std::isfinite(alpha(i)))
4038 return 1.0;
4039 z2.push_back(alpha(i) * alpha(i) / q);
4040 }
4041 std::sort(z2.begin(), z2.end());
4042 const std::size_t n = z2.size();
4043 const double median_z2 =
4044 (n % 2 == 1) ? z2[n / 2] : 0.5 * (z2[n / 2 - 1] + z2[n / 2]);
4045 constexpr double kChiSquare1Median = 0.4549364231195727;
4046 const double c = median_z2 / kChiSquare1Median;
4047 return (std::isfinite(c) && c > 1.0) ? c : 1.0;
4048}
4049
4051 double sigma2) const
4052{
4053 if (y.size() < 2 || y.size() != Psi_.rows()) return 1.0;
4054 const Eigen::VectorXd alpha = solveNoisy(y, sigma2);
4055 const Eigen::VectorXd q = noisyInverseDiagonal(sigma2);
4056 return looVarianceCalibrationFactor(alpha, q);
4057}
4058
4060 const Eigen::MatrixXd& dK, double sigma2) const
4061{
4062 // Same regularized operator as the mean path: every mean, logdet,
4063 // and LOO route floors sigma2 through conditionFlooredSigma2; a raw
4064 // sigma2 here yields moments of a DIFFERENT posterior (systematic
4065 // overconfidence exactly when the floor is active).
4066 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4067 if (Psi_.rows() == 0 || Psi_.cols() != Sr_.size() || !(sigma2 > 0.0) ||
4068 dK.rows() != Psi_.rows() || dK.cols() != Psi_.rows()) {
4069 return Eigen::VectorXd();
4070 }
4071
4072 if (Psi_.cols() == Psi_.rows()) {
4073 // With no orthogonal complement, contract the inverse spectrum
4074 // directly instead of subtracting four noise-scaled projector terms.
4075 const Eigen::ArrayXd mu =
4077 ? Eigen::ArrayXd(noisy_eigvals_.array())
4078 : Eigen::ArrayXd(Sr_.array().square() + sigma2);
4079 const Eigen::MatrixXd scaled =
4080 Psi_ * mu.inverse().matrix().asDiagonal();
4081 const Eigen::MatrixXd projected = Psi_.transpose() * dK * Psi_;
4082 const Eigen::MatrixXd action = scaled * projected;
4083 return (action.array() * scaled.array()).rowwise().sum();
4084 }
4085
4086 const double inv_noise = 1.0 / sigma2;
4087 const Eigen::VectorXd shrink =
4088 (Sr_.array().square() / (Sr_.array().square() + sigma2)).matrix();
4089 const Eigen::MatrixXd Urho = Psi_ * shrink.asDiagonal();
4090
4091 const Eigen::MatrixXd dKT_U = dK.transpose() * Psi_;
4092 const Eigen::VectorXd left = (Urho.array() * dKT_U.array()).rowwise().sum();
4093 const Eigen::MatrixXd dK_Urho = dK * Urho;
4094 const Eigen::VectorXd right =
4095 (dK_Urho.array() * Psi_.array()).rowwise().sum();
4096
4097 const Eigen::MatrixXd projected = Psi_.transpose() * dK * Psi_;
4098 const Eigen::MatrixXd Urho_projected = Urho * projected;
4099 const Eigen::VectorXd low_rank =
4100 (Urho_projected.array() * Urho.array()).rowwise().sum();
4101
4102 return inv_noise * inv_noise * (dK.diagonal() - left - right + low_rank);
4103}
4104
4105double
4107 const Eigen::VectorXd& y, double sigma2, const Eigen::MatrixXd& dK) const
4108{
4109 if (y.size() != Psi_.rows() || !(sigma2 > 0.0) ||
4110 dK.rows() != Psi_.rows() || dK.cols() != Psi_.rows()) {
4111 return std::numeric_limits<double>::quiet_NaN();
4112 }
4113
4114 const Eigen::VectorXd alpha = solveNoisy(y, sigma2);
4115 const Eigen::VectorXd inv_diag = noisyInverseDiagonal(sigma2);
4116 const Eigen::VectorXd dalpha = -solveNoisy(dK * alpha, sigma2);
4117 const Eigen::VectorXd dq = -noisyInverseSandwichDiagonal(dK, sigma2);
4118 if (alpha.size() != y.size() || inv_diag.size() != y.size() ||
4119 dalpha.size() != y.size() || dq.size() != y.size()) {
4120 return std::numeric_limits<double>::quiet_NaN();
4121 }
4122
4123 double derivative = 0.0;
4124 for (Eigen::Index i = 0; i < y.size(); ++i) {
4125 const double q = inv_diag(i);
4126 if (!(q > 0.0) || !std::isfinite(q) || !std::isfinite(alpha(i)) ||
4127 !std::isfinite(dalpha(i)) || !std::isfinite(dq(i))) {
4128 return std::numeric_limits<double>::quiet_NaN();
4129 }
4130 derivative +=
4131 0.5 * ((-1.0 / q - alpha(i) * alpha(i) / (q * q)) * dq(i) +
4132 2.0 * alpha(i) * dalpha(i) / q);
4133 }
4134 return derivative;
4135}
4136
4137Eigen::MatrixXd StableBasisND::noisyInverse(double sigma2) const
4138{
4139 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4140 // (K+sigma2 I)^-1 = Psi diag(1/(S^2+sigma2)) Psi^T + (1/sigma2)(I-Psi
4141 // Psi^T)
4142 const Eigen::Index n = Psi_.rows();
4143 if (n == 0 || Psi_.cols() != Sr_.size() || !(sigma2 > 0.0)) {
4144 return Eigen::MatrixXd();
4145 }
4146 const Eigen::ArrayXd mu =
4147 hasNoisyEigenvalues() ? Eigen::ArrayXd(noisy_eigvals_.array())
4148 : Eigen::ArrayXd(Sr_.array().square() + sigma2);
4149 const double q = Psi_.cols() == n ? 0.0 : 1.0 / sigma2;
4150 const Eigen::ArrayXd d = mu.inverse() - q;
4151 Eigen::MatrixXd inv = Eigen::MatrixXd::Identity(n, n) * q;
4152 inv.noalias() += Psi_ * d.matrix().asDiagonal() * Psi_.transpose();
4153 return inv;
4154}
4155
4157 const Eigen::VectorXd& y, double sigma2,
4158 const std::vector<std::vector<Eigen::Index>>& groups) const
4159{
4160 if (y.size() != Psi_.rows() || !(sigma2 > 0.0)) {
4161 return std::numeric_limits<double>::quiet_NaN();
4162 }
4163 const Eigen::VectorXd alpha = solveNoisy(y, sigma2);
4164 if (alpha.size() != y.size()) {
4165 return std::numeric_limits<double>::quiet_NaN();
4166 }
4167 // Block-diagonal of (K+sigma2 I)^-1 WITHOUT forming the dense n x n
4168 // inverse. noisyInverse() = q I + Psi diag(d) Psi^T, d = 1/mu - q;
4169 // q = 0 for a full basis and 1/s otherwise.
4170 // grouped LOO needs only the b x b diagonal blocks Cinv_BB, so build each
4171 // directly from the b x r rows of Psi: Cinv_BB = q I_b + Psi_B diag(d)
4172 // Psi_B^T. This is O(sum_B b^2 r) with no O(n^2 r) inverse assembly and no
4173 // O(n^2) storage.
4174 const double sig_f = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4175 const Eigen::Index rrank = Sr_.size();
4176 if (Psi_.rows() != y.size() || Psi_.cols() != rrank || !(sig_f > 0.0)) {
4177 return std::numeric_limits<double>::quiet_NaN();
4178 }
4179 const Eigen::ArrayXd mu =
4180 hasNoisyEigenvalues() ? Eigen::ArrayXd(noisy_eigvals_.array())
4181 : Eigen::ArrayXd(Sr_.array().square() + sig_f);
4182 // The complement weight is the one solveNoisy gives alpha, so the block
4183 // inverse and the weights describe one and the same (K + sigma2 I)^-1.
4184 const double q = complementWeight(sig_f);
4185 const Eigen::ArrayXd d = mu.inverse() - q;
4186 const double log_two_pi = std::log(2.0 * std::acos(-1.0));
4187 double nlp = 0.0;
4188 for (const auto& g: groups) {
4189 const Eigen::Index b = static_cast<Eigen::Index>(g.size());
4190 if (b <= 0) continue;
4191 Eigen::MatrixXd PB(b, rrank); // Psi rows for this block
4192 Eigen::VectorXd aB(b);
4193 for (Eigen::Index r = 0; r < b; ++r) {
4194 const Eigen::Index idx = g[static_cast<size_t>(r)];
4195 aB(r) = alpha(idx);
4196 PB.row(r) = Psi_.row(idx);
4197 }
4198 Eigen::MatrixXd M =
4199 (PB * d.matrix().asDiagonal()) * PB.transpose(); // low-rank part
4200 M.diagonal().array() += q;
4201 // Condition-floor ridge: a redundant geometry block makes Cinv_BB
4202 // near-singular so its inverse (the LOO predictive covariance) blows up
4203 // and the score/gradient go pathological (the 19/24 divergence). Floor
4204 // the smallest eigenvalue at max_diag*sqrt(eps) so cond(M) <=
4205 // 1/sqrt(eps).
4206 const double ridge =
4207 std::sqrt(std::numeric_limits<double>::epsilon()) *
4208 std::max(1e-300, M.diagonal().cwiseAbs().maxCoeff());
4209 M.diagonal().array() += ridge;
4210 const Eigen::LDLT<Eigen::MatrixXd> ldlt(M);
4211 if (ldlt.info() != Eigen::Success)
4212 return std::numeric_limits<double>::quiet_NaN();
4213 const Eigen::VectorXd Sa = ldlt.solve(aB); // (Cinv_BB)^-1 alpha_B
4214 const double logdetM = ldlt.vectorD().array().abs().log().sum();
4215 const double quad = aB.dot(Sa);
4216 if (!std::isfinite(logdetM) || !std::isfinite(quad))
4217 return std::numeric_limits<double>::quiet_NaN();
4218 nlp += 0.5 * (static_cast<double>(b) * log_two_pi - logdetM + quad);
4219 }
4220 return nlp;
4221}
4222
4225 const Eigen::VectorXd& y, double sigma2, const Eigen::MatrixXd& dK,
4226 const std::vector<std::vector<Eigen::Index>>& groups) const
4227{
4228 if (y.size() != Psi_.rows() || !(sigma2 > 0.0) ||
4229 dK.rows() != Psi_.rows() || dK.cols() != Psi_.rows()) {
4230 return std::numeric_limits<double>::quiet_NaN();
4231 }
4232 const double sig_f = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4233 const Eigen::Index rrank = Sr_.size();
4234 const Eigen::VectorXd alpha = solveNoisy(y, sigma2);
4235 if (alpha.size() != y.size() || Psi_.rows() != y.size() ||
4236 Psi_.cols() != rrank || !(sig_f > 0.0)) {
4237 return std::numeric_limits<double>::quiet_NaN();
4238 }
4239 // The value is the objective of the truncated kernel K_r = P S^2 P^T
4240 // (P = Psi): a dropped direction carries no kernel variance at any
4241 // theta, so the kernel derivative it sees is dK with its dropped-dropped
4242 // block removed,
4243 // dK_r = dK - Q dK Q = R P^T + P R^T + P G P^T,
4244 // with G = P^T dK P (r x r) and R = dK P - P G = Q dK P (n x r), the
4245 // coupling of the retained modes into the complement. R is formed as a
4246 // residual, so a structurally null direction contributes rounding of dK
4247 // and not a q-weighted copy of it.
4248 //
4249 // Cinv = q I + P D P^T with D = 1/mu - q, so Cinv P = P diag(1/mu) and
4250 // Cinv R = q R (P^T R = 0). The sandwich S = Cinv dK_r Cinv is then
4251 // S = P Minv G Minv P^T + q (R Minv P^T + P Minv R^T),
4252 // whose block S_BB follows from the b x r rows of P and R. The dense
4253 // form q^2 dK_BB + q[(dK P)_B D P_B^T + sym] + P_B D G D P_B^T is equal
4254 // in exact arithmetic and cancels q^2 |dK| against itself, which at
4255 // q = 1/sigma2 and a collapsed length scale leaves no digits.
4256 const double q = complementWeight(sig_f);
4257 const Eigen::ArrayXd mu =
4258 hasNoisyEigenvalues() ? Eigen::ArrayXd(noisy_eigvals_.array())
4259 : Eigen::ArrayXd(Sr_.array().square() + sig_f);
4260 const Eigen::VectorXd minv = mu.inverse().matrix();
4261 const Eigen::VectorXd dvec = (mu.inverse() - q).matrix();
4262 const Eigen::MatrixXd dKP = dK * Psi_; // n x r
4263 const Eigen::MatrixXd G = Psi_.transpose() * dKP; // r x r
4264 const Eigen::MatrixXd R = dKP - Psi_ * G; // n x r
4265 // dK_r alpha = R z + P (G z + R^T alpha), z = P^T alpha.
4266 const Eigen::VectorXd z = Psi_.transpose() * alpha;
4267 const Eigen::VectorXd u = R * z + Psi_ * (G * z + R.transpose() * alpha);
4268 const Eigen::VectorXd dalpha = -solveNoisy(u, sigma2);
4269 if (dalpha.size() != y.size()) {
4270 return std::numeric_limits<double>::quiet_NaN();
4271 }
4272 const Eigen::MatrixXd MinvGMinv =
4273 minv.asDiagonal() * G * minv.asDiagonal(); // r x r
4274 double deriv = 0.0;
4275 for (const auto& g: groups) {
4276 const Eigen::Index b = static_cast<Eigen::Index>(g.size());
4277 if (b <= 0) continue;
4278 Eigen::MatrixXd PB(b, rrank), RB(b, rrank);
4279 Eigen::VectorXd aB(b), daB(b);
4280 for (Eigen::Index r = 0; r < b; ++r) {
4281 const Eigen::Index gr = g[static_cast<size_t>(r)];
4282 aB(r) = alpha(gr);
4283 daB(r) = dalpha(gr);
4284 PB.row(r) = Psi_.row(gr);
4285 RB.row(r) = R.row(gr);
4286 }
4287 Eigen::MatrixXd M = (PB * dvec.asDiagonal()) * PB.transpose();
4288 M.diagonal().array() += q; // Cinv_BB
4289 const Eigen::MatrixXd PBMinv = PB * minv.asDiagonal(); // b x r
4290 const Eigen::MatrixXd cross = RB * PBMinv.transpose(); // b x b
4291 const Eigen::MatrixXd dM =
4292 -(PB * MinvGMinv * PB.transpose() +
4293 q * (cross + cross.transpose())); // = -S_BB
4294 // Same condition-floor ridge as the value (treated as a constant in
4295 // theta -- the ridge is O(sqrt(eps)) so its dtheta term is negligible).
4296 const double ridge =
4297 std::sqrt(std::numeric_limits<double>::epsilon()) *
4298 std::max(1e-300, M.diagonal().cwiseAbs().maxCoeff());
4299 M.diagonal().array() += ridge;
4300 const Eigen::LDLT<Eigen::MatrixXd> ldlt(M);
4301 if (ldlt.info() != Eigen::Success)
4302 return std::numeric_limits<double>::quiet_NaN();
4303 const Eigen::MatrixXd Sig = ldlt.solve(Eigen::MatrixXd::Identity(b, b));
4304 const Eigen::VectorXd Sa = Sig * aB; // Sigma alpha_B
4305 // d(-logdet M) = -tr(Sigma dM)
4306 const double dlogdet = -(Sig * dM).trace();
4307 // d(alpha_B^T Sigma alpha_B) = 2 alpha_B^T Sigma dalpha_B
4308 // - (Sigma alpha_B)^T dM (Sigma alpha_B)
4309 const double dquad = 2.0 * Sa.dot(daB) - Sa.dot(dM * Sa);
4310 if (!std::isfinite(dlogdet) || !std::isfinite(dquad))
4311 return std::numeric_limits<double>::quiet_NaN();
4312 deriv += 0.5 * (dlogdet + dquad);
4313 }
4314 return deriv;
4315}
4316
4317double StableBasisND::logDetNoisy(double sigma2) const
4318{
4319 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4320 // eigenvalues of K+sigma2 I: S_i^2+sigma2 (i<rank), sigma2 (the rest).
4321 // The noisy-objective path stores mu_i = eig(K+sigma2 I) directly (no mode
4322 // dropped, rank == nobs), so sum log(mu_i) is the exact log-determinant.
4323 const Eigen::Index nobs = Psi_.rows();
4324 if (hasNoisyEigenvalues()) return noisy_eigvals_.array().log().sum();
4325 double ld = (Sr_.array().square() + sigma2).log().sum();
4326 ld += static_cast<double>(nobs - rank_) * std::log(sigma2);
4327 return ld;
4328}
4329
4331 const Eigen::VectorXd& alpha) const
4332{
4333 if (!linalg::stablePosteriorVarianceEnabled() || dropped_s2_max_ > 0.0 ||
4334 Psi_.cols() == Psi_.rows() || alpha.size() != Psi_.rows())
4335 return alpha;
4336 Eigen::VectorXd coefficients = Psi_.transpose() * alpha;
4337 coefficients += Psi_.transpose() * (alpha - Psi_ * coefficients);
4338 return Psi_ * coefficients;
4339}
4340
4342 const Eigen::MatrixXd& Xstar, const Eigen::VectorXd& alpha) const
4343{
4344 // mu(x*) = k*(x*)^T alpha, k*(x*) = A(x*) A_train^T, so
4345 // mu(x*) = A_E(x*) (A_train^T alpha).
4346 Eigen::MatrixXd A_E;
4347 std::vector<Eigen::MatrixXd> A_g;
4348 designAt(Xstar, A_E, A_g);
4349 const Eigen::VectorXd v =
4350 A_train_.transpose() * posteriorMeanWeights(alpha); // N
4351 return A_E * v;
4352}
4353
4355 const Eigen::MatrixXd& Xstar, const Eigen::VectorXd& alpha) const
4356{
4357 Eigen::MatrixXd A_E;
4358 std::vector<Eigen::MatrixXd> A_g;
4359 designAt(Xstar, A_E, A_g);
4360 const Eigen::VectorXd v =
4361 A_train_.transpose() * posteriorMeanWeights(alpha); // N
4362 Eigen::MatrixXd G(Xstar.rows(), dim_);
4363 for (int j = 0; j < dim_; ++j)
4364 G.col(j) = A_g[j] * v;
4365 return G;
4366}
4367
4368bool stabilizePosteriorCovariance(Eigen::MatrixXd& covariance)
4369{
4370 if (covariance.rows() != covariance.cols() || !covariance.allFinite())
4371 return false;
4372 const Eigen::VectorXd diagonal = covariance.diagonal();
4373 if ((diagonal.array() < 0.0).any()) return false;
4374 if (covariance.rows() <= 1) return true;
4375
4376 // sqrt(d_i * d_j) overflows when both marginals are large even though
4377 // the geometric mean is finite. Scaling each square root keeps that
4378 // product inside the finite range.
4379 const auto geometric_mean = [](double left, double right) noexcept {
4380 if (!(left > 0.0) || !(right > 0.0)) return 0.0;
4381 return std::sqrt(left) * std::sqrt(right);
4382 };
4383
4384 // Finiteness and positive-semidefiniteness are decided before any clamp.
4385 // Clamping an overflowing ratio to +/-1, or dropping a large negative
4386 // eigenvalue, hides an input that is not a covariance. A negative
4387 // eigenvalue inside the backward-error allowance is the rounding of a
4388 // singular posterior; only that one is projected onto the PSD cone.
4389 // The grouped LOO ridge floors a near-null eigenvalue at scale*sqrt(eps),
4390 // so a retained block has cond <= 1/sqrt(eps). A cancelled correlation
4391 // entry is then wrong by at most cond*eps = sqrt(eps), measured on the
4392 // unit scale of a correlation. An entrywise perturbation of that size
4393 // has Frobenius norm at most n*sqrt(eps), and Weyl's inequality moves an
4394 // eigenvalue by at most that. The allowance is therefore
4395 // c*n*eps*||R|| with c = 1/sqrt(eps) and ||R|| = 1. A computed entry
4396 // outside [-1, 1] is the defect, so ||R|| does not grow with it. The
4397 // congruence by sqrt(diagonal) then preserves the cancellation-free
4398 // marginal variances.
4399 Eigen::MatrixXd correlation =
4400 Eigen::MatrixXd::Identity(covariance.rows(), covariance.cols());
4401 for (Eigen::Index column = 0; column < covariance.cols(); ++column) {
4402 for (Eigen::Index row = 0; row < column; ++row) {
4403 const double scale =
4404 geometric_mean(diagonal(row), diagonal(column));
4405 if (!std::isfinite(scale)) return false;
4406 double value = 0.0;
4407 if (!(scale > 0.0)) {
4408 if (covariance(row, column) != 0.0) return false;
4409 } else {
4410 value = covariance(row, column) / scale;
4411 if (!std::isfinite(value)) return false;
4412 }
4413 correlation(row, column) = value;
4414 correlation(column, row) = value;
4415 }
4416 }
4417 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> solver(correlation);
4418 if (solver.info() != Eigen::Success) return false;
4419 const Eigen::VectorXd raw_eigenvalues = solver.eigenvalues();
4420 if (!raw_eigenvalues.allFinite()) return false;
4421 const double eps = std::numeric_limits<double>::epsilon();
4422 const double rows = static_cast<double>(correlation.rows());
4423 // ||R|| is the unit scale of a correlation, not the largest entry.
4424 constexpr double correlation_norm = 1.0;
4425 const double backward_constant = 1.0 / std::sqrt(eps);
4426 const double tolerance = backward_constant * rows * eps * correlation_norm;
4427 if (!std::isfinite(tolerance) ||
4428 !(raw_eigenvalues.minCoeff() >= -tolerance))
4429 return false;
4430 const Eigen::VectorXd eigenvalues = raw_eigenvalues.cwiseMax(0.0);
4431 correlation = solver.eigenvectors() * eigenvalues.asDiagonal() *
4432 solver.eigenvectors().transpose();
4433 const Eigen::VectorXd norm =
4434 correlation.diagonal().cwiseMax(0.0).cwiseSqrt();
4435 if ((norm.array() <= 0.0).any()) return false;
4436 for (Eigen::Index column = 0; column < covariance.cols(); ++column) {
4437 for (Eigen::Index row = 0; row < column; ++row) {
4438 const double norm_scale = norm(row) * norm(column);
4439 if (!(norm_scale > 0.0) || !std::isfinite(norm_scale)) return false;
4440 const double rho =
4441 std::clamp(correlation(row, column) / norm_scale, -1.0, 1.0);
4442 const double scale =
4443 geometric_mean(diagonal(row), diagonal(column));
4444 if (!std::isfinite(scale) || !std::isfinite(rho)) return false;
4445 covariance(row, column) = rho * scale;
4446 covariance(column, row) = covariance(row, column);
4447 if (!std::isfinite(covariance(row, column))) return false;
4448 }
4449 }
4450 covariance.diagonal() = diagonal;
4451 if (!covariance.allFinite()) return false;
4452 return true;
4453}
4454
4456 const Eigen::MatrixXd& cross, const Eigen::VectorXd& prior,
4457 double sigma2) const
4458{
4459 sigma2 = varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
4460 if (cross.rows() != Psi_.rows() || prior.size() != cross.cols() ||
4461 Psi_.cols() != Sr_.size())
4463 "stable posterior variance: cross covariance does not match the "
4464 "stable basis");
4465 if (!(sigma2 > 0.0) || !std::isfinite(sigma2))
4467 "stable posterior variance: noise floor is not finite and "
4468 "positive");
4469
4470 Eigen::MatrixXd projected, residual;
4471 projectOntoStableBasis(Psi_, cross, projected, residual);
4472 // A complement whose spectrum is below the eigensolver's backward-error
4473 // threshold is the null space of the retained model. Its cross residual
4474 // is projection roundoff and belongs in the unresolved prior tail; do not
4475 // divide it by an invented signal eigenvalue.
4476 const bool use_complement = dropped_s2_max_ > 0.0;
4477 const double complement_eigenvalue = covarianceComplementEigenvalue();
4478 Eigen::VectorXd variance(prior.size());
4479 for (Eigen::Index column = 0; column < cross.cols(); ++column) {
4480 linalg::ExactSum local_prior;
4481 local_prior.add(prior(column));
4482 variance(column) = nonnegativeEigenmodeVariance(
4483 projected.col(column), residual.col(column), Sr_, sigma2,
4484 complement_eigenvalue, use_complement, local_prior);
4485 }
4486 return variance;
4487}
4488
4489Eigen::MatrixXd StableBasisND::posteriorCovariance(const Eigen::MatrixXd& cross,
4490 const Eigen::MatrixXd& prior,
4491 double sigma2) const
4492{
4493 if (prior.rows() != prior.cols() || prior.rows() != cross.cols())
4495 "stable posterior covariance: prior and query columns disagree");
4496 const Eigen::VectorXd diagonal =
4497 posteriorVarianceDiagonal(cross, prior.diagonal(), sigma2);
4498 sigma2 = varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
4499
4500 Eigen::MatrixXd projected, residual;
4501 projectOntoStableBasis(Psi_, cross, projected, residual);
4502 Eigen::MatrixXd retained = projected;
4503 for (Eigen::Index mode = 0; mode < Sr_.size(); ++mode) {
4504 if (!(Sr_(mode) > 0.0) || !std::isfinite(Sr_(mode)))
4506 "stable posterior covariance: retained singular value is not "
4507 "finite and positive");
4508 retained.row(mode) /= Sr_(mode);
4509 }
4510 const bool use_complement = dropped_s2_max_ > 0.0;
4511 Eigen::MatrixXd complement;
4512 if (use_complement) {
4513 if (!std::isfinite(dropped_s2_max_))
4515 "stable posterior covariance: complement eigenvalue is not "
4516 "finite");
4517 complement = residual / std::sqrt(dropped_s2_max_);
4518 }
4519
4520 // For each pair, combine the unresolved-tail subtraction and the
4521 // noise-damped retained terms in one exact accumulator:
4522 // T_ij = K_ij - sum_m c_mi c_mj,
4523 // C_ij = T_ij + sum_m sigma2/(s_m^2+sigma2) c_mi c_mj.
4524 // The diagonal is the explicitly nonnegative form; sharing these exact
4525 // pair reductions keeps the surrounding covariance and every linear
4526 // action consistent with it.
4527 Eigen::MatrixXd covariance(prior.rows(), prior.cols());
4528 for (Eigen::Index column = 0; column < prior.cols(); ++column) {
4529 for (Eigen::Index row = 0; row < column; ++row) {
4530 linalg::ExactSum value;
4531 value.add(prior(row, column));
4532 for (Eigen::Index mode = 0; mode < Sr_.size(); ++mode) {
4533 value.addProduct(-retained(mode, row), retained(mode, column));
4534 const double s2 = Sr_(mode) * Sr_(mode);
4535 value.addTripleProduct(retained(mode, row),
4536 retained(mode, column),
4537 sigma2 / (s2 + sigma2));
4538 }
4539 if (use_complement) {
4540 const double attenuation = sigma2 / (dropped_s2_max_ + sigma2);
4541 for (Eigen::Index mode = 0; mode < complement.rows(); ++mode) {
4542 value.addProduct(-complement(mode, row),
4543 complement(mode, column));
4544 value.addTripleProduct(complement(mode, row),
4545 complement(mode, column),
4546 attenuation);
4547 }
4548 }
4549 covariance(row, column) = value.value();
4550 covariance(column, row) = covariance(row, column);
4551 }
4552 covariance(column, column) = diagonal(column);
4553 }
4554 return covariance;
4555}
4556
4557double StableBasisND::posteriorVarianceAction(const Eigen::MatrixXd& cross,
4558 const Eigen::MatrixXd& prior,
4559 const Eigen::VectorXd& weights,
4560 double sigma2) const
4561{
4562 if (prior.rows() != prior.cols() || prior.rows() != cross.cols() ||
4563 weights.size() != prior.rows() || cross.rows() != Psi_.rows() ||
4564 Psi_.cols() != Sr_.size())
4566 "stable posterior action variance: weights, prior and cross "
4567 "covariance disagree");
4568 sigma2 = varianceFlooredSigma2(Sr_, sigma2, Psi_.rows());
4569 if (!(sigma2 > 0.0) || !std::isfinite(sigma2))
4571 "stable posterior action variance: noise floor is not finite and "
4572 "positive");
4573
4574 Eigen::MatrixXd action(cross.rows(), 1);
4575 for (Eigen::Index row = 0; row < cross.rows(); ++row) {
4576 linalg::ExactSum value;
4577 for (Eigen::Index column = 0; column < cross.cols(); ++column)
4578 value.addProduct(cross(row, column), weights(column));
4579 action(row, 0) = value.value();
4580 }
4581 Eigen::MatrixXd projected, residual;
4582 projectOntoStableBasis(Psi_, action, projected, residual);
4583
4584 linalg::ExactSum local_prior;
4585 for (Eigen::Index column = 0; column < prior.cols(); ++column)
4586 for (Eigen::Index row = 0; row < prior.rows(); ++row)
4587 local_prior.addTripleProduct(weights(row), prior(row, column),
4588 weights(column));
4589 return nonnegativeEigenmodeVariance(
4590 projected.col(0), residual.col(0), Sr_, sigma2,
4591 covarianceComplementEigenvalue(), dropped_s2_max_ > 0.0, local_prior);
4592}
4593
4594namespace {
4595// The type the design variance accumulates in. It must carry more than
4596// binary64, so it follows the working type, not the native long double.
4597using DesignVarianceReal = gpr::extended::WorkingReal;
4598
4599double affineResidualTail(double squared_radius)
4600{
4601 // The residual expansion retains mass exp(-x) * (1 + x), with
4602 // x = 2 * |r|^2. The missing fraction is the integral of t * exp(-t)
4603 // from zero to x.
4604 const double x = 2.0 * squared_radius;
4605 if (x >= 48.0) return 1.0;
4606 if (x >= 1.0 / 16.0) return std::fma(-x, std::exp(-x), -std::expm1(-x));
4607
4608 // Integrate the exponential series through degree eight. For this
4609 // interval the first omitted term is below binary64 unit roundoff
4610 // relative to the tail.
4611 double term = 0.5;
4612 double sum = term;
4613 for (int k = 1; k <= 8; ++k) {
4614 term *= -x * (k + 1) / (k * (k + 2));
4615 sum += term;
4616 }
4617 return x * x * sum;
4618}
4619} // namespace
4620
4621Eigen::VectorXd StableBasisND::rangeVarianceFromDesign(
4622 const Eigen::MatrixXd& A_E, double sigma2,
4623 const AffineVariancePrior* affine_prior) const
4624{
4625 sigma2 = conditionFlooredSigma2(Sr_, sigma2, Psi_.rows());
4626 const Eigen::Index m = A_E.rows();
4627 if (!(sigma2 > 0.0) || !std::isfinite(sigma2)) {
4628 throw BorderedVarianceError(
4629 "design variance requires a strictly positive noise variance");
4630 }
4631 if (affine_prior && affine_prior->diagonal.size() != m) {
4632 throw BorderedVarianceError(
4633 "exact prior diagonal size mismatch in design variance");
4634 }
4635 using Extended = DesignVarianceReal;
4636 using ExtendedMatrix =
4637 Eigen::Matrix<Extended, Eigen::Dynamic, Eigen::Dynamic>;
4638 using ExtendedVector = Eigen::Matrix<Extended, Eigen::Dynamic, 1>;
4639 const Extended sigma2_ext = static_cast<Extended>(sigma2);
4640 const Extended s_sig = workingSqrt(sigma2_ext);
4641 const ExtendedMatrix A_train_ext = A_train_.cast<Extended>();
4642 const Eigen::Index nobs = A_train_ext.rows();
4643 const Eigen::Index N = A_train_ext.cols();
4644
4645 ExtendedMatrix stacked(N + nobs, nobs);
4646 stacked.topRows(N) = A_train_ext.transpose();
4647 stacked.bottomRows(nobs) = s_sig * ExtendedMatrix::Identity(nobs, nobs);
4648 Eigen::HouseholderQR<ExtendedMatrix> qr(stacked);
4649 const ExtendedMatrix R_m = qr.matrixQR()
4650 .topLeftCorner(nobs, nobs)
4651 .template triangularView<Eigen::Upper>();
4652
4653 // k*(x*) = A_train a*, formed in the working type. In binary64 each entry
4654 // carries a relative error of u, and the solve below is not insensitive
4655 // to it: the variance is the minimum over u of |a - A^T u|^2 + sigma2 |u|^2
4656 // only for the exact right-hand side, and a perturbation dk raises it by
4657 // dk^T (A A^T + sigma2 I)^-1 dk <= |dk|^2/sigma2, which at the condition
4658 // floor of a rank-deficient basis is no longer below the final rounding.
4659 Eigen::VectorXd var(m);
4660 for (Eigen::Index i = 0; i < m; ++i) {
4661 const ExtendedVector a_star = A_E.row(i).transpose().cast<Extended>();
4662 const ExtendedVector ks = A_train_ext * a_star;
4663 ExtendedVector w = ks;
4664 R_m.transpose().template triangularView<Eigen::Lower>().solveInPlace(w);
4665 ExtendedVector u = w;
4666 R_m.template triangularView<Eigen::Upper>().solveInPlace(u);
4667 const ExtendedVector res = a_star - A_train_ext.transpose() * u;
4668 Extended value = res.squaredNorm() + sigma2_ext * u.squaredNorm();
4669 if (affine_prior) {
4670 Extended missing = affine_prior->diagonal(i);
4671 if (!affine_prior->stable) {
4672 const Extended a_norm2 = a_star.squaredNorm();
4673 if (!(missing >= a_norm2)) {
4674 throw BorderedVarianceError(
4675 "affine prior diagonal is smaller than its truncated "
4676 "design norm");
4677 }
4678 missing -= a_norm2;
4679 } else if (!(missing >= Extended(0)) || !workingIsFinite(missing)) {
4680 throw BorderedVarianceError(
4681 "unrepresented prior variance is negative or nonfinite");
4682 }
4683 value += missing;
4684 }
4685 var(i) = gpr::extended::roundUpToDouble(value);
4686 }
4687 return var;
4688}
4689
4691 const Eigen::MatrixXd& Xstar, double sigma2) const
4692{
4693 Eigen::MatrixXd A_E;
4694 std::vector<Eigen::MatrixXd> A_g;
4695 designAt(Xstar, A_E, A_g);
4696 return rangeVarianceFromDesign(A_E, sigma2);
4697}
4698
4700 const Eigen::MatrixXd& Ustar, const Eigen::MatrixXd& residuals,
4701 double sigma2) const
4702{
4703 Eigen::MatrixXd A_E;
4704 AffineVariancePrior affine_prior;
4705 designAtAffineEnergy(Ustar, residuals, A_E, &affine_prior);
4706 if (affine_prior.stable) {
4707 // Form the missing mass independently of the binary64 design entries.
4708 // Their rounded squared norm can exceed the prior for near-span
4709 // queries.
4710 for (Eigen::Index i = 0; i < affine_prior.diagonal.size(); ++i)
4711 affine_prior.diagonal(i) *= DesignVarianceReal(
4712 affineResidualTail(residuals.row(i).squaredNorm()));
4713 }
4714 return rangeVarianceFromDesign(A_E, sigma2, &affine_prior);
4715}
4716
4718{
4719 return condition_number_;
4720}
4721
4722Eigen::MatrixXd StableBasisND::reconstructKernel(bool truncated) const
4723{
4724 if (truncated) {
4725 if (Psi_.size() == 0 || Sr_.size() == 0) return Eigen::MatrixXd();
4726 // K_trunc = Psi diag(S^2) Psi^T (the rank-kept kernel solveNoisy uses).
4727 return Psi_ * Sr_.array().square().matrix().asDiagonal() *
4728 Psi_.transpose();
4729 }
4730 // K_exact = A_full A_full^T (the full Mercer Gram at this max_degree).
4731 if (A_train_.size() == 0) return Eigen::MatrixXd();
4732 return A_train_ * A_train_.transpose();
4733}
4734
4735namespace {
4736
4737// Rounded operations on one term of the latent variance
4738// eta2 - eta2^2 q, q = w_c + sum_k psi_k^2 (1/(s_k^2 + eta2) - w_c),
4739// as the caller forms it in binary64, and the depth a term passes through.
4740// chain s_k^2, + eta2, the reciprocal, - w_c, psi_k^2 and the product:
4741// 6 operations, one per factor of the term.
4742// reduction the rank terms are added in some order. Any order, including
4743// a blocked dot product, a thread split and a tree over a
4744// process grid, has at most rank - 1 additions on any term, so
4745// rank - 1 bounds every layout and keeps the bound the same for
4746// every rank count, grid and thread count.
4747// assembly + w_c, eta2 * eta2, the product with q and the subtraction
4748// from eta2: 4 operations.
4749inline constexpr long long kLatentTermChainOps = 6;
4750inline constexpr long long kLatentAssemblyOps = 4;
4751
4752// The magnitude is formed in the loop below: a term passes through the same
4753// 6 operations, then at most rank additions into `sum` (which starts at the
4754// complement weight), then eta2 * eta2, the product with sum and eta2 +.
4755inline constexpr long long kLatentMagnitudeAssemblyOps = 3;
4756
4757long long latentMagnitudeOperationDepth(Eigen::Index rank)
4758{
4759 return kLatentTermChainOps + static_cast<long long>(rank) +
4760 kLatentMagnitudeAssemblyOps;
4761}
4762
4763long long latentVarianceOperationDepth(Eigen::Index rank)
4764{
4765 const long long reduction = rank > 0 ? static_cast<long long>(rank) - 1 : 0;
4766 return kLatentTermChainOps + reduction + kLatentAssemblyOps;
4767}
4768
4769} // namespace
4770
4771namespace {
4772
4773std::atomic<long long> g_schur_floored{0};
4774std::atomic<long long> g_schur_proven_negative{0};
4775std::atomic<long long> g_schur_uncertified{0};
4776std::atomic<long long> g_schur_raised{0};
4777
4778void recordSchurFloor(const StableBasisND::SchurFloorReport& report) noexcept
4779{
4780 if (report.floored)
4781 g_schur_floored.fetch_add(report.floored, std::memory_order_relaxed);
4782 if (report.proven_negative)
4783 g_schur_proven_negative.fetch_add(report.proven_negative,
4784 std::memory_order_relaxed);
4785 if (report.uncertified)
4786 g_schur_uncertified.fetch_add(report.uncertified,
4787 std::memory_order_relaxed);
4788 if (report.raised)
4789 g_schur_raised.fetch_add(report.raised, std::memory_order_relaxed);
4790}
4791
4792} // namespace
4793
4795 Eigen::Index rank) noexcept
4796{
4797 return latentVarianceOperationDepth(rank);
4798}
4799
4801{
4802 return std::numeric_limits<DesignVarianceReal>::digits;
4803}
4804
4806 const Eigen::MatrixXd& A_E, double sigma2) const
4807{
4808 return rangeVarianceFromDesign(A_E, sigma2);
4809}
4810
4811void StableBasisND::borderedEpsKForTesting(double& hi, double& lo,
4812 int& operations) const
4813{
4814 using Extended = gpr::extended::WorkingReal;
4815 std::lock_guard<std::mutex> lock(bordered_cache_.mutex);
4816 buildBorderedFactorLocked();
4817 const auto factor = bordered_cache_.factor;
4818 hi = static_cast<double>(factor->eps_k);
4819 lo = static_cast<double>(factor->eps_k - static_cast<Extended>(hi));
4820 operations = factor->eps_k_ops;
4821}
4822
4824{
4825 SchurFloorReport totals;
4826 totals.floored = g_schur_floored.load(std::memory_order_relaxed);
4827 totals.proven_negative =
4828 g_schur_proven_negative.load(std::memory_order_relaxed);
4829 totals.uncertified = g_schur_uncertified.load(std::memory_order_relaxed);
4830 totals.raised = g_schur_raised.load(std::memory_order_relaxed);
4831 return totals;
4832}
4833
4835{
4836 g_schur_floored.store(0, std::memory_order_relaxed);
4837 g_schur_proven_negative.store(0, std::memory_order_relaxed);
4838 g_schur_uncertified.store(0, std::memory_order_relaxed);
4839 g_schur_raised.store(0, std::memory_order_relaxed);
4840}
4841
4843 const Eigen::MatrixXd& cross, const Eigen::VectorXd& prior, double sigma2,
4844 Eigen::VectorXd& value, const std::vector<char>* skip) const
4845{
4846 if (cross.cols() != value.size() || prior.size() != value.size() ||
4847 cross.rows() != Psi_.rows() ||
4848 (skip && static_cast<Eigen::Index>(skip->size()) != value.size()))
4849 throw std::invalid_argument(
4850 "Schur diagonal certification needs one cross column and one "
4851 "prior entry per value");
4852 const double inf = std::numeric_limits<double>::infinity();
4853 SchurFloorReport report;
4854 std::vector<Eigen::Index> negative;
4855 for (Eigen::Index i = 0; i < value.size(); ++i) {
4856 if (skip && (*skip)[static_cast<std::size_t>(i)]) continue;
4857 if (std::isnan(value(i)) || value(i) == -inf) {
4858 value(i) = inf;
4859 ++report.uncertified;
4860 } else if (value(i) < 0.0) {
4861 if (!cross.col(i).allFinite() || !std::isfinite(prior(i))) {
4862 value(i) = inf;
4863 ++report.uncertified;
4864 } else {
4865 negative.push_back(i);
4866 }
4867 }
4868 }
4869 if (!negative.empty()) {
4870 std::vector<BorderedVarianceInterval> intervals;
4871 bool enclosed = false;
4872 if (supportsBorderedVarianceInterval() && std::isfinite(sigma2) &&
4873 sigma2 >= 0.0) {
4874 Eigen::MatrixXd rhs(cross.rows(),
4875 static_cast<Eigen::Index>(negative.size()));
4876 Eigen::VectorXd prior_subset(rhs.cols());
4877 for (Eigen::Index k = 0; k < rhs.cols(); ++k) {
4878 rhs.col(k) = cross.col(negative[static_cast<std::size_t>(k)]);
4879 prior_subset(k) = prior(negative[static_cast<std::size_t>(k)]);
4880 }
4881 try {
4883 rhs, prior_subset, sigma2,
4885 enclosed = intervals.size() == negative.size();
4886 } catch (const std::runtime_error&) {
4887 enclosed = false;
4888 }
4889 }
4890 for (std::size_t k = 0; k < negative.size(); ++k) {
4891 double& entry = value(negative[k]);
4892 if (!enclosed) {
4893 entry = inf;
4894 ++report.uncertified;
4895 } else if (intervals[k].upper < 0.0) {
4896 entry = inf;
4897 ++report.proven_negative;
4898 } else if (intervals[k].lower <= 0.0) {
4899 // The enclosure contains zero, so the true value may be zero
4900 // and the negative computed value is roundoff.
4901 entry = 0.0;
4902 ++report.floored;
4903 } else {
4904 // The enclosure is wholly positive: binary64 cancellation put
4905 // the computed value below a true value of at least lower.
4906 entry = intervals[k].lower;
4907 ++report.raised;
4908 }
4909 }
4910 }
4911 recordSchurFloor(report);
4912 return report;
4913}
4914
4916 Eigen::Index row, double statistical_sigma2) const
4917{
4918 using Extended = gpr::extended::WorkingReal;
4919 const double inf = std::numeric_limits<double>::infinity();
4920 if (row < 0 || row >= Psi_.rows() || Psi_.cols() != Sr_.size() ||
4921 !(statistical_sigma2 > 0.0) || !std::isfinite(statistical_sigma2))
4922 return inf;
4923 try {
4924 const Eigen::Index rank = Psi_.cols();
4925 const Extended eta2(statistical_sigma2);
4926 const Extended complement(
4927 covarianceComplementWeight(statistical_sigma2));
4928 Extended sum = complement;
4929 Extended row_norm2 = 0;
4930 for (Eigen::Index k = 0; k < rank; ++k) {
4931 const Extended psi = static_cast<Extended>(Psi_(row, k));
4932 const Extended s = static_cast<Extended>(Sr_(k));
4933 const Extended psi2 = psi * psi;
4934 const Extended inverse = Extended(1) / (s * s + eta2);
4935 sum += psi2 * (inverse + complement);
4936 row_norm2 += psi2;
4937 }
4938 // Magnitude of every term of eta2 - eta2^2 q. Each double operation
4939 // on a term costs at most one unit roundoff of that term, and a term
4940 // passes through latentVarianceOperationDepth(rank) of them.
4941 const long long ops = latentVarianceOperationDepth(rank);
4942 const Extended magnitude = directedUpper(
4943 eta2 + eta2 * eta2 * sum, latentMagnitudeOperationDepth(rank));
4944 const Extended unit(std::ldexp(1.0, -53));
4945 const Extended order = static_cast<Extended>(ops);
4946 if (!(order * unit < Extended(1))) return inf;
4947 const Extended gamma =
4948 directedUpper((order * unit) / (Extended(1) - order * unit), 4);
4949 Extended bound = directedUpper(gamma * magnitude, 1);
4950 // The latent variance is eta2 (1 - eta2 w_c)(1 - ||psi_row||^2) plus
4951 // nonnegative terms, so a retained row longer than 1 by delta lets
4952 // it fall below zero by at most eta2 delta.
4953 const Extended norm2 =
4954 directedUpper(row_norm2, 2 * static_cast<long long>(rank) + 2);
4955 if (norm2 > Extended(1))
4956 bound = directedUpper(bound + eta2 * (norm2 - Extended(1)), 3);
4957 if (!gpr::extended::workingFinite(bound)) return inf;
4958 return gpr::extended::roundUpToDouble(bound);
4959 } catch (const BorderedVarianceError&) {
4960 return inf;
4961 }
4962}
4963
4964double StableBasisND::floorLatentVariance(double latent, double error_bound,
4965 SchurFloorReport* report) noexcept
4966{
4967 if (latent >= 0.0) return latent;
4968 const double inf = std::numeric_limits<double>::infinity();
4969 SchurFloorReport local;
4970 double result = inf;
4971 if (!std::isfinite(latent) || !std::isfinite(error_bound) ||
4972 !(error_bound >= 0.0))
4973 ++local.uncertified;
4974 else if (latent + error_bound >= 0.0) {
4975 ++local.floored;
4976 result = 0.0;
4977 } else
4978 ++local.proven_negative;
4979 recordSchurFloor(local);
4980 if (report) {
4981 report->floored += local.floored;
4982 report->proven_negative += local.proven_negative;
4983 report->uncertified += local.uncertified;
4984 }
4985 return result;
4986}
4987
4988} // namespace gpr
Implementation-independent symmetric eigenpairs.
Runtime-dlopen'd cuSOLVER dense symmetric eigensolver (syevd).
@ z
Definition Enums.h:28
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
Correctly rounded Schur-complement diagonals from Cholesky solves.
Exact floating-point accumulator (Kulisch long accumulator).
void dsyevr_(char *, char *, char *, int *, double *, int *, double *, double *, int *, int *, double *, int *, double *, double *, int *, int *, double *, int *, int *, int *, int *)
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
void eigenfunctionsWithEpsDerivative(const Eigen::VectorXd &x, Eigen::MatrixXd &Phi, Eigen::MatrixXd &dPhi_deps) const
Eigen::VectorXd sqrtLambdaEpsDerivative() const
Eigen::VectorXd solve(const Eigen::VectorXd &y) const
Eigen::MatrixXd evalBasis(const Eigen::VectorXd &xstar) const
static double conditionFlooredSigma2ForTesting(const Eigen::VectorXd &singular_values, double sigma2, Eigen::Index nobs)
bool factorizeKernelLapackRrr(const Eigen::MatrixXd &kernel, double sv_rtol=1e-13, double sv_abs_tol=0.0, double sv_chop_tol=0.0, bool allow_value_range=false)
bool factorizeKernelAppend(const StableBasisND &old_basis, const Eigen::MatrixXd &cross_old_new, const Eigen::MatrixXd &new_kernel, double sv_rtol=1e-13, double sv_abs_tol=0.0, double sv_chop_tol=0.0)
Eigen::VectorXd noisyInverseSandwichDiagonal(const Eigen::MatrixXd &dK, double sigma2) const
static void resetSchurFloorTotals() noexcept
void borderedEpsKForTesting(double &hi, double &lo, int &operations) const
double conditionNumber() const
static bool gradedModeCountExceedsLimit(int dim, int max_degree, Eigen::Index limit)
static Eigen::MatrixXd affineSpanBasis(const Eigen::MatrixXd &centered_X)
bool hasNoisyEigenvalues() const
static int capMaxDegreeByModeCount(int dim, int requested_degree, Eigen::Index mode_limit)
Eigen::VectorXd posteriorMeanWeights(const Eigen::VectorXd &alpha) const
Eigen::VectorXd posteriorVarianceDiagonal(const Eigen::MatrixXd &cross, const Eigen::VectorXd &prior, double sigma2) const
Cancellation-free posterior diagonal for arbitrary query channels.
double covarianceComplementEigenvalue() const noexcept
Largest signal eigenvalue represented by the discarded covariance complement.
Eigen::VectorXd noisySelfQuadratic(const Eigen::MatrixXd &rhs, double sigma2) const
void factorizeGPCartesian(const Eigen::MatrixXd &X, const Eigen::VectorXd &eps, double alpha, double overall_scale, int max_degree, const std::vector< Eigen::MatrixXd > &jacobians, bool component_major=false, double sv_rtol=1e-13, int sketch_size=0, int n_power_iter=2, double mode_prune_rtol=0.0, double sv_abs_tol=0.0)
bool permuteObservationRows(const Eigen::VectorXi &source_for_target)
double varianceFlooredNoise(double sigma2) const
Variance-specific likelihood-noise floor for the retained spectrum.
static SchurFloorReport schurFloorTotals() noexcept
Process-wide totals of SchurFloorReport over every call.
Eigen::MatrixXd predictGradientAffine(const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, const Eigen::MatrixXd &basis, const Eigen::VectorXd &b) const
Eigen::VectorXd stableRangePosteriorDiagonal(const Eigen::MatrixXd &rhs, const Eigen::VectorXd &prior, const Eigen::VectorXd &signal, double sigma2, bool check_variance=true) const
Range-only posterior diagonal as a nonnegative eigenmode sum.
static int designVarianceWorkingDigitsForTesting() noexcept
double logDetNoisy(double sigma2) const
Eigen::VectorXd predictEnergy(const Eigen::MatrixXd &Xstar, const Eigen::VectorXd &b) const
Eigen::VectorXd posteriorMeanReducedCoeffs(const Eigen::VectorXd &y, double sigma2) const
void factorizeNoisyKernel(const Eigen::MatrixXd &noisy_kernel, double sigma2)
Eigen::VectorXd predictEnergyAffine(const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, const Eigen::VectorXd &b) const
Eigen::VectorXd noisyInverseDiagonal(double sigma2) const
Eigen::MatrixXd posteriorMeanGradient(const Eigen::MatrixXd &Xstar, const Eigen::VectorXd &alpha) const
static double floorLatentVariance(double latent, double error_bound, SchurFloorReport *report) noexcept
double posteriorVarianceAction(const Eigen::MatrixXd &cross, const Eigen::MatrixXd &prior, const Eigen::VectorXd &weights, double sigma2) const
Variance of a linear action on a joint query covariance, evaluated by the same nonnegative eigenmode ...
double covarianceComplementWeight(double sigma2) const noexcept
Eigen::VectorXd posteriorMeanEnergy(const Eigen::MatrixXd &Xstar, const Eigen::VectorXd &alpha) 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
Eigen::VectorXd energyAffineDesignRow(const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals) const
static long long latentVarianceOperationDepthForTesting(Eigen::Index rank) noexcept
double leaveOneOutNegativeLogPredictiveDensityDirectionalDerivative(const Eigen::VectorXd &y, double sigma2, const Eigen::MatrixXd &dK) const
void factorize(const Eigen::MatrixXd &X, const Eigen::VectorXd &eps, double alpha, int max_degree, bool gradient_enhanced, double sv_rtol=1e-13)
void factorizeGPCartesianAffine(const Eigen::MatrixXd &U, const Eigen::VectorXd &eps, double alpha, double overall_scale, int max_degree, const std::vector< Eigen::MatrixXd > &jac_tangent, const std::vector< Eigen::MatrixXd > &jac_normal, bool component_major=false, double sv_rtol=1e-13, int sketch_size=0, int n_power_iter=2, double mode_prune_rtol=0.0, double sv_abs_tol=0.0)
static int autoMaxDegree(const Eigen::VectorXd &eps, double alpha, int dim, double target_tol, int max_degree_cap=40)
double leaveOneOutNegativeLogPredictiveDensityGroupedDirectionalDerivative(const Eigen::VectorXd &y, double sigma2, const Eigen::MatrixXd &dK, const std::vector< std::vector< Eigen::Index > > &groups) const
Eigen::MatrixXd predictGradient(const Eigen::MatrixXd &Xstar, const Eigen::VectorXd &b) const
Eigen::MatrixXd posteriorCovariance(const Eigen::MatrixXd &cross, const Eigen::MatrixXd &prior, double sigma2) const
Joint posterior covariance from the same exact eigenmode sums.
Eigen::VectorXd solve(const Eigen::VectorXd &y) const
double trainingRowLatentErrorBound(Eigen::Index row, double sigma2) const
Eigen::MatrixXd predictGradientHessianVectorAffine(const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, const Eigen::MatrixXd &basis, const Eigen::MatrixXd &tangent_directions, const Eigen::MatrixXd &residual_directions, const Eigen::VectorXd &b) const
Eigen::VectorXd noisyRangeSelfQuadratic(const Eigen::MatrixXd &rhs, double sigma2) const
double leaveOneOutNegativeLogPredictiveDensity(const Eigen::VectorXd &y, double sigma2) const
bool supportsBorderedVarianceInterval() const noexcept
void liftFromDeflatedSubspace(Eigen::Index full_rows, Eigen::MatrixXd lifted_psi, const detail::RigidDeflationState &deflation, double extra_assembly_error=0.0)
double complementWeight(double sigma2) const noexcept
Eigen::MatrixXd reconstructKernel(bool truncated) const
const Eigen::MatrixXd & leftSingularVectors() const
bool factorizeNoisyKernelLapackRrr(const Eigen::MatrixXd &noisy_kernel, double sigma2)
Eigen::VectorXd solveNoisy(const Eigen::VectorXd &y, double sigma2) const
std::vector< BorderedVarianceInterval > noisyBorderedVarianceIntervals(const Eigen::MatrixXd &rhs, const Eigen::VectorXd &prior_diag, double sigma2) const
static std::size_t factorizationCount() noexcept
static void projectToAffineSpan(const Eigen::MatrixXd &centered_X, const Eigen::MatrixXd &basis, Eigen::MatrixXd &coords, Eigen::MatrixXd &residuals)
Eigen::VectorXd noisyInverseDiagonalEntries(const Eigen::VectorXi &rows, double sigma2) const
void recordDroppedSpectrum(const Eigen::VectorXd &S)
Eigen::VectorXd rangeVarianceFromDesignForTesting(const Eigen::MatrixXd &A_E, double sigma2) const
BorderedNoiseReport borderedNoiseReport(double sigma2) const
double conditionFlooredNoise(double sigma2) const
const Eigen::VectorXd & singularValues() const
void eigenTensorEpsDerivative(const Eigen::MatrixXd &X, int j, Eigen::MatrixXd &Phi, Eigen::MatrixXd &dPhi_eps) const
Eigen::VectorXd posteriorVarianceEnergy(const Eigen::MatrixXd &Xstar, double sigma2) const
static Eigen::Index standardChop(const Eigen::VectorXd &coeffs, double tol)
Eigen::MatrixXd noisyInverse(double sigma2) const
double leaveOneOutNegativeLogPredictiveDensityGrouped(const Eigen::VectorXd &y, double sigma2, const std::vector< std::vector< Eigen::Index > > &groups) const
Eigen::Index numObs() const
StableBasisPosteriorWeights noisyPosteriorWeights(const Eigen::VectorXd &y, double sigma2) const
void factorizeKernel(const Eigen::MatrixXd &kernel, double sv_rtol=1e-13, double sv_abs_tol=0.0, double sv_chop_tol=0.0)
Eigen::VectorXd posteriorVarianceEnergyAffine(const Eigen::MatrixXd &Ustar, const Eigen::MatrixXd &residuals, double sigma2) const
void factorizeKernelRandomized(const Eigen::MatrixXd &kernel, int sketch_size, int n_power_iter=2, double sv_rtol=1e-13, double sv_abs_tol=0.0, double sv_chop_tol=0.0)
double computeVarianceCalibrationFactor(const Eigen::VectorXd &y, double sigma2) const
void assumeExtendedCertificationForTesting(bool available)
static CusolverEighLib & instance()
void addProduct(double a, double b) noexcept
Definition ExactSum.h:70
void add(double x) noexcept
Definition ExactSum.h:54
double value() const noexcept
The exact sum rounded once to the nearest double, ties to even.
Definition ExactSum.h:190
void addTripleProduct(double a, double b, double c) noexcept
Definition ExactSum.h:86
Raised when a stable posterior variance is not finite, is materially negative, or its operands do not...
Definition ExactSchur.h:57
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
bool isfinite(DoubleDouble a)
Work frobeniusResidualUpperBound(const ComputedMatrix &computed, const AbsMatrix &abs_terms, long long entry_ops)
std::conditional_t< nativeLongDoubleIsExtended(), long double, DoubleDouble > WorkingReal
void outwardProduct(double a, double b, double &down, double &up)
double roundDownToDouble(Work value)
FormedFactor< Work > formScaledFactor(const DiagScale &diag_scale, const Vectors &evecs_asc, const Values &evals_asc, Eigen::Index rank, int entry_ops)
DoubleDouble sqrt(DoubleDouble a)
DoubleDouble abs(DoubleDouble a)
VarianceScaleEnclosure< Work > varianceScaleEnclosure(double y_scale, double calibration)
double scaledUpperBound(double value, const VarianceScaleEnclosure< Work > &scale)
constexpr bool certificationAvailable()
bool workingFinite(Work value)
double roundUpToDouble(Work value)
double scaledLowerBound(double value, const VarianceScaleEnclosure< Work > &scale)
constexpr int kDirectedScaleOps
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
void canonicalizeEigenpairs(Eigen::Ref< Eigen::VectorXd > evals, Eigen::Ref< Eigen::MatrixXd > evecs)
evals has one entry per leading column of evecs. Both are rewritten.
void requireStablePosteriorVariance(double &variance, double signal_variance, double relative_allowance)
Accept one stable posterior variance or throw.
Definition ExactSchur.h:131
Eigen::MatrixXd trainingProduct(ConstProductMatrix a, ConstProductMatrix b, bool transpose_a, bool transpose_b)
Allocating form with a native Eigen product when no device product runs.
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
Definition ExactSchur.h:40
bool distributed_thin_svd_tsqr(const EigenMatrix &A_local, int nobs, int N, EigenMatrix &U, Eigen::VectorXd &S, EigenMatrix &V, DistributedState &st=DistributedState::instance())
bool unconstrainedLibraryReductions() noexcept
DistributedFactorization distributedFactorization() noexcept
Process-wide selection; Reproducible unless configured otherwise.
bool tryTrainingProduct(ConstProductMatrix a, ConstProductMatrix b, ProductMatrix c, bool transpose_a, bool transpose_b, double alpha, double beta, bool partitioned)
Eigen::Index resolvedSingularRank(const Eigen::VectorXd &singular, double cutoff)
constexpr Eigen::Index kMinDistributedGemmOrder
bool teamDivideConquerEigen(const Eigen::MatrixXd &sym, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs)
Definition TeamEigen.cpp:11
bool trainingProductConfigured()
A device library or an in-process engine is configured.
bool covarianceDsyevr(const Eigen::MatrixXd &sym, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs)
constexpr Eigen::Index kMinDistributedSymmetricEigenOrder
double variance(const Weights &w, const Matrix &covariance)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
bool extendSymmetricSpectrum(const Eigen::Ref< const Eigen::MatrixXd > &grown, const Eigen::Ref< const Eigen::VectorXd > &diagonal, const Eigen::Ref< const Eigen::MatrixXd > &basis, Eigen::VectorXd &evals, Eigen::MatrixXd &evecs)
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...
STL namespace.
static long factorization_rows
static double eigensolve_seconds
static int factorization_count
static double factorization_seconds
Eigen::Matrix< Extended, Eigen::Dynamic, 1 > ExtendedVector
Eigen::Matrix< Extended, Eigen::Dynamic, Eigen::Dynamic > ExtendedMatrix
gpr::extended::WorkingReal Extended
gpr::extended::WorkingReal Extended
Eigen::Matrix< Extended, Eigen::Dynamic, Eigen::Dynamic > ExtendedMatrix
What floorCertifiedSchurDiagonal did to a diagonal.
Eigen::Matrix< Work, Eigen::Dynamic, Eigen::Dynamic > B