Loading...
Searching...
No Matches
Decompose.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// Cholesky decomposition entrypoints for the training covariance.
6// decomposeCovarianceMatrixScalapack assembles the training kernel
7// directly into the BLACS block-cyclic buffer consumed by pdpotrf.
8
9#include <cstdio>
10
16#ifdef GPR_LINALG_KOKKOS
18#endif
19#include "../PhaseTimers.h"
20#include "Helpers.h"
22#include "OptimizerState.h"
23#ifdef GPR_LINALG_SCALAPACK
24#include <mpi.h>
25
30#ifdef GPR_LINALG_SLATE
32#ifdef GPR_LINALG_SCALAPACK
34#endif
35#endif
36#endif
37
39#if defined(USE_OPENMP)
40#include <omp.h>
41#endif
42
43#include <Eigen/Cholesky>
44#include <Eigen/Core>
45#include <Eigen/SVD>
46#include <algorithm>
47#include <cmath>
48#include <cstddef>
49#include <cstdio>
50#include <cstring>
51#include <limits>
52#include <numeric>
53#include <utility>
54#include <vector>
55
56namespace gpr {
57
58namespace {
59using HessianAccumMatrix =
60 Eigen::Matrix<long double, Eigen::Dynamic, Eigen::Dynamic>;
61using HessianAccumRow = Eigen::Matrix<long double, 1, Eigen::Dynamic>;
62
63void fillConservativeVariance(Observation& image)
64{
65 const Eigen::Index n = image.R.rows();
66 const Eigen::Index dof = image.R.cols();
67 const double inf = std::numeric_limits<double>::infinity();
68 image.E.resize(1, n);
69 image.E.setConstant(inf);
70 image.G.resize(n, dof);
71 image.G.setConstant(inf);
72}
73
74// Projected self-quadratic diag(K*^T (K_r + eta2 I)^+ K*) of a joint query
75// block whose first n_energy columns are the energy channels. The energy
76// block is projected by a call of exactly the shape the energy-only gate
77// (tryGateEnergyVariance) issues, and the gradient block by a second call.
78// A GEMM's per-column rounding depends on the total column count (BLAS tail
79// kernels and panel widths differ), and the posterior variance
80// prior - projected cancels the prior down to O(1e-8) relative near the
81// data, which amplifies a one-ulp difference in projected to 1e-8 relative.
82// Equal operand shapes give both routes the same kernel sequence, so the
83// gate and the joint energy channel agree bitwise on every BLAS.
84Eigen::VectorXd rangeSelfQuadraticByChannelBlock(const StableBasisND& basis,
85 const Eigen::MatrixXd& Kstar,
86 Eigen::Index n_energy,
87 double total_sigma2)
88{
89 if (n_energy <= 0 || n_energy >= Kstar.cols())
90 return basis.noisyRangeSelfQuadratic(Kstar, total_sigma2);
91 const Eigen::MatrixXd energy_block = Kstar.leftCols(n_energy);
92 const Eigen::MatrixXd gradient_block =
93 Kstar.rightCols(Kstar.cols() - n_energy);
94 const Eigen::VectorXd energy =
95 basis.noisyRangeSelfQuadratic(energy_block, total_sigma2);
96 const Eigen::VectorXd gradient =
97 basis.noisyRangeSelfQuadratic(gradient_block, total_sigma2);
98 if (energy.size() != n_energy || gradient.size() != Kstar.cols() - n_energy)
99 return Eigen::VectorXd();
100 Eigen::VectorXd projected(Kstar.cols());
101 projected.head(n_energy) = energy;
102 projected.tail(gradient.size()) = gradient;
103 return projected;
104}
105
106// Same range quadratic as rangeSelfQuadraticByChannelBlock, reduced with
107// ExactSum by StableBasisND::stableRangePosteriorDiagonal in the same
108// channel blocks, so the joint energy channel and the energy-only gate
109// contract operands of one shape. Every failure throws
110// linalg::StableVarianceError.
111void stableRangePosteriorDiagonal(const StableBasisND& basis,
112 const Eigen::MatrixXd& Kstar,
113 const Eigen::VectorXd& prior,
114 const Eigen::VectorXd& signal,
115 Eigen::Index n_energy, double total_sigma2,
116 Eigen::VectorXd& variance)
117{
118 if (prior.size() != Kstar.cols() || signal.size() != prior.size())
120 "stable range posterior variance: prior, signal and query "
121 "columns disagree");
122 if (n_energy <= 0 || n_energy >= Kstar.cols()) {
123 variance = basis.stableRangePosteriorDiagonal(Kstar, prior, signal,
124 total_sigma2,
125 /*check_variance=*/false);
126 return;
127 }
128 const Eigen::Index n_gradient = Kstar.cols() - n_energy;
129 variance.resize(Kstar.cols());
130 variance.head(n_energy) = basis.stableRangePosteriorDiagonal(
131 Kstar.leftCols(n_energy), prior.head(n_energy), signal.head(n_energy),
132 total_sigma2, /*check_variance=*/false);
133 variance.tail(n_gradient) = basis.stableRangePosteriorDiagonal(
134 Kstar.rightCols(n_gradient), prior.tail(n_gradient),
135 signal.tail(n_gradient), total_sigma2, /*check_variance=*/false);
136}
137
138template <typename Emit>
139bool assembleHssvdDualKernelEntries(const Eigen::MatrixXd& qtil,
140 const std::vector<Eigen::MatrixXd>& jtil,
141 const double magn,
142 const double const_sigma2, Emit&& emit)
143{
144 const Eigen::Index ntrain = qtil.rows();
145 const Eigen::Index dfeat = qtil.cols();
146 const Eigen::Index dof = jtil.empty() ? 0 : jtil.front().cols();
147 if (ntrain <= 0 || dfeat <= 0 || dof <= 0 ||
148 static_cast<Eigen::Index>(jtil.size()) != ntrain)
149 return false;
150 for (const auto& J: jtil)
151 if (J.rows() != dfeat || J.cols() != dof) return false;
152
153 for (Eigen::Index i = 0; i < ntrain; ++i) {
154 const Eigen::MatrixXd& Ji = jtil[static_cast<std::size_t>(i)];
155 for (Eigen::Index j = i; j < ntrain; ++j) {
156 const Eigen::MatrixXd& Jj = jtil[static_cast<std::size_t>(j)];
157 const Eigen::RowVectorXd r = qtil.row(i) - qtil.row(j);
158 const double k = magn * std::exp(-r.squaredNorm());
159 const double kee = const_sigma2 + k;
160 emit(i, j, kee);
161 emit(j, i, kee);
162
163 Eigen::VectorXd ri_dot(dof);
164 Eigen::VectorXd rj_dot(dof);
165 for (Eigen::Index c = 0; c < dof; ++c) {
166 ri_dot(c) = r.dot(Ji.col(c));
167 rj_dot(c) = r.dot(Jj.col(c));
168
169 const Eigen::Index row_ic = ntrain + c * ntrain + i;
170 const Eigen::Index row_jc = ntrain + c * ntrain + j;
171 const double force_i_energy_j = -2.0 * k * ri_dot(c);
172 const double energy_i_force_j = 2.0 * k * rj_dot(c);
173 emit(row_ic, j, force_i_energy_j);
174 emit(j, row_ic, force_i_energy_j);
175 emit(i, row_jc, energy_i_force_j);
176 emit(row_jc, i, energy_i_force_j);
177 }
178
179 for (Eigen::Index c = 0; c < dof; ++c) {
180 const Eigen::Index row_ic = ntrain + c * ntrain + i;
181 for (Eigen::Index d = 0; d < dof; ++d) {
182 const Eigen::Index row_jd = ntrain + d * ntrain + j;
183 const double force_force =
184 2.0 * k * Ji.col(c).dot(Jj.col(d)) -
185 4.0 * k * ri_dot(c) * rj_dot(d);
186 emit(row_ic, row_jd, force_force);
187 emit(row_jd, row_ic, force_force);
188 }
189 }
190 }
191 }
192 return true;
193}
194} // namespace
195
197 Eigen::Index expected_rows) const noexcept
198{
199 const Eigen::Index n = activeFactorOrder(expected_rows);
200 if (n <= 0) return false;
201#ifdef GPR_LINALG_KOKKOS
203 resident_training_factor_->order() == n)
204 return true;
205#endif
206 if (L.rows() == n && L.cols() == n) return true;
207#ifdef GPR_LINALG_SCALAPACK
208 if (training_cholesky_is_distributed_) {
209 const auto& st = backend().distributed();
210 return st.cached_L_owned_by(this) &&
211 st.cached_n() == static_cast<int>(n);
212 }
213#endif
214 return false;
215}
216
218{
219#ifdef GPR_LINALG_KOKKOS
221 device_posterior_.reset();
222#endif
223}
224
226{
227#ifdef GPR_LINALG_KOKKOS
228 // Host execution memory already holds the factor in L. Copying it into
229 // a KokkosFactor makes every later solve, whiten and log determinant
230 // skip BackendContext's in-place Eigen kernels. One check here covers
231 // every caller. Device memory keeps the copy. Either way a previous
232 // device posterior is released, so a query never sees a posterior
233 // whose resident factor is null.
236 return;
237 }
238 device_posterior_.reset();
239 resident_training_factor_ = std::make_shared<linalg::KokkosFactor>(L);
240#endif
241}
242
244{
245 L.resize(0, 0);
246 rigid_deflation_.reset();
247#ifdef GPR_LINALG_KOKKOS
249 device_posterior_.reset();
250#endif
251}
252
254{
257 C.resize(0, 0);
260 a.resize(0);
261 b.resize(0);
262 serial_factor_signature_.valid = false;
263#ifdef GPR_LINALG_SCALAPACK
264 auto& distributed_state = backend().distributed();
265 if (distributed_state.cached_L_owned_by(this)) {
266 distributed_state.invalidate_L();
267 }
268 distributed_state.invalidate_inv();
269 training_cholesky_is_distributed_ = false;
270 distributed_factor_signature_.valid = false;
271 parked_training_cholesky_.clear();
272#endif
273}
274
275Eigen::VectorXd
277 const Eigen::VectorXd& rhs) const
278{
279 if (!hasTrainingCholeskyFactor(rhs.size()))
280 throw std::logic_error("training covariance factor is unavailable");
281 if (rigid_deflation_.isActiveForFullOrder(rhs.size())) {
282 const Eigen::VectorXd rhs_r = rigid_deflation_.projectVector(rhs);
283 const Eigen::VectorXd solved_r = trainingSolver().solve(rhs_r);
284 return rigid_deflation_.liftSolvedVector(rhs, solved_r);
285 }
286 return trainingSolver().solve(rhs);
287}
288
290{
291#ifdef GPR_LINALG_SCALAPACK
292 if (!training_cholesky_is_distributed_) return false;
293 auto& state = backend().distributed();
294 auto snapshot = state.take_cached_L(this);
295 if (!snapshot.valid()) return false;
296 parked_training_cholesky_ = std::move(snapshot);
297 return true;
298#else
299 return false;
300#endif
301}
302
303bool GaussianProcessRegression::hasMaterializedHssvdBackground() const noexcept
304{
305 return !atomic_environment_model_ && use_hssvd_backend_ &&
306 hssvd_basis_valid_ && hssvd_basis_.rank() > 0 &&
307 hssvd_basis_.numObs() == energy_and_gradient.size() &&
308 hssvd_p_.size() == hssvd_basis_.rank() &&
309 (!hssvd_dual_kernel_ ||
310 hssvd_dual_predict_weights_.size() == hssvd_basis_.numObs());
311}
312
314{
315 if (atomic_environment_model_) return atomicEnvironmentPosteriorBuilt();
316#ifdef GPR_LINALG_KOKKOS
318#endif
319 // The spectral background owns its factors even when an active correction
320 // contributes to prediction. Background-only curvature shortcuts still
321 // require hasReusableHssvdPosterior().
322 if (hasMaterializedHssvdBackground() || rff_replaces_exact_) return true;
323 if (!is_decomposed_succesfully || a.size() != R_matrix.rows()) {
324 return false;
325 }
327 return true;
328 }
329#ifdef GPR_LINALG_SCALAPACK
330 if (!training_cholesky_is_distributed_ ||
331 parked_training_cholesky_.order != R_matrix.rows()) {
332 return false;
333 }
334 auto snapshot = std::move(parked_training_cholesky_);
335 parked_training_cholesky_.clear();
336 return backend().distributed().restore_cached_L(std::move(snapshot), this);
337#else
338 return false;
339#endif
340}
341
342void GaussianProcessRegression::ensurePosteriorFactorForPrediction()
343{
344 if (atomic_environment_model_) {
346 throw std::runtime_error(
347 "atomic environment posterior is not fitted");
348 return;
349 }
350 if (!is_decomposed_succesfully || canUseHssvdVariance() ||
352 return;
354 throw std::runtime_error("cannot materialize the fitted posterior");
355 refreshPosteriorWeights(energy_and_gradient);
356}
357
359{
360#ifdef GPR_LINALG_SCALAPACK
361 if (!training_cholesky_is_distributed_) return;
362 auto& state = backend().distributed();
363 if (state.has_cached_L() &&
364 state.cached_n() == static_cast<int>(R_matrix.rows()) &&
365 state.cached_L_is_unowned()) {
366 state.claim_cached_L(this);
367 }
368#endif
369}
370
371void GaussianProcessRegression::clearHssvdBasisState()
372{
373 hssvd_basis_valid_ = false;
374 hssvd_dual_kernel_ = false;
375 descriptor_predictor_ready_ = false;
376 hssvd_variance_calibration_factor_ = 1.0;
377 hssvd_mean_feat_.resize(0);
378 hssvd_l_feat_.resize(0);
379 hssvd_feature_basis_.resize(0, 0);
380 hssvd_train_qtil_.resize(0, 0);
381 hssvd_train_jtil_.clear();
382 hssvd_dual_predict_weights_.resize(0);
383 hssvd_dual_force_jacobian_weights_.resize(0, 0);
384 hssvd_dual_alpha_k_prepared_ = SexpatCF::PreparedAlphaK{};
385 hssvd_p_.resize(0);
386 hssvd_objective_basis_valid_ = false;
387 clearHssvdPendingCovariance();
388 hssvd_objective_alpha_.resize(0);
389 hssvd_objective_trace_basis_.resize(0, 0);
390 hssvd_objective_trace_weighted_basis_.resize(0, 0);
391 hssvd_objective_trace_inv_noise_ = 0.0;
392 hssvd_objective_trace_direct_inverse_ = false;
393 hssvd_trace_basis_ = nullptr;
394 hssvd_trace_weighted_basis_ = nullptr;
395 hssvd_trace_inv_noise_ = 0.0;
396 hssvd_trace_direct_inverse_ = false;
397}
398
425bool GaussianProcessRegression::buildDualDescriptors(
426 const EigenMatrix& x, Eigen::VectorXd& l_feat,
427 Eigen::RowVectorXd& mean_feat, Eigen::MatrixXd& Q,
428 std::vector<Eigen::MatrixXd>& jac) const
429{
430 if (!sexpat_cov_func || sexpat_cov_func->usesManifoldChart() ||
431 sexpat_cov_func->usesGeodesicHeatKernel())
432 return false;
433 const Eigen::Index D_cart = x.cols() - 1;
434 if (D_cart <= 0) return false;
435 const Eigen::Index repeat = D_cart + 1;
436 if (x.rows() % repeat != 0) return false;
437 const Eigen::Index N_im = x.rows() / repeat;
438 if (N_im <= 0) return false;
439 const std::vector<int> feat_pt =
441 sexpat_cov_func->getConfInfo(), sexpat_cov_func->farFieldRadius());
442 const auto& ls = sexpat_cov_func->getLengthScaleRef(); // 1 x n_pt
443 const Eigen::Index dfeat = static_cast<Eigen::Index>(feat_pt.size());
444 if (dfeat <= 0) return false;
445 l_feat.resize(dfeat);
446 for (Eigen::Index k = 0; k < dfeat; ++k) {
447 const int pt = feat_pt[static_cast<std::size_t>(k)];
448 if (pt < 0 || pt >= ls.size()) return false;
449 const double l = *(ls.data() + pt);
450 if (!(l > 0.0)) return false;
451 l_feat(k) = l;
452 }
453
454 // Descriptors q and Jacobian dq/dx per config. Block 0 (rows 0..N_im-1)
455 // holds the positions; the position is the first D_cart columns (the last
456 // column is the derivative index, dropped via .head(D_cart)).
457 Q.resize(N_im, dfeat);
458 jac.assign(static_cast<std::size_t>(N_im), Eigen::MatrixXd());
459 for (Eigen::Index i = 0; i < N_im; ++i) {
460 Coord xr = x.block(i, 0, 1, D_cart); // (1 x D_cart) position
461 Eigen::VectorXd q;
462 EigenMatrix J;
464 xr, sexpat_cov_func->getConfInfo(), q, J,
465 sexpat_cov_func->farFieldRadius());
466 if (q.size() != dfeat || J.rows() != dfeat || J.cols() != D_cart)
467 return false;
468 Q.row(i) = q.transpose();
469 jac[static_cast<std::size_t>(i)] = J;
470 }
471
472 // Input standardization for the Mercer expansion. The production SexpatCF
473 // kernel (SexpatCF.cpp: dist_sq = sum_p two_inv_l2_p (dq_p)^2 with
474 // two_inv_l2 = 2/l_p^2, then k = magn exp(-0.5 dist_sq)) is
475 // K = magn * prod_k exp(-(1/l_k^2) (q_k - q'_k)^2)
476 // = magn * prod_k exp(-eps_k^2 (q_k - q'_k)^2), eps_k = 1/l_k.
477 // (NOT 1/(sqrt(2) l_k): the 2/l^2 convention cancels the 0.5, so the shape
478 // is 1/l, verified against the assembled C in StableBasisNDTest.) That
479 // value is identical on standardized q~_k = (q_k - mean_k)/l_k with the
480 // UNIT shape eps~ = 1 (the q-q' difference is mean-shift invariant and the
481 // l_k scaling cancels eps_k). The Fasshauer-McCourt Hermite-Mercer basis is
482 // centred at the origin with an O(1) Gaussian weight, so feeding raw offset
483 // inverse-distance descriptors with a large eps under-resolves the kernel;
484 // standardizing returns the data to the convergent regime WITHOUT changing
485 // the represented kernel. The gradient feature uses the chain rule
486 // dq~/dx = (1/l_k) dq/dx, so the Jacobian rows scale by 1/l_k.
487 mean_feat = Q.colwise().mean();
488 for (Eigen::Index i = 0; i < N_im; ++i) {
489 Q.row(i) = (Q.row(i) - mean_feat).array() / l_feat.transpose().array();
490 Eigen::MatrixXd& J = jac[static_cast<std::size_t>(i)];
491 for (Eigen::Index k = 0; k < dfeat; ++k)
492 J.row(k) /= l_feat(k);
493 }
494 return true;
495}
496bool GaussianProcessRegression::factorizeStableBasisFromTraining(
497 const EigenMatrix& x, const Eigen::VectorXd& x_ind)
498{
499 hssvd_dual_predict_weights_.resize(0);
500 hssvd_p_.resize(0);
501 auto fail = [&]() {
502 clearHssvdBasisState();
503 return false;
504 };
505 if (sexpat_cov_func == nullptr) return fail();
506 // x has D_cart+1 columns (position + derivative-index column); the last
507 // column is the index, so the Cartesian DOF per config is one fewer.
508 const Eigen::Index D_cart = x.cols() - 1;
509 if (D_cart <= 0) return fail();
510 const detail::ObservationChannelLayout channels(x_ind);
511 const bool descriptor_layout = channels.completeCartesian(D_cart) &&
512 channels.repeatsCoordinates(x, D_cart);
513 const Eigen::Index N_im = channels.rowsPerChannel();
514 if (!channels.valid() || x.rows() <= 0 || x_ind.size() != x.rows())
515 return fail();
516
517 // Per-feature length scale l_k = the pairtype length scale (= per-pairtype
518 // descriptor std; setHyperparameters sets the SexpatCF length scale to the
519 // training descriptor std -- the standard input normalization).
520 Eigen::VectorXd l_feat;
521 Eigen::RowVectorXd mean_feat;
522 Eigen::MatrixXd Q;
523 std::vector<Eigen::MatrixXd> jac;
524 if (descriptor_layout) {
525 ScopedPhaseTimer descriptor_timer(PhaseTimers::descriptor_seconds);
526 if (!buildDualDescriptors(x, l_feat, mean_feat, Q, jac)) return fail();
527 }
528 const Eigen::Index dfeat = l_feat.size();
529 if (report_level >= 2) {
530 log_man << "HS-SVD stable basis: descriptors built configs=" << N_im
531 << " cart_dim=" << D_cart << " features=" << dfeat << ".\n";
532 }
533 if (report_level >= 2) {
534 log_man << "HS-SVD stable basis: descriptors standardized.\n";
535 }
536
537 const double magn = sexpat_cov_func->getMagnSigma2();
538 constexpr double hssvd_kernel_target_rel_tol = 1.0e-6;
539 const double total_sigma2 = totalPosteriorNoiseVariance();
540 const double posterior_shrinkage_tol = hssvd_kernel_target_rel_tol;
541 const double hssvd_sv_abs_tol =
542 (total_sigma2 > 0.0 && posterior_shrinkage_tol > 0.0 &&
543 posterior_shrinkage_tol < 1.0)
544 ? std::sqrt(total_sigma2 * posterior_shrinkage_tol /
545 (1.0 - posterior_shrinkage_tol))
546 : 0.0;
547
549 detail::validateRigidNullDeflationConfiguration(true,
550 principled_nugget_);
551 }
552 const bool can_attempt_hssvd_deflation =
554 !principled_nugget_ && !sexpat_cov_func->usesManifoldChart() &&
555 !sexpat_cov_func->usesGeodesicHeatKernel();
556 EigenMatrix kernel;
557#ifdef GPR_LINALG_SCALAPACK
558 bool assembled_distributed = false;
559 auto& st = backend().distributed();
560 st.initialize(static_cast<int>(channels.channelCount()));
561 if (st.nprocs() > 1) {
562 // The HS-SVD rank cut is trajectory-sensitive, so production uses the
563 // same covariance contract as the dense path while distributing the
564 // block work through evaluateTrainingCovarianceMatrix.
566 x, x_ind, kernel,
567 /*serial_per_rank=*/false,
568 /*include_constant=*/true,
569 /*include_noise=*/!can_attempt_hssvd_deflation);
570 assembled_distributed = kernel.rows() == kernel.cols() &&
571 kernel.rows() == x.rows() && kernel.allFinite();
572 if (assembled_distributed)
573 ++distributed_hssvd_dual_kernel_assemblies_for_testing_;
574 }
575 if (!assembled_distributed) {
577 x, x_ind, kernel,
578 /*serial_per_rank=*/false,
579 /*include_constant=*/true,
580 /*include_noise=*/!can_attempt_hssvd_deflation);
581 }
582#else
584 x, x_ind, kernel,
585 /*serial_per_rank=*/false,
586 /*include_constant=*/true,
587 /*include_noise=*/!can_attempt_hssvd_deflation);
588#endif
589 if (kernel.rows() <= 0 || kernel.rows() != kernel.cols() ||
590 !kernel.allFinite())
591 return fail();
592 clearHssvdBasisState();
593 rigid_deflation_.reset();
594 Eigen::Index full_rows_for_lift = 0;
595 EigenMatrix kernel_deflated;
596 const EigenMatrix* kernel_to_factor = &kernel;
597 bool rigid_deflated_hssvd = false;
598 if (!can_attempt_hssvd_deflation) {
599 if (lik_gaussian != nullptr && kernel.rows() == kernel.cols())
600 kernel.diagonal().array() -= lik_gaussian->getSigma2();
601 const Eigen::VectorXd noise_diag =
602 lik_gaussian != nullptr ? lik_gaussian->evaluateTrainingVariance(x)
603 : Eigen::VectorXd::Zero(x.rows());
604 Eigen::VectorXd unused_constant;
606 x, x_ind, noise_diag, jitter_sigma2, kernel, Eigen::VectorXd(),
607 unused_constant, /*factor_order=*/false);
608 } else {
609 const Eigen::VectorXd noise_diag =
610 lik_gaussian != nullptr ? lik_gaussian->evaluateTrainingVariance(x)
611 : Eigen::VectorXd::Zero(x.rows());
612 const double base_sigma2 =
613 lik_gaussian != nullptr ? lik_gaussian->getSigma2() : 0.0;
614 const Eigen::VectorXd extra_var = noise_diag.array() - base_sigma2;
615 const bool has_extra_noise = extra_var.size() == x.rows() &&
616 extra_var.cwiseAbs().maxCoeff() > 0.0;
617 if (has_extra_noise) {
618 kernel.diagonal() += extra_var;
619 } else {
620 Eigen::VectorXd unused_constant;
621 kernel_deflated = kernel;
623 x, x_ind, noise_diag, jitter_sigma2, kernel_deflated,
624 Eigen::VectorXd(), unused_constant,
625 /*factor_order=*/false)) {
626 full_rows_for_lift = kernel.rows();
627 kernel_to_factor = &kernel_deflated;
628 rigid_deflated_hssvd = true;
629 }
630 }
631 }
632 // Relative singular-value cutoff for the stable-basis truncation. The
633 // legacy 1e-13 sat at the float64 noise floor: the marginal retained mode
634 // was within BLAS-blocking precision (~1e-13) of the keep/drop threshold,
635 // so the number of retained modes -- and hence the basis -- changed with
636 // the BLAS thread count (the kernel gemm rounds differently when blocked),
637 // tipping the saddle search into a different basin (system 16: barrier 0.99
638 // at BLAS<=2 vs 0.166 at BLAS=4). sqrt(eps) places the cutoff far above
639 // that noise floor so the rank decision is reduction-order invariant, and
640 // it bounds the retained basis condition number at 1/sqrt(eps) = kappa_max
641 // (the same principled machine-epsilon bound as the Marchildon-Zingg
642 // nugget); modes below it are genuine sub-precision noise that 1/S would
643 // otherwise amplify.
644 const double hssvd_sv_rtol =
645 std::sqrt(std::numeric_limits<double>::epsilon());
646 hssvd_basis_.setChopNoiseVariance(total_sigma2);
647 const char* hssvd_dual_driver = "eigen";
648 bool hssvd_dual_factorized = false;
649 if (hssvd_dual_randomized_sketch_ > 0) {
650 ++hssvd_full_factorizations_for_testing_;
651 hssvd_basis_.factorizeKernelRandomized(
652 *kernel_to_factor, hssvd_dual_randomized_sketch_,
653 /*n_power_iter=*/2,
654 /*sv_rtol=*/hssvd_sv_rtol, hssvd_sv_abs_tol, hssvd_dual_chop_tol_);
655 hssvd_dual_driver = "randomized";
656 hssvd_dual_factorized = true;
657 }
658#ifdef GPR_LINALG_SCALAPACK
659 else if (backend().distributed().nprocs() > 1 &&
660 hssvd_basis_.factorizeKernelDistributed(
661 *kernel_to_factor, /*sv_rtol=*/hssvd_sv_rtol, hssvd_sv_abs_tol,
662 hssvd_dual_chop_tol_)) {
663 ++hssvd_full_factorizations_for_testing_;
664 ++distributed_hssvd_dual_kernel_factorizations_for_testing_;
665 hssvd_dual_driver = hssvd_basis_.lastKernelFactorizeDriver();
666 hssvd_dual_factorized = true;
667 }
668#endif
669 else if (hssvd_dual_lapack_rrr_ &&
670 hssvd_basis_.factorizeKernelLapackRrr(
671 *kernel_to_factor, /*sv_rtol=*/hssvd_sv_rtol, hssvd_sv_abs_tol,
672 hssvd_dual_chop_tol_)) {
673 ++hssvd_full_factorizations_for_testing_;
674 hssvd_dual_driver = hssvd_basis_.usedLapackRrrValueRange()
675 ? "lapack_rrr_range"
676 : "lapack_rrr";
677 hssvd_dual_factorized = true;
678 } else {
679 ++hssvd_full_factorizations_for_testing_;
680 hssvd_basis_.factorizeKernel(*kernel_to_factor,
681 /*sv_rtol=*/hssvd_sv_rtol,
682 hssvd_sv_abs_tol, hssvd_dual_chop_tol_);
683 hssvd_dual_factorized = true;
684 }
685 if (rigid_deflated_hssvd) {
686 if (hssvd_dual_factorized && hssvd_basis_.rank() > 0) {
687 Eigen::MatrixXd lifted_psi = rigid_deflation_.liftRowsZeroRigid(
688 hssvd_basis_.leftSingularVectors());
689 hssvd_basis_.liftFromDeflatedSubspace(
690 full_rows_for_lift, std::move(lifted_psi), rigid_deflation_,
691 2.0 * rigid_deflation_diag_.kernel_null_norm);
692 }
693 // The HS-SVD basis is now in full N-row observation space; clear the
694 // active dense-factor projector while retaining rigid_deflation_diag_.
695 rigid_deflation_.reset();
696 }
697 if (hssvd_dual_factorized && hssvd_basis_.rank() > 0) {
698 hssvd_mean_feat_ = mean_feat;
699 hssvd_l_feat_ = l_feat;
700 hssvd_train_qtil_ = Q;
701 hssvd_train_jtil_ = jac;
702 hssvd_dual_kernel_ = true;
703 hssvd_basis_valid_ = true;
704 if (report_level >= 2) {
705 // factorizeKernel clears the Mercer multi-index, so numBasis()
706 // is 0 here and would be read as the retained rank. This path
707 // has no Mercer basis; rank is the eigenbasis size.
708 log_man << "HS-SVD stable basis: dual kernel factorize done rank="
709 << hssvd_basis_.rank() << " basis=none"
710 << " cond=" << hssvd_basis_.conditionNumber()
711 << " sv_abs_tol=" << hssvd_sv_abs_tol
712 << " sv_chop_tol=" << hssvd_dual_chop_tol_
713 << " dual_sketch=" << hssvd_dual_randomized_sketch_
714 << " dual_driver=" << hssvd_dual_driver << ".\n";
715 }
716 return true;
717 }
718
719 if (!descriptor_layout) return fail();
720 const Eigen::MatrixXd feature_basis = StableBasisND::affineSpanBasis(Q);
721 if (feature_basis.cols() <= 0) {
722 if (report_level >= 2) {
723 log_man << "HS-SVD stable basis: skipped because the standardized "
724 "descriptor affine span has zero numerical rank.\n";
725 }
726 return fail();
727 }
728 Eigen::MatrixXd U;
729 Eigen::MatrixXd train_residuals;
730 StableBasisND::projectToAffineSpan(Q, feature_basis, U, train_residuals);
731 std::vector<Eigen::MatrixXd> jac_tangent(static_cast<std::size_t>(N_im));
732 std::vector<Eigen::MatrixXd> jac_normal(static_cast<std::size_t>(N_im));
733 for (Eigen::Index i = 0; i < N_im; ++i) {
734 const Eigen::MatrixXd& J = jac[static_cast<std::size_t>(i)];
735 jac_tangent[static_cast<std::size_t>(i)] =
736 feature_basis.transpose() * J;
737 jac_normal[static_cast<std::size_t>(i)] =
738 J - feature_basis * jac_tangent[static_cast<std::size_t>(i)];
739 }
740 const Eigen::VectorXd eps =
741 Eigen::VectorXd::Constant(feature_basis.cols(), 1.0);
742 if (report_level >= 2) {
743 log_man << "HS-SVD stable basis: affine span rank="
744 << feature_basis.cols()
745 << " residual_norm=" << train_residuals.norm() << ".\n";
746 }
747
748 // alpha (Gaussian-weight scale) and max_degree are O(1) Mercer-expansion
749 // knobs (validated in StableBasisNDTest); graded truncation above the obs
750 // count. overall_scale = magnSigma2. component_major matches the GP's
751 // [E ; G column-major] target / a_unpermuted layout.
752 // Adaptive Chebyshev chopping (doi:10.1145/2998442) selects the Mercer
753 // total degree from E_D = prod_k sqrt(lambda_0k) *
754 // (max_k sqrt(r_k))^D. The tensor set has C(r + D, D) graded modes; with
755 // normal-derivative blocks the design has nobs * (dfeat + 1) rows, so
756 // unrepresentable expansions are rejected before multi-index enumeration.
757 constexpr int hssvd_degree_cap = 80;
758 if (feature_basis.cols() > std::numeric_limits<int>::max()) {
759 if (report_level >= 2) {
760 log_man << "HS-SVD stable basis: skipped affine_rank="
761 << feature_basis.cols()
762 << " because the span rank exceeds the matrix "
763 "index limit.\n";
764 }
765 return fail();
766 }
767 const int affine_rank_int = static_cast<int>(feature_basis.cols());
768 const int requested_hssvd_max_degree = StableBasisND::autoMaxDegree(
769 eps, /*alpha=*/1.0, affine_rank_int, hssvd_kernel_target_rel_tol,
770 hssvd_degree_cap);
771 const Eigen::Index nobs_hssvd = x.rows();
772 const Eigen::Index matrix_entry_limit =
773 nobs_hssvd > 0 ? std::numeric_limits<int>::max() / nobs_hssvd
774 : std::numeric_limits<int>::max();
775 const Eigen::Index augmented_blocks = dfeat + 1;
776 const Eigen::Index mode_entry_limit =
777 augmented_blocks > 0 ? matrix_entry_limit / augmented_blocks : 0;
778 const Eigen::Index mode_limit =
779 std::max<Eigen::Index>(1, std::min(mode_entry_limit, nobs_hssvd));
780 const int hssvd_max_degree = StableBasisND::capMaxDegreeByModeCount(
781 affine_rank_int, requested_hssvd_max_degree, mode_limit);
782 if (hssvd_max_degree <= 0) {
783 if (report_level >= 2) {
784 log_man << "HS-SVD stable basis: skipped features=" << dfeat
785 << " affine_rank=" << feature_basis.cols()
786 << " because the augmented affine design has no "
787 "representable Mercer modes under the column budget.\n";
788 }
789 return fail();
790 }
792 affine_rank_int, hssvd_max_degree, mode_entry_limit)) {
793 if (report_level >= 2) {
794 log_man << "HS-SVD stable basis: skipped features=" << dfeat
795 << " affine_rank=" << feature_basis.cols()
796 << " max_degree=" << hssvd_max_degree
797 << " because the augmented affine design exceeds the "
798 "matrix index limit.\n";
799 }
800 return fail();
801 }
802
803 const int hssvd_initial_sketch =
804 (nobs_hssvd > 1)
805 ? static_cast<int>(std::min<Eigen::Index>(
806 (nobs_hssvd + 1) / 2, std::numeric_limits<int>::max()))
807 : 0;
808
809 if (report_level >= 2) {
810 log_man << "HS-SVD stable basis: factorize start magnSigma2=" << magn
811 << " max_degree=" << hssvd_max_degree
812 << " requested_degree=" << requested_hssvd_max_degree
813 << " mode_limit=" << mode_limit
814 << " sv_abs_tol=" << hssvd_sv_abs_tol
815 << " sketch=" << hssvd_initial_sketch << ".\n";
816 }
817 ++hssvd_full_factorizations_for_testing_;
818 hssvd_basis_.factorizeGPCartesianAffine(
819 U, eps, /*alpha=*/1.0, magn, hssvd_max_degree, jac_tangent, jac_normal,
820 /*component_major=*/true, /*sv_rtol=*/hssvd_sv_rtol,
821 /*sketch_size=*/hssvd_initial_sketch, /*n_power_iter=*/2,
822 /*mode_prune_rtol=*/1e-13, hssvd_sv_abs_tol);
823 if (report_level >= 2) {
824 log_man << "HS-SVD stable basis: factorize done rank="
825 << hssvd_basis_.rank() << " basis=" << hssvd_basis_.numBasis()
826 << ".\n";
827 }
828 // Store the descriptor standardization for the cancellation-free predict.
829 hssvd_mean_feat_ = mean_feat;
830 hssvd_l_feat_ = l_feat;
831 hssvd_feature_basis_ = feature_basis;
832 hssvd_basis_valid_ = true;
833 return true;
834}
835
836bool GaussianProcessRegression::assembleHssvdDualTrainingKernel(
837 const Eigen::MatrixXd& qtil, const std::vector<Eigen::MatrixXd>& jtil,
838 EigenMatrix& kernel) const
839{
840 kernel.resize(0, 0);
841 if (sexpat_cov_func == nullptr || qtil.rows() <= 0 || qtil.cols() <= 0 ||
842 static_cast<Eigen::Index>(jtil.size()) != qtil.rows())
843 return false;
844
845 const Eigen::Index ntrain = qtil.rows();
846 const Eigen::Index dfeat = qtil.cols();
847 const Eigen::Index dof = jtil.empty() ? 0 : jtil.front().cols();
848 if (dof <= 0) return false;
849 for (const auto& J: jtil)
850 if (J.rows() != dfeat || J.cols() != dof) return false;
851
852 const Eigen::Index repeat = dof + 1;
853 const Eigen::Index nobs = ntrain * repeat;
854 kernel = EigenMatrix::Zero(nobs, nobs);
855
856 auto emit = [&](const Eigen::Index row, const Eigen::Index col,
857 const double value) { kernel(row, col) = value; };
858 const bool ok = assembleHssvdDualKernelEntries(
859 qtil, jtil, sexpat_cov_func->getMagnSigma2(),
860 const_cov_fun ? const_cov_fun->getConstSigma2() : 0.0, emit);
861 return ok && kernel.allFinite();
862}
863
864#ifdef GPR_LINALG_SCALAPACK
865bool GaussianProcessRegression::assembleHssvdDualTrainingKernelDistributed(
866 const EigenMatrix& x, const Eigen::VectorXd& x_ind,
867 std::vector<double>& kernel_dist, int desc[9], int& nobs)
868{
869 kernel_dist.clear();
870 std::fill(desc, desc + 9, 0);
871 nobs = 0;
872 if (sexpat_cov_func == nullptr || x.rows() <= 0 || x.cols() <= 0 ||
873 x_ind.size() != x.rows())
874 return false;
875 if (x.rows() > std::numeric_limits<int>::max()) return false;
876 nobs = static_cast<int>(x.rows());
877 if (nobs <= 0) return false;
878
879 auto& st = backend().distributed();
880 const int tile_size =
881 static_cast<int>(detail::storedObservationChannelCount(x_ind));
882 st.initialize(tile_size);
884 if (!hasTrainingPermutation()) return false;
885 if (tile_size <= 0 || nobs % tile_size != 0) return false;
886
887 const EigenMatrix x_tiled = permuteTrainingRows(x);
888 const Eigen::VectorXd x_ind_tiled = permuteTrainingVector(x_ind);
889 const Eigen::VectorXd tile_ind = x_ind_tiled.head(tile_size);
890 Eigen::VectorXd tile_uDdim;
891 extractUniqueIndices(tile_ind, tile_uDdim);
892
893 st.make_desc(nobs, nobs, desc);
894 const int leading = desc[8];
895 const int local_cols = st.local_cols(nobs);
896 kernel_dist.assign(static_cast<std::size_t>(leading) *
897 static_cast<std::size_t>(local_cols),
898 0.0);
899
900 auto owns_any_entry = [&](const int row_start, const Index_t row_count,
901 const int col_start, const Index_t col_count) {
902 for (Index_t local_j = 0; local_j < col_count; ++local_j) {
903 const int global_j = col_start + static_cast<int>(local_j);
904 for (Index_t local_i = 0; local_i < row_count; ++local_i) {
905 const int global_i = row_start + static_cast<int>(local_i);
906 if (st.owns_global_entry(global_i, global_j)) return true;
907 }
908 }
909 return false;
910 };
911
912 const Index_t n_tiles = static_cast<Index_t>(nobs / tile_size);
913 EigenMatrix tile_cov;
914 EigenMatrix tile_temp;
915 pairlocal::TiledLayoutSource tiles;
916 if (use_pair_local_tiles_ && !sexpat_cov_func->usesManifoldChart() &&
917 !sexpat_cov_func->usesGeodesicHeatKernel())
918 (void)tiles.prepare(sexpat_cov_func->getConfInfo(),
919 sexpat_cov_func->combineParameters(), x_tiled,
920 tile_size, tile_ind);
921 for (Index_t obs_i = 0; obs_i < n_tiles; ++obs_i) {
922 const int row_start = static_cast<int>(obs_i * tile_size);
923 const EigenMatrix x_tile_i = x_tiled.middleRows(row_start, tile_size);
924 for (Index_t obs_j = 0; obs_j < n_tiles; ++obs_j) {
925 const int col_start = static_cast<int>(obs_j * tile_size);
926 if (st.block_size() == tile_size
927 ? !st.owns_global_entry(row_start, col_start)
928 : !owns_any_entry(row_start, tile_size, col_start,
929 tile_size))
930 continue;
931
932 const EigenMatrix x_tile_j =
933 x_tiled.middleRows(col_start, tile_size);
934 tile_cov.resize(tile_size, tile_size);
935 tile_cov.setZero();
936
937 if (tiles.ready()) {
938 tiles.tile(obs_i, obs_j, tile_temp);
939 } else {
940 applyCrossCovarianceFunction(
941 x_tile_i, x_tile_j, tile_ind, tile_uDdim, tile_ind,
942 tile_uDdim, *sexpat_cov_func, tile_temp, false);
943 }
944 tile_cov.noalias() += tile_temp;
945 if (const_cov_fun != nullptr) {
946 applyCrossCovarianceFunction(x_tile_i, x_tile_j, tile_ind,
947 tile_uDdim, tile_ind, tile_uDdim,
948 *const_cov_fun, tile_temp, false);
949 tile_cov.noalias() += tile_temp;
950 }
951
952 if (st.block_size() == tile_size) {
953 // A tile is one block of the block-cyclic layout: one owner,
954 // contiguous local rows and columns.
955 const int dist_i = st.local_index_for_global(
956 row_start, st.block_size(), st.myrow(), st.nprow());
957 const int dist_j = st.local_index_for_global(
958 col_start, st.block_size(), st.mycol(), st.npcol());
959 Eigen::Map<EigenMatrix, 0, Eigen::OuterStride<>> target(
960 kernel_dist.data() + static_cast<std::size_t>(dist_i) +
961 static_cast<std::size_t>(dist_j) *
962 static_cast<std::size_t>(leading),
963 tile_size, tile_size, Eigen::OuterStride<>(leading));
964 target = tile_cov;
965 continue;
966 }
967 for (int local_j = 0; local_j < tile_size; ++local_j) {
968 const int global_j = col_start + local_j;
969 for (int local_i = 0; local_i < tile_size; ++local_i) {
970 const int global_i = row_start + local_i;
971 if (!st.owns_global_entry(global_i, global_j)) continue;
972 const int dist_i = st.local_index_for_global(
973 global_i, st.block_size(), st.myrow(), st.nprow());
974 const int dist_j = st.local_index_for_global(
975 global_j, st.block_size(), st.mycol(), st.npcol());
976 kernel_dist[static_cast<std::size_t>(dist_i) +
977 static_cast<std::size_t>(dist_j) *
978 static_cast<std::size_t>(leading)] =
979 tile_cov(local_i, local_j);
980 }
981 }
982 }
983 }
984 const bool finite =
985 std::all_of(kernel_dist.begin(), kernel_dist.end(),
986 [](double value) { return std::isfinite(value); });
987 // A process with no matrix entries still participates in the solve.
988 // All ranks must agree on validity before entering its collectives.
989 double invalid = !finite || desc[2] != nobs || desc[3] != nobs;
990 backend().ordered_sum_bcast(&invalid, 1);
991 if (invalid != 0.0) return false;
992 ++distributed_hssvd_dual_kernel_assemblies_for_testing_;
993 return true;
994}
995#endif
996
997bool GaussianProcessRegression::refreshFullDataPosteriorHssvd()
998{
999 if (!use_hssvd_backend_ || R_matrix.rows() <= 0 ||
1000 R_indices.rows() != R_matrix.rows() ||
1001 energy_and_gradient.size() != R_matrix.rows())
1002 return false;
1003
1004 // The full-data posterior refresh is a clean boundary after the SCG
1005 // objective. Drop any Cholesky-trace objective state the objective left so
1006 // the prediction / Laplace paths rebuild their own factors instead of
1007 // reusing a stale SCG factor.
1008 hssvd_objective_trace_via_cholesky_ = false;
1009
1011 if (!factorizeStableBasisFromTraining(R_matrix, R_indices)) return false;
1012 if (!hssvd_dual_kernel_) return false;
1013 maybeDiagnoseHssvd();
1014
1015#ifdef GPR_LINALG_SCALAPACK
1016 auto& st = backend().distributed();
1017 st.invalidate_L();
1018 st.invalidate_inv();
1019#endif
1020 C.resize(0, 0);
1022 b.resize(0);
1023#ifdef GPR_LINALG_SCALAPACK
1024 training_cholesky_is_distributed_ = false;
1025#endif
1027
1028 refreshPosteriorWeights(energy_and_gradient);
1029 return hssvd_basis_valid_ && hssvd_basis_.rank() > 0 &&
1030 hssvd_p_.size() == hssvd_basis_.rank();
1031}
1032
1034 Eigen::VectorXd& design,
1035 Eigen::VectorXd& coeff) const
1036{
1037 if (!use_hssvd_backend_ || !hssvd_basis_valid_ || query.rows() != 1)
1038 return false;
1039 if (hssvd_dual_kernel_) {
1040 if (hssvd_dual_predict_weights_.size() == 0 || R_matrix.rows() == 0)
1041 return false;
1043 EigenMatrix query_rows;
1044 Eigen::VectorXd query_ind;
1045 aux.assembleMatrixOfRepetitiveCoordinates(query, query_rows, query_ind);
1046 EigenMatrix cross;
1048 R_matrix, query_rows, R_indices, query_ind, cross,
1049 /*serial_per_rank=*/true);
1050 if (cross.rows() != hssvd_dual_predict_weights_.size() ||
1051 cross.cols() < 1)
1052 return false;
1053 design = cross.col(0);
1054 coeff = hssvd_dual_predict_weights_;
1055 return true;
1056 }
1057 if (hssvd_p_.size() == 0 || hssvd_l_feat_.size() == 0) return false;
1058 const Eigen::Index dfeat = hssvd_l_feat_.size();
1059 Coord xr = query.row(0);
1060 Eigen::VectorXd q;
1061 EigenMatrix J;
1063 xr, sexpat_cov_func->getConfInfo(), q, J);
1064 Eigen::MatrixXd Qtil(1, dfeat);
1065 for (Eigen::Index k = 0; k < dfeat; ++k)
1066 Qtil(0, k) = (q(k) - hssvd_mean_feat_(k)) / hssvd_l_feat_(k);
1067 Eigen::MatrixXd Uq;
1068 Eigen::MatrixXd Rq;
1069 StableBasisND::projectToAffineSpan(Qtil, hssvd_feature_basis_, Uq, Rq);
1070 design = hssvd_basis_.energyAffineDesignRow(Uq, Rq);
1071 coeff = hssvd_p_;
1072 return design.size() == coeff.size() && design.size() > 0;
1073}
1074
1075void GaussianProcessRegression::predictPotentialHssvd(Observation& image1)
1076{
1077 if (hssvd_dual_kernel_) {
1078 predictPotentialHssvdDual(image1);
1079 return;
1080 }
1081
1082 // Cancellation-free HS-SVD prediction: energy mu_E(x*) = A_E(x*) c and the
1083 // Cartesian force d mu_E/dx via the chain rule, with c folded into the
1084 // reduced coeff hssvd_p_ (predictEnergy/predictGradient consume p, never
1085 // forming the large alpha). The query descriptor is standardized the SAME
1086 // way the basis was built (q~ = (q-mean)/l), and the descriptor Jacobian is
1087 // scaled by 1/l so dmu_E/dx = sum_j (dmu_E/dq~_j) (J(x*)_{j,:}/l_j).
1088 const Eigen::Index N_im = image1.R.rows();
1089 const Eigen::Index D = image1.R.cols();
1090 const Eigen::Index dfeat = hssvd_l_feat_.size();
1091 image1.E.resize(1, N_im);
1092 image1.G.resize(N_im, D);
1093
1094 Eigen::MatrixXd Qtil(N_im, dfeat);
1095 std::vector<Eigen::MatrixXd> Jtil(static_cast<std::size_t>(N_im));
1096 // One image is one test point. Its descriptor and Jacobian do not
1097 // read another image, so the team writes disjoint rows.
1098 // One subtraction and one division per feature, then one division
1099 // per feature coordinate. The Jacobian builder is extra work, so this
1100 // count is a lower bound taken from the loop that is written here.
1101 const double descriptor_flops =
1102 static_cast<double>(N_im) *
1103 static_cast<double>(std::max<Eigen::Index>(dfeat, 1)) *
1104 (2.0 + static_cast<double>(std::max<Eigen::Index>(D, 1)));
1105 const bool parallel_images = linalg::teamParallelPays(descriptor_flops);
1106#if defined(USE_OPENMP)
1107#pragma omp parallel for schedule(static) if (parallel_images)
1108#endif
1109 for (Eigen::Index i = 0; i < N_im; ++i) {
1110 Coord xr = image1.R.row(i);
1111 Eigen::VectorXd q;
1112 EigenMatrix J;
1114 xr, sexpat_cov_func->getConfInfo(), q, J,
1115 sexpat_cov_func->farFieldRadius());
1116 for (Eigen::Index k = 0; k < dfeat; ++k)
1117 Qtil(i, k) = (q(k) - hssvd_mean_feat_(k)) / hssvd_l_feat_(k);
1118 Eigen::MatrixXd Js = J; // dfeat x D
1119 for (Eigen::Index k = 0; k < dfeat; ++k)
1120 Js.row(k) /= hssvd_l_feat_(k);
1121 Jtil[static_cast<std::size_t>(i)] = Js;
1122 }
1123
1124 Eigen::MatrixXd Uq;
1125 Eigen::MatrixXd Rq;
1126 StableBasisND::projectToAffineSpan(Qtil, hssvd_feature_basis_, Uq, Rq);
1127
1128 const Eigen::VectorXd muE = hssvd_basis_.predictEnergyAffine(
1129 Uq, Rq, hssvd_p_); // N_im (standardized)
1130 const Eigen::MatrixXd Gdesc = hssvd_basis_.predictGradientAffine(
1131 Uq, Rq, hssvd_feature_basis_, hssvd_p_); // N_im x dfeat
1132
1133 // Return STANDARDIZED predictions; calculatePotentialDispatched applies the
1134 // single un-normalization E = y_scale_*E~ + y_mean_, grad = y_scale_*grad~.
1135 // Applying y_scale_ here too double-counted it whenever output
1136 // normalization was active (y_scale_ != 1), shrinking the predicted forces
1137 // by a factor of y_scale_ and derailing the dimer step / trust geometry.
1138 const double force_flops =
1139 2.0 * static_cast<double>(N_im) * static_cast<double>(D) *
1140 static_cast<double>(std::max<Eigen::Index>(dfeat, 1));
1141 const bool parallel_forces = linalg::teamParallelPays(force_flops);
1142#if defined(USE_OPENMP)
1143#pragma omp parallel for schedule(static) if (parallel_forces)
1144#endif
1145 for (Eigen::Index i = 0; i < N_im; ++i) {
1146 image1.E(0, i) = muE(i);
1147 const Eigen::MatrixXd& Js = Jtil[static_cast<std::size_t>(i)];
1148 for (Eigen::Index c = 0; c < D; ++c) {
1149 double g = 0.0;
1150 for (Eigen::Index k = 0; k < dfeat; ++k)
1151 g += Gdesc(i, k) * Js(k, c);
1152 image1.G(i, c) = g;
1153 }
1154 }
1155 ++num_of_potential_calls;
1156}
1157
1158void GaussianProcessRegression::predictPotentialHssvdDual(Observation& image1)
1159{
1160 const Eigen::Index N_im = image1.R.rows();
1161 const Eigen::Index D = image1.R.cols();
1162
1163 const double const_sigma2 =
1164 const_cov_fun ? const_cov_fun->getConstSigma2() : 0.0;
1165 const bool sexpat_only_kernel =
1166 sexpat_cov_func != nullptr &&
1167 std::abs(const_sigma2) <= std::numeric_limits<double>::epsilon();
1168 const bool alpha_k_layout =
1169 full_cartesian_training_dimension_ == D && D >= 0 &&
1170 R_matrix.rows() > 0 &&
1171 R_matrix.rows() == hssvd_dual_predict_weights_.size() && (D + 1) > 0 &&
1172 R_matrix.rows() % (D + 1) == 0;
1173 if (use_alpha_k_predict_mean_ && sexpat_only_kernel && alpha_k_layout) {
1174 const Eigen::Index num_train_pts = R_matrix.rows() / (D + 1);
1175 Eigen::VectorXd mu_E_out = Eigen::VectorXd::Zero(N_im);
1176 Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
1177 mu_G_out = Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic,
1178 Eigen::RowMajor>::Zero(N_im, D);
1179 if (hssvd_dual_alpha_k_prepared_.valid &&
1180 hssvd_dual_alpha_k_prepared_.num_train == num_train_pts &&
1181 hssvd_dual_alpha_k_prepared_.dof == D) {
1182 sexpat_cov_func->predictMeanAlphaKPrepared(
1183 hssvd_dual_alpha_k_prepared_, image1.R, mu_E_out, mu_G_out);
1184 } else {
1185 sexpat_cov_func->predictMeanAlphaK(
1186 R_matrix.topRows(num_train_pts), image1.R,
1187 hssvd_dual_predict_weights_.head(num_train_pts),
1188 hssvd_dual_predict_weights_, mu_E_out, mu_G_out);
1189 }
1190
1191 // Standardized output; calculatePotentialDispatched un-normalizes once.
1192 image1.E.resize(1, N_im);
1193 image1.E = mu_E_out.transpose();
1194 image1.G.resize(N_im, D);
1195 image1.G = mu_G_out;
1196 ++num_of_potential_calls;
1197 return;
1198 }
1199
1200 aux::AuxiliaryFunctionality aux_func;
1201 EigenMatrix R_mod;
1202 Eigen::VectorXd R_mod_ind;
1203 aux_func.assembleMatrixOfRepetitiveCoordinates(image1.R, R_mod, R_mod_ind);
1204
1205 EigenMatrix Kstar;
1206 evaluateCovarianceMatrix(R_matrix, R_mod, R_indices, R_mod_ind, Kstar,
1207 /*serial_per_rank=*/true);
1208 const Eigen::VectorXd EG_R =
1209 Kstar.transpose() * hssvd_dual_predict_weights_;
1210
1211 // Standardized output; calculatePotentialDispatched un-normalizes once.
1212 image1.E.resize(1, N_im);
1213 image1.E = Eigen::Map<const Eigen::RowVectorXd>(EG_R.data(), N_im);
1214 image1.G.resize(N_im, D);
1215 image1.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
1216 Eigen::Dynamic, Eigen::ColMajor>>(
1217 EG_R.data() + N_im, N_im, D);
1218 ++num_of_potential_calls;
1219}
1220
1222GaussianProcessRegression::meanHessianProductHssvd(
1223 const Coord& R, const Eigen::VectorXd& direction,
1224 Eigen::VectorXd& hessian_vector) const
1225{
1226 // The spectral weights differentiate the MAP mean. A Laplace, SVGD, or
1227 // BMA mean is a factor mixture with its own derivative dispatch.
1228 const bool map_mean = uncertainty_mode_ == UncertaintyMode::MAP ||
1229 uncertainty_mode_ == UncertaintyMode::EB ||
1230 uncertainty_mode_ == UncertaintyMode::LAPLACE_SLICE;
1231 const bool feature_mean =
1232 rff_model_.isBuilt() &&
1233 (rff_replaces_exact_ ||
1234 (uncertainty_mode_ == UncertaintyMode::LAPLACE_SLICE &&
1235 rff_features_ > 0));
1236 if (!map_mean || active_posterior_ || feature_mean || !sexpat_cov_func ||
1237 sexpat_cov_func->usesManifoldChart() ||
1238 sexpat_cov_func->usesGeodesicHeatKernel())
1240 ++hssvd_hessian_vector_calls_for_testing_;
1241 const auto add_physical_prior = [&]() {
1242 if (ffPriorMeanActive())
1244 ff_prior_mean_->hessianPairs(R.row(0)), direction);
1245 else if (zblPriorMeanActive())
1247 zbl_prior_mean_->hessianPairs(R.row(0)), direction);
1249 hessian_vector += secantQuadraticHessian() * direction;
1250 return hessian_vector.allFinite();
1251 };
1252 if (hssvd_dual_kernel_ ||
1253 (!use_hssvd_backend_ && descriptor_predictor_ready_)) {
1254 // The prepared descriptor operator includes the physical prior and
1255 // secant quadratic Hessians.
1256 return calculateMeanHessianVectorHssvdDual(R, direction,
1257 hessian_vector);
1258 }
1259
1260 if (!use_hssvd_backend_ || !hssvd_basis_valid_ || hssvd_p_.size() == 0 ||
1261 hssvd_mean_feat_.size() == 0 || R.rows() != 1 ||
1262 direction.size() != R.cols())
1264
1265 const Eigen::Index dfeat = hssvd_l_feat_.size();
1266 Coord xr = R.row(0);
1267 Eigen::VectorXd q;
1268 EigenMatrix J;
1269 EigenMatrix HJ_direction;
1271 xr, sexpat_cov_func->getConfInfo(), direction, q, J, HJ_direction,
1272 sexpat_cov_func->farFieldRadius());
1273
1274 Eigen::MatrixXd Qtil(1, dfeat);
1275 Eigen::MatrixXd Dqtil(1, dfeat);
1276 Eigen::MatrixXd Jtil = J;
1277 Eigen::MatrixXd HJtil = HJ_direction;
1278 for (Eigen::Index k = 0; k < dfeat; ++k) {
1279 Qtil(0, k) = (q(k) - hssvd_mean_feat_(k)) / hssvd_l_feat_(k);
1280 Jtil.row(k) /= hssvd_l_feat_(k);
1281 HJtil.row(k) /= hssvd_l_feat_(k);
1282 Dqtil(0, k) = Jtil.row(k).dot(direction);
1283 }
1284
1285 Eigen::MatrixXd Uq;
1286 Eigen::MatrixXd Rq;
1287 StableBasisND::projectToAffineSpan(Qtil, hssvd_feature_basis_, Uq, Rq);
1288 const Eigen::MatrixXd tangent_direction = Dqtil * hssvd_feature_basis_;
1289 const Eigen::MatrixXd residual_direction =
1290 Dqtil - tangent_direction * hssvd_feature_basis_.transpose();
1291
1292 const Eigen::MatrixXd Gdesc = hssvd_basis_.predictGradientAffine(
1293 Uq, Rq, hssvd_feature_basis_, hssvd_p_);
1294 const Eigen::MatrixXd Hdesc_direction =
1295 hssvd_basis_.predictGradientHessianVectorAffine(
1296 Uq, Rq, hssvd_feature_basis_, tangent_direction, residual_direction,
1297 hssvd_p_);
1298
1299 hessian_vector = Jtil.transpose() * Hdesc_direction.row(0).transpose() +
1300 HJtil.transpose() * Gdesc.row(0).transpose();
1301 hessian_vector *= y_scale_;
1302 return add_physical_prior() ? MeanHessianProductStatus::Computed
1304}
1305
1307 const Coord& R, const Eigen::VectorXd& direction,
1308 Eigen::VectorXd& hessian_vector) const
1309{
1310 return meanHessianProductHssvd(R, direction, hessian_vector) ==
1312}
1313
1314std::vector<int> GaussianProcessRegression::selectHssvdLocalActiveSet(
1315 const Coord& R, const int active_set_size) const
1316{
1317 const Eigen::Index ntrain = hssvd_train_qtil_.rows();
1318 const Eigen::Index dfeat = hssvd_l_feat_.size();
1319 const Eigen::Index dof = R.cols();
1320 if (active_set_size <= 0 || ntrain <= 0 || active_set_size >= ntrain ||
1321 R.rows() != 1 || dfeat <= 0 || hssvd_mean_feat_.size() != dfeat)
1322 return {};
1323
1324 Coord xr = R.row(0);
1325 Eigen::VectorXd q;
1326 EigenMatrix J;
1328 xr, sexpat_cov_func->getConfInfo(), q, J,
1329 sexpat_cov_func->farFieldRadius());
1330 if (q.size() != dfeat || J.rows() != dfeat || J.cols() != dof) return {};
1331
1332 Eigen::RowVectorXd qtil(dfeat);
1333 for (Eigen::Index k = 0; k < dfeat; ++k) {
1334 if (!(hssvd_l_feat_(k) > 0.0)) return {};
1335 qtil(k) = (q(k) - hssvd_mean_feat_(k)) / hssvd_l_feat_(k);
1336 }
1337
1338 std::vector<double> distances(static_cast<std::size_t>(ntrain),
1339 std::numeric_limits<double>::infinity());
1340 std::vector<int> order(static_cast<std::size_t>(ntrain));
1341 std::iota(order.begin(), order.end(), 0);
1342 for (Eigen::Index i = 0; i < ntrain; ++i) {
1343 distances[static_cast<std::size_t>(i)] =
1344 (hssvd_train_qtil_.row(i) - qtil).squaredNorm();
1345 }
1346
1347 const int cap = std::min<int>(active_set_size, static_cast<int>(ntrain));
1348 std::partial_sort(
1349 order.begin(), order.begin() + cap, order.end(), [&](int a, int b) {
1350 const double da = distances[static_cast<std::size_t>(a)];
1351 const double db = distances[static_cast<std::size_t>(b)];
1352 if (da == db) return a < b;
1353 return da < db;
1354 });
1355 order.resize(static_cast<std::size_t>(cap));
1356 std::sort(order.begin(), order.end());
1357 return order;
1358}
1359
1360std::vector<int>
1361GaussianProcessRegression::selectHssvdLocalActiveSetForPositions(
1362 const EigenMatrix& positions, const int active_set_size) const
1363{
1364 const Eigen::Index ntrain = hssvd_train_qtil_.rows();
1365 const Eigen::Index dfeat = hssvd_l_feat_.size();
1366 const Eigen::Index dof = positions.cols();
1367 if (active_set_size <= 0 || ntrain <= 0 || active_set_size >= ntrain ||
1368 positions.rows() <= 0 || dof <= 0 || dfeat <= 0 ||
1369 hssvd_mean_feat_.size() != dfeat)
1370 return {};
1371
1372 Eigen::MatrixXd query_qtil(positions.rows(), dfeat);
1373 for (Eigen::Index r = 0; r < positions.rows(); ++r) {
1374 Coord xr = positions.row(r);
1375 Eigen::VectorXd q;
1376 EigenMatrix J;
1378 xr, sexpat_cov_func->getConfInfo(), q, J,
1379 sexpat_cov_func->farFieldRadius());
1380 if (q.size() != dfeat || J.rows() != dfeat || J.cols() != dof)
1381 return {};
1382 for (Eigen::Index k = 0; k < dfeat; ++k) {
1383 if (!(hssvd_l_feat_(k) > 0.0)) return {};
1384 query_qtil(r, k) = (q(k) - hssvd_mean_feat_(k)) / hssvd_l_feat_(k);
1385 }
1386 }
1387
1388 std::vector<double> distances(static_cast<std::size_t>(ntrain),
1389 std::numeric_limits<double>::infinity());
1390 std::vector<int> order(static_cast<std::size_t>(ntrain));
1391 std::iota(order.begin(), order.end(), 0);
1392 for (Eigen::Index i = 0; i < ntrain; ++i) {
1393 double best = std::numeric_limits<double>::infinity();
1394 for (Eigen::Index r = 0; r < query_qtil.rows(); ++r) {
1395 const double dist =
1396 (hssvd_train_qtil_.row(i) - query_qtil.row(r)).squaredNorm();
1397 if (dist < best) best = dist;
1398 }
1399 distances[static_cast<std::size_t>(i)] = best;
1400 }
1401
1402 const int cap = std::min<int>(active_set_size, static_cast<int>(ntrain));
1403 std::partial_sort(
1404 order.begin(), order.begin() + cap, order.end(), [&](int a, int b) {
1405 const double da = distances[static_cast<std::size_t>(a)];
1406 const double db = distances[static_cast<std::size_t>(b)];
1407 if (da == db) return a < b;
1408 return da < db;
1409 });
1410 order.resize(static_cast<std::size_t>(cap));
1411 std::sort(order.begin(), order.end());
1412 return order;
1413}
1414
1415bool GaussianProcessRegression::buildHssvdDualLocalModelFromSelection(
1416 const std::vector<int>& selected, HssvdDualLocalModel& model) const
1417{
1418 model = HssvdDualLocalModel{};
1419 if (selected.empty()) return false;
1420
1421 const Eigen::Index ntrain = hssvd_train_qtil_.rows();
1422 const Eigen::Index dfeat = hssvd_l_feat_.size();
1423 const Eigen::Index dof = R_matrix.cols() - 1;
1424 const Eigen::Index repeat = dof + 1;
1425 const Eigen::Index nlocal = static_cast<Eigen::Index>(selected.size());
1426 if (nlocal <= 0 || dof <= 0 || repeat <= 1 ||
1427 R_matrix.rows() != ntrain * repeat ||
1428 R_indices.size() != R_matrix.rows() ||
1429 energy_and_gradient.size() != R_matrix.rows() ||
1430 static_cast<Eigen::Index>(hssvd_train_jtil_.size()) != ntrain)
1431 return false;
1432
1433 EigenMatrix local_x(nlocal * repeat, R_matrix.cols());
1434 Eigen::VectorXd local_ind(nlocal * repeat);
1435 Eigen::VectorXd local_y(nlocal * repeat);
1436 for (Eigen::Index block = 0; block < repeat; ++block) {
1437 for (Eigen::Index j = 0; j < nlocal; ++j) {
1438 const int selected_config = selected[static_cast<std::size_t>(j)];
1439 if (selected_config < 0 || selected_config >= ntrain) return false;
1440 const Eigen::Index src =
1441 block * ntrain + static_cast<Eigen::Index>(selected_config);
1442 const Eigen::Index dst = block * nlocal + j;
1443 local_x.row(dst) = R_matrix.row(src);
1444 local_ind(dst) = R_indices(src);
1445 local_y(dst) = energy_and_gradient(src);
1446 }
1447 }
1448
1449 EigenMatrix local_kernel;
1450 auto* mutable_self = const_cast<GaussianProcessRegression*>(this);
1451 mutable_self->evaluateTrainingCovarianceMatrix(local_x, local_ind,
1452 local_kernel,
1453 /*serial_per_rank=*/true);
1454 if (lik_gaussian != nullptr && local_kernel.rows() == local_kernel.cols()) {
1455 local_kernel.diagonal().array() -= lik_gaussian->getSigma2();
1456 }
1457
1458 // Local active-set Schur complements subtract full Kstar/Kqq blocks.
1459 // The active-set eigensystem therefore keeps every positive local
1460 // eigenmode; truncating only Ktrain makes the posterior covariance
1461 // algebra inconsistent. Psi remains orthonormal, so cond(Psi)=1.
1462 StableBasisND local_basis(backend_context_);
1463 bool factorized = false;
1464 if (hssvd_dual_lapack_rrr_) {
1465 factorized = local_basis.factorizeKernelLapackRrr(
1466 local_kernel, /*sv_rtol=*/0.0, /*sv_abs_tol=*/0.0,
1467 /*sv_chop_tol=*/0.0);
1468 }
1469 if (!factorized) {
1470 local_basis.factorizeKernel(local_kernel, /*sv_rtol=*/0.0,
1471 /*sv_abs_tol=*/0.0,
1472 /*sv_chop_tol=*/0.0);
1473 factorized = local_basis.rank() > 0;
1474 }
1475 if (!factorized || local_basis.rank() <= 0 ||
1476 local_basis.numObs() != local_y.size())
1477 return false;
1478
1479 const double total_sigma2 = totalPosteriorNoiseVariance();
1480 const StableBasisPosteriorWeights weights =
1481 local_basis.noisyPosteriorWeights(local_y, total_sigma2);
1482 if (weights.alpha.size() != local_y.size()) return false;
1483
1484 model.train_x = std::move(local_x);
1485 model.train_indices = std::move(local_ind);
1486 model.basis = std::move(local_basis);
1487 model.train_qtil.resize(nlocal, dfeat);
1488 model.train_jtil.clear();
1489 model.train_jtil.reserve(static_cast<std::size_t>(nlocal));
1490 for (Eigen::Index j = 0; j < nlocal; ++j) {
1491 const int src = selected[static_cast<std::size_t>(j)];
1492 model.train_qtil.row(j) = hssvd_train_qtil_.row(src);
1493 model.train_jtil.push_back(
1494 hssvd_train_jtil_[static_cast<std::size_t>(src)]);
1495 }
1496 model.predict_weights = weights.alpha;
1497 for (const auto& Ji: model.train_jtil)
1498 if (Ji.rows() != dfeat || Ji.cols() != dof) return false;
1500 if (!sexpat_cov_func->prepareAlphaK(model.train_x.topRows(nlocal),
1501 model.predict_weights.head(nlocal),
1502 model.predict_weights, alpha_k))
1503 return false;
1504 model.force_jacobian_weights = descriptorForceJacobianWeights(
1505 alpha_k, model.train_jtil, model.predict_weights);
1506 model.config_count = nlocal;
1507 model.observation_count = local_y.size();
1508 model.condition_number = model.basis.conditionNumber();
1509 return true;
1510}
1511
1512bool GaussianProcessRegression::buildHssvdDualLocalModel(
1513 const Coord& R, HssvdDualLocalModel& model) const
1514{
1515 return buildHssvdDualLocalModelFromSelection(
1516 selectHssvdLocalActiveSet(R, hssvd_local_active_set_size_), model);
1517}
1518
1519bool GaussianProcessRegression::prepareMeanHessianVectorHssvdDualFromWeights(
1520 const Coord& R, const Eigen::MatrixXd& train_qtil,
1521 const std::vector<Eigen::MatrixXd>& train_jtil,
1522 const Eigen::VectorXd& predict_weights,
1523 const Eigen::MatrixXd& force_jacobian_weights,
1524 PreparedHssvdHessianVector& prepared) const
1525{
1526 const Eigen::Index ntrain = train_qtil.rows();
1527 const Eigen::Index dfeat = hssvd_l_feat_.size();
1528 const Eigen::Index dof = R.cols();
1529 if (ntrain <= 0 || dfeat <= 0 ||
1530 predict_weights.size() != ntrain * (dof + 1) ||
1531 static_cast<Eigen::Index>(train_jtil.size()) != ntrain)
1532 return false;
1533
1534 Coord xr = R.row(0);
1535 Eigen::VectorXd q;
1536 EigenMatrix J;
1538 xr, sexpat_cov_func->getConfInfo(), q, J,
1539 sexpat_cov_func->farFieldRadius());
1540 if (q.size() != dfeat || J.rows() != dfeat || J.cols() != dof) return false;
1541
1542 Eigen::RowVectorXd qtil(dfeat);
1543 Eigen::MatrixXd Jtil = J;
1544 for (Eigen::Index k = 0; k < dfeat; ++k) {
1545 if (!(hssvd_l_feat_(k) > 0.0)) return false;
1546 qtil(k) = (q(k) - hssvd_mean_feat_(k)) / hssvd_l_feat_(k);
1547 Jtil.row(k) /= hssvd_l_feat_(k);
1548 }
1549
1550 const double magn = sexpat_cov_func->getMagnSigma2();
1551 HessianAccumRow desc_grad = HessianAccumRow::Zero(dfeat);
1552 Eigen::MatrixXd residuals = Eigen::MatrixXd::Zero(ntrain, dfeat);
1553 Eigen::VectorXd energy_kernel_weights = Eigen::VectorXd::Zero(ntrain);
1554 Eigen::MatrixXd prepared_force_jacobian_weights =
1555 Eigen::MatrixXd::Zero(ntrain, dfeat);
1556 Eigen::VectorXd force_kernel_weights = Eigen::VectorXd::Zero(ntrain);
1557 Eigen::VectorXd force_residual_dots = Eigen::VectorXd::Zero(ntrain);
1558 long double energy_kernel_weight_sum = 0.0L;
1559 long double force_kernel_residual_dot_sum = 0.0L;
1560 // Descriptor-space gradient and Hessian of k(r)=magn*exp(-r^T r).
1561 // The prepared HVP applies H_desc (J v) in matrix-free form and adds
1562 // (D_v J)^T grad_desc; tests/symbolic/test_hssvd_dual_hvp.py proves the
1563 // contraction identities.
1564 const bool have_force_weight_cache =
1565 force_jacobian_weights.rows() == ntrain &&
1566 force_jacobian_weights.cols() == dfeat;
1567 for (Eigen::Index i = 0; i < ntrain; ++i) {
1568 const Eigen::RowVectorXd r_row = qtil - train_qtil.row(i);
1569 const Eigen::VectorXd r = r_row.transpose();
1570 const double k = magn * std::exp(-r.squaredNorm());
1571 const double wE = predict_weights(i);
1572 residuals.row(i) = r_row;
1573 energy_kernel_weights(i) = wE * k;
1574 energy_kernel_weight_sum += energy_kernel_weights(i);
1575 desc_grad += (-2.0L * static_cast<long double>(wE) * k) *
1576 r_row.cast<long double>();
1577
1578 const Eigen::MatrixXd& Ji = train_jtil[static_cast<std::size_t>(i)];
1579 if (Ji.rows() != dfeat || Ji.cols() != dof) return false;
1580 Eigen::VectorXd gi = Eigen::VectorXd::Zero(dfeat);
1581 if (have_force_weight_cache) {
1582 gi = force_jacobian_weights.row(i).transpose();
1583 } else {
1584 for (Eigen::Index c = 0; c < dof; ++c) {
1585 const double wG = predict_weights(ntrain + c * ntrain + i);
1586 gi.noalias() += wG * Ji.col(c);
1587 }
1588 }
1589 const double rg = r.dot(gi);
1590 prepared_force_jacobian_weights.row(i) = gi.transpose();
1591 force_kernel_weights(i) = k;
1592 force_residual_dots(i) = rg;
1593 force_kernel_residual_dot_sum += k * rg;
1594 desc_grad += (2.0L * gi.transpose().cast<long double>() -
1595 4.0L * rg * r_row.cast<long double>()) *
1596 k;
1597 }
1598
1599 prepared.R = R;
1600 prepared.Jtil = std::move(Jtil);
1601 prepared.desc_grad = desc_grad.cast<double>();
1602 prepared.residuals = std::move(residuals);
1603 prepared.energy_kernel_weights = std::move(energy_kernel_weights);
1604 prepared.force_jacobian_weights =
1605 std::move(prepared_force_jacobian_weights);
1606 prepared.force_kernel_weights = std::move(force_kernel_weights);
1607 prepared.force_residual_dots = std::move(force_residual_dots);
1608 prepared.length_scales = hssvd_l_feat_;
1609 const Eigen::VectorXd scaled_desc_grad =
1610 prepared.desc_grad.transpose().cwiseQuotient(hssvd_l_feat_);
1611 // A non-finite descriptor gradient is the inverse-distance pole. Pair
1612 // blocks are undefined there. The preparation stays in place so the
1613 // caller does not substitute another Hessian, and it is invalid so
1614 // apply refuses instead of publishing the remaining finite terms.
1615 if (!scaled_desc_grad.allFinite()) {
1616 prepared.descriptor_hessian_pairs.clear();
1617 prepared.valid = false;
1618 return true;
1619 }
1621 R.row(0), sexpat_cov_func->getConfInfo(), scaled_desc_grad,
1622 prepared.descriptor_hessian_pairs, sexpat_cov_func->farFieldRadius());
1623 prepared.energy_kernel_weight_sum = energy_kernel_weight_sum;
1624 prepared.force_kernel_residual_dot_sum = force_kernel_residual_dot_sum;
1625 prepared.y_scale = y_scale_;
1626 if (ffPriorMeanActive())
1627 prepared.prior_hessian_pairs = ff_prior_mean_->hessianPairs(R.row(0));
1628 else if (zblPriorMeanActive())
1629 prepared.prior_hessian_pairs = zbl_prior_mean_->hessianPairs(R.row(0));
1631 prepared.secant_quadratic_hessian = secantQuadraticHessian();
1632 prepared.valid = true;
1633 return true;
1634}
1635
1637 const Coord& R, PreparedHssvdHessianVector& prepared) const
1638{
1639 prepared = PreparedHssvdHessianVector{};
1640 if (atomic_environment_model_) return false;
1641 // These descriptor weights differentiate the MAP mean. Mixture and
1642 // feature-model means use their own derivative dispatch.
1643 const bool map_mean = uncertainty_mode_ == UncertaintyMode::MAP ||
1644 uncertainty_mode_ == UncertaintyMode::EB ||
1645 uncertainty_mode_ == UncertaintyMode::LAPLACE_SLICE;
1646 const bool feature_mean =
1647 rff_model_.isBuilt() &&
1648 (rff_replaces_exact_ ||
1649 (uncertainty_mode_ == UncertaintyMode::LAPLACE_SLICE &&
1650 rff_features_ > 0));
1651 if (!map_mean || feature_mean || active_posterior_ || !sexpat_cov_func ||
1652 sexpat_cov_func->usesManifoldChart() ||
1653 sexpat_cov_func->usesGeodesicHeatKernel())
1654 return false;
1655 hssvd_last_local_active_set_config_count_for_testing_ = 0;
1656 hssvd_last_local_active_set_observation_count_for_testing_ = 0;
1657 hssvd_last_local_active_set_condition_for_testing_ = 0.0;
1658 const bool descriptor_mean_ready =
1659 use_hssvd_backend_ ? hssvd_basis_valid_ && hssvd_dual_kernel_
1660 : descriptor_predictor_ready_;
1661 // The derivative follows the fitted mean representation. Cholesky and
1662 // spectral factorization supply weights to the same analytic descriptor
1663 // contraction, independently of how those weights are obtained.
1664 if (!descriptor_mean_ready || hssvd_dual_predict_weights_.size() == 0 ||
1665 hssvd_train_qtil_.rows() == 0 || R.rows() != 1 ||
1666 sexpat_cov_func == nullptr)
1667 return false;
1668
1669 const Eigen::Index ntrain = hssvd_train_qtil_.rows();
1670 const Eigen::Index dof = R.cols();
1671 if (full_cartesian_training_dimension_ != dof) return false;
1672 if (hssvd_dual_predict_weights_.size() != ntrain * (dof + 1)) return false;
1673
1674 HssvdDualLocalModel local_model;
1675 if (use_hssvd_backend_ && buildHssvdDualLocalModel(R, local_model)) {
1676 const bool ok = prepareMeanHessianVectorHssvdDualFromWeights(
1677 R, local_model.train_qtil, local_model.train_jtil,
1678 local_model.predict_weights, local_model.force_jacobian_weights,
1679 prepared);
1680 if (ok) {
1681 hssvd_last_local_active_set_config_count_for_testing_ =
1682 local_model.config_count;
1683 hssvd_last_local_active_set_observation_count_for_testing_ =
1684 local_model.observation_count;
1685 hssvd_last_local_active_set_condition_for_testing_ =
1686 local_model.condition_number;
1687 }
1688 return ok;
1689 }
1690
1691 hssvd_last_local_active_set_config_count_for_testing_ = ntrain;
1692 hssvd_last_local_active_set_observation_count_for_testing_ =
1693 hssvd_dual_predict_weights_.size();
1694 hssvd_last_local_active_set_condition_for_testing_ =
1695 hssvd_basis_.conditionNumber();
1696 return prepareMeanHessianVectorHssvdDualFromWeights(
1697 R, hssvd_train_qtil_, hssvd_train_jtil_, hssvd_dual_predict_weights_,
1698 hssvd_dual_force_jacobian_weights_, prepared);
1699}
1700
1702 const PreparedHssvdHessianVector& prepared,
1703 const Eigen::VectorXd& direction, Eigen::VectorXd& hessian_vector) const
1704{
1705 ++hssvd_hessian_vector_calls_for_testing_;
1706 Eigen::MatrixXd directions(direction.size(), 1);
1707 directions.col(0) = direction;
1708 Eigen::MatrixXd hessian_block;
1709 if (!applyMeanHessianBlockHssvdImpl(prepared, directions, hessian_block)) {
1710 return false;
1711 }
1712 hessian_vector = hessian_block.col(0);
1713 return hessian_vector.allFinite();
1714}
1715
1716namespace {
1717
1723void extendedTransposeAdd(Eigen::MatrixXd& dest, const Eigen::MatrixXd& left,
1724 const Eigen::MatrixXd& right)
1725{
1726 const Eigen::Index n = left.rows();
1727 const Eigen::Index m = left.cols();
1728 const Eigen::Index k = right.cols();
1729 if (n == 0 || m == 0 || k == 0) return;
1730 const double term =
1731 left.cwiseAbs().maxCoeff() * right.cwiseAbs().maxCoeff();
1732 // A double sum of n products is off by at most n * eps * |term|.
1733 // The two cross terms of this action are required to agree to 1e-10,
1734 // the symmetry of the extended-precision accumulation. A GEMM whose
1735 // error bound is already inside that agreement is the fast path.
1736 const double roundoff =
1737 static_cast<double>(n) * std::numeric_limits<double>::epsilon() * term;
1738 if (!(roundoff > 1e-10)) {
1739 dest.noalias() += left.transpose() * right;
1740 return;
1741 }
1742 Eigen::Matrix<long double, Eigen::Dynamic, Eigen::Dynamic> sum(m, k);
1743 sum.setZero();
1744 for (Eigen::Index i = 0; i < n; ++i) {
1745 for (Eigen::Index col = 0; col < k; ++col) {
1746 const double coeff = right(i, col);
1747 for (Eigen::Index row = 0; row < m; ++row)
1748 sum(row, col) += static_cast<long double>(left(i, row) * coeff);
1749 }
1750 }
1751 dest += sum.cast<double>();
1752}
1753
1754} // namespace
1755
1757 const Eigen::MatrixXd& jacobian, const Eigen::MatrixXd& residuals,
1758 const Eigen::MatrixXd& force_weights,
1759 const Eigen::VectorXd& energy_kernel_weights,
1760 const Eigen::VectorXd& force_kernel_weights,
1761 const Eigen::VectorXd& force_residual_dots, double energy_kernel_weight_sum,
1762 double force_kernel_residual_dot_sum, const Eigen::MatrixXd& directions)
1763{
1764 const Eigen::MatrixXd vq = jacobian * directions;
1765 const Eigen::MatrixXd rv = residuals * vq;
1766 Eigen::MatrixXd desc_hv = -2.0 * energy_kernel_weight_sum * vq;
1767 const Eigen::VectorXd energy_coeff = 4.0 * energy_kernel_weights;
1768 const Eigen::MatrixXd weighted_rv =
1769 (rv.array().colwise() * energy_coeff.array()).matrix();
1770 extendedTransposeAdd(desc_hv, residuals, weighted_rv);
1771
1772 const Eigen::MatrixXd gv = force_weights * vq;
1773 const Eigen::VectorXd force_g_scale = -4.0 * force_kernel_weights;
1774 const Eigen::VectorXd force_rv_scale =
1775 8.0 * force_kernel_weights.array() * force_residual_dots.array();
1776 const Eigen::MatrixXd force_g_coeff =
1777 (rv.array().colwise() * force_g_scale.array()).matrix();
1778 const Eigen::MatrixXd force_r_coeff =
1779 (gv.array().colwise() * force_g_scale.array() +
1780 rv.array().colwise() * force_rv_scale.array())
1781 .matrix();
1782 extendedTransposeAdd(desc_hv, force_weights, force_g_coeff);
1783 extendedTransposeAdd(desc_hv, residuals, force_r_coeff);
1784 desc_hv.noalias() += -4.0 * force_kernel_residual_dot_sum * vq;
1785 return jacobian.transpose() * desc_hv;
1786}
1787
1789 const PreparedHssvdHessianVector& prepared,
1790 const Eigen::MatrixXd& directions, Eigen::MatrixXd& hessian_block) const
1791{
1792 ++hssvd_hessian_vector_calls_for_testing_;
1793 if (optimizer_state_->mean_hessian.hssvd_block_apply_fails) return false;
1794 return applyMeanHessianBlockHssvdImpl(prepared, directions, hessian_block);
1795}
1796
1797bool GaussianProcessRegression::applyMeanHessianBlockHssvdImpl(
1798 const PreparedHssvdHessianVector& prepared,
1799 const Eigen::MatrixXd& directions, Eigen::MatrixXd& hessian_block) const
1800{
1801 if (active_posterior_) return false;
1802 if (!prepared.valid || prepared.R.rows() != 1 ||
1803 directions.rows() != prepared.R.cols() || directions.cols() == 0 ||
1804 !directions.allFinite() || prepared.Jtil.cols() != directions.rows() ||
1805 prepared.desc_grad.size() != prepared.Jtil.rows() ||
1806 prepared.residuals.cols() != prepared.Jtil.rows() ||
1807 prepared.energy_kernel_weights.size() != prepared.residuals.rows() ||
1808 prepared.force_jacobian_weights.rows() != prepared.residuals.rows() ||
1809 prepared.force_jacobian_weights.cols() != prepared.Jtil.rows() ||
1810 prepared.force_kernel_weights.size() != prepared.residuals.rows() ||
1811 prepared.force_residual_dots.size() != prepared.residuals.rows() ||
1812 prepared.length_scales.size() != prepared.Jtil.rows())
1813 return false;
1814
1815 // The products are double GEMMs. An extended-precision product of the
1816 // full Jacobian on every inner spectrum was the search host time.
1817 Eigen::MatrixXd cartesian = hssvdHermiteCartesianAction(
1818 prepared.Jtil, prepared.residuals, prepared.force_jacobian_weights,
1819 prepared.energy_kernel_weights, prepared.force_kernel_weights,
1820 prepared.force_residual_dots, prepared.energy_kernel_weight_sum,
1821 prepared.force_kernel_residual_dot_sum, directions);
1822 // The stored pairs are the same curvature, kept so a non-finite
1823 // descriptor gradient can refuse the block. The search pins were
1824 // measured with this directional contraction, so folding the pairs
1825 // changes the sum those pins recorded.
1826 for (Eigen::Index column = 0; column < directions.cols(); ++column) {
1827 EigenMatrix HJ_direction;
1828 const Eigen::VectorXd direction = directions.col(column);
1830 prepared.R.row(0), sexpat_cov_func->getConfInfo(), direction,
1831 HJ_direction, sexpat_cov_func->farFieldRadius());
1832 if (HJ_direction.rows() != prepared.Jtil.rows() ||
1833 HJ_direction.cols() != directions.rows()) {
1834 return false;
1835 }
1836 for (Eigen::Index k = 0; k < HJ_direction.rows(); ++k)
1837 HJ_direction.row(k) /= prepared.length_scales(k);
1838 cartesian.col(column).noalias() +=
1839 HJ_direction.transpose() * prepared.desc_grad.transpose();
1840 }
1841 hessian_block = cartesian * prepared.y_scale;
1842 if (!prepared.prior_hessian_pairs.empty())
1843 hessian_block += priors::applyPriorHessianPairs(
1844 prepared.prior_hessian_pairs, directions);
1845 if (prepared.secant_quadratic_hessian.size() > 0) {
1846 if (prepared.secant_quadratic_hessian.rows() != directions.rows() ||
1847 prepared.secant_quadratic_hessian.cols() != directions.rows())
1848 return false;
1849 hessian_block += prepared.secant_quadratic_hessian * directions;
1850 }
1851 return hessian_block.allFinite();
1852}
1853
1855GaussianProcessRegression::calculateMeanHessianVectorHssvdDual(
1856 const Coord& R, const Eigen::VectorXd& direction,
1857 Eigen::VectorXd& hessian_vector) const
1858{
1859 if (R.rows() != 1 || R.cols() != direction.size() || !R.allFinite() ||
1860 !direction.allFinite())
1862
1864 // Not prepared: another source may answer. Prepared and unable to apply:
1865 // this block owns the product, including a non-finite descriptor gradient.
1866 if (!prepareMeanHessianVectorHssvd(R, prepared))
1868 Eigen::MatrixXd directions(direction.size(), 1);
1869 directions.col(0) = direction;
1870 Eigen::MatrixXd hessian_block;
1871 if (!applyMeanHessianBlockHssvdImpl(prepared, directions, hessian_block))
1873 hessian_vector = hessian_block.col(0);
1874 return hessian_vector.allFinite() ? MeanHessianProductStatus::Computed
1876}
1877
1878bool GaussianProcessRegression::canUseHssvdVariance() const noexcept
1879{
1880 return !atomic_environment_model_ && use_hssvd_backend_ &&
1881 hssvd_basis_valid_ &&
1882 (hssvd_dual_kernel_ || hssvd_basis_.hasCrossCovariance()) &&
1883 hssvd_basis_.rank() > 0;
1884}
1885
1886Eigen::VectorXi GaussianProcessRegression::hssvdTrainingChannelsForQueries(
1887 const EigenMatrix& query_positions) const
1888{
1889 if (query_positions.rows() <= 0 || query_positions.cols() <= 0 ||
1890 !hssvd_basis_valid_ || hssvd_basis_.numObs() <= 0) {
1891 return Eigen::VectorXi();
1892 }
1893
1894 const Eigen::Index N_im = query_positions.rows();
1895 const Eigen::Index D = query_positions.cols();
1896 if (R_matrix.cols() < D || R_indices.size() != R_matrix.rows() ||
1897 hssvd_basis_.numObs() != R_matrix.rows())
1898 return Eigen::VectorXi();
1899 const geometry::PairBox box(atoms_config.cell);
1900 const auto same_position = [&](const Eigen::RowVectorXd& position,
1901 const Eigen::RowVectorXd& query) {
1902 const Eigen::VectorXd a = position.transpose();
1903 const Eigen::VectorXd b = query.transpose();
1904 Eigen::VectorXd delta = a - b;
1905 if (D % 3 == 0)
1907 const double scale =
1908 std::max({1.0, a.cwiseAbs().maxCoeff(), b.cwiseAbs().maxCoeff()});
1909 const double tolerance = std::max(
1910 1e-12, 128 * std::numeric_limits<double>::epsilon() * scale);
1911 return delta.cwiseAbs().maxCoeff() <= tolerance;
1912 };
1913 if (full_cartesian_training_dimension_ != D || R_matrix.cols() != D + 1) {
1914 Eigen::VectorXi training_channels =
1915 Eigen::VectorXi::Constant(N_im * (D + 1), -1);
1916 for (Eigen::Index row = 0; row < R_matrix.rows(); ++row) {
1917 const double raw_channel = R_indices(row);
1918 if (!detail::validObservationChannel(raw_channel) ||
1919 raw_channel > D)
1920 continue;
1921 const auto channel = static_cast<Eigen::Index>(raw_channel);
1922 for (Eigen::Index image = 0; image < N_im; ++image) {
1923 const Eigen::Index query_channel = channel * N_im + image;
1924 if (training_channels(query_channel) >= 0) continue;
1925 if (same_position(R_matrix.row(row).head(D),
1926 query_positions.row(image)))
1927 training_channels(query_channel) = row;
1928 }
1929 }
1930 return training_channels;
1931 }
1932 if (full_cartesian_training_dimension_ != D || R_matrix.cols() != D + 1 ||
1933 R_matrix.rows() <= 0 || R_matrix.rows() % (D + 1) != 0) {
1934 return Eigen::VectorXi();
1935 }
1936 const Eigen::Index ntrain = R_matrix.rows() / (D + 1);
1937 if (ntrain <= 0 || hssvd_basis_.numObs() != ntrain * (D + 1)) {
1938 return Eigen::VectorXi();
1939 }
1940
1941 Eigen::VectorXi training_channels =
1942 Eigen::VectorXi::Constant(N_im * (D + 1), -1);
1943 for (Eigen::Index m = 0; m < N_im; ++m) {
1944 const Eigen::RowVectorXd query = query_positions.row(m);
1945 Eigen::Index train_config = -1;
1946 for (Eigen::Index t = 0; t < ntrain; ++t) {
1947 if (same_position(R_matrix.row(t).head(D), query)) {
1948 train_config = t;
1949 break;
1950 }
1951 }
1952 if (train_config < 0) continue;
1953
1954 training_channels(m) = train_config;
1955 for (Eigen::Index d = 0; d < D; ++d) {
1956 training_channels(N_im + d * N_im + m) =
1957 ntrain + d * ntrain + train_config;
1958 }
1959 }
1960 return training_channels;
1961}
1962
1963bool GaussianProcessRegression::applyHssvdTrainingRowLatentVariance(
1964 const EigenMatrix& query_positions, Eigen::VectorXd& VarEG_R,
1965 double total_sigma2, const Eigen::VectorXd* observation_noise,
1966 std::vector<char>* replaced) const
1967{
1968 if (replaced) replaced->assign(static_cast<std::size_t>(VarEG_R.size()), 0);
1969 // Under the HS-SVD observation model K_r, latent training covariance is
1970 // Sigma = eta2 I - eta2^2 (K_r + eta2 I)^{-1}
1971 // so every channel is in (0, eta2]. Dual variance uses the full dual
1972 // prior minus a rank-r projection and therefore leaves residual force
1973 // variance O(prior) even when the query is an exact training geometry.
1974 if (!(total_sigma2 > 0.0) || !std::isfinite(total_sigma2)) {
1975 return true;
1976 }
1977
1978 const Eigen::VectorXi training_channels =
1979 hssvdTrainingChannelsForQueries(query_positions);
1980 if (training_channels.size() == 0 ||
1981 VarEG_R.size() != training_channels.size() ||
1982 (observation_noise && observation_noise->size() != VarEG_R.size())) {
1983 return true;
1984 }
1985 // The identity K - K (K + eta2 I)^-1 K = eta2 I - eta2^2 (K + eta2 I)^-1
1986 // holds only for the eta2 inside the inverse. The inverse diagonal is
1987 // formed with the condition-floored noise, so the identity uses it too;
1988 // the joint covariance applies the same noise to its mixed blocks.
1989 const double statistical_sigma2 =
1990 hssvd_basis_.conditionFlooredNoise(total_sigma2);
1991 if (!(statistical_sigma2 > 0.0) || !std::isfinite(statistical_sigma2)) {
1992 return true;
1993 }
1994 // Only the channels this query actually matched are read, so the
1995 // diagonal is formed for those rows rather than for every observation.
1996 // It carries the covariance complement weight, so the marginal equals
1997 // the diagonal of the joint training-row covariance.
1998 const Eigen::MatrixXd& psi = hssvd_basis_.leftSingularVectors();
1999 const Eigen::VectorXd& singular_values = hssvd_basis_.singularValues();
2000 if (psi.cols() != singular_values.size()) return true;
2001 const double complement_weight =
2002 hssvd_basis_.covarianceComplementWeight(statistical_sigma2);
2003 const Eigen::ArrayXd inverse_correction =
2004 (singular_values.array().square() + statistical_sigma2).inverse() -
2005 complement_weight;
2006
2007 for (Eigen::Index query_channel = 0;
2008 query_channel < training_channels.size(); ++query_channel) {
2009 const Eigen::Index train_channel = training_channels(query_channel);
2010 if (train_channel < 0 || train_channel >= psi.rows()) continue;
2011 const bool stable = linalg::stablePosteriorVarianceEnabled();
2012 double q = 0.0;
2013 if (stable) {
2014 linalg::ExactSum accumulated;
2015 accumulated.add(complement_weight);
2016 const auto row = psi.row(train_channel);
2017 for (Eigen::Index mode = 0; mode < inverse_correction.size();
2018 ++mode)
2019 accumulated.addTripleProduct(row(mode), row(mode),
2020 inverse_correction(mode));
2021 q = accumulated.value();
2022 } else {
2023 q = complement_weight +
2024 (psi.row(train_channel).array().square().transpose() *
2025 inverse_correction)
2026 .sum();
2027 }
2028 if (!std::isfinite(q)) {
2029 if (stable) return false;
2030 continue;
2031 }
2032 if (!(q > 0.0)) continue;
2033 double latent = 0.0;
2034 if (stable) {
2035 linalg::ExactSum accumulated;
2036 accumulated.add(statistical_sigma2);
2037 accumulated.addTripleProduct(-statistical_sigma2,
2038 statistical_sigma2, q);
2039 latent = accumulated.value();
2041 statistical_sigma2))
2042 return false;
2043 } else {
2044 latent = statistical_sigma2 -
2045 statistical_sigma2 * statistical_sigma2 * q;
2046 if (!std::isfinite(latent)) continue;
2047 if (latent < 0.0)
2049 latent,
2050 hssvd_basis_.trainingRowLatentErrorBound(
2051 train_channel, statistical_sigma2),
2052 nullptr);
2053 }
2054 double written =
2055 latent +
2056 (observation_noise ? (*observation_noise)(query_channel) : 0.0);
2057 if (stable) {
2058 const double noise =
2059 observation_noise ? (*observation_noise)(query_channel) : 0.0;
2060 const double scale = statistical_sigma2 + std::max(0.0, noise);
2061 if (!linalg::acceptStablePosteriorVariance(written, scale))
2062 return false;
2063 }
2064 VarEG_R(query_channel) = written;
2065 if (replaced) (*replaced)[static_cast<std::size_t>(query_channel)] = 1;
2066 }
2067 return true;
2068}
2069
2070void GaussianProcessRegression::applyHssvdTrainingRowLatentCovariance(
2071 const EigenMatrix& query_positions, EigenMatrix& covariance,
2072 double total_sigma2, std::vector<char>* replaced) const
2073{
2074 applyHssvdTrainingRowLatentCrossCovariance(
2075 query_positions, query_positions, covariance, total_sigma2, replaced);
2076}
2077
2078void GaussianProcessRegression::applyHssvdTrainingRowLatentCrossCovariance(
2079 const EigenMatrix& left, const EigenMatrix& right, EigenMatrix& covariance,
2080 double total_sigma2, std::vector<char>* replaced_diagonal) const
2081{
2082 if (replaced_diagonal)
2083 replaced_diagonal->assign(static_cast<std::size_t>(std::min(
2084 covariance.rows(), covariance.cols())),
2085 0);
2086 if (!(total_sigma2 > 0.0) || !std::isfinite(total_sigma2)) {
2087 return;
2088 }
2089 const Eigen::VectorXi training_channels =
2090 hssvdTrainingChannelsForQueries(left);
2091 const Eigen::VectorXi right_channels =
2092 hssvdTrainingChannelsForQueries(right);
2093 if (training_channels.size() == 0 ||
2094 covariance.rows() != training_channels.size() ||
2095 covariance.cols() != right_channels.size()) {
2096 return;
2097 }
2098
2099 const double factored_sigma2 =
2100 hssvd_basis_.conditionFlooredNoise(total_sigma2);
2101 const Eigen::MatrixXd& psi = hssvd_basis_.leftSingularVectors();
2102 const Eigen::VectorXd& singular_values = hssvd_basis_.singularValues();
2103 if (!(factored_sigma2 > 0.0) || !std::isfinite(factored_sigma2) ||
2104 psi.rows() != hssvd_basis_.numObs() ||
2105 psi.cols() != singular_values.size()) {
2106 return;
2107 }
2108 // The shifted spectrum comes from the latent singular values and the
2109 // floored nugget, as in noisyRangeSelfQuadratic, so the training blocks
2110 // and the query block subtract the same inverse.
2111 const Eigen::ArrayXd noisy_eigenvalues =
2112 singular_values.array().square() + factored_sigma2;
2113 if (noisy_eigenvalues.size() != psi.cols() ||
2114 !(noisy_eigenvalues > 0.0).all() ||
2115 !noisy_eigenvalues.isFinite().all()) {
2116 return;
2117 }
2118 const double complement_weight =
2119 hssvd_basis_.covarianceComplementWeight(factored_sigma2);
2120 const Eigen::ArrayXd inverse_correction =
2121 noisy_eigenvalues.inverse() - complement_weight;
2122
2123 std::vector<Eigen::Index> matched_left, matched_right;
2124 for (Eigen::Index row = 0; row < training_channels.size(); ++row) {
2125 const Eigen::Index train_row = training_channels(row);
2126 if (train_row >= 0 && train_row < psi.rows())
2127 matched_left.push_back(row);
2128 }
2129 for (Eigen::Index col = 0; col < right_channels.size(); ++col) {
2130 const Eigen::Index train_col = right_channels(col);
2131 if (train_col >= 0 && train_col < psi.rows())
2132 matched_right.push_back(col);
2133 }
2134 if (matched_left.empty() && matched_right.empty()) return;
2135
2136 // C(X,q | y) = eta^2 (K(X,X)+eta^2 I)^-1 K(X,q).
2137 // A training self block and its mixed blocks must use the same
2138 // statistical inverse; replacing only the self block can violate
2139 // the covariance Cauchy-Schwarz inequality. The query block subtracts
2140 // K(q,X) (K + f I)^-1 K(X,q) with the condition-floored noise f, and
2141 // K - K (K + f I)^-1 K = f I - f^2 (K + f I)^-1, so every training
2142 // block carries f as its prefactor. A raw eta^2 < f against the
2143 // floored inverse describes a different posterior, whose mixed blocks
2144 // exceed the Cauchy-Schwarz bound once a rank-deficient basis raises f.
2145 const double statistical_sigma2 = factored_sigma2;
2146 const auto inverse_cross = [&](const EigenMatrix& positions) {
2147 EigenMatrix cross;
2148 if (!assembleHssvdDualFullCrossCovariance(positions, cross, nullptr)) {
2149 EigenMatrix rows;
2150 Eigen::VectorXd indices;
2151 aux::AuxiliaryFunctionality{}.assembleMatrixOfRepetitiveCoordinates(
2152 positions, rows, indices);
2153 evaluateCovarianceMatrix(R_matrix, rows, R_indices, indices, cross,
2154 true);
2155 }
2156 using WideMatrix =
2157 Eigen::Matrix<long double, Eigen::Dynamic, Eigen::Dynamic>;
2158 const WideMatrix basis = psi.cast<long double>();
2159 const WideMatrix projected =
2160 basis.transpose() * cross.cast<long double>();
2161 const WideMatrix residual =
2162 cross.cast<long double>() - basis * projected;
2163 WideMatrix action = basis *
2164 noisy_eigenvalues.inverse()
2165 .cast<long double>()
2166 .matrix()
2167 .asDiagonal() *
2168 projected;
2169 action.noalias() +=
2170 static_cast<long double>(complement_weight) * residual;
2171 return action;
2172 };
2173 if (!matched_left.empty() &&
2174 matched_right.size() <
2175 static_cast<std::size_t>(right_channels.size())) {
2176 const auto action = inverse_cross(right);
2177 for (const auto row: matched_left)
2178 for (Eigen::Index col = 0; col < right_channels.size(); ++col)
2179 if (right_channels(col) < 0)
2180 covariance(row, col) = static_cast<double>(
2181 static_cast<long double>(statistical_sigma2) *
2182 action(training_channels(row), col));
2183 }
2184 if (!matched_right.empty() &&
2185 matched_left.size() <
2186 static_cast<std::size_t>(training_channels.size())) {
2187 const auto action = inverse_cross(left);
2188 for (const auto col: matched_right)
2189 for (Eigen::Index row = 0; row < training_channels.size(); ++row)
2190 if (training_channels(row) < 0)
2191 covariance(row, col) = static_cast<double>(
2192 static_cast<long double>(statistical_sigma2) *
2193 action(right_channels(col), row));
2194 }
2195 if (matched_left.empty() || matched_right.empty()) return;
2196
2197 // Row selection preserves repeated training channels. The covariance
2198 // correction is Psi_L diag(inverse_correction) Psi_R^T.
2199 EigenMatrix weighted_left(matched_left.size(), psi.cols());
2200 EigenMatrix selected_right(matched_right.size(), psi.cols());
2201 for (Eigen::Index row = 0; row < weighted_left.rows(); ++row)
2202 weighted_left.row(row) =
2203 psi.row(training_channels(matched_left[row])).array() *
2204 inverse_correction.transpose();
2205 for (Eigen::Index col = 0; col < selected_right.rows(); ++col)
2206 selected_right.row(col) = psi.row(right_channels(matched_right[col]));
2207 const EigenMatrix correction = weighted_left * selected_right.transpose();
2208 const bool stable = linalg::stablePosteriorVarianceEnabled();
2209
2210 for (Eigen::Index local_col = 0; local_col < correction.cols();
2211 ++local_col) {
2212 const Eigen::Index col = matched_right[local_col];
2213 const Eigen::Index train_col = right_channels(col);
2214 for (Eigen::Index local_row = 0; local_row < correction.rows();
2215 ++local_row) {
2216 const Eigen::Index row = matched_left[local_row];
2217 const Eigen::Index train_row = training_channels(row);
2218 double latent = 0.0;
2219 if (stable && train_row == train_col) {
2220 // The same exact accumulation as the diagonal identity, so a
2221 // marginal read from this block equals the one read from
2222 // applyHssvdTrainingRowLatentVariance. A value that is not
2223 // finite and nonnegative within roundoff is refused; there is
2224 // no binary64 subtraction and no floor behind it.
2225 linalg::ExactSum inverse_entry;
2226 inverse_entry.add(complement_weight);
2227 const auto basis_row = psi.row(train_row);
2228 for (Eigen::Index mode = 0; mode < inverse_correction.size();
2229 ++mode)
2230 inverse_entry.addTripleProduct(basis_row(mode),
2231 basis_row(mode),
2232 inverse_correction(mode));
2233 const double q = inverse_entry.value();
2234 linalg::ExactSum accumulated;
2235 accumulated.add(statistical_sigma2);
2236 accumulated.addTripleProduct(-statistical_sigma2,
2237 statistical_sigma2, q);
2238 latent = accumulated.value();
2240 statistical_sigma2))
2241 throw linalg::StableVarianceError(
2242 "stable posterior covariance: the training-row "
2243 "identity failed");
2244 } else {
2245 double inverse_entry =
2246 train_row == train_col ? complement_weight : 0.0;
2247 inverse_entry += correction(local_row, local_col);
2248 latent =
2249 (train_row == train_col ? statistical_sigma2 : 0.0) -
2250 statistical_sigma2 * statistical_sigma2 * inverse_entry;
2251 if (!std::isfinite(latent)) continue;
2252 if (train_row == train_col && latent < 0.0)
2254 latent,
2255 hssvd_basis_.trainingRowLatentErrorBound(
2256 train_row, statistical_sigma2),
2257 nullptr);
2258 }
2259 covariance(row, col) = latent;
2260 if (replaced_diagonal && row == col)
2261 (*replaced_diagonal)[static_cast<std::size_t>(row)] = 1;
2262 }
2263 }
2264}
2265
2267{
2268 const Eigen::Index N_im = image1.R.rows();
2269 const Eigen::Index D = image1.R.cols();
2270 if (N_im <= 0 || D <= 0 || R_matrix.rows() <= 0 ||
2271 R_indices.size() != R_matrix.rows() || hssvd_basis_.rank() <= 0) {
2272 fillConservativeVariance(image1);
2273 return;
2274 }
2275
2276 if (hssvd_dual_kernel_) {
2277 EigenMatrix Kstar;
2278 Eigen::VectorXd prior_diag;
2279 if (assembleHssvdDualFullCrossCovariance(image1.R, Kstar,
2280 &prior_diag) &&
2281 Kstar.rows() == hssvd_basis_.numObs() &&
2282 Kstar.cols() == N_im * (D + 1) &&
2283 prior_diag.size() == Kstar.cols()) {
2284 Eigen::VectorXd observation_noise =
2285 Eigen::VectorXd::Zero(prior_diag.size());
2286 {
2287 EigenMatrix query_rows;
2288 Eigen::VectorXd query_ind;
2289 aux::AuxiliaryFunctionality aux_layout;
2291 image1.R, query_rows, query_ind);
2292 if (query_rows.rows() == prior_diag.size()) {
2293 priorFromKernelDiagonal(query_rows, observation_noise);
2294 prior_diag += observation_noise;
2295 }
2296 }
2297 const double total_sigma2 = totalPosteriorNoiseVariance();
2298 // The allowance tracks the diagonal that is cancelled, which
2299 // already includes observation noise when that noise was added.
2300 const Eigen::VectorXd& signal = prior_diag;
2301 Eigen::VectorXd VarEG_R;
2302 bool ready = false;
2303 std::vector<char> replaced;
2305 stableRangePosteriorDiagonal(hssvd_basis_, Kstar, prior_diag,
2306 signal, N_im, total_sigma2,
2307 VarEG_R);
2308 ready = true;
2309 } else {
2310 const Eigen::VectorXd projected =
2311 rangeSelfQuadraticByChannelBlock(hssvd_basis_, Kstar, N_im,
2312 total_sigma2);
2313 if (projected.size() == Kstar.cols() && projected.allFinite()) {
2314 VarEG_R = prior_diag - projected;
2315 ready = true;
2316 }
2317 }
2318 if (ready) {
2319 // The latent training-row formula replaces the Schur value of
2320 // the channels it matches, so it runs first; the certified
2321 // floor then sees, and counts, only the entries that remain.
2322 if (!applyHssvdTrainingRowLatentVariance(
2323 image1.R, VarEG_R, total_sigma2, &observation_noise,
2324 &replaced))
2326 "stable posterior variance is not finite and "
2327 "nonnegative");
2329 for (Eigen::Index channel = 0; channel < VarEG_R.size();
2330 ++channel)
2331 if (!replaced[static_cast<std::size_t>(channel)])
2333 VarEG_R(channel), signal(channel));
2335 hssvd_basis_.floorCertifiedSchurDiagonal(
2336 Kstar, prior_diag, total_sigma2, VarEG_R, &replaced);
2337
2338 // LOO calibration factor rescales the REPORTED variance only
2339 // (see hssvd_variance_calibration_factor_); the threshold
2340 // that gates against it must stay in the model's own units.
2342 image1.E.resize(1, N_im);
2343 image1.E =
2344 Eigen::Map<const Eigen::RowVectorXd>(VarEG_R.data(), N_im);
2345 image1.G.resize(N_im, D);
2346 image1.G = Eigen::Map<const Eigen::Matrix<
2347 double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>>(
2348 VarEG_R.data() + N_im, N_im, D);
2349 return;
2350 }
2351 }
2352 }
2353
2355 EigenMatrix R_mod;
2356 Eigen::VectorXd R_mod_ind;
2357 aux_func.assembleMatrixOfRepetitiveCoordinates(image1.R, R_mod, R_mod_ind);
2358 if (R_mod.rows() != N_im * (D + 1) || R_mod_ind.size() != R_mod.rows()) {
2359 fillConservativeVariance(image1);
2360 return;
2361 }
2362
2363 EigenMatrix Kstar;
2364 evaluateCovarianceMatrix(R_matrix, R_mod, R_indices, R_mod_ind, Kstar,
2365 /*serial_per_rank=*/true);
2366 if (Kstar.rows() != hssvd_basis_.numObs() || Kstar.cols() != R_mod.rows()) {
2367 fillConservativeVariance(image1);
2368 return;
2369 }
2370
2371 Eigen::VectorXd prior_diag = observationKernelDiagonal(image1.R);
2372 if (prior_diag.size() != R_mod.rows()) {
2373 fillConservativeVariance(image1);
2374 return;
2375 }
2376
2377 const double total_sigma2 = totalPosteriorNoiseVariance();
2378 // R_mod is dim-major, so its first N_im rows are the energy channels.
2379 Eigen::VectorXd projected;
2381 projected = rangeSelfQuadraticByChannelBlock(hssvd_basis_, Kstar, N_im,
2382 total_sigma2);
2383 if (projected.size() != R_mod.rows()) {
2384 fillConservativeVariance(image1);
2385 return;
2386 }
2387 }
2388
2389 Eigen::VectorXd observation_noise =
2390 Eigen::VectorXd::Zero(prior_diag.size());
2391 priorFromKernelDiagonal(R_mod, observation_noise);
2392 prior_diag += observation_noise;
2393 // The allowance tracks the diagonal that is cancelled, which already
2394 // includes observation noise.
2395 const Eigen::VectorXd& signal = prior_diag;
2396 Eigen::VectorXd VarEG_R;
2398 stableRangePosteriorDiagonal(hssvd_basis_, Kstar, prior_diag, signal,
2399 N_im, total_sigma2, VarEG_R);
2400 } else {
2401 VarEG_R = prior_diag - projected;
2402 }
2403 std::vector<char> replaced;
2404 if (!applyHssvdTrainingRowLatentVariance(image1.R, VarEG_R, total_sigma2,
2405 &observation_noise, &replaced))
2407 "stable posterior variance is not finite and nonnegative");
2409 for (Eigen::Index channel = 0; channel < VarEG_R.size(); ++channel)
2410 if (!replaced[static_cast<std::size_t>(channel)])
2412 signal(channel));
2414 hssvd_basis_.floorCertifiedSchurDiagonal(
2415 Kstar, prior_diag, total_sigma2, VarEG_R, &replaced);
2416
2417 // LOO calibration factor rescales the REPORTED variance only (see
2418 // hssvd_variance_calibration_factor_); the threshold that gates against
2419 // it must stay in the model's own units.
2421
2422 image1.E.resize(1, N_im);
2423 image1.E = Eigen::Map<const Eigen::RowVectorXd>(VarEG_R.data(), N_im);
2424 image1.G.resize(N_im, D);
2425 image1.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
2426 Eigen::Dynamic, Eigen::ColMajor>>(
2427 VarEG_R.data() + N_im, N_im, D);
2428}
2429
2431 Eigen::Ref<Eigen::VectorXd> variance) const
2432{
2433 const double y_scale = y_scale_;
2434 const double calibration = hssvd_variance_calibration_factor_;
2435 if (!std::isfinite(y_scale) || !(y_scale > 0.0))
2436 throw std::domain_error(
2437 "training variance scaling needs a finite positive output scale");
2438 if (!std::isfinite(calibration) || !(calibration > 0.0))
2439 throw std::domain_error(
2440 "training variance scaling needs a finite positive calibration "
2441 "factor");
2442 const double factor = y_scale * y_scale * calibration;
2443 const bool normal_factor =
2444 std::isfinite(factor) && factor >= std::numeric_limits<double>::min();
2445 for (Eigen::Index i = 0; i < variance.size(); ++i) {
2446 const double value = variance(i);
2447 if (std::isinf(value) && value > 0.0) continue;
2448 variance(i) = normal_factor ? value * factor
2449 : value * y_scale * y_scale * calibration;
2450 }
2451}
2452
2453bool GaussianProcessRegression::assembleHssvdDualCrossCovariance(
2454 const EigenMatrix& positions, EigenMatrix& Kstar,
2455 Eigen::VectorXd* prior_diag, bool energy_only) const
2456{
2457 Kstar.resize(0, 0);
2458 if (prior_diag != nullptr) prior_diag->resize(0);
2459 if ((!hssvd_dual_kernel_ && !descriptor_predictor_ready_) ||
2460 sexpat_cov_func == nullptr || positions.cols() <= 0 ||
2461 hssvd_train_qtil_.rows() <= 0 || hssvd_l_feat_.size() <= 0 ||
2462 hssvd_mean_feat_.size() != hssvd_l_feat_.size())
2463 return false;
2464
2465 const Eigen::Index ntrain = hssvd_train_qtil_.rows();
2466 const Eigen::Index nquery = positions.rows();
2467 const Eigen::Index dfeat = hssvd_l_feat_.size();
2468 const Eigen::Index dof = positions.cols();
2469 const Eigen::Index repeat = dof + 1;
2470 if (nquery <= 0 || R_matrix.rows() != ntrain * repeat ||
2471 R_indices.size() != R_matrix.rows() ||
2472 static_cast<Eigen::Index>(hssvd_train_jtil_.size()) != ntrain)
2473 return false;
2474
2475 Eigen::MatrixXd query_qtil(nquery, dfeat);
2476 std::vector<Eigen::MatrixXd> query_jtil(static_cast<std::size_t>(nquery));
2477 for (Eigen::Index m = 0; m < nquery; ++m) {
2478 Coord xr = positions.row(m);
2479 Eigen::VectorXd q;
2480 EigenMatrix J;
2482 xr, sexpat_cov_func->getConfInfo(), q, J,
2483 sexpat_cov_func->farFieldRadius());
2484 if (q.size() != dfeat || J.rows() != dfeat || J.cols() != dof) {
2485 Kstar.resize(0, 0);
2486 if (prior_diag != nullptr) prior_diag->resize(0);
2487 return false;
2488 }
2489 for (Eigen::Index k = 0; k < dfeat; ++k) {
2490 if (!(hssvd_l_feat_(k) > 0.0)) {
2491 Kstar.resize(0, 0);
2492 if (prior_diag != nullptr) prior_diag->resize(0);
2493 return false;
2494 }
2495 query_qtil(m, k) = (q(k) - hssvd_mean_feat_(k)) / hssvd_l_feat_(k);
2496 J.row(k) /= hssvd_l_feat_(k);
2497 }
2498 query_jtil[static_cast<std::size_t>(m)] = J;
2499 }
2500
2501 const double magn = sexpat_cov_func->getMagnSigma2();
2502 const double const_sigma2 =
2503 const_cov_fun ? const_cov_fun->getConstSigma2() : 0.0;
2504 // The query side carries one energy column per configuration and,
2505 // unless energy_only, dof gradient columns; the training side always
2506 // carries every joint row so the projection sees the whole model.
2507 const Eigen::Index query_cols = energy_only ? nquery : nquery * repeat;
2508 Kstar = EigenMatrix::Zero(ntrain * repeat, query_cols);
2509
2510 if (prior_diag != nullptr) {
2511 prior_diag->resize(query_cols);
2512 prior_diag->head(nquery).setConstant(const_sigma2 + magn);
2513 for (Eigen::Index d = 0; d < dof && !energy_only; ++d) {
2514 for (Eigen::Index m = 0; m < nquery; ++m) {
2515 const Eigen::MatrixXd& Jq =
2516 query_jtil[static_cast<std::size_t>(m)];
2517 (*prior_diag)(nquery + d * nquery + m) =
2518 2.0 * magn * Jq.col(d).squaredNorm();
2519 }
2520 }
2521 }
2522
2523 for (Eigen::Index m = 0; m < nquery; ++m) {
2524 const Eigen::MatrixXd& Jq = query_jtil[static_cast<std::size_t>(m)];
2525 for (Eigen::Index i = 0; i < ntrain; ++i) {
2526 const Eigen::MatrixXd& Ji =
2527 hssvd_train_jtil_[static_cast<std::size_t>(i)];
2528 if (Ji.rows() != dfeat || Ji.cols() != dof) {
2529 Kstar.resize(0, 0);
2530 if (prior_diag != nullptr) prior_diag->resize(0);
2531 return false;
2532 }
2533
2534 const Eigen::RowVectorXd r =
2535 hssvd_train_qtil_.row(i) - query_qtil.row(m);
2536 const double k = magn * std::exp(-r.squaredNorm());
2537 const Eigen::VectorXd train_proj = Ji.transpose() * r.transpose();
2538 Kstar(i, m) = const_sigma2 + k;
2539 for (Eigen::Index c = 0; c < dof; ++c) {
2540 Kstar(ntrain + c * ntrain + i, m) = -2.0 * k * train_proj(c);
2541 }
2542 if (energy_only) continue;
2543 const Eigen::VectorXd query_proj = Jq.transpose() * r.transpose();
2544 const Eigen::MatrixXd jac_cross = Ji.transpose() * Jq;
2545 for (Eigen::Index d = 0; d < dof; ++d)
2546 Kstar(i, nquery + d * nquery + m) = 2.0 * k * query_proj(d);
2547
2548 for (Eigen::Index c = 0; c < dof; ++c) {
2549 const Eigen::Index row = ntrain + c * ntrain + i;
2550 for (Eigen::Index d = 0; d < dof; ++d) {
2551 Kstar(row, nquery + d * nquery + m) =
2552 k * (2.0 * jac_cross(c, d) -
2553 4.0 * train_proj(c) * query_proj(d));
2554 }
2555 }
2556 }
2557 }
2558 return Kstar.allFinite() &&
2559 (prior_diag == nullptr || prior_diag->allFinite());
2560}
2561
2562void GaussianProcessRegression::calculateVarianceHssvdDual(Observation& image1)
2563{
2564 calculateVarianceHssvd(image1);
2565}
2566
2573void GaussianProcessRegression::maybeDiagnoseHssvd()
2574{
2575 if (!use_hssvd_backend_) return;
2576 static bool printed = false;
2577 if (printed) return; // the validation line is one-shot only
2578 printed = true;
2579 if (!hssvd_basis_valid_) {
2580 std::fprintf(stderr,
2581 "[hssvd] stable-basis mapping unavailable; Cholesky\n");
2582 return;
2583 }
2584 // Only the dual-kernel path reaches this line, and that basis keeps no
2585 // Mercer modes, so numBasis() would print a 0 that reads as the rank.
2586 const Eigen::VectorXd& sr = hssvd_basis_.singularValues();
2587 const double eig_kept_min =
2588 sr.size() > 0 ? sr(sr.size() - 1) * sr(sr.size() - 1) : 0.0;
2589 std::fprintf(stderr,
2590 "[hssvd] dual-kernel rank=%d of nobs=%lld cond(Psi)=%.6f"
2591 " eig_kept_min=%.6e eig_dropped_max=%.6e\n",
2592 hssvd_basis_.rank(),
2593 static_cast<long long>(hssvd_basis_.numObs()),
2594 hssvd_basis_.conditionNumber(), eig_kept_min,
2595 hssvd_basis_.droppedEigenvalueMax());
2596}
2597
2599 Eigen::Index old_order, Eigen::Index new_order)
2600{
2601 if (old_order <= 0 || new_order <= old_order ||
2602 training_inverse_diagonal_.size() != old_order) {
2604 return;
2605 }
2606 const Eigen::Index added = new_order - old_order;
2607 EigenMatrix columns = EigenMatrix::Zero(new_order, added);
2608 columns.bottomRows(added).setIdentity();
2609 const auto solver = trainingSolver();
2610 const EigenMatrix whitened = solver.whitenColumns(columns);
2611 const EigenMatrix precision_columns = solver.unwhitenColumns(whitened);
2612 // For K' = [A B; B^T D], Q = K'^-1[:, new] has blocks
2613 // [-A^-1 B S^-1; S^-1], where S = D - B^T A^-1 B = Ls Ls^T.
2614 // The old inverse diagonal gains the row norms of Q_old Ls.
2615 // The lower block of L'^-1 [0; I] is Ls^-1, so a small triangular
2616 // solve forms that product without storing either full inverse.
2617 EigenMatrix correction = precision_columns.topRows(old_order).transpose();
2618 whitened.bottomRows(added)
2619 .transpose()
2620 .template triangularView<Eigen::Upper>()
2621 .solveInPlace(correction);
2622 Eigen::VectorXd diagonal(new_order);
2623 diagonal.head(old_order) = training_inverse_diagonal_ +
2624 correction.colwise().squaredNorm().transpose();
2625 diagonal.tail(added) = precision_columns.bottomRows(added).diagonal();
2626 if (!diagonal.allFinite() || (diagonal.array() <= 0.0).any()) {
2628 return;
2629 }
2630 training_inverse_diagonal_ = std::move(diagonal);
2631 ++inverse_diagonal_appends_for_testing_;
2632}
2633
2634#ifdef GPR_LINALG_SCALAPACK
2635bool GaussianProcessRegression::decomposeCovarianceMatrixScalapack(
2636 const EigenMatrix& x, const Eigen::VectorXd& x_ind)
2637{
2639 detail::validateRigidNullDeflationConfiguration(
2640 true, principled_nugget_, /*scalapack_backend=*/true);
2641 }
2642 auto& st = backend().distributed();
2643 const detail::ObservationChannelLayout channels(x_ind);
2644 const bool rectangular = channels.valid() &&
2645 channels.rowsPerChannel() > 0 &&
2647 const Index_t obs_tile_size =
2648 static_cast<Index_t>(detail::storedObservationChannelCount(x_ind));
2649 st.initialize(static_cast<int>(obs_tile_size));
2650 const auto discard_factor = [&]() {
2652 st.invalidate_L();
2653 st.invalidate_inv();
2654 training_cholesky_is_distributed_ = false;
2655 distributed_factor_signature_.valid = false;
2656 };
2657
2658 const int n = static_cast<int>(x.rows());
2659 if (report_level >= 2) {
2660 log_man << "ScaLAPACK decompose: start rows=" << n
2661 << " tile=" << obs_tile_size << " ranks=" << st.nprocs()
2662 << ".\n";
2663 }
2664 if (obs_tile_size <= 0 || n <= 0) {
2665 discard_factor();
2666 return false;
2667 }
2668
2669 const Index_t n_obs =
2670 rectangular ? static_cast<Index_t>(n) / obs_tile_size : 0;
2671
2672 const int local_rows = st.local_rows(n);
2673 const EigenMatrix x_tiled = permuteTrainingRows(x);
2674 const Eigen::VectorXd x_ind_tiled = permuteTrainingVector(x_ind);
2675 const Eigen::VectorXd constant_update = permuteTrainingVector(
2676 detail::constantCovarianceUpdate(const_cov_fun.get(), x_ind));
2677 const Eigen::VectorXd tile_ind = x_ind_tiled.head(obs_tile_size);
2678 Eigen::VectorXd tile_uDdim;
2679 extractUniqueIndices(tile_ind, tile_uDdim);
2680
2681 int desc[9];
2682 st.make_desc(n, n, desc);
2683
2684 auto owns_any_entry = [&](const int row_start, const Index_t row_count,
2685 const int col_start, const Index_t col_count) {
2686 for (Index_t local_j = 0; local_j < col_count; ++local_j) {
2687 const int global_j = col_start + static_cast<int>(local_j);
2688 for (Index_t local_i = 0; local_i < row_count; ++local_i) {
2689 const int global_i = row_start + static_cast<int>(local_i);
2690 if (st.owns_global_entry(global_i, global_j)) return true;
2691 }
2692 }
2693 return false;
2694 };
2695
2696 auto add_diagonal_shift = [&](std::vector<double>& cov_dist,
2697 const double shift) {
2698 if (shift == 0.0) return;
2699 for (int i = 0; i < n; ++i) {
2700 if (!st.owns_global_entry(i, i)) continue;
2701 const int local_row_start = st.local_index_for_global(
2702 i, st.block_size(), st.myrow(), st.nprow());
2703 const int local_col_start = st.local_index_for_global(
2704 i, st.block_size(), st.mycol(), st.npcol());
2705 cov_dist[static_cast<size_t>(local_row_start) +
2706 static_cast<size_t>(local_col_start) * local_rows] +=
2707 shift;
2708 }
2709 };
2710
2711 auto diagonal_sum = [&](const std::vector<double>& cov_dist) {
2712 // Exact accumulation: the trace does not depend on which rank owns
2713 // a diagonal entry.
2714 linalg::ExactSum sum;
2715 for (int i = 0; i < n; ++i) {
2716 if (!st.owns_global_entry(i, i)) continue;
2717 const int local_row_start = st.local_index_for_global(
2718 i, st.block_size(), st.myrow(), st.nprow());
2719 const int local_col_start = st.local_index_for_global(
2720 i, st.block_size(), st.mycol(), st.npcol());
2721 sum.add(
2722 cov_dist[static_cast<size_t>(local_row_start) +
2723 static_cast<size_t>(local_col_start) * local_rows]);
2724 }
2725 if (st.nprocs() > 1) backend().exact_sum_bcast(&sum, 1);
2726 return sum.value();
2727 };
2728
2729 // Per-row likelihood variance over the leading ~rows~ design rows, in
2730 // the tiled layout; part of what the cached factor represents.
2731 const auto training_noise = [&](Eigen::Index rows) {
2732 if (!rectangular)
2733 return lik_gaussian->evaluateTrainingVariance(
2734 x_tiled.topRows(rows));
2735 Eigen::VectorXd noise(rows);
2736 for (Eigen::Index start = 0; start + obs_tile_size <= rows;
2737 start += obs_tile_size)
2738 noise.segment(start, obs_tile_size) =
2739 lik_gaussian->evaluateTrainingVariance(
2740 x_tiled.middleRows(start, obs_tile_size));
2741 return noise;
2742 };
2743
2744 // Targets do not change the covariance. Keep its factor and inverse
2745 // diagonal when every input represented by the owned factor agrees.
2746 const auto can_reuse_factor = [&]() {
2747 const auto& signature = distributed_factor_signature_;
2748 if (!rectangular || !signature.valid || use_correction_ ||
2749 lik_gaussian == nullptr || sexpat_cov_func == nullptr ||
2750 sexpat_cov_func->usesManifoldChart() ||
2751 sexpat_cov_func->usesGeodesicHeatKernel() ||
2752 !st.cached_L_owned_by(this) || st.cached_n() != n ||
2753 signature.rows.rows() != n ||
2754 signature.rows.cols() != x_tiled.cols() ||
2755 signature.indices.size() != n || signature.constant.size() != n ||
2756 signature.noise.size() != n ||
2757 signature.configured_jitter != jitter_sigma2 ||
2758 signature.nugget_coefficient != kernelNuggetCoefficient(n) ||
2759 !detail::sameSexpatGeometry(
2760 signature.kernel_configuration, sexpat_cov_func->getConfInfo(),
2761 signature.far_field_radius, sexpat_cov_func->farFieldRadius()))
2762 return false;
2763 return (signature.rows.array() == x_tiled.array()).all() &&
2764 (signature.indices.array() == x_ind_tiled.array()).all() &&
2765 (signature.constant.array() == constant_update.array()).all() &&
2766 signature.theta == sexpat_cov_func->combineParameters() &&
2767 signature.noise == training_noise(n);
2768 };
2769 int reuse_factor = can_reuse_factor() ? 1 : 0;
2770 if (st.nprocs() > 1)
2771 MPI_Allreduce(MPI_IN_PLACE, &reuse_factor, 1, MPI_INT, MPI_MIN,
2772 st.world_comm());
2773 if (reuse_factor != 0) {
2774 C.resize(0, 0);
2776 training_cholesky_is_distributed_ = true;
2777 return true;
2778 }
2779
2780 auto build_distributed_covariance = [&](Index_t first_obs) {
2781 std::vector<double> cov_dist(
2782 static_cast<size_t>(local_rows) * st.local_cols(n), 0.0);
2783 if (!rectangular) {
2784 EigenMatrix covariance;
2785 evaluateTrainingCovarianceMatrix(x, x_ind, covariance,
2786 /*serial_per_rank=*/true,
2787 /*include_constant=*/false);
2789 covariance =
2791 for (int column = 0; column < n; ++column)
2792 for (int row = column; row < n; ++row) {
2793 if (!st.owns_global_entry(row, column)) continue;
2794 const int local_row = st.local_index_for_global(
2795 row, st.block_size(), st.myrow(), st.nprow());
2796 const int local_column = st.local_index_for_global(
2797 column, st.block_size(), st.mycol(), st.npcol());
2798 cov_dist[local_row +
2799 static_cast<std::size_t>(local_column) *
2800 local_rows] = covariance(row, column);
2801 }
2802 return cov_dist;
2803 }
2804 EigenMatrix tile_cov;
2805 EigenMatrix tile_temp;
2806 pairlocal::TiledLayoutSource tiles;
2807 if (use_pair_local_tiles_ && !sexpat_cov_func->usesManifoldChart() &&
2808 !sexpat_cov_func->usesGeodesicHeatKernel())
2809 (void)tiles.prepare(sexpat_cov_func->getConfInfo(),
2810 sexpat_cov_func->combineParameters(), x_tiled,
2811 obs_tile_size, tile_ind);
2812
2813 for (Index_t obs_i = first_obs; obs_i < n_obs; ++obs_i) {
2814 const int row_start = static_cast<int>(obs_i * obs_tile_size);
2815 const EigenMatrix x_tile_i =
2816 x_tiled.middleRows(row_start, obs_tile_size);
2817
2818 for (Index_t obs_j = 0; obs_j <= obs_i; ++obs_j) {
2819 const int col_start = static_cast<int>(obs_j * obs_tile_size);
2820 if (st.block_size() == obs_tile_size
2821 ? !st.owns_global_entry(row_start, col_start)
2822 : !owns_any_entry(row_start, obs_tile_size, col_start,
2823 obs_tile_size))
2824 continue;
2825
2826 const EigenMatrix x_tile_j =
2827 x_tiled.middleRows(col_start, obs_tile_size);
2828 tile_cov.resize(obs_tile_size, obs_tile_size);
2829 tile_cov.setZero();
2830
2831 if (tiles.ready()) {
2832 tiles.tile(obs_i, obs_j, tile_temp);
2833 } else {
2834 applyCrossCovarianceFunction(
2835 x_tile_i, x_tile_j, tile_ind, tile_uDdim, tile_ind,
2836 tile_uDdim, *sexpat_cov_func, tile_temp, false);
2837 }
2838 tile_cov.noalias() += tile_temp;
2839
2840 if (obs_i == obs_j) {
2841 applyKernelNugget(tile_cov, n);
2842 detail::addSeparatedConstantNugget(
2843 const_cov_fun.get(), tile_ind,
2844 kernelNuggetCoefficient(n), tile_cov);
2845 tile_cov.diagonal() +=
2846 lik_gaussian->evaluateTrainingVariance(x_tile_i);
2847 }
2848
2849 if (st.block_size() == obs_tile_size) {
2850 const int dist_i = st.local_index_for_global(
2851 row_start, st.block_size(), st.myrow(), st.nprow());
2852 const int dist_j = st.local_index_for_global(
2853 col_start, st.block_size(), st.mycol(), st.npcol());
2854 Eigen::Map<EigenMatrix, 0, Eigen::OuterStride<>> target(
2855 cov_dist.data() + static_cast<size_t>(dist_i) +
2856 static_cast<size_t>(dist_j) * local_rows,
2857 obs_tile_size, obs_tile_size,
2858 Eigen::OuterStride<>(local_rows));
2859 target = tile_cov;
2860 continue;
2861 }
2862 for (Index_t local_j = 0; local_j < obs_tile_size; ++local_j) {
2863 const int global_j = col_start + static_cast<int>(local_j);
2864 for (Index_t local_i = 0; local_i < obs_tile_size;
2865 ++local_i) {
2866 const int global_i =
2867 row_start + static_cast<int>(local_i);
2868 if (!st.owns_global_entry(global_i, global_j)) {
2869 continue;
2870 }
2871 const int dist_i = st.local_index_for_global(
2872 global_i, st.block_size(), st.myrow(), st.nprow());
2873 const int dist_j = st.local_index_for_global(
2874 global_j, st.block_size(), st.mycol(), st.npcol());
2875 cov_dist[static_cast<size_t>(dist_i) +
2876 static_cast<size_t>(dist_j) * local_rows] =
2877 tile_cov(local_i, local_j);
2878 }
2879 }
2880 }
2881 }
2882
2883 return cov_dist;
2884 };
2885
2886 // Rows appended to a design the cached factor already represents
2887 // extend that factor: with K' = [K B^T; B C] and K = L L^T,
2888 // L' = [L 0; L21 L22] with L21 = B L^-T (one triangular solve,
2889 // O(n^2 k)), L22 L22^T = C - L21 L21^T (O(n k^2 + k^3)). The new
2890 // blocks carry the constant-kernel update the cached factor holds as
2891 // a rank-one update, and the jitter the cached factor was built with;
2892 // a count-dependent nugget requires a full rebuild.
2893 auto attempt_append = [&]() -> bool {
2894 auto& signature = distributed_factor_signature_;
2895 if (!rectangular || !signature.valid || use_correction_ ||
2896 principled_nugget_ || signature.nugget_coefficient != 0.0 ||
2897 lik_gaussian == nullptr || sexpat_cov_func->usesManifoldChart() ||
2898 sexpat_cov_func->usesGeodesicHeatKernel() ||
2899 signature.configured_jitter != jitter_sigma2 ||
2900 !detail::sameSexpatGeometry(
2901 signature.kernel_configuration, sexpat_cov_func->getConfInfo(),
2902 signature.far_field_radius, sexpat_cov_func->farFieldRadius()))
2903 return false;
2904 const int n_old = static_cast<int>(signature.rows.rows());
2905 if (n_old <= 0 || n <= n_old || (n - n_old) % obs_tile_size != 0)
2906 return false;
2907 if (!st.cached_L_owned_by(this) || st.cached_n() != n_old) return false;
2908 if (signature.rows.cols() != x_tiled.cols() ||
2909 !(x_tiled.topRows(n_old).array() == signature.rows.array()).all())
2910 return false;
2911 if (signature.indices.size() != n_old ||
2912 !(x_ind_tiled.head(n_old).array() == signature.indices.array())
2913 .all())
2914 return false;
2915 if (signature.constant.size() != n_old ||
2916 !(constant_update.head(n_old).array() == signature.constant.array())
2917 .all())
2918 return false;
2919 if (signature.theta.size() == 0 ||
2920 signature.theta != sexpat_cov_func->combineParameters())
2921 return false;
2922 const Eigen::VectorXd noise_now = training_noise(n_old);
2923 if (signature.noise.size() != n_old ||
2924 !(noise_now.array() == signature.noise.array()).all())
2925 return false;
2926 auto snapshot = st.take_cached_L(this);
2927 // Every derived copy of the old factor (the redistributed solve
2928 // layout, the inverse) is stale at the new order; the full path
2929 // clears them before factorizing and so must the append.
2930 st.invalidate_L();
2931 st.invalidate_inv();
2932 if (!snapshot.valid()) return false;
2933 if (snapshot.values.empty()) snapshot.values.resize(1, 0.0);
2934 const int k = n - n_old;
2935#ifdef GPR_LINALG_SLATE
2936 const bool canonical_append = st.reproducible();
2937#else
2938 const bool canonical_append = st.tile_kernels(desc, "pdpotrf");
2939#endif
2940 // The tile kernels extend a factor from a tile boundary. When the
2941 // old order ends inside a computation tile, the rows of that tile
2942 // are rebuilt from the covariance and factored with the new rows;
2943 // the factor of the leading n_keep rows and columns is kept.
2944 const int n_keep = canonical_append ? n_old / desc[4] * desc[4] : n_old;
2945 const Index_t first_obs = static_cast<Index_t>(n_keep) / obs_tile_size;
2946 std::vector<double> factor;
2947 {
2948 ScopedPhaseTimer assembly_timer(PhaseTimers::assembly_seconds);
2949 factor = build_distributed_covariance(first_obs);
2950 }
2951 if (factor.empty()) factor.resize(1, 0.0);
2952 ++distributed_training_covariance_assemblies_for_testing_;
2953 const auto local_offset = [&](int i, int j) {
2954 const int local_i = st.local_index_for_global(
2955 i, st.block_size(), st.myrow(), st.nprow());
2956 const int local_j = st.local_index_for_global(
2957 j, st.block_size(), st.mycol(), st.npcol());
2958 return static_cast<size_t>(local_i) +
2959 static_cast<size_t>(local_j) * local_rows;
2960 };
2961 const bool constant_active = !constant_update.isZero(0.0);
2962 const double shift = jitter_sigma2 + signature.jitter;
2963 for (int i = n_keep; i < n; ++i) {
2964 for (int j = 0; j <= i; ++j) {
2965 if (!st.owns_global_entry(i, j)) continue;
2966 double& entry = factor[local_offset(i, j)];
2967 if (constant_active)
2968 entry += constant_update(i) * constant_update(j);
2969 if (i == j) entry += shift;
2970 }
2971 }
2972 ScopedPhaseTimer cholesky_timer(PhaseTimers::cholesky_seconds);
2973 const int* old_desc = snapshot.descriptor.data();
2974 if (old_desc[1] == desc[1] && old_desc[4] == desc[4] &&
2975 old_desc[5] == desc[5] && old_desc[6] == desc[6] &&
2976 old_desc[7] == desc[7]) {
2977 // Same grid and blocking: a global entry keeps its local
2978 // position, so the old factor moves column by column with
2979 // offsets in std::size_t. Cpdgemr2d forms LP64 offsets and
2980 // cannot reach past 2^31 - 1 local entries.
2981 const int old_rows = st.local_rows(n_keep);
2982 const int old_cols = st.local_cols(n_keep);
2983 for (int column = 0; column < old_cols && old_rows > 0; ++column)
2984 std::copy_n(
2985 snapshot.values.data() +
2986 static_cast<std::size_t>(column) * old_desc[8],
2987 old_rows,
2988 factor.data() + static_cast<std::size_t>(column) * desc[8]);
2989 } else if (n_keep > 0) {
2990 st.require_lp64(old_desc, "Cpdgemr2d");
2991 st.require_lp64(desc, "Cpdgemr2d");
2992 Cpdgemr2d(n_keep, n_keep, snapshot.values.data(), 1, 1, old_desc,
2993 factor.data(), 1, 1, desc, st.context());
2994 }
2995#ifdef GPR_LINALG_SLATE
2996 if (canonical_append) {
2997 linalg::slate_kernels::configure_nested_blas_threading(st);
2998 if (!linalg::canonical::potrfLower(st, factor.data(), desc, n,
2999 n_keep)) {
3000 signature.valid = false;
3001 return false;
3002 }
3003 } else if (!linalg::slate_kernels::rank_block_cholesky_append_lower(
3004 factor.data(), desc, n, n_old, st)) {
3005 signature.valid = false;
3006 return false;
3007 }
3008#else
3009 if (canonical_append) {
3010 // Tile-ordered extension: the border tiles receive the same
3011 // updates in the same order whatever the process grid.
3012 linalg::ScopedTileKernelThreads tile_threads(st);
3013 if (!linalg::canonical::potrfLower(st, factor.data(), desc, n,
3014 n_keep)) {
3015 signature.valid = false;
3016 return false;
3017 }
3018 } else {
3019 linalg::KernelWall wall(linalg::KernelWall::Kind::Factor);
3020 const int one = 1;
3021 const int trailing = n_old + 1;
3022 const double plus_one = 1.0, minus_one = -1.0;
3023 pdtrsm_("R", "L", "T", "N", &k, &n_old, &plus_one, factor.data(),
3024 &one, &one, desc, factor.data(), &trailing, &one, desc);
3025 pdsyrk_("L", "N", &k, &n_old, &minus_one, factor.data(), &trailing,
3026 &one, desc, &plus_one, factor.data(), &trailing, &trailing,
3027 desc);
3028 int info = 0;
3029 pdpotrf_("L", &k, factor.data(), &trailing, &trailing, desc, &info);
3030 if (info != 0) {
3031 signature.valid = false;
3032 return false;
3033 }
3034 }
3035#endif
3036 st.cache_L(std::move(factor), desc, n);
3037 st.claim_cached_L(this);
3040 ++distributed_factor_appends_for_testing_;
3041 signature.rows = x_tiled;
3042 signature.indices = x_ind_tiled;
3043 signature.constant = constant_update;
3044 signature.noise = training_noise(n);
3045 signature.observations = n_obs;
3046 if (report_level >= 2) {
3047 log_man << "ScaLAPACK decompose: appended " << k
3048 << " rows to the cached factor of order " << n_old << ".\n";
3049 }
3050 return true;
3051 };
3052 if (attempt_append()) {
3054 C.resize(0, 0);
3056 training_cholesky_is_distributed_ = true;
3057 return true;
3058 }
3059 if (require_factor_append_) return false;
3060 discard_factor();
3061
3062 const std::vector<double> base_covariance = build_distributed_covariance(0);
3063 ++distributed_training_covariance_assemblies_for_testing_;
3064 if (report_level >= 2) {
3065 log_man << "ScaLAPACK decompose: covariance assembled local_rows="
3066 << local_rows << " local_cols=" << st.local_cols(n) << ".\n";
3067 }
3068
3069 auto attempt_factorization = [&](const double extra_jitter) {
3070 std::vector<double> trial = base_covariance;
3071 add_diagonal_shift(trial, jitter_sigma2 + extra_jitter);
3072
3073 if (use_correction_) {
3074 const double K_sum =
3075 diagonal_sum(trial) + constant_update.squaredNorm();
3076 const double denom =
3077 1.0 / correction_eps_ - static_cast<double>(n) * n;
3078 if (std::abs(denom) > 1e-30) {
3079 const double corr = K_sum * K_sum / denom;
3080 add_diagonal_shift(trial, corr);
3081 }
3082 }
3083
3084 if (report_level >= 2) {
3085 log_man << "ScaLAPACK decompose: cholesky start extra_jitter="
3086 << extra_jitter << ".\n";
3087 }
3088 ScopedPhaseTimer cholesky_timer(PhaseTimers::cholesky_seconds);
3089 return backend().cholesky_distributed(std::move(trial), desc, n, L) &&
3090 backend().cholesky_rank_update(L, constant_update);
3091 };
3092
3093 const auto record_signature = [&](double extra_jitter) {
3094 auto& signature = distributed_factor_signature_;
3095 signature.rows = x_tiled;
3096 signature.indices = x_ind_tiled;
3097 signature.constant = constant_update;
3098 signature.noise =
3099 lik_gaussian != nullptr ? training_noise(n) : Eigen::VectorXd();
3100 signature.theta = sexpat_cov_func->combineParameters();
3101 signature.kernel_configuration = sexpat_cov_func->getConfInfo();
3102 signature.far_field_radius = sexpat_cov_func->farFieldRadius();
3103 signature.observations = n_obs;
3104 signature.configured_jitter = jitter_sigma2;
3105 signature.jitter = extra_jitter;
3106 signature.nugget_coefficient = kernelNuggetCoefficient(n);
3107 signature.valid = rectangular && !use_correction_ &&
3108 lik_gaussian != nullptr &&
3109 !sexpat_cov_func->usesManifoldChart() &&
3110 !sexpat_cov_func->usesGeodesicHeatKernel();
3111 };
3112 if (attempt_factorization(0.0)) {
3113 st.claim_cached_L(this);
3114 record_signature(0.0);
3115 if (report_level >= 2) {
3116 log_man << "ScaLAPACK decompose: cholesky done extra_jitter=0.\n";
3117 }
3118 C.resize(0, 0);
3120 training_cholesky_is_distributed_ = true;
3121 return true;
3122 }
3123
3124 double rescue_jitter = std::max(jitter_sigma2, 1e-10);
3125 for (int attempt = 0; attempt < 5; ++attempt) {
3126 if (attempt_factorization(rescue_jitter)) {
3127 st.claim_cached_L(this);
3128 record_signature(rescue_jitter);
3129 if (report_level >= 2) {
3130 log_man << "ScaLAPACK decompose: cholesky done extra_jitter="
3131 << rescue_jitter << ".\n";
3132 }
3133 C.resize(0, 0);
3135 training_cholesky_is_distributed_ = true;
3136 return true;
3137 }
3138 rescue_jitter *= 10.0;
3139 }
3140
3141 C.resize(0, 0);
3143 training_cholesky_is_distributed_ = false;
3144 return false;
3145}
3146#endif
3147
3149 Eigen::Index observations) const
3150{
3151#ifdef GPR_LINALG_KOKKOS
3153 !principled_nugget_) {
3154 if (!device_posterior_->matchesConfiguration(
3155 sexpat_cov_func->getConfInfo(),
3156 sexpat_cov_func->farFieldRadius()))
3157 return false;
3158 const auto& lengths = sexpat_cov_func->getLengthScaleRef();
3159 return device_posterior_->canAppend(
3160 observations,
3161 lik_gaussian->evaluateTrainingVariance(
3162 device_posterior_->trainingRows()),
3163 Eigen::Map<const Eigen::VectorXd>(lengths.data(), lengths.size()),
3164 sexpat_cov_func->getMagnSigma2(), const_cov_fun->getConstSigma2(),
3165 jitter_sigma2);
3166 }
3167#endif
3168#ifdef GPR_LINALG_SCALAPACK
3169 const auto& signature = distributed_factor_signature_;
3170 if (!signature.valid || sexpat_cov_func == nullptr ||
3171 signature.rows.rows() <= 0 || !training_cholesky_is_distributed_ ||
3172 use_correction_ || principled_nugget_ ||
3173 signature.nugget_coefficient != 0.0 ||
3174 sexpat_cov_func->usesManifoldChart() ||
3175 sexpat_cov_func->usesGeodesicHeatKernel() ||
3176 signature.configured_jitter != jitter_sigma2 ||
3177 !detail::sameSexpatGeometry(
3178 signature.kernel_configuration, sexpat_cov_func->getConfInfo(),
3179 signature.far_field_radius, sexpat_cov_func->farFieldRadius()))
3180 return false;
3181 return observations > signature.observations &&
3182 signature.theta == sexpat_cov_func->combineParameters();
3183#else
3184 const auto& signature = serial_factor_signature_;
3185 const Eigen::Index rows = signature.rows.rows();
3186 if (!signature.valid || rows <= 0 || signature.indices.size() != rows ||
3187 !signature.indices.allFinite())
3188 return false;
3189 const Eigen::Index channels =
3190 detail::storedObservationChannelCount(signature.indices);
3191 if (channels <= 0 || rows % channels != 0) return false;
3192 for (Eigen::Index row = channels; row < rows; ++row)
3193 if (signature.indices(row) != signature.indices(row % channels))
3194 return false;
3195 const Eigen::Index expected_rows = activeFactorOrder(rows);
3196 if (observations <= rows / channels || sexpat_cov_func == nullptr ||
3197 lik_gaussian == nullptr || use_correction_ || principled_nugget_ ||
3198 signature.nugget_coefficient != 0.0 || signature.manifold_chart ||
3199 sexpat_cov_func->usesManifoldChart() ||
3200 signature.geodesic_heat != sexpat_cov_func->usesGeodesicHeatKernel() ||
3201 signature.heat_identity != sexpat_cov_func->geodesicHeatKernel() ||
3202 signature.jitter_sigma2 != jitter_sigma2 ||
3203 signature.theta != sexpat_cov_func->combineParameters() ||
3205 !detail::sameSexpatGeometry(
3206 signature.kernel_geometry, sexpat_cov_func->getConfInfo(),
3207 signature.far_field_radius, sexpat_cov_func->farFieldRadius()) ||
3208 L.rows() != expected_rows || L.cols() != expected_rows ||
3209 C.rows() != expected_rows || C.cols() != expected_rows ||
3210 signature.indices.size() != rows || signature.constant.size() != rows ||
3211 signature.noise.size() != rows)
3212 return false;
3213 const Eigen::VectorXd noise =
3214 lik_gaussian->evaluateTrainingVariance(signature.rows);
3215 const Eigen::VectorXd constant = detail::constantCovarianceUpdate(
3216 const_cov_fun.get(), signature.indices);
3217 return noise == signature.noise && constant == signature.constant;
3218#endif
3219}
3220
3221bool GaussianProcessRegression::reuseSerialFactorIfCurrent(
3222 const EigenMatrix& x_ordered, const Eigen::VectorXd& ind_ordered,
3223 const Eigen::VectorXd& constant_update)
3224{
3225#ifdef GPR_LINALG_SCALAPACK
3226 (void)x_ordered;
3227 (void)ind_ordered;
3228 (void)constant_update;
3229 return false;
3230#else
3231 const auto& signature = serial_factor_signature_;
3232 const Eigen::Index n = x_ordered.rows();
3233 const Eigen::Index expected_rows = activeFactorOrder(n);
3234 if (!signature.valid || use_correction_ || principled_nugget_ ||
3235 signature.nugget_coefficient != 0.0 || lik_gaussian == nullptr ||
3236 sexpat_cov_func == nullptr || n <= 0 ||
3238 L.rows() != expected_rows || L.cols() != expected_rows ||
3239 C.rows() != expected_rows || C.cols() != expected_rows)
3240 return false;
3241 // The factor already belongs to this operator. A chart or geodesic
3242 // flag that has changed since it was recorded is a different kernel.
3243 if (sexpat_cov_func->usesManifoldChart() != signature.manifold_chart ||
3244 sexpat_cov_func->usesGeodesicHeatKernel() != signature.geodesic_heat ||
3245 signature.chart_identity != sexpat_cov_func->manifoldChart() ||
3246 signature.heat_identity != sexpat_cov_func->geodesicHeatKernel())
3247 return false;
3248 if (!detail::sameSexpatGeometry(
3249 signature.kernel_geometry, sexpat_cov_func->getConfInfo(),
3250 signature.far_field_radius, sexpat_cov_func->farFieldRadius()))
3251 return false;
3252 if (signature.jitter_sigma2 != jitter_sigma2 ||
3253 signature.rows.cols() != x_ordered.cols() ||
3254 signature.indices.size() != n || signature.constant.size() != n ||
3255 signature.noise.size() != n || signature.theta.size() == 0)
3256 return false;
3257 if (!(x_ordered.array() == signature.rows.array()).all() ||
3258 !(ind_ordered.array() == signature.indices.array()).all() ||
3259 !(constant_update.array() == signature.constant.array()).all() ||
3260 signature.theta != sexpat_cov_func->combineParameters())
3261 return false;
3262 const Eigen::VectorXd noise =
3263 lik_gaussian->evaluateTrainingVariance(x_ordered);
3264 if (noise.size() != n || !(noise.array() == signature.noise.array()).all())
3265 return false;
3267 ++serial_factor_reuses_for_testing_;
3268 return true;
3269#endif
3270}
3271
3273{
3274 const bool decomposed = decomposeCovarianceMatrix(R_matrix, R_indices);
3275#ifdef GPR_LINALG_KOKKOS
3276 if (decomposed && hasDevicePosterior() && device_targets_placeholder_ &&
3277 energy_and_gradient.size() == R_matrix.rows())
3278 refreshPosteriorWeights(energy_and_gradient);
3279#endif
3280 return decomposed;
3281}
3282
3284 const EigenMatrix& x, const Eigen::VectorXd& x_ind)
3285{
3286#ifdef GPR_LINALG_KOKKOS
3287 if (const auto value = conditionDevicePosterior(
3288 x, x_ind, Eigen::VectorXd::Zero(x.rows()), true))
3289 return std::isfinite(*value);
3290#endif
3292 // The rank-one constant kernel needs the permuted design; it is bound
3293 // once the permutation is in place below.
3294 Eigen::VectorXd factor_constant;
3295 const auto timedFactor = [&](const EigenMatrix& matrix) {
3296 ++full_cholesky_factorizations_for_testing_;
3299 backend(), matrix, factor_constant, L);
3300 if (accepted)
3302 else
3304 return accepted;
3305 };
3306#ifdef GPR_LINALG_SCALAPACK
3307 return decomposeCovarianceMatrixScalapack(x, x_ind);
3308#else
3309 EigenMatrix x_ordered = x;
3310 Eigen::VectorXd ind_ordered = x_ind;
3311 if (hasTrainingPermutation()) {
3313 ind_ordered = permuteTrainingVector(x_ind);
3314 }
3315 const Eigen::VectorXd constant_update = permuteTrainingVector(
3316 detail::constantCovarianceUpdate(const_cov_fun.get(), x_ind));
3317 const Eigen::Index n_rows = x_ordered.rows();
3318 auto invalidate_serial_signature = [&]() {
3319 serial_factor_signature_.valid = false;
3320 };
3321 auto record_serial_signature = [&]() {
3322 auto& signature = serial_factor_signature_;
3323 signature.rows = x_ordered;
3324 signature.indices = ind_ordered;
3325 signature.constant = constant_update;
3326 signature.jitter_sigma2 = jitter_sigma2;
3327 signature.nugget_coefficient = kernelNuggetCoefficient(n_rows);
3328 if (lik_gaussian != nullptr) {
3329 signature.noise = lik_gaussian->evaluateTrainingVariance(x_ordered);
3330 } else {
3331 signature.noise.resize(0);
3332 }
3333 if (sexpat_cov_func != nullptr) {
3334 signature.theta = sexpat_cov_func->combineParameters();
3335 signature.manifold_chart = sexpat_cov_func->usesManifoldChart();
3336 signature.geodesic_heat = sexpat_cov_func->usesGeodesicHeatKernel();
3337 signature.chart_identity = sexpat_cov_func->manifoldChart();
3338 signature.heat_identity = sexpat_cov_func->geodesicHeatKernel();
3339 signature.kernel_geometry = sexpat_cov_func->getConfInfo();
3340 signature.far_field_radius = sexpat_cov_func->farFieldRadius();
3341 } else {
3342 signature.theta.resize(0);
3343 signature.manifold_chart = false;
3344 signature.geodesic_heat = false;
3345 signature.chart_identity.reset();
3346 signature.heat_identity.reset();
3347 signature.kernel_geometry = AtomsConfiguration{};
3348 signature.far_field_radius = 0.0;
3349 }
3350 signature.valid = lik_gaussian != nullptr &&
3351 sexpat_cov_func != nullptr && !use_correction_ &&
3352 L.rows() == activeFactorOrder(n_rows) &&
3353 C.rows() == activeFactorOrder(n_rows);
3355 };
3356 // Fixed hyperparameters: the new permuted design is the cached one plus
3357 // k rows. Reuse the leading covariance and extend its Cholesky factor.
3358 // Woodbury on the inverse is the same block step; the factor is what
3359 // the solves store.
3360 auto try_serial_append = [&]() -> bool {
3361 auto& signature = serial_factor_signature_;
3362 const Eigen::Index n_old = signature.rows.rows();
3363 const Eigen::Index m_old = activeFactorOrder(n_old);
3364 if (!signature.valid || use_correction_ || principled_nugget_ ||
3365 signature.nugget_coefficient != 0.0 || lik_gaussian == nullptr ||
3366 sexpat_cov_func == nullptr ||
3368 return false;
3369 if (rigid_deflation_.active && rigid_deflation_.full_rows != n_old)
3370 return false;
3371 // Theta does not identify the manifold chart or the geodesic
3372 // summand. The border below is the same cross operator as a full
3373 // factor, including a geodesic summand already present in the saved
3374 // factor. A chart, or a geodesic flag that differs from that factor,
3375 // rebuilds. Immutable chart and heat-kernel identities bind the factor
3376 // to its anchor, weight, and reference path.
3377 if (sexpat_cov_func->usesManifoldChart() || signature.manifold_chart ||
3378 sexpat_cov_func->usesGeodesicHeatKernel() !=
3379 signature.geodesic_heat ||
3380 signature.heat_identity != sexpat_cov_func->geodesicHeatKernel())
3381 return false;
3382 // factor_epoch_ counts a fitted posterior, not an objective
3383 // evaluation that borrows C and L. Geometry identity, including the
3384 // active type count, is detail::sameSexpatGeometry.
3385 if (!detail::sameSexpatGeometry(
3386 signature.kernel_geometry, sexpat_cov_func->getConfInfo(),
3387 signature.far_field_radius, sexpat_cov_func->farFieldRadius()))
3388 return false;
3389 if (n_old <= 0 || m_old <= 0 || n_rows <= n_old || L.rows() != m_old ||
3390 L.cols() != m_old || C.rows() != m_old || C.cols() != m_old)
3391 return false;
3392 if (signature.jitter_sigma2 != jitter_sigma2) return false;
3393 if (signature.rows.cols() != x_ordered.cols() ||
3394 signature.indices.size() != n_old ||
3395 signature.constant.size() != n_old ||
3396 signature.noise.size() != n_old || signature.theta.size() == 0)
3397 return false;
3398 if (!(x_ordered.topRows(n_old).array() == signature.rows.array())
3399 .all() ||
3400 !(ind_ordered.head(n_old).array() == signature.indices.array())
3401 .all() ||
3402 !(constant_update.head(n_old).array() == signature.constant.array())
3403 .all() ||
3404 signature.theta != sexpat_cov_func->combineParameters())
3405 return false;
3406 const Eigen::VectorXd noise_now =
3407 lik_gaussian->evaluateTrainingVariance(x_ordered);
3408 if (noise_now.size() != n_rows ||
3409 !(noise_now.head(n_old).array() == signature.noise.array()).all())
3410 return false;
3411
3412 const Eigen::Index k = n_rows - n_old;
3413 const EigenMatrix x_new = x_ordered.bottomRows(k);
3414 const Eigen::VectorXd ind_new = ind_ordered.tail(k);
3415 // Cross-covariance assembly consumes contiguous channel blocks;
3416 // the cached factor orders every geometry's channels together.
3417 const auto new_groups = buildStructuredPermutation(ind_new);
3418 const auto all_groups = buildStructuredPermutation(ind_ordered);
3419 const EigenMatrix x_new_grouped = permuteMatrixRows(x_new, new_groups);
3420 const EigenMatrix x_all_grouped =
3421 permuteMatrixRows(x_ordered, all_groups);
3422 const Eigen::VectorXd ind_new_grouped =
3423 permuteVector(ind_new, new_groups);
3424 const Eigen::VectorXd ind_all_grouped =
3425 permuteVector(ind_ordered, all_groups);
3426 Eigen::VectorXd u_new, u_all;
3427 extractUniqueIndices(ind_new_grouped, u_new);
3428 extractUniqueIndices(ind_all_grouped, u_all);
3429 EigenMatrix grouped_kernel;
3430 applyCrossCovarianceFunction(x_new_grouped, x_all_grouped,
3431 ind_new_grouped, u_new, ind_all_grouped,
3432 u_all, *sexpat_cov_func, grouped_kernel,
3433 /*do_reduce=*/false);
3434 if (grouped_kernel.rows() != k || grouped_kernel.cols() != n_rows ||
3435 !grouped_kernel.allFinite())
3436 return false;
3437 EigenMatrix kernel(k, n_rows);
3438 for (Eigen::Index col = 0; col < n_rows; ++col)
3439 for (Eigen::Index row = 0; row < k; ++row)
3440 kernel(new_groups.perm[row], all_groups.perm[col]) =
3441 grouped_kernel(row, col);
3442 grouped_kernel.resize(0, 0);
3443 kernel += constant_update.tail(k) * constant_update.transpose();
3444
3445 EigenMatrix left_block;
3446 EigenMatrix right_block;
3447 detail::RigidDeflationState tail_state;
3448 RigidDeflationDiagnostic tail_diag;
3449 if (rigid_deflation_.active) {
3450 const AtomsConfiguration& effective_conf =
3451 sexpat_cov_func->getConfInfo().atoms_mov.type.size() > 0
3452 ? sexpat_cov_func->getConfInfo()
3453 : atoms_config;
3454 if (!detail::prepareRigidDeflationState(
3455 use_rigid_null_deflation_, /*factor_order=*/true,
3456 effective_conf, x_new, ind_new, noise_now.tail(k),
3457 jitter_sigma2, /*unsupported=*/false, tail_state,
3458 tail_diag))
3459 return false;
3460 EigenMatrix right_raw = kernel.rightCols(k);
3461 if (!detail::verifySignalKernelRigidNullspace(right_raw, tail_state,
3462 tail_diag))
3463 return false;
3464 EigenMatrix left_raw = kernel.leftCols(n_old);
3465 if (!detail::verifyCrossBlockRigidNullspace(
3466 left_raw, tail_state, rigid_deflation_, tail_diag))
3467 return false;
3468 left_block = tail_state.projectRows(left_raw);
3469 left_block = rigid_deflation_.projectRows(left_block.transpose())
3470 .transpose();
3471 right_block = tail_state.projectSymmetric(right_raw);
3472 for (Eigen::Index i = 0; i < tail_state.num_geometries; ++i) {
3473 const auto& blk =
3474 tail_state.blocks[static_cast<std::size_t>(i)];
3475 right_block(blk.deflated_row_offset, blk.deflated_row_offset) +=
3476 noise_now(n_old + blk.full_row_offset) + jitter_sigma2;
3477 if (blk.deflated_grad_dim > 0) {
3478 right_block.diagonal()
3479 .segment(blk.deflated_row_offset + 1,
3480 blk.deflated_grad_dim)
3481 .array() += blk.grad_noise_variance;
3482 }
3483 }
3484 } else {
3485 kernel.rightCols(k).diagonal() += noise_now.tail(k);
3486 if (jitter_sigma2 > 0.0)
3487 kernel.rightCols(k).diagonal().array() += jitter_sigma2;
3488 left_block = kernel.leftCols(n_old);
3489 right_block = kernel.rightCols(k);
3490 }
3491
3492 const Eigen::Index k_eff = right_block.rows();
3493 Eigen::MatrixXd border_old = left_block.transpose();
3494 L.triangularView<Eigen::Lower>().solveInPlace(border_old);
3495 Eigen::MatrixXd schur(k_eff, k_eff);
3496 // A constant energy covariance can dwarf the conditional variance.
3497 // Accumulate the small Schur block at wider precision so cancellation
3498 // does not discard the likelihood noise. The large triangular solve
3499 // retains the backend's dense arithmetic and no wider matrix is kept.
3500 for (Eigen::Index col = 0; col < k_eff; ++col) {
3501 for (Eigen::Index row = col; row < k_eff; ++row) {
3502 long double value =
3503 0.5L * (static_cast<long double>(right_block(row, col)) +
3504 static_cast<long double>(right_block(col, row)));
3505 for (Eigen::Index i = 0; i < m_old; ++i)
3506 value -= static_cast<long double>(border_old(i, row)) *
3507 static_cast<long double>(border_old(i, col));
3508 schur(row, col) = schur(col, row) = static_cast<double>(value);
3509 }
3510 }
3511 Eigen::LLT<Eigen::MatrixXd> schur_factor(schur);
3512 if (schur_factor.info() != Eigen::Success) return false;
3513
3514 const Eigen::Index m_new = m_old + k_eff;
3515 EigenMatrix factor = EigenMatrix::Zero(m_new, m_new);
3516 factor.topLeftCorner(m_old, m_old) = L;
3517 factor.bottomLeftCorner(k_eff, m_old) = border_old.transpose();
3518 factor.bottomRightCorner(k_eff, k_eff) = schur_factor.matrixL();
3519 signature.valid = false;
3520 L = std::move(factor);
3522 EigenMatrix covariance = EigenMatrix::Zero(m_new, m_new);
3523 covariance.topLeftCorner(m_old, m_old) = C;
3524 covariance.bottomLeftCorner(k_eff, m_old) = left_block;
3525 covariance.topRightCorner(m_old, k_eff) = left_block.transpose();
3526 covariance.bottomRightCorner(k_eff, k_eff) = right_block;
3527 C = std::move(covariance);
3528 if (rigid_deflation_.active) {
3529 for (auto blk: tail_state.blocks) {
3530 blk.full_row_offset += n_old;
3531 blk.deflated_row_offset += m_old;
3532 rigid_deflation_.blocks.push_back(std::move(blk));
3533 }
3534 rigid_deflation_.full_rows = n_rows;
3535 rigid_deflation_.deflated_rows = m_new;
3536 rigid_deflation_.num_geometries += tail_state.num_geometries;
3537 rigid_deflation_diag_.full_rows = n_rows;
3538 rigid_deflation_diag_.deflated_rows = m_new;
3539 rigid_deflation_diag_.geometries = rigid_deflation_.num_geometries;
3540 rigid_deflation_diag_.rigid_modes += tail_diag.rigid_modes;
3541 rigid_deflation_diag_.kernel_null_norm =
3542 std::max(rigid_deflation_diag_.kernel_null_norm,
3543 tail_diag.kernel_null_norm);
3544 rigid_deflation_diag_.kernel_relative_null_norm =
3545 std::max(rigid_deflation_diag_.kernel_relative_null_norm,
3546 tail_diag.kernel_relative_null_norm);
3547 rigid_deflation_diag_.kernel_schur_null_error =
3548 std::max(rigid_deflation_diag_.kernel_schur_null_error,
3549 tail_diag.kernel_schur_null_error);
3550 rigid_deflation_diag_.kernel_relative_schur_null_error =
3551 std::max(rigid_deflation_diag_.kernel_relative_schur_null_error,
3553 rigid_deflation_diag_.applied = true;
3554 rigid_deflation_diag_.reason =
3555 (rigid_deflation_diag_.reason == "deflated_exact" &&
3556 tail_diag.reason == "deflated_exact")
3557 ? "deflated_exact"
3558 : "deflated_projected";
3560 } else {
3561 extendTrainingInverseDiagonal(m_old, m_new);
3562 }
3564 ++incremental_cholesky_updates_for_testing_;
3565 record_serial_signature();
3566 return signature.valid;
3567 };
3568 if (reuseSerialFactorIfCurrent(x_ordered, ind_ordered, constant_update))
3569 return true;
3570 if (try_serial_append()) return true;
3571 if (require_factor_append_) return false;
3573
3574 // Assemble C and apply every configured diagonal regularisation. Factored
3575 // out so the rescue path below rebuilds the same operator: rebuilding with
3576 // only the escalating jitter would drop the conditioning bound the
3577 // principled nugget exists to enforce, on exactly the matrices that just
3578 // failed to factorise.
3579 const bool can_attempt_deflation =
3581 sexpat_cov_func != nullptr && lik_gaussian != nullptr &&
3582 !sexpat_cov_func->usesManifoldChart() &&
3583 !sexpat_cov_func->usesGeodesicHeatKernel() && !principled_nugget_;
3584 const Eigen::VectorXd noise_ordered =
3585 lik_gaussian != nullptr
3586 ? lik_gaussian->evaluateTrainingVariance(x_ordered)
3587 : Eigen::VectorXd::Zero(n_rows);
3588 const auto assemble_regularized_C = [&](double extra_jitter) {
3590 x, x_ind, C, /*include_noise=*/!can_attempt_deflation)) {
3592 x, x_ind, C,
3593 /*serial_per_rank=*/false,
3594 /*include_constant=*/false,
3595 /*include_noise=*/!can_attempt_deflation);
3598 }
3599 if (!can_attempt_deflation) {
3600 if (jitter_sigma2 > 0.) C.diagonal().array() += jitter_sigma2;
3601 if (use_correction_) {
3602 double K_sum =
3603 C.diagonal().sum() + constant_update.squaredNorm();
3604 Eigen::Index n = C.rows();
3605 double denom =
3606 1.0 / correction_eps_ - static_cast<double>(n * n);
3607 if (std::abs(denom) > 1e-30) {
3608 double corr = K_sum * K_sum / denom;
3609 C.diagonal().array() += corr;
3610 }
3611 }
3612 if (extra_jitter > 0.) C.diagonal().array() += extra_jitter;
3613 (void)detail::prepareRigidDeflationState(
3614 use_rigid_null_deflation_, /*factor_order=*/true, atoms_config,
3615 x_ordered, ind_ordered, noise_ordered, jitter_sigma2,
3616 /*unsupported_kernel_or_likelihood=*/true, rigid_deflation_,
3618 rigid_deflation_.reset();
3619 factor_constant = constant_update;
3620 return;
3621 }
3622 double corr = 0.0;
3623 if (use_correction_) {
3624 const double K_sum = C.diagonal().sum() + noise_ordered.sum() +
3625 static_cast<double>(n_rows) * jitter_sigma2 +
3626 constant_update.squaredNorm();
3627 const Eigen::Index n = C.rows();
3628 const double denom =
3629 1.0 / correction_eps_ - static_cast<double>(n * n);
3630 if (std::abs(denom) > 1e-30) corr = K_sum * K_sum / denom;
3631 }
3632 const double extra_uniform = jitter_sigma2 + corr + extra_jitter;
3634 x_ordered, ind_ordered, noise_ordered, extra_uniform, C,
3635 constant_update, factor_constant, /*factor_order=*/true)) {
3636 C.diagonal() += noise_ordered;
3637 if (extra_uniform != 0.0) C.diagonal().array() += extra_uniform;
3638 factor_constant = constant_update;
3639 }
3640 };
3641
3642 rigid_deflation_.reset();
3643 assemble_regularized_C(0.);
3644
3645 const auto factor_covariance = [&](const EigenMatrix& matrix) {
3646 return timedFactor(matrix);
3647 };
3648 if (detail::factorCovarianceOrSymmetricPart(C, factor_covariance)) {
3649 C.noalias() += factor_constant * factor_constant.transpose();
3650 record_serial_signature();
3651 return true;
3652 }
3653
3654 // Cholesky failed: the covariance matrix is not positive definite.
3655 // This can happen at higher optimization levels (-O2/-O3) due to
3656 // floating-point rounding in the kernel evaluation. Retry with
3657 // progressively larger jitter as a numerical safeguard.
3658 double rescue_jitter = std::max(jitter_sigma2, 1e-10);
3659 for (int attempt = 0; attempt < 5; ++attempt) {
3660 // The quiet default used to retry an indefinite factor with no
3661 // trace. The extra factorizations are the stall, when they happen.
3662 std::fprintf(stderr, "[chol-rescue] n=%lld attempt=%d jitter=%.3g\n",
3663 static_cast<long long>(C.rows()), attempt, rescue_jitter);
3664 assemble_regularized_C(rescue_jitter);
3665 if (timedFactor(C)) {
3666 C.noalias() += factor_constant * factor_constant.transpose();
3667 invalidate_serial_signature();
3668 return true;
3669 }
3670 rescue_jitter *= 10.0;
3671 }
3672 rigid_deflation_.reset();
3673 invalidate_serial_signature();
3674 return false;
3675#endif
3676}
3677
3678} // namespace gpr
Linear algebra abstraction layer for GPR hot-path operations.
Triangular solves and Cholesky inverse whose floating-point result does not depend on the process gri...
@ x
Definition Enums.h:28
Correctly rounded Schur-complement diagonals from Cholesky solves.
Exact floating-point accumulator (Kulisch long accumulator).
Runtime loader for ScaLAPACK / BLACS symbols (dlopen + dlsym).
void Cpdgemr2d(int m, int n, const double *a, int ia, int ja, const int *desca, double *b, int ib, int jb, const int *descb, int ictxt)
void pdpotrf_(const char *uplo, const int *n, double *a, const int *ia, const int *ja, const int *desca, int *info)
void pdtrsm_(const char *side, const char *uplo, const char *trans, const char *diag, const int *m, const int *n, const double *alpha, const double *a, const int *ia, const int *ja, const int *desca, double *b, const int *ib, const int *jb, const int *descb)
void pdsyrk_(const char *uplo, const char *trans, const int *n, const int *k, const double *alpha, const double *a, const int *ia, const int *ja, const int *desca, const double *beta, double *c, const int *ic, const int *jc, const int *descc)
void assembleMatrixOfRepetitiveCoordinates(const gpr::Coord &coord, gpr::EigenMatrix &matrix, Eigen::VectorXd &ind)
Assemble Eigen matrix with repetitive rows based on provided set of coordinates R.
linalg::BackendContext & backend() const
Eigen::VectorXd permuteTrainingVector(const Eigen::VectorXd &input) const
std::optional< double > conditionDevicePosterior(const EigenMatrix &rows, const Eigen::VectorXd &indices, const Eigen::VectorXd &targets, bool placeholder_targets=false)
void extendTrainingInverseDiagonal(Eigen::Index old_order, Eigen::Index new_order)
void evaluateCovarianceMatrix(const EigenMatrix &x1, const EigenMatrix &x2, const Eigen::VectorXd &x1_ind, const Eigen::VectorXd &x2_ind, EigenMatrix &C, bool serial_per_rank=false) const
Evaluate covariance matrix between two input vectors.
bool evaluateTrainingCovarianceInFactorOrder(const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool include_noise=true)
void claimActiveTrainingCholeskyFactor()
Associate the live ScaLAPACK factor with this GP after a materialize.
Eigen::VectorXd solveTrainingCovarianceInFactorLayout(const Eigen::VectorXd &rhs) const
const Eigen::MatrixXd & secantQuadraticHessian() const
detail::RigidDeflationState rigid_deflation_
bool decomposeCovarianceMatrix(const EigenMatrix &x, const Eigen::VectorXd &x_ind)
Evaluate and decompose the covariance matrix using Cholesky decomposition.
EigenMatrix permuteTrainingRows(const EigenMatrix &input) const
void calculateVarianceHssvd(Observation &image1)
std::shared_ptr< linalg::KokkosMolecularPosterior > device_posterior_
bool hasDevicePosterior() const noexcept
std::unique_ptr< SexpatCF > sexpat_cov_func
bool prepareMeanHessianVectorHssvd(const Coord &R, PreparedHssvdHessianVector &prepared) const
bool tryDeflateFactorSignalCovariance(const EigenMatrix &x_ordered, const Eigen::VectorXd &ind_ordered, const Eigen::VectorXd &noise_ordered, double extra_uniform_noise, EigenMatrix &signal_cov, const Eigen::VectorXd &constant_update, Eigen::VectorXd &factor_constant, bool factor_order=true)
std::shared_ptr< const linalg::KokkosFactor > resident_training_factor_
void prepareTrainingPermutation(const Eigen::VectorXd &x_ind)
bool calculateMeanHessianVectorHssvd(const Coord &R, const Eigen::VectorXd &direction, Eigen::VectorXd &hessian_vector) const
RigidDeflationDiagnostic rigid_deflation_diag_
virtual bool supportsRigidNullDeflation() const noexcept
bool applyMeanHessianVectorHssvd(const PreparedHssvdHessianVector &prepared, const Eigen::VectorXd &direction, Eigen::VectorXd &hessian_vector) const
void extractUniqueIndices(const Eigen::VectorXd &input_ind, Eigen::VectorXd &output_ind) const
Extract unique indices from the input vector.
bool decomposeForFittedTargets()
Factor the fitted design at the current hyperparameters and leave the posterior weights those of the ...
linalg::linop::DenseCholeskySolver trainingSolver() const
bool trainingFactorAppendable(Eigen::Index observations) const
void scaleTrainingVarianceToPhysical(Eigen::Ref< Eigen::VectorXd > variance) const
bool applyMeanHessianBlockHssvd(const PreparedHssvdHessianVector &prepared, const Eigen::MatrixXd &directions, Eigen::MatrixXd &hessian_block) const
bool hssvdEnergyDesign(const FieldMatrixd &query, Eigen::VectorXd &design, Eigen::VectorXd &coeff) const
Eigen::Index activeFactorOrder(Eigen::Index full_rows) const noexcept
bool hasTrainingCholeskyFactor(Eigen::Index expected_rows) const noexcept
void evaluateTrainingCovarianceMatrix(const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool serial_per_rank=false, bool include_constant=true, bool include_noise=true)
Evaluate training covariance matrix (gp_cov + noise covariance).
static std::vector< int > featurePairtypes(const AtomsConfiguration &conf_info)
Pairtype index for each feature.
static void computeWithJacobian(const Coord &x, const AtomsConfiguration &conf_info, Eigen::VectorXd &phi, EigenMatrix &J_phi)
Compute phi(x) and its Jacobian d(phi)/d(x).
static void computeDirectionalHessian(const Coord &x, const AtomsConfiguration &conf_info, const Eigen::VectorXd &direction, EigenMatrix &H_phi_direction)
Compute D_direction d(phi)/d(x) for a fixed descriptor point.
static void computeWithJacobianAndDirectionalHessian(const Coord &x, const AtomsConfiguration &conf_info, const Eigen::VectorXd &direction, Eigen::VectorXd &phi, EigenMatrix &J_phi, EigenMatrix &H_phi_direction)
Compute phi(x), d(phi)/d(x), and D_direction d(phi)/d(x).
static void computeWeightedHessianPairs(const Coord &x, const AtomsConfiguration &conf_info, const Eigen::VectorXd &feature_weights, std::vector< priors::PriorHessianPair > &hessian_pairs, double far_radius=0.0)
Precompute weighted 3x3 Cartesian pair-Hessian blocks for sum_f feature_weights(f) * nabla^2_x phi_f(...
Sexpat::PreparedAlphaK PreparedAlphaK
Definition SexpatCF.h:82
static bool gradedModeCountExceedsLimit(int dim, int max_degree, Eigen::Index limit)
static Eigen::MatrixXd affineSpanBasis(const Eigen::MatrixXd &centered_X)
static int capMaxDegreeByModeCount(int dim, int requested_degree, Eigen::Index mode_limit)
static double floorLatentVariance(double latent, double error_bound, SchurFloorReport *report) noexcept
static int autoMaxDegree(const Eigen::VectorXd &eps, double alpha, int dim, double target_tol, int max_degree_cap=40)
static void projectToAffineSpan(const Eigen::MatrixXd &centered_X, const Eigen::MatrixXd &basis, Eigen::MatrixXd &coords, Eigen::MatrixXd &residuals)
Eigen::Index numObs() const
bool cholesky_rank_update(EigenMatrix &lower, const Eigen::VectorXd &vector)
Raised when a stable posterior variance is not finite, is materially negative, or its operands do not...
Definition ExactSchur.h:57
Eigen::VectorXd solve(const Eigen::VectorXd &y) const override
static bool factorize(BackendContext &backend, const EigenMatrix &covariance, const Eigen::VectorXd &rank_one, EigenMatrix &factor)
factor factor^T = covariance + rank_one rank_one^T.
static Eigen::MatrixXd applyHessianPairs(const std::vector< HessianPair > &pairs, const Eigen::MatrixBase< Eigen::MatrixXd > &directions)
static Eigen::MatrixXd applyHessianPairs(const std::vector< HessianPair > &pairs, const Eigen::MatrixBase< Derived > &directions)
Apply physical prior curvature without forming a dense Hessian.
Eigen::VectorXd flatMinimumImageDisplacement(const PairBox *box, const Eigen::VectorXd &from, const Eigen::VectorXd &to)
Definition MinImage.h:259
bool potrfLower(DistributedState &st, double *A, const int *desc, int n, int n_factored=0)
void requireStablePosteriorVariance(double &variance, double signal_variance, double relative_allowance)
Accept one stable posterior variance or throw.
Definition ExactSchur.h:131
bool kokkosHostExecutionMemory() noexcept
bool teamParallelPays(double flops)
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
Definition ExactSchur.h:40
bool acceptStablePosteriorVariance(double &variance, double signal_variance, double relative_allowance) noexcept
Accept one stable posterior variance.
Definition ExactSchur.h:86
Eigen::MatrixXd applyPriorHessianPairs(const std::vector< PriorHessianPair > &pairs, const Eigen::MatrixBase< Derived > &directions)
Apply physical prior curvature without forming a dense Hessian.
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
Eigen::VectorXd permuteVector(const Eigen::VectorXd &input, const StructuredPermutation &p)
StructuredPermutation buildStructuredPermutation(const Eigen::VectorXd &ind_Ddim)
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
EigenMatrix permuteMatrixRows(const EigenMatrix &input, const StructuredPermutation &p)
EigenMatrix permuteSymmetricMatrix(const EigenMatrix &input, const StructuredPermutation &p)
Eigen::MatrixXd hssvdHermiteCartesianAction(const Eigen::MatrixXd &jacobian, const Eigen::MatrixXd &residuals, const Eigen::MatrixXd &force_weights, const Eigen::VectorXd &energy_kernel_weights, const Eigen::VectorXd &force_kernel_weights, const Eigen::VectorXd &force_residual_dots, double energy_kernel_weight_sum, double force_kernel_residual_dot_sum, const Eigen::MatrixXd &directions)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
Stores configurations of all atoms in the system.
Definition Structures.h:832
Observation data: energy, gradient and positions.
FieldMatrixd E
static double cholesky_seconds
static double assembly_seconds
static double descriptor_seconds