Loading...
Searching...
No Matches
EnergyGradient.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// SCG-side NLML evaluation: energy, gradient, and joint energy+gradient
6// entrypoints used inside the SCG outer loop. The local variants
7// (evaluateEnergyAndGradientLocal, evaluateEnergyLocal, etc.) skip
8// MPI/ScaLAPACK collectives so per-rank theta_k chains in SVGD can use
9// them without deadlocking the global Cholesky.
10
19#include "Helpers.h"
20#include "PriorFreeInverse.h"
21#ifdef GPR_LINALG_SCALAPACK
24#endif
25
26#include <Eigen/Core>
27#include <Eigen/Eigenvalues>
28#include <algorithm>
29#include <bit>
30#include <cfloat>
31#include <chrono>
32#include <cmath>
33#include <cstdint>
34#include <cstdlib>
35#include <limits>
36#include <memory>
37#include <random>
38#include <utility>
39
41#include "../PhaseTimers.h"
42
43namespace gpr {
44
45using detail::addConstantCovarianceBlock;
46using detail::applyPrincipledDiagonalNugget;
47using detail::computePrincipledNugget;
48using detail::principledKappaMaxDefault;
49using detail::priorParametersVector;
50using detail::reduce_laplace_factor_vectors_in_grid_order;
51
52// Conditioning diagnostics: running max of cond(K) (from the local Cholesky
53// diagonal) and max|alpha| across SCG NLML evaluations. Surfaced in the
54// end-of-run telemetry to discriminate ill-conditioning (huge alpha, the
55// prediction mu = sum alpha_i k_i becomes a catastrophic cancellation of large
56// terms) from descriptor cancellation as the source of FP hypersensitivity.
57double g_max_cond_k = 0.0;
58double g_max_abs_alpha = 0.0;
59
60namespace {
61bool extractGroupedGeometryPositions(
62 const EigenMatrix& rows, const detail::ObservationChannelLayout& channels,
63 const AtomsConfiguration& configuration, Coord& positions)
64{
65 const Eigen::Index dimensions = 3 * configuration.atoms_mov.type.size();
66 const Eigen::Index geometries = channels.rowsPerChannel();
67 if (!channels.valid() || channels.channelCount() <= 0 || geometries <= 0 ||
68 dimensions <= 0 || rows.cols() < dimensions ||
69 rows.rows() != geometries * channels.channelCount())
70 return false;
71 positions = rows.topLeftCorner(geometries, dimensions);
72 if (!positions.allFinite()) return false;
73 for (Eigen::Index channel = 1; channel < channels.channelCount(); ++channel)
74 if (!(rows.block(channel * geometries, 0, geometries, dimensions)
75 .array() == positions.array())
76 .all())
77 return false;
78 return true;
79}
80
81// Component fingerprints locate a rounding difference in a detailed fit log.
82std::uint64_t fitComponentFingerprint(const double* values, std::size_t count)
83{
84 std::uint64_t value = 14695981039346656037ULL;
85 for (std::size_t index = 0; index < count; ++index) {
86 value ^= std::bit_cast<std::uint64_t>(values[index]);
87 value *= 1099511628211ULL;
88 }
89 return value;
90}
91
92// The first detailed objective records the scalar kernel arguments. Hexadecimal
93// values preserve every bit needed to compare elementary-function libraries.
94void traceFitKernelArguments(const pairlocal::Geometry& geometry,
95 const Eigen::VectorXd& theta)
96{
97 static thread_local bool recorded = false;
98 if (recorded || !geometry.valid) return;
99 const auto weights =
101 if (!weights.valid) return;
102 recorded = true;
103 std::fprintf(
104 stderr,
105 "[map-kernel-input] geometry=%016llx gradient=%016llx "
106 "theta=%016llx weights=%016llx magnitude=%a\n",
107 static_cast<unsigned long long>(
108 fitComponentFingerprint(geometry.q.data(), geometry.q.size())),
109 static_cast<unsigned long long>(fitComponentFingerprint(
110 geometry.grad.data(), geometry.grad.size())),
111 static_cast<unsigned long long>(
112 fitComponentFingerprint(theta.data(), theta.size())),
113 static_cast<unsigned long long>(fitComponentFingerprint(
114 weights.inverse_square.data(), weights.inverse_square.size())),
115 weights.magnitude);
116 Eigen::VectorXd distances = Eigen::VectorXd::Zero(geometry.n_pt);
117 for (Eigen::Index i = 0; i < geometry.n_conf; ++i)
118 for (Eigen::Index j = 0; j <= i; ++j) {
119 distances.setZero();
120 for (Eigen::Index f = 0;
121 f < static_cast<Eigen::Index>(geometry.pairs.size()); ++f) {
122 const auto type =
123 geometry.pairs[static_cast<std::size_t>(f)].type;
124 const double delta = geometry.q(i, f) - geometry.q(j, f);
125 distances(type) += weights.inverse_square(type) * delta * delta;
126 }
127 const double exponent = -distances.sum();
128 std::fprintf(stderr,
129 "[map-kernel] i=%lld j=%lld exponent=%a value=%a\n",
130 static_cast<long long>(i), static_cast<long long>(j),
131 exponent, weights.magnitude * numerics::exp(exponent));
132 }
133}
134} // namespace
135
137 const Eigen::VectorXd& w, const EigenMatrix& x,
138 const Eigen::VectorXd& x_ind, const Eigen::VectorXd& y,
140{
141 if (detail::rejectInvalidHyperparameters(w, energy_and_gradient)) return;
142 if (hyperparameter_objective_mode_ ==
144 // Neighborhood LOO needs neither the full-training geometry cache
145 // nor the HS-SVD backend (each held-out geometry gets its own
146 // small dense solve), so it bypasses the geometry auto-build
147 // below entirely. The geometry argument is unused (see the
148 // declaration in GaussianProcessRegression.h).
149 const TrainingKernelGeometry unused_geometry;
151 w, unused_geometry, x, x_ind, y, energy_and_gradient);
152 return;
153 }
158 if (use_hssvd_backend_ && use_hssvd_objective_contractions_ &&
160 hyperparameter_objective_mode_ != HyperparameterObjectiveMode::LOO) {
161 // The block geometry does not depend on theta: one build serves
162 // every evaluation of the fit (16_oxirane: 31 evaluations per
163 // refit each rebuilt and streamed the 3403 blocks of the same ten
164 // configurations, 0.5 s each).
165 if (const TrainingKernelGeometry* geom = fitGeometryFor(x, x_ind)) {
166 evaluateEnergyAndGradientFromGeometry(w, *geom, x, x_ind, y,
168 return;
169 }
170 }
171
172 setParameters(w);
173
174 energy_and_gradient.energy = evaluateEnergy(x, x_ind, y);
175
176 if (!std::isfinite(energy_and_gradient.energy) ||
177 fabs(energy_and_gradient.energy) <= DBL_EPSILON) {
178 if (report_level >= 1) {
179 if (!std::isfinite(energy_and_gradient.energy)) {
180 log_man << "Energy is not finite; skipping gradient "
181 "evaluation.\n";
182 } else {
183 log_man << "Energy field is empty!\n";
184 }
185 }
186 // When energy is non-finite, fall back to a sized zero gradient.
187 // setConstant(NaN) cascades through SCG's evaluate_penalized retry
188 // loop and corrupts the next iteration's gamma = (p.dot(r_new - r))
189 // / sigma step.
190 energy_and_gradient.gradient.resize(w.size());
191 energy_and_gradient.gradient.setZero();
192 } else {
193 evaluateGradient(x, x_ind, y, energy_and_gradient.gradient);
194 }
195}
196
198 const Eigen::VectorXd& w, const EigenMatrix& x,
199 const Eigen::VectorXd& x_ind, const Eigen::VectorXd& y,
201{
202 if (detail::rejectInvalidHyperparameters(w, energy_and_gradient)) return;
203 // Local-only NLML + gradient evaluator. Uses Eigen LLT on a stack-
204 // local copy of the training kernel; never enters the ScaLAPACK
205 // collective Cholesky path and never mutates rigid_deflation_. Required
206 // by the SVGD particle oracle distributed across MPI ranks: each rank
207 // holds a different theta_k and a collective Cholesky would either
208 // deadlock or feed different matrices into the same global call.
209 const detail::RigidDeflationState no_deflation;
210 setParameters(w);
211
212 const Eigen::Index n = x.rows();
213
214 // Build the training kernel matrix on this rank only:
215 // serial_per_rank=true skips the round-robin block distribution
216 // and the MPI_Reduce that the default assembly fires. Required by
217 // the SVGD per-rank oracle (each rank holds a different theta_k;
218 // a collective would deadlock on mismatched matrices).
219 EigenMatrix C_local;
221 const TrainingKernelGeometry* gradient_geometry = nullptr;
222 if (use_training_geometry_handle_ &&
223 // Objective values share the reusable fit's derivative arithmetic;
224 // retaining geometry changes its storage, not its kernel values.
225 prepareTrainingKernelGeometry(x, x_ind, geometry, /*reused=*/true) &&
227 geometry, x, x_ind, C_local, /*serial_per_rank=*/true,
228 /*include_constant=*/false)) {
229 // Alpha and inverse entries use the original observation channels;
230 // the full geometry has the same ordering on every particle rank.
231 // Its derivative tensors serve both assembly and this gradient.
232 gradient_geometry = &geometry;
233 } else {
234 evaluateTrainingCovarianceMatrix(x, x_ind, C_local,
235 /*serial_per_rank=*/true,
236 /*include_constant=*/false);
237 }
239 Eigen::VectorXd constant_update =
240 detail::constantCovarianceUpdate(const_cov_fun.get(), x_ind);
241 EigenMatrix C_factor = C_local;
242 Eigen::VectorXd y_factor = y;
245 y_factor = permuteTrainingVector(y_factor);
246 constant_update = permuteTrainingVector(constant_update);
247 }
248 if (jitter_sigma2 > 0.0) C_factor.diagonal().array() += jitter_sigma2;
249 Eigen::VectorXd uDdim_local;
250 extractUniqueIndices(x_ind, uDdim_local);
251
252 Eigen::VectorXd alpha_local;
253 Eigen::VectorXd alpha_factor;
254 Eigen::VectorXd b_local;
255 double log_det = 0.0;
256 bool factorise_ok = true;
257
258 Eigen::LLT<EigenMatrix> llt(C_factor);
259 EigenMatrix matrix_llt;
260 if (llt.info() == Eigen::Success) matrix_llt = llt.matrixL();
261 factorise_ok = llt.info() == Eigen::Success &&
262 linalg::rank_one_update_lower(matrix_llt, constant_update);
263 if (factorise_ok) {
264 const auto lower = matrix_llt.template triangularView<Eigen::Lower>();
265 b_local = lower.solve(y_factor);
266 alpha_factor = lower.adjoint().solve(b_local);
267 log_det = matrix_llt.diagonal().array().log().sum();
269 alpha_local =
271 } else {
272 alpha_local = alpha_factor;
273 }
274 // cond(K) ~ (max L_ii / min L_ii)^2 from the Cholesky diagonal; track
275 // it and max|alpha| to attribute the FP hypersensitivity.
276 {
277 const auto ldiag = matrix_llt.diagonal().array().abs();
278 const double lmin = ldiag.minCoeff();
279 const double lmax = ldiag.maxCoeff();
280 if (lmin > 0.0) {
281 const double ratio = lmax / lmin;
282 const double cond = ratio * ratio;
283 if (cond > g_max_cond_k) g_max_cond_k = cond;
284 }
285 if (alpha_local.size() > 0) {
286 const double amax = alpha_local.cwiseAbs().maxCoeff();
287 if (amax > g_max_abs_alpha) g_max_abs_alpha = amax;
288 }
289 }
290 }
291
292 if (!factorise_ok) {
293 // Non-PD kernel -- fall back to NaN energy + zero gradient,
294 // mirroring the distributed evaluator's failure path so SVGD
295 // (and other consumers) treat both backends identically.
296 energy_and_gradient.energy = std::numeric_limits<double>::quiet_NaN();
297 energy_and_gradient.gradient.resize(w.size());
298 energy_and_gradient.gradient.setZero();
299 return;
300 }
301
302 // log marginal likelihood: 0.5 n log(2 pi) + sum(log diag(L))
303 // + 0.5 ||L^{-1} y||^2 - log p(theta).
304 const double e_data =
305 0.5 * static_cast<double>(n) * numerics::log(2.0 * M_PI) + log_det +
306 0.5 * b_local.squaredNorm();
307 double e_prior = 0.0;
308 if (const_cov_fun) e_prior -= const_cov_fun->calculateLogPrior();
309 if (sexpat_cov_func) e_prior -= sexpat_cov_func->calculateLogPrior();
310 if (lik_gaussian) e_prior -= lik_gaussian->evaluateLogPrior();
311
312 const double energy = e_data + e_prior;
313 energy_and_gradient.energy = energy;
314
315 if (!std::isfinite(energy) ||
316 std::fabs(energy) <= std::numeric_limits<double>::epsilon()) {
317 // Mirror evaluateEnergyAndGradient: SCG's evaluate_penalized
318 // retry loop expects a sized zero gradient (not NaN) on
319 // degenerate energies.
320 energy_and_gradient.gradient.resize(w.size());
321 energy_and_gradient.gradient.setZero();
322 return;
323 }
324
325 // Gradient w.r.t. hyperparameters. The quadratic term is alpha alpha^T.
326 // The trace solves against each dK instead of forming K^{-1}.
327 FieldMatrixd gdata;
328 FieldMatrixd gprior;
329 const EigenMatrix no_inverse;
330 calculateGradientWithCovFunc(x, x_ind, uDdim_local, alpha_local, no_inverse,
331 *const_cov_fun, gdata, gprior,
332 /*serial_per_rank=*/true, gradient_geometry,
333 &matrix_llt, &no_deflation);
334 calculateGradientWithCovFunc(x, x_ind, uDdim_local, alpha_local, no_inverse,
335 *sexpat_cov_func, gdata, gprior,
336 /*serial_per_rank=*/true, gradient_geometry,
337 &matrix_llt, &no_deflation);
338
339 FieldMatrixd gprior_lik;
340 if (lik_gaussian) lik_gaussian->evaluateLogPriorGradient(gprior_lik);
341 if (gprior_lik.size() != 0) {
342 gprior_lik *= -1.;
343 gpr::field::appendRows(gprior, gprior_lik);
344 }
345
346 // matrix_llt is this rank's Eigen LLT. The noise trace has to stay
347 // on that dense factor. A collective trace_inverse would write it
348 // over the shared distributed factor cache.
349 appendLikelihoodNoiseGradient(alpha_local, no_inverse, matrix_llt,
350 /*use_solve_based_trace=*/true, gdata, gprior,
351 &no_deflation);
352
353 if (gprior.size() != 0) {
354 if (energy_and_gradient.gradient.rows() != gprior.size()) {
355 energy_and_gradient.gradient.resize(gprior.size());
356 }
357 energy_and_gradient.gradient =
358 Eigen::Map<const Eigen::VectorXd>(gdata.data(), gdata.size()) +
359 Eigen::Map<const Eigen::VectorXd>(gprior.data(), gprior.size());
360 } else {
361 energy_and_gradient.gradient.resize(w.size());
362 energy_and_gradient.gradient.setZero();
363 }
364}
365
366double GaussianProcessRegression::evaluateEnergy(const Eigen::VectorXd& w,
367 const EigenMatrix& x,
368 const Eigen::VectorXd& x_ind,
369 const Eigen::VectorXd& y)
370{
371 if (!detail::logParametersAreRepresentable(w)) {
372 return std::numeric_limits<double>::infinity();
373 }
374 if (hyperparameter_objective_mode_ ==
376 return evaluateLocalNeighborhoodLooEnergy(w, x, x_ind, y);
377 }
378 if (use_hssvd_backend_ && use_hssvd_objective_contractions_ &&
380 hyperparameter_objective_mode_ != HyperparameterObjectiveMode::LOO) {
381 if (const TrainingKernelGeometry* geom = fitGeometryFor(x, x_ind)) {
382 const double energy =
383 evaluateEnergyFromGeometry(w, *geom, x, x_ind, y);
384 if (std::isfinite(energy)) last_objective_theta_ = w;
385 return energy;
386 }
387 }
388
389 setParameters(w);
390 const double energy = evaluateEnergy(x, x_ind, y);
391 if (std::isfinite(energy)) last_objective_theta_ = w;
392 return energy;
393}
394
396 const Eigen::VectorXd& w, const EigenMatrix& x,
397 const Eigen::VectorXd& x_ind, const Eigen::VectorXd& y,
398 Eigen::VectorXd& gradient)
399{
400 if (hyperparameter_objective_mode_ == HyperparameterObjectiveMode::LOO ||
401 hyperparameter_objective_mode_ ==
403 return false;
404 }
405 if (last_objective_theta_.size() != w.size() ||
406 last_objective_theta_ != w || !is_decomposed_succesfully ||
407 !is_training_cov_matrix_evaluated || y.size() != x.rows()) {
408 return false;
409 }
410#ifndef GPR_LINALG_SCALAPACK
411#ifdef GPR_LINALG_KOKKOS
412 if (!hasDevicePosterior())
413#endif
414 if (L.rows() != activeFactorOrder(y.size()) ||
415 L.cols() != activeFactorOrder(y.size()))
416 return false;
417#endif
418 gradient.resize(w.size());
419 evaluateGradient(x, x_ind, y, gradient);
420 return gradient.size() == w.size() && gradient.allFinite();
421}
422
424 const Eigen::VectorXd& x_ind,
425 const Eigen::VectorXd& y)
426{
427#ifdef GPR_LINALG_KOKKOS
428 if (const auto value = conditionDevicePosterior(x, x_ind, y))
429 return unregularized_marginal_likelihood_
430 ? *value
431 : *value - const_cov_fun->calculateLogPrior() -
432 sexpat_cov_func->calculateLogPrior() -
433 lik_gaussian->evaluateLogPrior();
434#endif
435 // Precomputed-geometry objective fast path, kept behind this virtual so a
436 // subclass that overrides evaluateEnergy intercepts it.
437 // active_training_geom_ and active_training_w_ are set by the geometry
438 // objective entry points around their virtual call (and cleared right
439 // after).
440 if (active_training_geom_ != nullptr && active_training_w_ != nullptr) {
441 const TrainingKernelGeometry* geom = active_training_geom_;
442 const Eigen::VectorXd* w = active_training_w_;
443 active_training_geom_ = nullptr;
444 active_training_w_ = nullptr;
445 return evaluateEnergyFromGeometry(*w, *geom, x, x_ind, y);
446 }
447 const bool profile_energy_split = profile_energy_split_;
448 auto reduce_max_seconds = [&](const double local_seconds) {
449#ifdef GPR_LINALG_SCALAPACK
450 int mpi_up = 0;
451 MPI_Initialized(&mpi_up);
452 if (!mpi_up) return local_seconds;
453
454 int nprocs = 1;
455 MPI_Comm_size(mpiContext().comm, &nprocs);
456 if (nprocs == 1) return local_seconds;
457
458 const double send_seconds = local_seconds;
459 double global_seconds = 0.0;
460 MPI_Allreduce(&send_seconds, &global_seconds, 1, MPI_DOUBLE, MPI_MAX,
461 mpiContext().comm);
462 return global_seconds;
463#else
464 return local_seconds;
465#endif
466 };
467 auto elapsed_seconds =
468 [&](const std::chrono::steady_clock::time_point& start) {
469 return std::chrono::duration<double>(
470 std::chrono::steady_clock::now() - start)
471 .count();
472 };
473
474 Index_t n = (Index_t)x.rows();
475 double zc = 0., edata = 0., eprior = 0.;
476 double energy = 0.;
477
478 const auto decompose_start = std::chrono::steady_clock::now();
480 const double decompose_seconds =
481 profile_energy_split
482 ? reduce_max_seconds(elapsed_seconds(decompose_start))
483 : 0.0;
484
485 // Test if the matrix is positive definite
487 if (report_level >= 1)
488 log_man << "Warning! Matrix L is not positive definite\n";
489 energy = std::numeric_limits<double>::quiet_NaN();
490 ;
491 } else {
492 const auto posterior_start = std::chrono::steady_clock::now();
494
496 const Index_t n_eff = rigid_deflation_.isActiveForFullOrder(n)
497 ? rigid_deflation_.deflated_rows
498 : n;
499 edata = 0.5 * n_eff * numerics::log(2 * M_PI) + zc +
500 0.5 * b.dot(b); // Line 7, zc should be negative
501 if (rigid_deflation_.isActiveForFullOrder(n)) {
502 edata += rigid_deflation_.nlmlPenalty();
503 }
504
505 // Evaluate the prior contribution to the error from covariance
506 // functions
507#ifndef NDEBUG
508 gpr::assertMsg(const_cov_fun != nullptr,
509 "Object of Gausian likelihood is not allocated!");
510 gpr::assertMsg(sexpat_cov_func != nullptr,
511 "Object of Gausian likelihood is not allocated!");
512#endif
513
514 eprior -= const_cov_fun->calculateLogPrior();
515
516 eprior -= sexpat_cov_func->calculateLogPrior();
517
518 // Evaluate the prior contribution to the error from Gaussian likelihood
519 eprior -= lik_gaussian->evaluateLogPrior();
520
521 energy = edata + eprior;
522 const double posterior_seconds =
523 profile_energy_split
524 ? reduce_max_seconds(elapsed_seconds(posterior_start))
525 : 0.0;
526 if (profile_energy_split) {
527 recordEnergyProfileSplit(0.0, decompose_seconds, posterior_seconds);
528 }
529 }
530
531 if (profile_energy_split && !is_decomposed_succesfully) {
532 recordEnergyProfileSplit(0.0, decompose_seconds, 0.0);
533 }
534 // std::cout << "\n in evaluateEnergy(): \n" << y << "\n\n";
535 return energy;
536}
537
538bool GaussianProcessRegression::ensureHssvdObjectiveTraceBasis() const
539{
540 if (!hssvdObjectiveStampMatches()) return false;
541 if (hssvd_objective_trace_basis_.size() > 0) return true;
542 const Eigen::Index n_obs = hssvd_objective_alpha_.size();
543#ifdef GPR_LINALG_SCALAPACK
544 if (n_obs > 0 && hssvd_objective_pending_descriptor_[2] == n_obs) {
545 EigenMatrix lower = backend().distributed().gather(
546 hssvd_objective_pending_owned_.data(),
547 hssvd_objective_pending_descriptor_.data(), static_cast<int>(n_obs),
548 static_cast<int>(n_obs));
549 hssvd_objective_pending_covariance_ =
550 lower.selfadjointView<Eigen::Lower>();
551 std::vector<double>().swap(hssvd_objective_pending_owned_);
552 hssvd_objective_pending_descriptor_.fill(0);
553 }
554#endif
555 if (n_obs == 0 || hssvd_objective_pending_covariance_.rows() != n_obs ||
556 hssvd_objective_pending_covariance_.cols() != n_obs ||
557 !(hssvd_objective_pending_noise_ > 0.0)) {
558 return false;
559 }
560 StableBasisND basis(backend_context_);
561 if (!hssvd_objective_pending_lapack_rrr_ ||
562 !basis.factorizeNoisyKernelLapackRrr(
563 hssvd_objective_pending_covariance_,
564 hssvd_objective_pending_noise_)) {
565 basis.factorizeNoisyKernel(hssvd_objective_pending_covariance_,
566 hssvd_objective_pending_noise_);
567 }
568 const EigenMatrix& Q = basis.leftSingularVectors();
569 const Eigen::ArrayXd mu = basis.noisyEigenvalues().array();
570 if (basis.numObs() != n_obs || Q.cols() != mu.size() || !Q.allFinite() ||
571 !mu.isFinite().all() || !(mu > 0.0).all()) {
572 return false;
573 }
574 const Eigen::VectorXd shrink =
575 (1.0 - hssvd_objective_pending_noise_ / mu).matrix();
576 const EigenMatrix weighted = Q * shrink.asDiagonal();
577 const bool permuted =
578 static_cast<Eigen::Index>(
579 hssvd_objective_pending_permutation_.perm.size()) == n_obs;
580 hssvd_objective_trace_basis_ =
581 permuted
582 ? gpr::unpermuteMatrixRows(Q, hssvd_objective_pending_permutation_)
583 : Q;
584 hssvd_objective_trace_weighted_basis_ =
585 permuted ? gpr::unpermuteMatrixRows(
586 weighted, hssvd_objective_pending_permutation_)
587 : weighted;
588 clearHssvdPendingCovariance();
589 return true;
590}
591
593 const Eigen::VectorXd& w, const TrainingKernelGeometry& geom,
594 const EigenMatrix& x, const Eigen::VectorXd& x_ind,
595 const Eigen::VectorXd& y)
596{
597 if (!detail::logParametersAreRepresentable(w)) {
598 return std::numeric_limits<double>::infinity();
599 }
600 const auto energy_start = std::chrono::steady_clock::now();
601 const double solve0 = linalg::teamSolveWallSeconds();
602 const double factor0 = linalg::teamFactorWallSeconds();
603 const double eigen0 = PhaseTimers::eigensolve_seconds;
604 const double kernel0 = PhaseTimers::assembly_seconds;
605 const double curvature0 = PhaseTimers::curvature_seconds;
606 struct ExclusiveEnergy {
607 std::chrono::steady_clock::time_point start;
608 double solve0, factor0, eigen0, kernel0, curvature0;
609 ~ExclusiveEnergy()
610 {
611 const double wall = std::chrono::duration<double>(
612 std::chrono::steady_clock::now() - start)
613 .count();
614 const double nested = (linalg::teamSolveWallSeconds() - solve0) +
615 (linalg::teamFactorWallSeconds() - factor0) +
618 (PhaseTimers::curvature_seconds - curvature0);
619 PhaseTimers::energy_seconds += std::max(0.0, wall - nested);
620 }
621 } exclusive_energy{energy_start, solve0, factor0,
622 eigen0, kernel0, curvature0};
623 // Objective evaluations replace the cached factor independently of the
624 // fitted posterior. Its append signature cannot describe that factor.
625#ifdef GPR_LINALG_SCALAPACK
626 distributed_factor_signature_.valid = false;
627#endif
628 serial_factor_signature_.valid = false;
629 setParameters(w);
630#ifdef GPR_LINALG_KOKKOS
632 const double energy = evaluateEnergy(x, x_ind, y);
633 if (std::isfinite(energy)) last_objective_theta_ = w;
634 return energy;
635 }
636#endif
637 hssvd_objective_basis_valid_ = false;
638 clearHssvdPendingCovariance();
639 hssvd_objective_alpha_.resize(0);
640 hssvd_objective_trace_basis_.resize(0, 0);
641 hssvd_objective_trace_weighted_basis_.resize(0, 0);
642 hssvd_objective_trace_inv_noise_ = 0.0;
643 hssvd_objective_trace_direct_inverse_ = false;
644 hssvd_objective_trace_via_cholesky_ = false;
645 hssvd_trace_basis_ = nullptr;
646 hssvd_trace_weighted_basis_ = nullptr;
647 hssvd_trace_inv_noise_ = 0.0;
648 hssvd_trace_direct_inverse_ = false;
649 const bool profile_energy_split = profile_energy_split_;
650 auto reduce_max_seconds = [&](const double local_seconds) {
651#ifdef GPR_LINALG_SCALAPACK
652 int mpi_up = 0;
653 MPI_Initialized(&mpi_up);
654 if (!mpi_up) return local_seconds;
655
656 int nprocs = 1;
657 MPI_Comm_size(mpiContext().comm, &nprocs);
658 if (nprocs == 1) return local_seconds;
659
660 const double send_seconds = local_seconds;
661 double global_seconds = 0.0;
662 MPI_Allreduce(&send_seconds, &global_seconds, 1, MPI_DOUBLE, MPI_MAX,
663 mpiContext().comm);
664 return global_seconds;
665#else
666 return local_seconds;
667#endif
668 };
669 auto elapsed_seconds =
670 [&](const std::chrono::steady_clock::time_point& start) {
671 return std::chrono::duration<double>(
672 std::chrono::steady_clock::now() - start)
673 .count();
674 };
675
676 // Geometry-driven training-cov assembly. Same algebraic K(theta) as
677 // evaluateTrainingCovarianceMatrix, but the per-block geometric work
678 // (dist_at + per-pair derivatives) was paid once in
679 // prepareTrainingKernelGeometry and is just elementwise-applied here.
680 const auto covariance_start = std::chrono::steady_clock::now();
682 rigid_deflation_.reset();
684 Eigen::VectorXd constant_update = permuteTrainingVector(
685 detail::constantCovarianceUpdate(const_cov_fun.get(), x_ind));
686 bool distributed_covariance = false;
687 bool covariance_valid = true;
689 detail::validateRigidNullDeflationConfiguration(true,
690 principled_nugget_);
691 }
692#ifdef GPR_LINALG_SCALAPACK
693 std::vector<double> covariance_owned;
694 int covariance_descriptor[9];
695 if ((!use_hssvd_backend_ || use_hssvd_objective_contractions_) &&
696 !use_correction_) {
697 const auto status = assembleTrainingCovarianceDistributedFromGeometry(
698 geom, x, x_ind, covariance_owned, covariance_descriptor);
699 covariance_valid = status != DistributedCovarianceStatus::Invalid;
700 distributed_covariance =
701 status == DistributedCovarianceStatus::Assembled;
702 }
703#endif
704 const bool can_attempt_deflation =
706 sexpat_cov_func != nullptr && lik_gaussian != nullptr &&
707 !sexpat_cov_func->usesManifoldChart() &&
708 !sexpat_cov_func->usesGeodesicHeatKernel() && !principled_nugget_;
709 const bool placed =
710 covariance_valid && !distributed_covariance &&
712 geom, x, x_ind, C, /*include_noise=*/!can_attempt_deflation);
713 if (!covariance_valid || (!distributed_covariance && !placed &&
715 geom, x, x_ind, C, /*serial_per_rank=*/false,
716 /*include_constant=*/false,
717 /*include_noise=*/!can_attempt_deflation))) {
718 if (profile_energy_split) {
719 const double covariance_seconds =
720 reduce_max_seconds(elapsed_seconds(covariance_start));
721 recordEnergyProfileSplit(covariance_seconds, 0.0, 0.0);
722 }
723 return std::numeric_limits<double>::quiet_NaN();
724 }
725 Eigen::VectorXd factor_constant = constant_update;
726 if (distributed_covariance) {
727 C.resize(0, 0);
728 } else {
729 if (!placed && hasTrainingPermutation())
731 if (!can_attempt_deflation) {
732 if (jitter_sigma2 > 0.) C.diagonal().array() += jitter_sigma2;
733 if (use_correction_) {
734 const double K_sum =
735 C.diagonal().sum() + constant_update.squaredNorm();
736 const Eigen::Index n_ind = C.rows();
737 const double denom =
738 1.0 / correction_eps_ - static_cast<double>(n_ind * n_ind);
739 if (std::abs(denom) > 1e-30) {
740 const double corr = K_sum * K_sum / denom;
741 C.diagonal().array() += corr;
742 }
743 }
744 const EigenMatrix x_ordered =
746 const Eigen::VectorXd ind_ordered = permuteTrainingVector(x_ind);
747 const Eigen::VectorXd noise_ordered =
748 lik_gaussian != nullptr
749 ? lik_gaussian->evaluateTrainingVariance(x_ordered)
750 : Eigen::VectorXd::Zero(x_ordered.rows());
751 Eigen::VectorXd unused_constant;
752 (void)detail::prepareRigidDeflationState(
753 use_rigid_null_deflation_, /*factor_order=*/true, atoms_config,
754 x_ordered, ind_ordered, noise_ordered, jitter_sigma2,
755 /*unsupported_kernel_or_likelihood=*/true, rigid_deflation_,
757 rigid_deflation_.reset();
758 factor_constant = constant_update;
759 } else {
760 const EigenMatrix x_ordered =
762 const Eigen::VectorXd ind_ordered = permuteTrainingVector(x_ind);
763 const Eigen::VectorXd noise_ordered =
764 lik_gaussian != nullptr
765 ? lik_gaussian->evaluateTrainingVariance(x_ordered)
766 : Eigen::VectorXd::Zero(x_ordered.rows());
767 double corr = 0.0;
768 if (use_correction_) {
769 const double K_sum =
770 C.diagonal().sum() + noise_ordered.sum() +
771 static_cast<double>(C.rows()) * jitter_sigma2 +
772 constant_update.squaredNorm();
773 const Eigen::Index n_ind = C.rows();
774 const double denom =
775 1.0 / correction_eps_ - static_cast<double>(n_ind * n_ind);
776 if (std::abs(denom) > 1e-30) corr = K_sum * K_sum / denom;
777 }
778 const double extra_uniform = jitter_sigma2 + corr;
779 const bool maybe_krylov =
780 !use_hssvd_backend_ &&
783 krylov_objective_.plan.order == C.rows() &&
784 krylov_objective_.plan.krylov));
785 if (maybe_krylov ||
787 x_ordered, ind_ordered, noise_ordered, extra_uniform, C,
788 constant_update, factor_constant, /*factor_order=*/true)) {
789 C.diagonal() += noise_ordered;
790 if (extra_uniform != 0.0) C.diagonal().array() += extra_uniform;
791 factor_constant = constant_update;
792 }
793 }
794 }
795 const double covariance_seconds =
796 profile_energy_split
797 ? reduce_max_seconds(elapsed_seconds(covariance_start))
798 : 0.0;
799
800 const bool trace_dense_fit = report_level >= 3 && mpiContext().nprocs == 1;
801 std::uint64_t covariance_fingerprint = 0;
802 if (trace_dense_fit) {
803 traceFitKernelArguments(geom.pair_local,
804 sexpat_cov_func->combineParameters());
805#ifdef GPR_LINALG_SCALAPACK
806 if (distributed_covariance)
807 covariance_fingerprint = fitComponentFingerprint(
808 covariance_owned.data(), covariance_owned.size());
809 else
810#endif
811 covariance_fingerprint =
812 fitComponentFingerprint(C.data(), C.size());
813 }
814
815 if (use_hssvd_backend_ && use_hssvd_objective_contractions_ &&
816 !use_correction_ &&
817 (distributed_covariance ||
818 (C.rows() == C.cols() && C.rows() == activeFactorOrder(y.size())))) {
819 const double total_sigma2 =
820 (lik_gaussian ? lik_gaussian->getSigma2() : 0.0) + jitter_sigma2;
821 if (total_sigma2 > 0.0) {
822 const auto hssvd_start = std::chrono::steady_clock::now();
823
824 // The objective and gradient share the Cholesky reduction of C.
825 // The diagnostic eigenbasis is materialized only on request.
826#ifdef GPR_LINALG_SCALAPACK
827 auto& st_obj = backend().distributed();
828 st_obj.invalidate_L();
829 st_obj.invalidate_inv();
830 training_cholesky_is_distributed_ = false;
831#endif
832 // Retain diagnostic input in the same distributed layout as
833 // the factor. Normal objective and gradient calls need no gather.
834#ifdef GPR_LINALG_SCALAPACK
835 std::vector<double> pending_owned;
836 if (distributed_covariance) pending_owned = covariance_owned;
837#endif
838 const bool chol_ok =
839#ifdef GPR_LINALG_SCALAPACK
840 (distributed_covariance
841 ? backend().cholesky_distributed(
842 std::move(covariance_owned), covariance_descriptor,
843 static_cast<int>(x.rows()), L)
844 : backend().cholesky(C, L)) &&
845 backend().cholesky_rank_update(L, factor_constant);
846#else
848 backend(), C, factor_constant, L);
849#endif
850#ifdef GPR_LINALG_KOKKOS
851 // Host versus device retention is decided in
852 // retainTrainingCholeskyFactor. A failed factor must release the
853 // device posterior as well: clearing only the resident pointer
854 // leaves hasTrainingCholeskyFactor to dereference it.
855 if (chol_ok)
857 else
859#endif
860 double obj_cnorm = (report_level >= 3) ? C.norm() : 0.0;
861#ifdef GPR_LINALG_SCALAPACK
862 if (distributed_covariance && report_level >= 3) {
863 double norm_squared = 0.0;
864 const int order = static_cast<int>(x.rows());
865 for (int col = 0; col < st_obj.local_cols(order); ++col) {
866 const int j = st_obj.global_index_for_local(
867 col, st_obj.block_size(), st_obj.mycol(),
868 st_obj.npcol());
869 for (int row = 0; row < st_obj.local_rows(order); ++row) {
870 const int i = st_obj.global_index_for_local(
871 row, st_obj.block_size(), st_obj.myrow(),
872 st_obj.nprow());
873 if (i < j) continue;
874 const double value =
875 pending_owned[row + static_cast<std::size_t>(col) *
876 covariance_descriptor[8]];
877 norm_squared += (i == j ? 1.0 : 2.0) * value * value;
878 }
879 }
880 backend().ordered_sum_bcast(&norm_squared, 1);
881 obj_cnorm = std::sqrt(norm_squared);
882 }
883#endif
884 if (chol_ok) {
885 const bool permuted_factor_layout =
887 static_cast<Eigen::Index>(
888 training_permutation_.perm.size()) == y.size();
889 const Eigen::VectorXd y_factor =
890 permuted_factor_layout ? permuteTrainingVector(y) : y;
891 const bool deflated_obj =
892 rigid_deflation_.isActiveForFullOrder(y_factor.size());
893 if (deflated_obj) {
894 rigid_deflation_.updateTargetStats(y_factor);
895 }
896 // b = L^{-1} y, alpha = L^{-T} b, logdet = 2 sum log diag(L);
897 // identical reduction to the Cholesky-backend objective.
898 const auto solver = trainingSolver();
899 const Eigen::VectorXd b_obj = solver.whiten(
900 deflated_obj ? rigid_deflation_.projectVector(y_factor)
901 : y_factor);
902 Eigen::VectorXd alpha_factor = solver.unwhiten(b_obj);
903 if (deflated_obj) {
904 alpha_factor =
905 rigid_deflation_.liftVectorZeroRigid(alpha_factor);
906 }
907 const Eigen::VectorXd alpha =
908 permuted_factor_layout
909 ? gpr::unpermuteVector(alpha_factor,
911 : alpha_factor;
912 const double quad = b_obj.dot(b_obj);
913 const double logdet = solver.logDeterminant();
914 if (alpha.size() == y.size() && std::isfinite(logdet) &&
915 alpha.allFinite()) {
916#ifdef GPR_LINALG_SCALAPACK
917 if (distributed_covariance) {
918 const int order = static_cast<int>(x.rows());
919 for (int col = 0; col < st_obj.local_cols(order);
920 ++col) {
921 const int j = st_obj.global_index_for_local(
922 col, st_obj.block_size(), st_obj.mycol(),
923 st_obj.npcol());
924 for (int row = 0; row < st_obj.local_rows(order);
925 ++row) {
926 const int i = st_obj.global_index_for_local(
927 row, st_obj.block_size(), st_obj.myrow(),
928 st_obj.nprow());
929 if (i >= j)
930 pending_owned
931 [row + static_cast<std::size_t>(col) *
932 covariance_descriptor[8]] +=
933 constant_update(i) * constant_update(j);
934 }
935 }
936 hssvd_objective_pending_owned_ =
937 std::move(pending_owned);
938 std::copy_n(
939 covariance_descriptor, 9,
940 hssvd_objective_pending_descriptor_.begin());
941 } else
942#endif
943 if (!deflated_obj) {
944 C.noalias() +=
945 constant_update * constant_update.transpose();
946 hssvd_objective_pending_covariance_ = std::move(C);
947 } else {
948 clearHssvdPendingCovariance();
949 }
950 hssvd_objective_pending_permutation_ =
951 permuted_factor_layout ? training_permutation_
953 hssvd_objective_pending_noise_ = total_sigma2;
954 hssvd_objective_pending_lapack_rrr_ =
955 hssvd_dual_lapack_rrr_;
956 hssvd_objective_alpha_ = alpha;
957 hssvd_objective_trace_inv_noise_ = 1.0 / total_sigma2;
958 hssvd_objective_trace_direct_inverse_ = false;
959 hssvd_objective_basis_valid_ = true;
960 stampHssvdObjective();
961 // Drive the gradient trace from the cached Cholesky factor.
962 hssvd_objective_trace_via_cholesky_ = true;
963 b = b_obj;
964 recordHyperparameterDataTerm(static_cast<double>(y.size()),
965 quad);
967#ifdef GPR_LINALG_SCALAPACK
968 if (chol_ok) {
969 C.resize(0, 0);
970 st_obj.claim_cached_L(this);
971 training_cholesky_is_distributed_ = true;
972 }
973#else
974 C.resize(0, 0);
975#endif
977
978 const Index_t n = deflated_obj
979 ? static_cast<Index_t>(
980 rigid_deflation_.deflated_rows)
981 : static_cast<Index_t>(x.rows());
982 if (report_level >= 3) {
983 static int obj_dbg = 0;
984 if (obj_dbg++ < 14) {
985 int rk = 0;
986 int np = 1;
987#ifdef GPR_LINALG_SCALAPACK
988 int mpi_initialized = 0;
989 MPI_Initialized(&mpi_initialized);
990 if (mpi_initialized) {
991 MPI_Comm_rank(mpiContext().comm, &rk);
992 MPI_Comm_size(mpiContext().comm, &np);
993 }
994#endif
995 if (rk == 0)
996 std::fprintf(
997 stderr,
998 "[OBJ] np=%d n=%lld ynorm=%.17g "
999 "Cnorm=%.17g logdet=%.17g quad=%.17g\n",
1000 np, (long long)n, y.norm(), obj_cnorm,
1001 logdet, quad);
1002 }
1003 }
1004 const double edata =
1005 0.5 * static_cast<double>(n) *
1006 numerics::log(2.0 * M_PI) +
1007 0.5 * logdet + 0.5 * quad +
1008 (deflated_obj ? rigid_deflation_.nlmlPenalty() : 0.0);
1009 double eprior = 0.0;
1010 if (const_cov_fun) {
1011 eprior -= const_cov_fun->calculateLogPrior();
1012 }
1013 if (sexpat_cov_func)
1014 eprior -= sexpat_cov_func->calculateLogPrior();
1015 if (lik_gaussian) {
1016 eprior -= lik_gaussian->evaluateLogPrior();
1017 }
1018 if (profile_energy_split) {
1019 const double hssvd_seconds =
1020 reduce_max_seconds(elapsed_seconds(hssvd_start));
1021 recordEnergyProfileSplit(covariance_seconds,
1022 hssvd_seconds, 0.0);
1023 }
1024 return edata + eprior;
1025 }
1026 }
1027#ifdef GPR_LINALG_SCALAPACK
1028 if (distributed_covariance)
1029 covariance_owned = std::move(pending_owned);
1030#endif
1031 }
1032 }
1033
1034 krylov_objective_.solver.reset();
1035 krylov_objective_.covariance.reset();
1036#ifndef GPR_LINALG_SCALAPACK
1037 if (const auto krylov_data =
1038 evaluateKrylovObjective(constant_update, x, y)) {
1039 double eprior = 0.0;
1040 if (const_cov_fun) eprior -= const_cov_fun->calculateLogPrior();
1041 if (sexpat_cov_func) eprior -= sexpat_cov_func->calculateLogPrior();
1042 if (lik_gaussian) eprior -= lik_gaussian->evaluateLogPrior();
1044 return *krylov_data + eprior;
1045 }
1046#endif
1047 const auto cholesky_start = std::chrono::steady_clock::now();
1048#ifdef GPR_LINALG_SCALAPACK
1049 auto& st = backend().distributed();
1050 st.invalidate_L();
1051 st.invalidate_inv();
1052 training_cholesky_is_distributed_ = false;
1054 (distributed_covariance
1055 ? backend().cholesky_distributed(std::move(covariance_owned),
1056 covariance_descriptor,
1057 static_cast<int>(x.rows()), L)
1058 : backend().cholesky(C, L)) &&
1059 backend().cholesky_rank_update(L, factor_constant);
1060#else
1062 backend(), C, factor_constant, L);
1063#endif
1064#ifdef GPR_LINALG_KOKKOS
1067 else
1069#endif
1070 if (is_decomposed_succesfully && !distributed_covariance)
1071 C.noalias() += factor_constant * factor_constant.transpose();
1072#ifdef GPR_LINALG_SCALAPACK
1074 C.resize(0, 0);
1075 st.claim_cached_L(this);
1076 training_cholesky_is_distributed_ = true;
1077 }
1078#endif
1080#ifdef GPR_LINALG_SCALAPACK
1081 training_cholesky_is_distributed_ = false;
1082#endif
1083 if (profile_energy_split) {
1084 const double cholesky_seconds =
1085 reduce_max_seconds(elapsed_seconds(cholesky_start));
1086 recordEnergyProfileSplit(covariance_seconds, cholesky_seconds, 0.0);
1087 }
1088 return std::numeric_limits<double>::quiet_NaN();
1089 }
1090 const double cholesky_seconds =
1091 profile_energy_split
1092 ? reduce_max_seconds(elapsed_seconds(cholesky_start))
1093 : 0.0;
1094
1095 const auto posterior_start = std::chrono::steady_clock::now();
1097#ifndef GPR_LINALG_SCALAPACK
1100#endif
1101
1102 const Index_t n = rigid_deflation_.isActiveForFullOrder(x.rows())
1103 ? static_cast<Index_t>(rigid_deflation_.deflated_rows)
1104 : static_cast<Index_t>(x.rows());
1105 const double zc = trainingSolver().halfLogDeterminant();
1106 double edata = 0.5 * n * numerics::log(2.0 * M_PI) + zc + 0.5 * b.dot(b);
1107 if (rigid_deflation_.isActiveForFullOrder(x.rows())) {
1108 edata += rigid_deflation_.nlmlPenalty();
1109 }
1110 double eprior = 0.0;
1111 if (const_cov_fun) eprior -= const_cov_fun->calculateLogPrior();
1112 if (sexpat_cov_func) eprior -= sexpat_cov_func->calculateLogPrior();
1113 if (lik_gaussian) eprior -= lik_gaussian->evaluateLogPrior();
1114 if (trace_dense_fit) {
1115 std::uint64_t factor_fingerprint = 0;
1116#ifdef GPR_LINALG_SCALAPACK
1117 if (training_cholesky_is_distributed_ && st.has_cached_L())
1118 factor_fingerprint = fitComponentFingerprint(
1119 st.cached_L(), static_cast<std::size_t>(st.cached_L_desc()[8]) *
1120 st.local_cols(st.cached_n()));
1121 else
1122#endif
1123 factor_fingerprint = fitComponentFingerprint(L.data(), L.size());
1124 std::fprintf(
1125 stderr,
1126 "[map-objective] n=%lld covariance=%016llx constant=%016llx "
1127 "factor=%016llx data=%016llx solution=%016llx "
1128 "logdet_half=%.17g quadratic=%.17g prior=%.17g\n",
1129 static_cast<long long>(n),
1130 static_cast<unsigned long long>(covariance_fingerprint),
1131 static_cast<unsigned long long>(fitComponentFingerprint(
1132 constant_update.data(), constant_update.size())),
1133 static_cast<unsigned long long>(factor_fingerprint),
1134 static_cast<unsigned long long>(
1135 fitComponentFingerprint(y.data(), y.size())),
1136 static_cast<unsigned long long>(
1137 fitComponentFingerprint(b.data(), b.size())),
1138 zc, b.dot(b), eprior);
1139 }
1141 if (profile_energy_split) {
1142 const double posterior_seconds =
1143 reduce_max_seconds(elapsed_seconds(posterior_start));
1144 recordEnergyProfileSplit(covariance_seconds, cholesky_seconds,
1145 posterior_seconds);
1146 }
1147 return edata + eprior;
1148}
1149
1151 const Eigen::VectorXd& w, const TrainingKernelGeometry& geom,
1152 const EigenMatrix& x, const Eigen::VectorXd& x_ind,
1153 const Eigen::VectorXd& y, EnergyAndGradient& energy_and_gradient)
1154{
1155 if (detail::rejectInvalidHyperparameters(w, energy_and_gradient)) return;
1160 // Route the scalar energy through the virtual evaluateEnergy so a subclass
1161 // that overrides it (e.g. forcing a non-finite energy to exercise the
1162 // optimizer rollback) intercepts the geometry fast path. setParameters is
1163 // applied inside the geometry path; pre-set it here so the virtual sees the
1164 // active hyperparameters.
1165 setParameters(w);
1166 active_training_geom_ = &geom;
1167 active_training_w_ = &w;
1168 energy_and_gradient.energy = evaluateEnergy(x, x_ind, y);
1169 active_training_geom_ = nullptr;
1170 active_training_w_ = nullptr;
1171#ifdef GPR_LINALG_SCALAPACK
1172 // Every rank must make the same decision before the gradient's solves.
1173 // A rank-local non-finite energy invalidates the collective objective.
1174 const auto process_group = mpiContext();
1175 if (process_group.is_distributed()) {
1176 int finite_energy = std::isfinite(energy_and_gradient.energy) ? 1 : 0;
1177 MPI_Allreduce(MPI_IN_PLACE, &finite_energy, 1, MPI_INT, MPI_MIN,
1178 process_group.comm);
1179 if (finite_energy == 0)
1180 energy_and_gradient.energy =
1181 std::numeric_limits<double>::quiet_NaN();
1182 }
1183#endif
1184 if (!std::isfinite(energy_and_gradient.energy)) {
1185 energy_and_gradient.gradient.resize(w.size());
1186 energy_and_gradient.gradient.setZero();
1187 return;
1188 }
1189
1190 // The geometry handle covers K(theta) assembly and the SExp dK/dtheta
1191 // block walk. Other covariance functions keep the live assembly path.
1193 &geom);
1194}
1195
1197 const Eigen::VectorXd& w, const TrainingKernelGeometry& geom,
1198 const EigenMatrix& x, const Eigen::VectorXd& x_ind,
1199 const Eigen::VectorXd& y, Eigen::VectorXd& gradient)
1200{
1201 if (hyperparameter_objective_mode_ == HyperparameterObjectiveMode::LOO ||
1202 hyperparameter_objective_mode_ ==
1204 return false;
1205 }
1206 gradient.resize(w.size());
1207 evaluateGradientWithGeometry(x, x_ind, y, gradient, &geom);
1208 return gradient.size() == w.size() && gradient.allFinite();
1209}
1210
1213 const Eigen::VectorXd& w, const TrainingKernelGeometry& geom,
1214 const EigenMatrix& x, const Eigen::VectorXd& x_ind,
1215 const Eigen::VectorXd& y, EnergyAndGradient& energy_and_gradient)
1216{
1217 if (detail::rejectInvalidHyperparameters(w, energy_and_gradient)) return;
1218 ++leave_one_out_objective_evaluations_for_testing_;
1219
1220 auto fail = [&]() {
1221 energy_and_gradient.energy = std::numeric_limits<double>::quiet_NaN();
1222 energy_and_gradient.gradient.resize(w.size());
1223 energy_and_gradient.gradient.setZero();
1224 };
1225
1226 setParameters(w);
1227 hssvd_objective_basis_valid_ = false;
1228 clearHssvdPendingCovariance();
1229 hssvd_objective_alpha_.resize(0);
1230 hssvd_objective_trace_basis_.resize(0, 0);
1231 hssvd_objective_trace_weighted_basis_.resize(0, 0);
1232 hssvd_objective_trace_inv_noise_ = 0.0;
1233 hssvd_objective_trace_direct_inverse_ = false;
1234 hssvd_objective_trace_via_cholesky_ = false;
1235
1236 if (!use_hssvd_backend_ || !use_hssvd_objective_contractions_) {
1237 fail();
1238 return;
1239 }
1240
1241 const detail::ObservationChannelLayout channels(x_ind);
1242 Coord geometry_positions;
1243 if (sexpat_cov_func == nullptr || y.size() != x.rows() ||
1244 x_ind.size() != x.rows() ||
1245 !extractGroupedGeometryPositions(
1246 x, channels, sexpat_cov_func->getConfInfo(), geometry_positions)) {
1247 fail();
1248 return;
1249 }
1250 const Eigen::Index n_geom = channels.rowsPerChannel();
1251
1253 EigenMatrix noisy_cov;
1255 geom, x, x_ind, noisy_cov, /*serial_per_rank=*/false)) {
1256 fail();
1257 return;
1258 }
1260 noisy_cov =
1262 if (jitter_sigma2 > 0.0) noisy_cov.diagonal().array() += jitter_sigma2;
1263 if (use_correction_) {
1264 const double K_sum = noisy_cov.diagonal().sum();
1265 const Eigen::Index n_ind = noisy_cov.rows();
1266 const double denom =
1267 1.0 / correction_eps_ - static_cast<double>(n_ind * n_ind);
1268 if (std::abs(denom) > 1e-30) {
1269 const double corr = K_sum * K_sum / denom;
1270 noisy_cov.diagonal().array() += corr;
1271 }
1272 }
1273
1274 const double total_sigma2 =
1275 (lik_gaussian ? lik_gaussian->getSigma2() : 0.0) + jitter_sigma2;
1276 if (!(total_sigma2 > 0.0) || noisy_cov.rows() != noisy_cov.cols() ||
1277 noisy_cov.rows() != y.size()) {
1278 fail();
1279 return;
1280 }
1281
1282 EigenMatrix kernel = noisy_cov;
1283 kernel.diagonal().array() -= total_sigma2;
1284 kernel = 0.5 * (kernel + kernel.transpose().eval());
1285
1286 StableBasisND loo_basis(backend_context_);
1287 // sqrt(eps) relative cutoff (NOT 0.0): a zero cutoff keeps singular modes
1288 // down to the float64 noise floor whose 1/S reinjection makes the LOO
1289 // objective depend on BLAS blocking (thread count), drifting the SCG theta
1290 // it feeds. sqrt(eps) drops only sub-precision noise and bounds the basis
1291 // condition at 1/sqrt(eps) = kappa_max, matching the dual-kernel cutoff in
1292 // factorizeStableBasisFromTraining; the colPivHouseholderQr solve is
1293 // rank-robust so the LOO residuals stay exact on the retained modes.
1294 const double loo_sv_rtol =
1295 std::sqrt(std::numeric_limits<double>::epsilon());
1296 loo_basis.factorizeKernel(kernel, /*sv_rtol=*/loo_sv_rtol,
1297 /*sv_abs_tol=*/0.0, /*sv_chop_tol=*/0.0);
1298 if (loo_basis.rank() <= 0 || loo_basis.numObs() != y.size()) {
1299 fail();
1300 return;
1301 }
1302
1303 const bool permuted_factor_layout =
1305 static_cast<Eigen::Index>(training_permutation_.perm.size()) ==
1306 y.size();
1307 const Eigen::VectorXd y_factor =
1308 permuted_factor_layout ? permuteTrainingVector(y) : y;
1309 const StableBasisPosteriorWeights weights =
1310 loo_basis.noisyPosteriorWeights(y_factor, total_sigma2);
1311 if (weights.alpha.size() != y.size() || !weights.alpha.allFinite()) {
1312 fail();
1313 return;
1314 }
1315
1316 const EigenMatrix& Q_factor = loo_basis.leftSingularVectors();
1317 const Eigen::ArrayXd s2 = loo_basis.singularValues().array().square();
1318 const Eigen::VectorXd shrink = (s2 / (s2 + total_sigma2)).matrix();
1319 const EigenMatrix Qshrink_factor = Q_factor * shrink.asDiagonal();
1320
1321 hssvd_objective_trace_basis_ =
1322 permuted_factor_layout
1324 : Q_factor;
1325 hssvd_objective_trace_weighted_basis_ =
1326 permuted_factor_layout
1328 : Qshrink_factor;
1329 hssvd_objective_alpha_ =
1330 permuted_factor_layout
1332 : weights.alpha;
1333 hssvd_objective_trace_inv_noise_ = 1.0 / total_sigma2;
1334 hssvd_objective_trace_direct_inverse_ = false;
1335 hssvd_objective_basis_valid_ = true;
1336 stampHssvdObjective();
1337
1338 const Eigen::Index n = y.size();
1339 // Per-geometry blocks contain every stored channel for one geometry.
1340 // Leaving out a whole geometry is the
1341 // correct derivative-GP LOO; a per-row LOO is blind to length-scale
1342 // collapse (same-geometry rows pin the held-out row), which lets ls -> 0
1343 // and blows up the dimer Hessian (~1/ls^4). The key is permuted into the
1344 // factor layout to match the basis rows.
1345 //
1346 // x_ind is NOT a geometry handle: it tags the derivative CHANNEL of a row
1347 // (0 = energy, 1..D = gradient component).
1348 // assembleMatrixOfRepetitiveCoordinates replicates the coordinate block
1349 // once per channel and assembleVectorFromEnergyAndGradient lays the
1350 // targets out channel-major (all energies, then all dE/dx, then dE/dy),
1351 // so rows sharing an x_ind value are one channel across EVERY geometry.
1352 // Grouping on it holds out a whole channel and leaves the remaining
1353 // channels at the held-out geometry in the training set -- which is the
1354 // same-geometry pinning this grouping exists to remove, so the length-
1355 // scale collapse it guards against survives it. Geometry g owns row
1356 // g + c * n_geom for stored channel ordinal c.
1357 Eigen::VectorXd geometry_id(n);
1358 for (Eigen::Index i = 0; i < n; ++i) {
1359 geometry_id(i) = static_cast<double>(n_geom > 0 ? i % n_geom : i);
1360 }
1361 const Eigen::VectorXd geometry_id_factor =
1362 permuted_factor_layout ? permuteTrainingVector(geometry_id)
1363 : geometry_id;
1364 std::vector<std::vector<Eigen::Index>> loo_groups;
1365 {
1366 std::unordered_map<long long, std::size_t> geom_to_group;
1367 for (Eigen::Index i = 0; i < geometry_id_factor.size(); ++i) {
1368 const long long gid =
1369 static_cast<long long>(std::llround(geometry_id_factor(i)));
1370 auto it = geom_to_group.find(gid);
1371 if (it == geom_to_group.end()) {
1372 geom_to_group.emplace(gid, loo_groups.size());
1373 loo_groups.emplace_back(1, i);
1374 } else {
1375 loo_groups[it->second].push_back(i);
1376 }
1377 }
1378 }
1379 // A geometry is one indivisible energy-and-gradient observation. Holding
1380 // out individual channels lets the retained channels at the same geometry
1381 // reveal the target and makes the score blind to length-scale collapse.
1382 const double loo_data =
1384 y_factor, total_sigma2, loo_groups);
1385 if (!std::isfinite(loo_data)) {
1386 fail();
1387 return;
1388 }
1389
1390 double eprior = 0.0;
1391 if (const_cov_fun) eprior -= const_cov_fun->calculateLogPrior();
1392 if (sexpat_cov_func) eprior -= sexpat_cov_func->calculateLogPrior();
1393 if (lik_gaussian) eprior -= lik_gaussian->evaluateLogPrior();
1394 energy_and_gradient.energy = loo_data + eprior;
1395
1396 energy_and_gradient.gradient.resize(w.size());
1397 energy_and_gradient.gradient.setZero();
1398
1399 Eigen::VectorXd uDdim;
1400 extractUniqueIndices(x_ind, uDdim);
1401
1402 for (Eigen::Index j = 0; j < w.size(); ++j) {
1403 Eigen::VectorXd direction = Eigen::VectorXd::Zero(w.size());
1404 direction(j) = 1.0;
1405 EigenMatrix dK;
1406 EigenMatrix d2K;
1408 geom, x, x_ind, uDdim, direction, dK, d2K,
1409 /*serial_per_rank=*/true)) {
1410 fail();
1411 return;
1412 }
1413 if (dK.rows() != n || dK.cols() != n || !dK.allFinite()) {
1414 fail();
1415 return;
1416 }
1417 if (permuted_factor_layout)
1419 dK = 0.5 * (dK + dK.transpose().eval());
1420
1421 const double derivative =
1422 loo_basis
1424 y_factor, total_sigma2, dK, loo_groups);
1425 if (!std::isfinite(derivative)) {
1426 fail();
1427 return;
1428 }
1429 energy_and_gradient.gradient(j) = derivative;
1430 }
1431
1432 if (sexpat_cov_func) {
1433 const FieldMatrixd gprior_cf =
1434 -sexpat_cov_func->calculateLogPriorGradient();
1435 const Eigen::Index n_prior = std::min<Eigen::Index>(
1436 gprior_cf.size(), energy_and_gradient.gradient.size());
1437 if (n_prior > 0) {
1438 energy_and_gradient.gradient.head(n_prior) +=
1439 Eigen::Map<const Eigen::VectorXd>(gprior_cf.data(), n_prior);
1440 }
1441 }
1442 if (theta_includes_likelihood_noise_ && lik_gaussian &&
1443 energy_and_gradient.gradient.size() > covarianceParameterCount()) {
1444 FieldMatrixd gprior_lik;
1445 lik_gaussian->evaluateLogPriorGradient(gprior_lik);
1446 if (gprior_lik.size() > 0) {
1447 energy_and_gradient.gradient(energy_and_gradient.gradient.size() -
1448 1) += -gprior_lik(0, 0);
1449 }
1450 }
1451 if (std::getenv("GPR_LOO_TRACE")) {
1452 static int loo_trace_count = 0;
1453 std::fprintf(stderr,
1454 "[loo-trace] eval=%d n=%lld theta=", loo_trace_count++,
1455 static_cast<long long>(n));
1456 for (Eigen::Index j = 0; j < w.size(); ++j)
1457 std::fprintf(stderr, " %.17g", w(j));
1458 std::fprintf(stderr,
1459 "\n[loo-trace] covnorm=%.17g covtrace=%.17g "
1460 "covsum=%.17g sigma2=%.17g rank=%d\n",
1461 noisy_cov.norm(), noisy_cov.trace(), noisy_cov.sum(),
1462 total_sigma2, loo_basis.rank());
1463 std::fprintf(stderr, "[loo-trace] S=");
1464 for (Eigen::Index j = 0; j < loo_basis.singularValues().size(); ++j)
1465 std::fprintf(stderr, " %.17g", loo_basis.singularValues()(j));
1466 std::fprintf(stderr,
1467 "\n[loo-trace] loo_data=%.17g eprior=%.17g "
1468 "energy=%.17g grad=",
1469 loo_data, eprior, energy_and_gradient.energy);
1470 for (Eigen::Index j = 0; j < energy_and_gradient.gradient.size(); ++j)
1471 std::fprintf(stderr, " %.17g", energy_and_gradient.gradient(j));
1472 std::fprintf(stderr, "\n");
1473 }
1474}
1475
1476namespace {
1477
1478// Each stored channel occupies n_geom rows in geometry order. The block
1479// ordinal identifies storage independently of its physical derivative label.
1480std::vector<Eigen::Index> localLooGeometryBlockRows(
1481 const std::vector<Eigen::Index>& geometry_ids, Eigen::Index n_geom,
1482 Eigen::Index n_blocks)
1483{
1484 std::vector<Eigen::Index> rows;
1485 rows.reserve(geometry_ids.size() * static_cast<std::size_t>(n_blocks));
1486 for (Eigen::Index b = 0; b < n_blocks; ++b) {
1487 for (const Eigen::Index g: geometry_ids)
1488 rows.push_back(b * n_geom + g);
1489 }
1490 return rows;
1491}
1492
1493void localLooGatherRows(const EigenMatrix& x, const Eigen::VectorXd& x_ind,
1494 const Eigen::VectorXd& y,
1495 const std::vector<Eigen::Index>& rows,
1496 EigenMatrix& x_out, Eigen::VectorXd& x_ind_out,
1497 Eigen::VectorXd& y_out)
1498{
1499 const Eigen::Index n = static_cast<Eigen::Index>(rows.size());
1500 x_out.resize(n, x.cols());
1501 x_ind_out.resize(n);
1502 y_out.resize(n);
1503 for (Eigen::Index r = 0; r < n; ++r) {
1504 const Eigen::Index src = rows[static_cast<std::size_t>(r)];
1505 x_out.row(r) = x.row(src);
1506 x_ind_out(r) = x_ind(src);
1507 y_out(r) = y(src);
1508 }
1509}
1510
1511// Neighborhood of held-out geometry i: every other geometry within one
1512// SExpAt correlation length (r <= 1, corr = exp(-r^2/2), the model's own
1513// validity radius -- see the GPNEB kernel-support-bound comment this
1514// mirrors). Degenerate guard: fewer than 2 geometries inside that radius
1515// is not a well-posed local solve (one point gives no handle on
1516// curvature vs. noise), so the neighborhood widens to the nearest 2
1517// geometries by r regardless of the radius; if fewer than 2 OTHER
1518// geometries exist at all, every one of them is used (there is no way to
1519// reach 2).
1520std::vector<Eigen::Index> localLooNeighborIndices(
1521 const gpr::FieldMatrixd& geom_dist, Eigen::Index i, Eigen::Index n_geom)
1522{
1523 std::vector<Eigen::Index> radius;
1524 radius.reserve(static_cast<std::size_t>(n_geom - 1));
1525 for (Eigen::Index j = 0; j < n_geom; ++j) {
1526 if (j == i) continue;
1527 if (std::isfinite(geom_dist(i, j)) && geom_dist(i, j) <= 1.0)
1528 radius.push_back(j);
1529 }
1530 if (static_cast<Eigen::Index>(radius.size()) >= 2) return radius;
1531
1532 std::vector<Eigen::Index> nearest;
1533 nearest.reserve(static_cast<std::size_t>(n_geom - 1));
1534 for (Eigen::Index j = 0; j < n_geom; ++j)
1535 if (j != i) nearest.push_back(j);
1536 std::sort(nearest.begin(), nearest.end(),
1537 [&](Eigen::Index a, Eigen::Index b) {
1538 return geom_dist(i, a) < geom_dist(i, b);
1539 });
1540 const std::size_t keep = std::min<std::size_t>(2, nearest.size());
1541 nearest.resize(keep);
1542 return nearest;
1543}
1544
1545// Sexpat directional cross-covariance of two arbitrary observation
1546// matrices. Empty where a block should exist is a refusal: the local-LOO
1547// gradient does not replace that with a difference.
1548bool sexpatCrossDirectional(const GaussianProcessRegression& model,
1549 const EigenMatrix& left,
1550 const Eigen::VectorXd& left_index,
1551 const EigenMatrix& right,
1552 const Eigen::VectorXd& right_index,
1553 const Eigen::VectorXd& direction,
1554 EigenMatrix& derivative)
1555{
1556 derivative.resize(left.rows(), right.rows());
1557 derivative.setZero();
1558 if (model.sexpat_cov_func == nullptr) return false;
1559 if (left.rows() == 0 || right.rows() == 0) return true;
1560
1561 SexpatCF& cov = *model.sexpat_cov_func;
1562 Eigen::VectorXd u_left, u_right;
1563 model.extractUniqueIndices(left_index, u_left);
1564 model.extractUniqueIndices(right_index, u_right);
1565 Eigen::Map<const Eigen::ArrayXd> left_arr(left_index.data(),
1566 left_index.size());
1567 Eigen::Map<const Eigen::ArrayXd> right_arr(right_index.data(),
1568 right_index.size());
1569
1570 FieldMatrixd left_0, right_0, left_1, right_1;
1571 FieldMatrixd block_first, block_second;
1572 FieldMatrixIdx dims_left(1, 1), dims_right(1, 1);
1573 const Eigen::Index n_left_0 = (left_arr == 0).count();
1574 const Eigen::Index n_right_0 = (right_arr == 0).count();
1575
1576 auto coordinates = [&](const EigenMatrix& rows,
1577 const Eigen::VectorXd& index, Index_t channel,
1578 Eigen::Index count, FieldMatrixd& out) {
1579 out.resize(count, rows.cols() + 1);
1580 out.setZero();
1581 model.extractCoordinatesByIndex(rows, index, channel, out);
1582 };
1583 auto place = [&](Index_t row_channel, Index_t col_channel,
1584 const FieldMatrixd& field, bool transpose,
1585 Eigen::Index field_rows, Eigen::Index field_cols) {
1586 if (field.rows() < field_rows || field.cols() < field_cols)
1587 return false;
1588 model.assignBlockToMatrix(left_index, right_index, row_channel,
1589 col_channel, field, derivative, transpose);
1590 return true;
1591 };
1592
1593 if (n_left_0 > 0 && n_right_0 > 0) {
1594 coordinates(left, left_index, 0, n_left_0, left_0);
1595 coordinates(right, right_index, 0, n_right_0, right_0);
1596 cov.calculateDirectionalCovarianceMatrix(left_0, right_0, direction,
1597 block_first, block_second);
1598 if (!place(0, 0, block_first, false, n_left_0, n_right_0)) return false;
1599 }
1600 if (n_left_0 > 0) {
1601 if (left_0.rows() != n_left_0)
1602 coordinates(left, left_index, 0, n_left_0, left_0);
1603 for (Eigen::Index j = 0; j < u_right.size(); ++j) {
1604 const auto channel = static_cast<Index_t>(u_right[j]);
1605 const Eigen::Index count = (right_arr == u_right[j]).count();
1606 if (count == 0) continue;
1607 dims_right(0, 0) = channel;
1608 coordinates(right, right_index, channel, count, right_1);
1609 cov.calculateDirectionalCovarianceMatrixWithDerivatives(
1610 right_1, left_0, dims_right, direction, block_first,
1611 block_second);
1612 if (!place(0, channel, block_first, true, count, n_left_0))
1613 return false;
1614 }
1615 }
1616 if (n_right_0 > 0) {
1617 if (right_0.rows() != n_right_0)
1618 coordinates(right, right_index, 0, n_right_0, right_0);
1619 for (Eigen::Index i = 0; i < u_left.size(); ++i) {
1620 const auto channel = static_cast<Index_t>(u_left[i]);
1621 const Eigen::Index count = (left_arr == u_left[i]).count();
1622 if (count == 0) continue;
1623 dims_left(0, 0) = channel;
1624 coordinates(left, left_index, channel, count, left_1);
1625 cov.calculateDirectionalCovarianceMatrixWithDerivatives(
1626 left_1, right_0, dims_left, direction, block_first,
1627 block_second);
1628 if (!place(channel, 0, block_first, false, count, n_right_0))
1629 return false;
1630 }
1631 }
1632 for (Eigen::Index i = 0; i < u_left.size(); ++i) {
1633 const auto left_channel = static_cast<Index_t>(u_left[i]);
1634 const Eigen::Index n_left = (left_arr == u_left[i]).count();
1635 if (n_left == 0) continue;
1636 dims_left(0, 0) = left_channel;
1637 coordinates(left, left_index, left_channel, n_left, left_1);
1638 for (Eigen::Index j = 0; j < u_right.size(); ++j) {
1639 const auto right_channel = static_cast<Index_t>(u_right[j]);
1640 const Eigen::Index n_right = (right_arr == u_right[j]).count();
1641 if (n_right == 0) continue;
1642 dims_right(0, 0) = right_channel;
1643 coordinates(right, right_index, right_channel, n_right, right_1);
1644 cov.calculateDirectionalCovarianceMatrixWithDerivatives2(
1645 left_1, right_1, dims_left, dims_right, direction, block_first,
1646 block_second);
1647 if (!place(left_channel, right_channel, block_first, false, n_left,
1648 n_right))
1649 return false;
1650 }
1651 }
1652 return derivative.allFinite();
1653}
1654
1655} // namespace
1656
1657double
1659 const Eigen::VectorXd& w, const EigenMatrix& x,
1660 const Eigen::VectorXd& x_ind, const Eigen::VectorXd& y,
1661 Eigen::Index geometry_index)
1662{
1663 if (!detail::logParametersAreRepresentable(w)) {
1664 return std::numeric_limits<double>::infinity();
1665 }
1666 setParameters(w);
1667 if (sexpat_cov_func == nullptr || lik_gaussian == nullptr ||
1668 x.rows() == 0 || x_ind.size() != x.rows() || y.size() != x.rows()) {
1669 return std::numeric_limits<double>::quiet_NaN();
1670 }
1671 const detail::ObservationChannelLayout channels(x_ind);
1672 const Eigen::Index n_blocks = channels.channelCount();
1673 const Eigen::Index n_geom = channels.rowsPerChannel();
1674 const auto& configuration = sexpat_cov_func->getConfInfo();
1675 Coord R_geom;
1676 if (!extractGroupedGeometryPositions(x, channels, configuration, R_geom)) {
1677 return std::numeric_limits<double>::quiet_NaN();
1678 }
1679 if (n_geom < 2 || geometry_index < 0 || geometry_index >= n_geom) {
1680 return std::numeric_limits<double>::quiet_NaN();
1681 }
1682
1683 const gpr::FieldMatrixd& ls_ref = sexpat_cov_func->getLengthScaleRef();
1684 if (ls_ref.size() == 0) return std::numeric_limits<double>::quiet_NaN();
1685
1686 aux::Distance kernel_distance;
1687 gpr::FieldMatrixd geom_dist;
1688 kernel_distance.dist_at(R_geom, R_geom, configuration, ls_ref, geom_dist);
1689 if (geom_dist.rows() != n_geom || geom_dist.cols() != n_geom) {
1690 return std::numeric_limits<double>::quiet_NaN();
1691 }
1692
1693 const double total_sigma2 = lik_gaussian->getSigma2() + jitter_sigma2;
1694 if (!(total_sigma2 > 0.0)) return std::numeric_limits<double>::quiet_NaN();
1695
1696 return evaluateLocalLooGeometryTerm(x, x_ind, y, geom_dist, geometry_index,
1697 n_geom, n_blocks, total_sigma2);
1698}
1699
1701 const EigenMatrix& x, const Eigen::VectorXd& x_ind,
1702 const Eigen::VectorXd& y, const gpr::FieldMatrixd& geom_dist,
1703 Eigen::Index i, Eigen::Index n_geom, Eigen::Index n_blocks,
1704 double total_sigma2, Eigen::VectorXd* parameter_gradient)
1705{
1706 const std::vector<Eigen::Index> neighbors =
1707 localLooNeighborIndices(geom_dist, i, n_geom);
1708 if (neighbors.empty()) return std::numeric_limits<double>::quiet_NaN();
1709
1710 const std::vector<Eigen::Index> rows_i =
1711 localLooGeometryBlockRows({i}, n_geom, n_blocks);
1712 const std::vector<Eigen::Index> rows_J =
1713 localLooGeometryBlockRows(neighbors, n_geom, n_blocks);
1714
1715 EigenMatrix x_i, x_J;
1716 Eigen::VectorXd x_ind_i, x_ind_J, y_i, y_J;
1717 localLooGatherRows(x, x_ind, y, rows_i, x_i, x_ind_i, y_i);
1718 localLooGatherRows(x, x_ind, y, rows_J, x_J, x_ind_J, y_J);
1719
1720 // K_JJ is the ordinary NOISY training covariance of the neighborhood
1721 // (evaluateTrainingCovarianceMatrix already adds lik_gaussian's sigma2
1722 // diagonal); jitter_sigma2 is layered on top to match the global LOO
1723 // path's total_sigma2 = getSigma2() + jitter_sigma2 convention.
1724 EigenMatrix K_JJ;
1725 evaluateTrainingCovarianceMatrix(x_J, x_ind_J, K_JJ,
1726 /*serial_per_rank=*/true);
1727 if (K_JJ.rows() != K_JJ.cols() || K_JJ.rows() != x_J.rows() ||
1728 !K_JJ.allFinite()) {
1729 return std::numeric_limits<double>::quiet_NaN();
1730 }
1731 if (jitter_sigma2 > 0.0) K_JJ.diagonal().array() += jitter_sigma2;
1732 // Marchildon-Zingg principled nugget (see Helpers.h): a data-driven
1733 // condition-floor for the dense LLT solve, the local-block analogue of
1734 // the HS-SVD path's conditionFlooredSigma2 (that helper floors the
1735 // singular values of a StableBasisND factorization, which this plain
1736 // dense block does not have). Small neighborhoods are exactly where
1737 // this matters: the degenerate-guard widening above can pull in two
1738 // near-duplicate geometries, and a handful of rows gives the LLT much
1739 // less slack against near-singularity than the full training kernel.
1740 if (!principled_nugget_)
1741 applyPrincipledDiagonalNugget(
1742 K_JJ, static_cast<Eigen::Index>(neighbors.size()), n_blocks - 1,
1743 principledKappaMaxDefault(),
1744 /*gradient_enhanced=*/true);
1745
1746 const Eigen::LLT<EigenMatrix> llt(K_JJ);
1747 if (llt.info() != Eigen::Success) {
1748 return std::numeric_limits<double>::quiet_NaN();
1749 }
1750
1751 EigenMatrix K_iJ, K_ii;
1752 evaluateCovarianceMatrix(x_i, x_J, x_ind_i, x_ind_J, K_iJ,
1753 /*serial_per_rank=*/true);
1754 evaluateCovarianceMatrix(x_i, x_i, x_ind_i, x_ind_i, K_ii,
1755 /*serial_per_rank=*/true);
1756 if (K_iJ.rows() != y_i.size() || K_iJ.cols() != y_J.size() ||
1757 !K_iJ.allFinite() || !K_ii.allFinite()) {
1758 return std::numeric_limits<double>::quiet_NaN();
1759 }
1760
1761 // Standard GP posterior predictive of a NEW noisy observation at i
1762 // given the neighborhood J: mu = K_iJ (K_JJ)^-1 y_J,
1763 // Sigma = K_ii - K_iJ (K_JJ)^-1 K_Ji + total_sigma2 I (the "+ noise"
1764 // term matches predicting y, not the latent f, the same convention the
1765 // global LOO path uses for its C = K + sigma2 I).
1766 // One refinement step. On this neighbourhood the unrefined solve
1767 // misses Richardson by 2.64e-9 on component 1 and the retired
1768 // cbrt(eps) difference by 1.15e-6, past the 1e-6 check. The extra
1769 // triangular correction brings those errors to 1.95e-9 and 6.63e-7.
1770 auto refine_vector = [&](const Eigen::VectorXd& rhs) {
1771 Eigen::VectorXd solved = llt.solve(rhs);
1772 solved += llt.solve(rhs - K_JJ * solved);
1773 return solved;
1774 };
1775 auto refine_matrix = [&](const EigenMatrix& rhs) {
1776 EigenMatrix solved = llt.solve(rhs);
1777 solved += llt.solve(rhs - K_JJ * solved);
1778 return solved;
1779 };
1780 const Eigen::VectorXd alpha_J = refine_vector(y_J);
1781 const EigenMatrix W = refine_matrix(K_iJ.transpose());
1782 const Eigen::VectorXd mu_i = K_iJ * alpha_J;
1783 EigenMatrix Sigma_i = K_ii - K_iJ * W;
1784 Sigma_i.diagonal().array() += total_sigma2;
1785
1786 double nlp = 0.0;
1787 const double log_two_pi = numerics::log(2.0 * std::acos(-1.0));
1788 for (Eigen::Index r = 0; r < y_i.size(); ++r) {
1789 const double v = Sigma_i(r, r);
1790 if (!(v > 0.0) || !std::isfinite(v)) {
1791 return std::numeric_limits<double>::quiet_NaN();
1792 }
1793 const double resid = y_i(r) - mu_i(r);
1794 nlp += 0.5 * (log_two_pi + numerics::log(v) + resid * resid / v);
1795 }
1796 if (parameter_gradient == nullptr || parameter_gradient->size() == 0)
1797 return nlp;
1798
1799 // Neighbors stay at the current length scale. The radius cutoff is
1800 // piecewise smooth; off that kink the derivative is this contraction.
1801 // A directional block that does not assemble refuses with NaN rather
1802 // than a difference of the scalar above.
1803 Eigen::VectorXd term_gradient =
1804 Eigen::VectorXd::Zero(parameter_gradient->size());
1805 Eigen::VectorXd u_J;
1806 extractUniqueIndices(x_ind_J, u_J);
1807 const double eta =
1808 principled_nugget_
1809 ? 0.0
1810 : computePrincipledNugget(
1811 static_cast<Eigen::Index>(neighbors.size()), n_blocks - 1,
1812 principledKappaMaxDefault(), /*gradient_enhanced=*/true);
1813 const double diagonal_scale = 1.0 + eta;
1814 const Eigen::Index n_cov = covarianceParameterCount();
1815 for (Eigen::Index j = 0; j < term_gradient.size(); ++j) {
1816 Eigen::VectorXd direction = Eigen::VectorXd::Zero(term_gradient.size());
1817 direction(j) = 1.0;
1818 EigenMatrix dK_JJ, unused_second;
1819 assembleDirectionalCovarianceDerivatives(x_J, x_ind_J, u_J, direction,
1820 dK_JJ, unused_second,
1821 /*serial_per_rank=*/true);
1822 if (dK_JJ.rows() != K_JJ.rows() || dK_JJ.cols() != K_JJ.cols() ||
1823 !dK_JJ.allFinite()) {
1824 return std::numeric_limits<double>::quiet_NaN();
1825 }
1826 dK_JJ = 0.5 * (dK_JJ + dK_JJ.transpose().eval());
1827 if (diagonal_scale != 1.0) dK_JJ.diagonal().array() *= diagonal_scale;
1828
1829 EigenMatrix dK_iJ, dK_ii;
1830 if (!sexpatCrossDirectional(*this, x_i, x_ind_i, x_J, x_ind_J,
1831 direction, dK_iJ) ||
1832 dK_iJ.rows() != K_iJ.rows() || dK_iJ.cols() != K_iJ.cols() ||
1833 !sexpatCrossDirectional(*this, x_i, x_ind_i, x_i, x_ind_i,
1834 direction, dK_ii) ||
1835 dK_ii.rows() != K_ii.rows() || dK_ii.cols() != K_ii.cols()) {
1836 return std::numeric_limits<double>::quiet_NaN();
1837 }
1838 dK_ii = 0.5 * (dK_ii + dK_ii.transpose().eval());
1839
1840 const Eigen::VectorXd d_alpha = refine_vector(-(dK_JJ * alpha_J));
1841 const EigenMatrix dW = refine_matrix(dK_iJ.transpose() - dK_JJ * W);
1842 const Eigen::VectorXd d_mu = dK_iJ * alpha_J + K_iJ * d_alpha;
1843 const EigenMatrix d_sigma = dK_ii - dK_iJ * W - K_iJ * dW;
1844 if (!d_mu.allFinite() || !d_sigma.allFinite()) {
1845 return std::numeric_limits<double>::quiet_NaN();
1846 }
1847 const double d_noise =
1848 (theta_includes_likelihood_noise_ &&
1849 j + 1 == term_gradient.size() && term_gradient.size() > n_cov)
1851 : 0.0;
1852 double d_nlp = 0.0;
1853 for (Eigen::Index r = 0; r < y_i.size(); ++r) {
1854 const double v = Sigma_i(r, r);
1855 const double resid = y_i(r) - mu_i(r);
1856 const double dv = d_sigma(r, r) + d_noise;
1857 d_nlp += 0.5 * (1.0 - resid * resid / v) * (dv / v) -
1858 (resid / v) * d_mu(r);
1859 }
1860 if (!std::isfinite(d_nlp))
1861 return std::numeric_limits<double>::quiet_NaN();
1862 term_gradient(j) = d_nlp;
1863 }
1864 parameter_gradient->noalias() += term_gradient;
1865 return nlp;
1866}
1867
1869 const Eigen::VectorXd& w, const EigenMatrix& x,
1870 const Eigen::VectorXd& x_ind, const Eigen::VectorXd& y)
1871{
1872 return evaluateLocalNeighborhoodLooObjective(w, x, x_ind, y, nullptr);
1873}
1874
1876 const Eigen::VectorXd& w, const EigenMatrix& x,
1877 const Eigen::VectorXd& x_ind, const Eigen::VectorXd& y,
1878 Eigen::VectorXd* gradient)
1879{
1880 if (!detail::logParametersAreRepresentable(w)) {
1881 return std::numeric_limits<double>::infinity();
1882 }
1883 setParameters(w);
1884 if (sexpat_cov_func == nullptr || lik_gaussian == nullptr ||
1885 x.rows() == 0 || x_ind.size() != x.rows() || y.size() != x.rows()) {
1886 return std::numeric_limits<double>::quiet_NaN();
1887 }
1888
1889 // Directional consumers reuse the training permutation, so the objective
1890 // refreshes its factor layout for the supplied observation rows.
1892
1893 const detail::ObservationChannelLayout channels(x_ind);
1894 const Eigen::Index n_blocks = channels.channelCount();
1895 const Eigen::Index n_geom = channels.rowsPerChannel();
1896 const auto& configuration = sexpat_cov_func->getConfInfo();
1897 Coord R_geom;
1898 if (!extractGroupedGeometryPositions(x, channels, configuration, R_geom)) {
1899 return std::numeric_limits<double>::quiet_NaN();
1900 }
1901 if (n_geom < 2) return std::numeric_limits<double>::quiet_NaN();
1902
1903 const gpr::FieldMatrixd& ls_ref = sexpat_cov_func->getLengthScaleRef();
1904 if (ls_ref.size() == 0) return std::numeric_limits<double>::quiet_NaN();
1905
1906 aux::Distance kernel_distance;
1907 gpr::FieldMatrixd geom_dist;
1908 kernel_distance.dist_at(R_geom, R_geom, configuration, ls_ref, geom_dist);
1909 if (geom_dist.rows() != n_geom || geom_dist.cols() != n_geom) {
1910 return std::numeric_limits<double>::quiet_NaN();
1911 }
1912
1913 const double total_sigma2 = lik_gaussian->getSigma2() + jitter_sigma2;
1914 if (!(total_sigma2 > 0.0)) return std::numeric_limits<double>::quiet_NaN();
1915
1916 int rank = 0;
1917 int nprocs = 1;
1918#ifdef GPR_LINALG_SCALAPACK
1919 {
1920 auto& st = backend().distributed();
1921 st.initialize();
1922 rank = st.myrank();
1923 nprocs = st.nprocs();
1924 }
1925#endif
1926
1927 // Rank r owns geometries with i % nprocs == r. Each term is a
1928 // deterministic double, so an exact accumulator merged by integer
1929 // addition gives the same objective for every rank count.
1930 linalg::ExactSum objective;
1931 std::vector<linalg::ExactSum> grad_sums;
1932 if (gradient != nullptr) grad_sums.resize(gradient->size());
1933 for (Eigen::Index i = 0; i < n_geom; ++i) {
1934 if (static_cast<int>(i % nprocs) != rank) continue;
1935 if (gradient == nullptr) {
1937 x, x_ind, y, geom_dist, i, n_geom, n_blocks, total_sigma2));
1938 continue;
1939 }
1940 Eigen::VectorXd term_gradient = Eigen::VectorXd::Zero(gradient->size());
1942 x, x_ind, y, geom_dist, i, n_geom, n_blocks, total_sigma2,
1943 &term_gradient));
1944 for (Eigen::Index j = 0; j < term_gradient.size(); ++j)
1945 grad_sums[static_cast<std::size_t>(j)].add(term_gradient(j));
1946 }
1947
1948#ifdef GPR_LINALG_SCALAPACK
1949 if (nprocs > 1) {
1950 backend().exact_sum_bcast(&objective, 1);
1951 for (auto& component: grad_sums)
1952 backend().exact_sum_bcast(&component, 1);
1953 }
1954#endif
1955
1956 double eprior = 0.0;
1957 if (const_cov_fun) eprior -= const_cov_fun->calculateLogPrior();
1958 if (sexpat_cov_func) eprior -= sexpat_cov_func->calculateLogPrior();
1959 if (lik_gaussian) eprior -= lik_gaussian->evaluateLogPrior();
1960 if (gradient != nullptr) {
1961 for (Eigen::Index j = 0; j < gradient->size(); ++j)
1962 (*gradient)(j) = grad_sums[static_cast<std::size_t>(j)].value();
1963 if (sexpat_cov_func) {
1964 const FieldMatrixd gprior_cf =
1965 -sexpat_cov_func->calculateLogPriorGradient();
1966 const Eigen::Index n_prior =
1967 std::min<Eigen::Index>(gprior_cf.size(), gradient->size());
1968 if (n_prior > 0) {
1969 gradient->head(n_prior) += Eigen::Map<const Eigen::VectorXd>(
1970 gprior_cf.data(), n_prior);
1971 }
1972 }
1973 if (theta_includes_likelihood_noise_ && lik_gaussian &&
1974 gradient->size() > covarianceParameterCount()) {
1975 FieldMatrixd gprior_lik;
1976 lik_gaussian->evaluateLogPriorGradient(gprior_lik);
1977 if (gprior_lik.size() > 0)
1978 (*gradient)(gradient->size() - 1) += -gprior_lik(0, 0);
1979 }
1980 }
1981 return objective.value() + eprior;
1982}
1983
1986 const Eigen::VectorXd& w, const TrainingKernelGeometry& /*geom*/,
1987 const EigenMatrix& x, const Eigen::VectorXd& x_ind,
1988 const Eigen::VectorXd& y, EnergyAndGradient& energy_and_gradient)
1989{
1990 if (detail::rejectInvalidHyperparameters(w, energy_and_gradient)) return;
1991 ++local_loo_objective_evaluations_for_testing_;
1992
1993 energy_and_gradient.gradient.resize(w.size());
1994 energy_and_gradient.gradient.setZero();
1996 w, x, x_ind, y, &energy_and_gradient.gradient);
1997 if (!std::isfinite(energy_and_gradient.energy)) {
1998 energy_and_gradient.gradient.setZero();
1999 setParameters(w);
2000 return;
2001 }
2002 // The objective's setParameters(w) is the point the returned energy
2003 // and gradient are at. Repeat it so a later read cannot observe a
2004 // directional assembly's temporary kernel state.
2005 setParameters(w);
2006}
2007
2009 const Eigen::VectorXd& x_ind,
2010 const Eigen::VectorXd& y,
2011 Eigen::VectorXd& gradient)
2012{
2013 // Both objective entry points use the same derivative assembly. A local
2014 // handle follows the current atom configuration and observation indices.
2015#ifdef GPR_LINALG_KOKKOS
2016 if (devicePosteriorGradient(gradient)) return;
2017#endif
2019 const TrainingKernelGeometry* handle = nullptr;
2020 if (use_training_geometry_handle_) {
2021 // Distances do not depend on theta. The fit's first evaluation
2022 // builds them; the gradient at that same theta applies them.
2023 handle = fitGeometryFor(x, x_ind);
2024 if (handle == nullptr &&
2026 /*reused=*/true)) {
2027 handle = &geometry;
2028 }
2029 }
2030 evaluateGradientWithGeometry(x, x_ind, y, gradient, handle);
2031}
2032
2034 const EigenMatrix& x, const Eigen::VectorXd& x_ind,
2035 const Eigen::VectorXd& y, Eigen::VectorXd& gradient,
2036 const TrainingKernelGeometry* training_geom)
2037{
2038 gradient_replicated_inverse_entries_for_testing_ = 0;
2039#ifdef GPR_LINALG_KOKKOS
2040 if (devicePosteriorGradient(gradient)) return;
2041#endif
2042 const bool profile_gradient_split = profile_gradient_split_;
2043 auto reduce_max_seconds = [&](const double local_seconds) {
2044#ifdef GPR_LINALG_SCALAPACK
2045 int mpi_up = 0;
2046 MPI_Initialized(&mpi_up);
2047 if (!mpi_up) return local_seconds;
2048
2049 int nprocs = 1;
2050 MPI_Comm_size(mpiContext().comm, &nprocs);
2051 if (nprocs == 1) return local_seconds;
2052
2053 const double send_seconds = local_seconds;
2054 double global_seconds = 0.0;
2055 MPI_Allreduce(&send_seconds, &global_seconds, 1, MPI_DOUBLE, MPI_MAX,
2056 mpiContext().comm);
2057 return global_seconds;
2058#else
2059 return local_seconds;
2060#endif
2061 };
2062 auto elapsed_seconds =
2063 [&](const std::chrono::steady_clock::time_point& start) {
2064 return std::chrono::duration<double>(
2065 std::chrono::steady_clock::now() - start)
2066 .count();
2067 };
2068
2069 EigenMatrix invC;
2070 Eigen::VectorXd alpha;
2071 Eigen::VectorXd uDdim;
2072 FieldMatrixd gdata;
2073 FieldMatrixd gprior;
2074
2075 // Note: the calculateTrainingCovarianceMatrix() method is always called in
2076 // the evaluateEnergy() method, and we always call for the
2077 // evaluateGradient() method after evaluateEnergy() being called (see
2078 // evaluateEnergyAndGradient(). So, there is no point to re-evaluate
2079 // covariance metrix here. However, we keep it hear guarded by an
2080 // if-statement for sake of unit tests. Otherwise, the matrix C will not be
2081 // allocated.
2087 }
2088
2089 const double hssvd_likelihood_sigma2 =
2090 lik_gaussian ? lik_gaussian->getSigma2() : 0.0;
2091 const double hssvd_total_sigma2 = hssvd_likelihood_sigma2 + jitter_sigma2;
2092 // The objective trace state can be active either as the orthonormal
2093 // Q-form contraction (use_hssvd_gradient) or, when the objective kept the
2094 // canonical Cholesky factor, through that factor exactly like the Cholesky
2095 // backend (hssvd_objective_trace_via_cholesky_). The latter keeps the
2096 // gradient bit-consistent with the reference; the eigenbasis markers stay
2097 // valid for diagnostics either way.
2098 const bool hssvd_objective_active =
2099 use_hssvd_backend_ && use_hssvd_objective_contractions_ &&
2100 hssvdObjectiveStampMatches() &&
2101 hssvd_objective_trace_basis_.rows() == y.size() &&
2102 hssvd_objective_trace_weighted_basis_.rows() == y.size() &&
2103 hssvd_objective_trace_basis_.cols() ==
2104 hssvd_objective_trace_weighted_basis_.cols() &&
2105 hssvd_objective_alpha_.size() == y.size() && hssvd_total_sigma2 > 0.0;
2106 const bool use_hssvd_gradient =
2107 hssvd_objective_active && !hssvd_objective_trace_via_cholesky_;
2108
2109#ifndef GPR_LINALG_SCALAPACK
2110 const auto& krylov = krylov_objective_.solver;
2111 if (!use_hssvd_gradient && krylov &&
2112 krylov_objective_.y.size() == y.size() && krylov_objective_.y == y &&
2114 evaluateKrylovGradient(x, x_ind, gradient, training_geom);
2115 return;
2116 }
2117 if (!use_hssvd_gradient && L.rows() != activeFactorOrder(y.rows()))
2119#endif
2120 if (!use_hssvd_gradient && b.rows() != activeFactorOrder(y.rows())) {
2122 }
2123
2124 const auto alpha_start = std::chrono::steady_clock::now();
2125 if (use_hssvd_gradient) {
2126 alpha = hssvd_objective_alpha_;
2127 hssvd_trace_basis_ = &hssvd_objective_trace_basis_;
2128 hssvd_trace_weighted_basis_ = &hssvd_objective_trace_weighted_basis_;
2129 hssvd_trace_inv_noise_ = hssvd_objective_trace_inv_noise_;
2130 hssvd_trace_direct_inverse_ = hssvd_objective_trace_direct_inverse_;
2131 } else {
2132 // Keep the SCG algebra in terms of the Cholesky factor and solves:
2133 // alpha = C^{-1} y is obtained as alpha = L^{-T} (L^{-1} y).
2134 alpha = trainingSolver().unwhiten(b);
2135 if (rigid_deflation_.isActiveForFullOrder(y.rows()) &&
2136 alpha.size() == rigid_deflation_.deflated_rows) {
2137 alpha = rigid_deflation_.liftVectorZeroRigid(alpha);
2138 }
2139 }
2140 const double alpha_seconds =
2141 profile_gradient_split
2142 ? reduce_max_seconds(elapsed_seconds(alpha_start))
2143 : 0.0;
2144
2145 double inverse_seconds = 0.0;
2146#ifdef GPR_LINALG_SCALAPACK
2147 auto& st = backend().distributed();
2148 if (!use_hssvd_gradient) {
2149 gpr::assertMsg(
2150 st.has_cached_L() && st.cached_n() == static_cast<int>(x.rows()),
2151 "ScaLAPACK gradient path requires the active distributed "
2152 "Cholesky factor");
2153 }
2154#endif
2155
2156 // The dense gradient does not replicate K^{-1}. Trace terms solve
2157 // against dK, so two factors of the same Gram do not each grow their
2158 // own inverse by cond(K) * eps.
2159 gradient_replicated_inverse_entries_for_testing_ = 0;
2160 if (!use_hssvd_gradient && hasTrainingPermutation()) {
2161#ifndef GPR_LINALG_SCALAPACK
2163#endif
2164 }
2165
2166 if (const double data_term_scale = hyperparameterDataTermScale();
2167 data_term_scale != 1.0)
2168 alpha *= std::sqrt(data_term_scale);
2169
2170 // Gradient with respect to covariance function parameters
2171 extractUniqueIndices(x_ind, uDdim);
2172
2173 // Hutchinson stochastic-trace estimator for the hyperparameter-gradient
2174 // trace term tr(K^-1 dK), controlled by the config field hutch_num_probes_
2175 // (setHutchinsonProbes; default 0 = off, exact). m Rademacher probes z_j
2176 // with w_j = K^-1 z_j;
2177 // accumulateBlockContribution estimates the trace from {w_j, z_j} instead
2178 // of contracting the full dense inverse, leaving the quadratic (alpha-K)
2179 // term exact. Fixed seed so SCG sees a deterministic gradient surrogate
2180 // across NLML evaluations. w_j = K^{-1} z_j is a solve against the
2181 // factor, in observation order. The distributed path keeps its own trace.
2182 EigenMatrix hutch_Z, hutch_W;
2183 {
2184 const int hutch_m = hutch_num_probes_;
2185 if (!use_hssvd_gradient && hutch_m > 0 &&
2186 L.rows() == activeFactorOrder(y.size()) &&
2187 L.cols() == activeFactorOrder(y.size())) {
2188 const Eigen::Index N = y.size();
2189 std::mt19937 rng(0x9E3779B9u);
2190 hutch_Z.resize(N, hutch_m);
2191 for (Eigen::Index a = 0; a < N; ++a)
2192 for (int j = 0; j < hutch_m; ++j)
2193 hutch_Z(a, j) = (rng() & 1u) ? 1.0 : -1.0;
2194 const EigenMatrix Z_factor =
2197 : hutch_Z;
2198 EigenMatrix W_factor;
2199 if (rigid_deflation_.isActiveForFullOrder(N)) {
2200 const EigenMatrix Z_r = rigid_deflation_.projectRows(Z_factor);
2203 W_factor = rigid_deflation_.liftSolvedColumns(Z_factor, W_r);
2204 } else {
2205 W_factor = linalg::back_solve_mat(
2206 L, linalg::forward_solve_mat(L, Z_factor));
2207 }
2208 hutch_W =
2211 : W_factor;
2212 hutch_trace_W_ = &hutch_W;
2213 hutch_trace_Z_ = &hutch_Z;
2214 }
2215 }
2216
2217 // Surrogate fits take tr(K^{-1} dK) from a solve, so two factors of one
2218 // Gram do not each grow an inverse by cond(K) * eps. That is the
2219 // OCINEB curvature. The prior-free marginal-likelihood fit was measured
2220 // on the explicit inverse: the solve disagrees by about that cond(K) *
2221 // eps, and this fit then stops one step early (27 against the measured
2222 // 28). Eigen forms that inverse again for the prior-free fit only.
2223 // CHOLMOD's solve already takes the measured number of steps.
2224 // ScaLAPACK and SLATE take the trace from the distributed factor and
2225 // never read this inverse.
2226 const bool prior_free_inverse = priorFreeReplicatedInverse(
2227#ifdef GPR_LINALG_CHOLMOD
2228 true,
2229#else
2230 false,
2231#endif
2233 true,
2234#else
2235 false,
2236#endif
2237#ifdef GPR_LINALG_SLATE
2238 true,
2239#else
2240 false,
2241#endif
2242 unregularized_marginal_likelihood_, use_hssvd_gradient);
2243 const bool deflated_grad =
2244 !use_hssvd_gradient && rigid_deflation_.isActiveForFullOrder(y.size());
2245 if (prior_free_inverse) {
2246 invC = trainingSolver().inverse();
2247 if (deflated_grad) {
2248 invC = rigid_deflation_.liftInverse(invC);
2249 }
2252 gradient_replicated_inverse_entries_for_testing_ =
2253 static_cast<std::size_t>(invC.size());
2254 }
2255#ifdef GPR_LINALG_SCALAPACK
2256 const bool distributed_factor = training_cholesky_is_distributed_;
2257#else
2258 constexpr bool distributed_factor = false;
2259#endif
2260 const EigenMatrix* trace_factor = nullptr;
2262 prior_free_inverse, use_hssvd_gradient, distributed_factor,
2263 static_cast<long long>(L.rows()), static_cast<long long>(L.cols()),
2264 static_cast<long long>(activeFactorOrder(y.size())))) {
2265 trace_factor = &L;
2266 }
2267
2268 const auto const_start = std::chrono::steady_clock::now();
2269 const double inverse_before_const = PhaseTimers::gradient_inverse_seconds;
2270 calculateGradientWithCovFunc(
2271 x, x_ind, uDdim, alpha, invC, *const_cov_fun, gdata, gprior,
2272 /*serial_per_rank=*/use_hssvd_gradient, training_geom, trace_factor);
2273 const double const_inverse_seconds =
2274 PhaseTimers::gradient_inverse_seconds - inverse_before_const;
2275 const double const_seconds =
2276 profile_gradient_split
2277 ? reduce_max_seconds(std::max(
2278 0.0, elapsed_seconds(const_start) - const_inverse_seconds))
2279 : 0.0;
2280
2281 const auto sexpat_start = std::chrono::steady_clock::now();
2282 const double inverse_before_sexpat = PhaseTimers::gradient_inverse_seconds;
2283 calculateGradientWithCovFunc(
2284 x, x_ind, uDdim, alpha, invC, *sexpat_cov_func, gdata, gprior,
2285 /*serial_per_rank=*/use_hssvd_gradient, training_geom, trace_factor);
2286 hutch_trace_W_ = nullptr;
2287 hutch_trace_Z_ = nullptr;
2288 const double sexpat_inverse_seconds =
2289 PhaseTimers::gradient_inverse_seconds - inverse_before_sexpat;
2290 const double sexpat_seconds =
2291 profile_gradient_split
2292 ? reduce_max_seconds(std::max(
2293 0.0, elapsed_seconds(sexpat_start) - sexpat_inverse_seconds))
2294 : 0.0;
2295
2296 // Gradient with respect to Gaussian likelihood function parameters
2297 // Evaluate the gradient from Gaussian likelihood
2298 FieldMatrixd gprior_lik;
2299
2300#ifndef NDEBUG
2301 gpr::assertMsg(lik_gaussian != nullptr,
2302 "Object of Gausian likelihood is not allocated!");
2303#endif
2304 lik_gaussian->evaluateLogPriorGradient(gprior_lik);
2305
2306 if (gprior_lik.size() != 0) {
2307 gprior_lik *= -1.;
2308 gpr::field::appendRows(gprior, gprior_lik);
2309 }
2310
2311#ifdef GPR_LINALG_SCALAPACK
2312 const bool use_solve_based_trace = true;
2313#else
2314 constexpr bool use_solve_based_trace = false;
2315#endif
2316 // Use the same guarded trace_factor as the covariance derivatives: when
2317 // prior_free_inverse, use_hssvd_gradient, a distributed factor, or a
2318 // missing/mismatched factor leaves trace_factor null, passing an empty
2319 // matrix avoids stale L and selects invC.trace() or the distributed trace.
2320 const EigenMatrix no_factor;
2321 appendLikelihoodNoiseGradient(
2322 alpha, invC, trace_factor != nullptr ? *trace_factor : no_factor,
2323 use_solve_based_trace, gdata, gprior);
2324 hssvd_trace_basis_ = nullptr;
2325 hssvd_trace_weighted_basis_ = nullptr;
2326 hssvd_trace_inv_noise_ = 0.0;
2327 hssvd_trace_direct_inverse_ = false;
2328
2329 if (gprior.size() != 0) {
2330 if (gradient.rows() != gprior.size()) gradient.resize(gprior.size());
2331 gradient =
2332 Eigen::Map<const Eigen::VectorXd>(gdata.data(), gdata.size()) +
2333 Eigen::Map<const Eigen::VectorXd>(gprior.data(), gprior.size());
2334 }
2335
2336 if (report_level >= 3 && mpiContext().nprocs == 1) {
2337 const double* inverse_data = invC.data();
2338 std::size_t inverse_size = static_cast<std::size_t>(invC.size());
2339#ifdef GPR_LINALG_SCALAPACK
2340 if (st.has_cached_inv()) {
2341 inverse_data = st.cached_inv();
2342 inverse_size = static_cast<std::size_t>(st.cached_inv_desc()[8]) *
2343 st.local_cols(st.cached_inv_n());
2344 }
2345#endif
2346 std::fprintf(
2347 stderr,
2348 "[map-gradient] alpha=%016llx inverse=%016llx data=%016llx "
2349 "prior=%016llx result=%016llx\n",
2350 static_cast<unsigned long long>(
2351 fitComponentFingerprint(alpha.data(), alpha.size())),
2352 static_cast<unsigned long long>(
2353 fitComponentFingerprint(inverse_data, inverse_size)),
2354 static_cast<unsigned long long>(
2355 fitComponentFingerprint(gdata.data(), gdata.size())),
2356 static_cast<unsigned long long>(
2357 fitComponentFingerprint(gprior.data(), gprior.size())),
2358 static_cast<unsigned long long>(
2359 fitComponentFingerprint(gradient.data(), gradient.size())));
2360 }
2361
2362 if (profile_gradient_split) {
2363 inverse_seconds +=
2364 reduce_max_seconds(const_inverse_seconds + sexpat_inverse_seconds);
2365 recordGradientProfileSplit(alpha_seconds, inverse_seconds,
2366 const_seconds, sexpat_seconds);
2367 }
2368}
2369
2371 const EigenMatrix& factor, const EigenMatrix& observation_order,
2372 const detail::RigidDeflationState* deflation_override) const
2373{
2374 if (observation_order.rows() != observation_order.cols())
2375 return std::numeric_limits<double>::quiet_NaN();
2376 const detail::RigidDeflationState& active_deflation =
2377 deflation_override != nullptr ? *deflation_override : rigid_deflation_;
2378 if (active_deflation.isActiveForFullOrder(observation_order.rows()) &&
2379 factor.rows() == active_deflation.deflated_rows &&
2380 factor.cols() == active_deflation.deflated_rows) {
2381 EigenMatrix factor_order = observation_order;
2382 if (hasTrainingPermutation() &&
2383 static_cast<Eigen::Index>(training_permutation_.perm.size()) ==
2384 observation_order.rows()) {
2385 factor_order = gpr::permuteSymmetricMatrix(observation_order,
2387 }
2389 factor, active_deflation.projectSymmetric(factor_order));
2390 }
2391 if (factor.rows() != observation_order.rows() ||
2392 factor.cols() != observation_order.cols())
2393 return std::numeric_limits<double>::quiet_NaN();
2394 if (hasTrainingPermutation() &&
2395 static_cast<Eigen::Index>(training_permutation_.perm.size()) ==
2396 factor.rows()) {
2398 factor, gpr::permuteSymmetricMatrix(observation_order,
2400 }
2401 return linalg::trace_solve_product(factor, observation_order);
2402}
2403
2404} // namespace gpr
Linear algebra abstraction layer for GPR hot-path operations.
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
Exact floating-point accumulator (Kulisch long accumulator).
Tiny value type describing the MPI dispatch context for a probe loop.
MPI-aware dispatcher for the Hutchinson-style probe loop used by the Laplace Hessian assembler and th...
#define GPR_LINALG_SCALAPACK
Definition SlateBackend.h:9
Methods to calculate distances between atoms.
Definition Distance.h:154
void dist_at(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, gpr::FieldMatrixd &dist, bool take_sqrt=true)
Give the distance between two atomic configurations as defined in the special GPstuff covariance func...
Definition Distance.cpp:620
virtual void recordHyperparameterDataTerm(double, double)
linalg::BackendContext & backend() const
void evaluateKrylovGradient(const EigenMatrix &x, const Eigen::VectorXd &x_ind, Eigen::VectorXd &gradient, const TrainingKernelGeometry *training_geom)
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)
bool evaluateTrainingCovarianceMatrixFromGeometry(const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool serial_per_rank=false, bool include_constant=true, bool include_noise=true)
double evaluateLocalNeighborhoodLooGeometryTermForTesting(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::Index geometry_index)
void prepareTrainingPermutationLocal(const Eigen::VectorXd &x_ind)
double evaluateEnergy(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
void evaluateGradientWithGeometry(const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &gradient, const TrainingKernelGeometry *training_geom)
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.
void evaluateEnergyAndGradient(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
Evaluate the energy function (un-normalized negative marginal log posterior) and its gradient.
void setParameters(const GPRSetup &parameters)
Set parameters of the GPR model.
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
bool prepareTrainingKernelGeometry(const EigenMatrix &x, const Eigen::VectorXd &x_ind, TrainingKernelGeometry &out, bool reused=false) const
bool assembleDirectionalCovarianceDerivativesFromGeometry(const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &ind_Ddim, const Eigen::VectorXd &uDdim, const Eigen::VectorXd &direction, EigenMatrix &first, EigenMatrix &second, bool serial_per_rank=false) const
double evaluateLocalNeighborhoodLooObjective(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd *gradient)
void evaluateLeaveOneOutEnergyAndGradientFromGeometry(const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
void calculateMeanPrediction(const Eigen::VectorXd &y)
Posterior mean prediction w.r.t energy. This function mimics the following step from the MATLAB code:...
Definition Predict.cpp:688
bool hasDevicePosterior() const noexcept
void planObjectiveBackend(const EigenMatrix &x, const Eigen::VectorXd &y)
Update the plan from the dense factor just formed at this order.
double evaluateLocalLooGeometryTerm(const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, const gpr::FieldMatrixd &geom_dist, Eigen::Index i, Eigen::Index n_geom, Eigen::Index n_blocks, double total_sigma2, Eigen::VectorXd *parameter_gradient=nullptr)
std::unique_ptr< SexpatCF > sexpat_cov_func
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)
void evaluateEnergyAndGradientLocal(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
void evaluateLocalNeighborhoodLooEnergyAndGradientFromGeometry(const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
void prepareTrainingPermutation(const Eigen::VectorXd &x_ind)
bool evaluateTrainingCovarianceInFactorOrderFromGeometry(const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool include_noise=true)
Eigen::VectorXd objectiveParameterStamp() const
double evaluateEnergyFromGeometry(const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
double traceInverseProduct(const EigenMatrix &factor, const EigenMatrix &observation_order, const detail::RigidDeflationState *deflation_override=nullptr) const
tr(K^{-1} A) through the training factor. A is in observation order.
RigidDeflationDiagnostic rigid_deflation_diag_
virtual bool supportsRigidNullDeflation() const noexcept
void extractUniqueIndices(const Eigen::VectorXd &input_ind, Eigen::VectorXd &output_ind) const
Extract unique indices from the input vector.
virtual void evaluateGradient(const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &gradient)
Evaluate the gradient of energy (GP_E) for Gaussian Process.
linalg::linop::DenseCholeskySolver trainingSolver() const
bool evaluateGradientAfterEnergy(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &gradient)
virtual double hyperparameterDataTermScale() const
bool evaluateGradientAfterEnergyFromGeometry(const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, Eigen::VectorXd &gradient)
std::optional< double > evaluateKrylovObjective(const Eigen::VectorXd &constant_update, const EigenMatrix &x, const Eigen::VectorXd &y)
double evaluateLocalNeighborhoodLooEnergy(const Eigen::VectorXd &w, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y)
void evaluateEnergyAndGradientFromGeometry(const Eigen::VectorXd &w, const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &y, EnergyAndGradient &energy_and_gradient)
void assembleDirectionalCovarianceDerivatives(const EigenMatrix &x, const Eigen::VectorXd &ind_Ddim, const Eigen::VectorXd &uDdim, const Eigen::VectorXd &direction, EigenMatrix &first, EigenMatrix &second, bool serial_per_rank=false) const
Assemble the directional first and second derivatives of the training covariance matrix for the optim...
Eigen::Index activeFactorOrder(Eigen::Index full_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).
const TrainingKernelGeometry * fitGeometryFor(const EigenMatrix &x, const Eigen::VectorXd &x_ind) const
bool devicePosteriorGradient(Eigen::VectorXd &gradient)
Pair-type inverse-distance squared-exponential primitive.
Definition SexpatCF.h:74
double leaveOneOutNegativeLogPredictiveDensityGroupedDirectionalDerivative(const Eigen::VectorXd &y, double sigma2, const Eigen::MatrixXd &dK, const std::vector< std::vector< Eigen::Index > > &groups) const
const Eigen::MatrixXd & leftSingularVectors() const
const Eigen::VectorXd & singularValues() const
double leaveOneOutNegativeLogPredictiveDensityGrouped(const Eigen::VectorXd &y, double sigma2, const std::vector< std::vector< Eigen::Index > > &groups) const
Eigen::Index numObs() const
StableBasisPosteriorWeights noisyPosteriorWeights(const Eigen::VectorXd &y, double sigma2) const
void factorizeKernel(const Eigen::MatrixXd &kernel, double sv_rtol=1e-13, double sv_abs_tol=0.0, double sv_chop_tol=0.0)
bool cholesky(const EigenMatrix &C, EigenMatrix &L)
bool cholesky_rank_update(EigenMatrix &lower, const Eigen::VectorXd &vector)
void add(double x) noexcept
Definition ExactSum.h:54
double value() const noexcept
The exact sum rounded once to the nearest double, ties to even.
Definition ExactSum.h:190
Eigen::VectorXd unwhiten(const Eigen::VectorXd &b) const
static bool factorize(BackendContext &backend, const EigenMatrix &covariance, const Eigen::VectorXd &rank_one, EigenMatrix &factor)
factor factor^T = covariance + rank_one rank_one^T.
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
void appendRows(Eigen::PlainObjectBase< Derived > &mat, const Eigen::PlainObjectBase< Derived > &other)
EigenMatrix back_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Back triangular solve with matrix RHS (BLAS equivalent: dtrsm with side=L, uplo=L,...
EigenMatrix forward_solve_mat(const EigenMatrix &L, const EigenMatrix &B)
Forward triangular solve with matrix RHS (BLAS equivalent: dtrsm).
double teamFactorWallSeconds()
double teamSolveWallSeconds()
bool rank_one_update_lower(EigenMatrix &lower, const Eigen::VectorXd &vector)
double trace_solve_product(const EigenMatrix &L, const EigenMatrix &A)
double log(double x) noexcept
double exp(double x) noexcept
Weights weightsFromLogParameters(const Eigen::VectorXd &theta, Eigen::Index n_pt)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29
Eigen::VectorXd unpermuteVector(const Eigen::VectorXd &input, const StructuredPermutation &p)
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
EigenMatrix permuteMatrixRows(const EigenMatrix &input, const StructuredPermutation &p)
double g_max_abs_alpha
EigenMatrix permuteSymmetricMatrix(const EigenMatrix &input, const StructuredPermutation &p)
EigenMatrix unpermuteSymmetricMatrix(const EigenMatrix &input, const StructuredPermutation &p)
double g_max_cond_k
EigenMatrix unpermuteMatrixRows(const EigenMatrix &input, const StructuredPermutation &p)
bool priorFreeReplicatedInverse(bool cholmod, bool scalapack, bool slate, bool unregularized, bool use_hssvd_gradient)
bool useDenseFactorForTrace(bool prior_free_inverse, bool use_hssvd_gradient, bool distributed_factor, long long factor_rows, long long factor_cols, long long target_size)
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
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844
Structure of energy and gradient stored in Eigen-compatible form.
Definition Structures.h:359
static double gradient_inverse_seconds
static long objective_channels
static double eigensolve_seconds
static double objective_seconds
static double energy_seconds
Objective energy outside factor, solve, eigen, kernel, and curvature.
static double assembly_seconds
static double curvature_seconds
static long objective_rows
static int objective_count