Loading...
Searching...
No Matches
gpr::laplace::TCovSecondOrder Class Reference

#include <gpr/ml/laplace/TCovSecondOrder.h>

Public Member Functions

 TCovSecondOrder ()=default
bool compute (const GaussianProcessRegression &gpr, const Eigen::MatrixXd &H_inv)
void applyCorrection (const GaussianProcessRegression &gpr, Observation &image1)
bool valid () const noexcept
 Is the cache populated and usable?
std::size_t nLs () const noexcept
 Number of cached lengthscale dimensions (0..n_ls).
void invalidate () noexcept
 Invalidate (drops all cached vectors).

Static Public Attributes

static constexpr double kTrustTau = 0.5

Detailed Description

Analytical closed-form 2nd-order TCOV-INLA correction cache (partial).

At the MAP hyperparameter theta_star, precomputes the vectors needed to evaluate the quadratic-in-Delta theta correction to the predictive mean at any query x*:

///     m(x*) = mu_MAP(x*)
///           + 0.5 * sum_{ij} (H^{-1})_{ij} * d^2 mu / d theta_i d theta_j (x*)
///
/// with
///
///     d^2 mu / d theta_i d theta_j (x*) =
///           k_{ij}(x*)^T * alpha_star
///         - k_i(x*)^T * z_j  -  k_j(x*)^T * z_i
///         + k_star(x*)^T * beta_{ij}
/// 

SymPy proof: python/tests/test_sympy_laplace_tcov_analytical.py (identities A1-A8; A8 is the partial-scope acceptance gate).

SCOPE: only (log_magn, log_magn) and (log_magn, log_ls_d) pairs are kept. Both (log_ls_d, log_ls_e) and (log_sn, *) are set to zero. The A8 gate shows this captures >= 50% of the full 2nd-order shift when H diagonal on log_ls is >= 10x the entry on log_magn, with sign agreement in the tight-posterior regime. The missed (ls, ls) terms are suppressed by 1/H_ls^2 and dominate only in the broad- posterior regime, which is opposite the post-SCG regime we target.

Required cached quantities, evaluated ONCE at theta_star:

///   K_d        = dK / d theta_d at theta_star  for d in {0 (magn), 1..nls
///   (ls)} z_d        = K_star^{-1} * K_d * alpha_star  (m_tr vectors, size
///   m_tr) beta_{0,d} = K_star^{-1} * (K_0 z_d + K_d z_0 - K_d alpha_star)  for
///   d in {0..nls}
///                (beta_{00} = K_star^{-1} * (2 K_0 z_0 - K_0 alpha_star))
///                 using A2: K_{0,0} = K_0 and K_{0,d} = K_d
/// 

m_tr = rows of gpr.R_matrix (= N_tr * (D+1) with gradient observations).

Non-copyable, value-semantic.

Definition at line 63 of file TCovSecondOrder.h.

Constructor & Destructor Documentation

◆ TCovSecondOrder()

gpr::laplace::TCovSecondOrder::TCovSecondOrder ( )
default

Member Function Documentation

◆ applyCorrection()

void gpr::laplace::TCovSecondOrder::applyCorrection ( const GaussianProcessRegression & gpr,
Observation & image1 )

Apply the partial 2nd-order correction to image1.E and image1.G per query point. Adds the quadratic shift in-place.

Definition at line 359 of file TCovSecondOrder.cpp.

361{
362 if (!valid_) return;
363 if (gpr.sexpat_cov_func == nullptr) return;
364 if (gpr.getRMatrix().size() == 0) return;
365
366 const Index_t N_im = static_cast<Index_t>(image1.R.rows());
367 const Index_t D = static_cast<Index_t>(image1.R.cols());
368 if (N_im == 0) return;
369
370 // Build R_mod + R_mod_ind from image1.R using the same stacked layout
371 // that calculatePotential uses. Row layout:
372 // [R_im (energy block, 0..N_im-1),
373 // R_im (d=1 block, N_im..2*N_im-1),
374 // ...,
375 // R_im (d=D block, D*N_im..(D+1)*N_im-1)]
376 // Column 0 of K_out will contain the energy prediction coefficients,
377 // cols N_im..2*N_im-1 the d=1 gradient coefficients, etc.
378 EigenMatrix R_mod;
379 Eigen::VectorXd R_mod_ind;
380 aux::AuxiliaryFunctionality aux_func;
381 aux_func.assembleMatrixOfRepetitiveCoordinates(image1.R, R_mod, R_mod_ind);
382
383 const Eigen::Index n_ls = static_cast<Eigen::Index>(n_ls_);
384 const Eigen::Index p_sex = 1 + n_ls;
385 const Eigen::Index m_q = R_mod.rows();
386
387 // Build cross-cov k_star(x*, X) between training and query (the
388 // full sexpat+const kernel; same as calculatePotential's KK without
389 // permutation). We reuse evaluateCovarianceMatrix for this.
390 EigenMatrix k_star;
391 gpr.evaluateCovarianceMatrix(gpr.getRMatrix(), R_mod, gpr.getRIndices(),
392 R_mod_ind, k_star);
393 k_star = gpr.rowsInTrainingFactorLayout(k_star);
394
395 // Build directional cross-cov derivatives at the query for each
396 // theta_d and for the sum-directions (e_i + e_j) needed by the
397 // polarisation identity. One directional probe per d returns BOTH
398 // first and second derivatives; the second output is the diagonal
399 // d^2 k / d theta_d^2 (x*, X). The sum-direction probes then supply
400 // the off-diagonal pairs via 0.5 * (d^2 k/d(e_i+e_j)^2 - k_{ii} - k_{jj}).
401 const std::size_t p_eff = n_ls_ + 1;
402 std::vector<EigenMatrix> dk_cross(p_eff); // k_d (first)
403 std::vector<EigenMatrix> dk2_cross(p_eff * (p_eff + 1) / 2); // k_{ij}
404 for (Eigen::Index d = 0; d <= n_ls; ++d) {
405 Eigen::VectorXd e_d = Eigen::VectorXd::Zero(p_sex);
406 e_d(d) = 1.0;
407 const std::size_t du = static_cast<std::size_t>(d);
408 EigenMatrix diag_second;
409 TCovSecondOrder::assembleCrossCovDirectional(
410 gpr, R_mod, R_mod_ind, e_d, &dk_cross[du], &diag_second);
411 dk_cross[du] = gpr.rowsInTrainingFactorLayout(dk_cross[du]);
412 diag_second = gpr.rowsInTrainingFactorLayout(diag_second);
413 dk2_cross[ijFlatIndex(du, du)] = std::move(diag_second);
414 }
415 for (Eigen::Index i = 0; i <= n_ls; ++i) {
416 for (Eigen::Index j = i + 1; j <= n_ls; ++j) {
417 Eigen::VectorXd sum_dir = Eigen::VectorXd::Zero(p_sex);
418 sum_dir(i) = 1.0;
419 sum_dir(j) = 1.0;
420 EigenMatrix sum_second;
421 TCovSecondOrder::assembleCrossCovDirectional(
422 gpr, R_mod, R_mod_ind, sum_dir, nullptr, &sum_second);
423 sum_second = gpr.rowsInTrainingFactorLayout(sum_second);
424 // k_{ij} = 0.5 * (sum_second - k_{ii} - k_{jj})
425 const auto& k_ii = dk2_cross[ijFlatIndex(
426 static_cast<std::size_t>(i), static_cast<std::size_t>(i))];
427 const auto& k_jj = dk2_cross[ijFlatIndex(
428 static_cast<std::size_t>(j), static_cast<std::size_t>(j))];
429 dk2_cross[ijFlatIndex(static_cast<std::size_t>(i),
430 static_cast<std::size_t>(j))] =
431 0.5 * (sum_second - k_ii - k_jj);
432 }
433 }
434
435 // Full quadratic-form accumulation with H_inv over all (i, j) pairs
436 // i, j in {0..n_ls}. For i == j the coefficient is 0.5 * H_inv(i,i);
437 // for i != j, the symmetric pair (i,j) + (j,i) contributes
438 // 2 * 0.5 * H_inv(i,j) = H_inv(i,j). Noise dim is omitted (A3 proves
439 // all cross-cov log_sn derivatives are zero).
440 Eigen::VectorXd corr = Eigen::VectorXd::Zero(m_q);
441
442 // Pre-compute the m_q-length inner-product row vectors for each d:
443 // z_dot_k[d][e][q] = z_[e]^T * dk_cross[d].col(q)
444 std::vector<std::vector<Eigen::RowVectorXd>> z_dot_k(p_eff);
445 for (std::size_t d = 0; d < p_eff; ++d) {
446 z_dot_k[d].resize(p_eff);
447 for (std::size_t e = 0; e < p_eff; ++e) {
448 z_dot_k[d][e] = z_[e].transpose() * dk_cross[d];
449 }
450 }
451 // k_star^T * beta_{ij}: row vector per upper-triangular pair
452 std::vector<Eigen::RowVectorXd> kstar_dot_beta(p_eff * (p_eff + 1) / 2);
453 for (std::size_t i = 0; i < p_eff; ++i) {
454 for (std::size_t j = i; j < p_eff; ++j) {
455 kstar_dot_beta[ijFlatIndex(i, j)] =
456 beta_full_[ijFlatIndex(i, j)].transpose() * k_star;
457 }
458 }
459
460 // Accumulate d^2 mu / d theta_i d theta_j contributions.
461 // d^2 mu / d theta_i d theta_j (x*) =
462 // k_{ij}(x*)^T alpha_star
463 // - k_i(x*)^T z_j - k_j(x*)^T z_i
464 // + k_star(x*)^T beta_{ij}
465 // corr[q] = sum_{i<=j} coeff_{ij} * d2mu_{ij}(x*[q])
466 // where coeff_{ii} = 0.5 * H_inv(i,i) and coeff_{ij}_{i<j} = H_inv(i,j).
467 for (std::size_t i = 0; i < p_eff; ++i) {
468 for (std::size_t j = i; j < p_eff; ++j) {
469 const Eigen::Index ii = static_cast<Eigen::Index>(i);
470 const Eigen::Index jj = static_cast<Eigen::Index>(j);
471 Eigen::RowVectorXd kij_dot_a =
472 alpha_star_.transpose() * dk2_cross[ijFlatIndex(i, j)];
473 Eigen::RowVectorXd d2_ij = kij_dot_a - z_dot_k[i][j] -
474 z_dot_k[j][i] +
475 kstar_dot_beta[ijFlatIndex(i, j)];
476 const double coeff =
477 (i == j) ? 0.5 * H_inv_(ii, jj) : H_inv_(ii, jj);
478 corr += coeff * d2_ij.transpose();
479 }
480 }
481
482 // Trust-region cap on the Taylor correction (TR2 in
483 // python/tests/test_sympy_laplace_trust_region.py): if the
484 // correction exceeds tau * |MAP|, fall back to bare MAP for that
485 // component. tau < 1 guarantees the corrected gradient stays in
486 // the same hemisphere as MAP -- so dimer acquisition decisions
487 // don't flip sign even with the (capped) Bayesian correction.
488 // Conn-Gould-Toint 2000 trust-region technique applied to the
489 // Bayesian Taylor expansion. No-op in the well-conditioned
490 // regime (PET-MAD-scale, TR3); active in the small-data regime
491 // (CuH2-scale, TR4).
492 auto cap = [](double map_val, double corr_val) {
493 // Quiet NaN must not reach fabs. Caller also skips this when the
494 // MAP energy is non-finite and has already zeroed the gradient.
495 if (!std::isfinite(map_val) || !std::isfinite(corr_val)) return 0.0;
496 const double bound = TCovSecondOrder::kTrustTau * std::fabs(map_val);
497 if (std::fabs(corr_val) <= bound) return corr_val;
498 return std::copysign(bound, corr_val);
499 };
500 // corr is m_q = N_im * (D + 1) entries: first N_im are energy, next
501 // N_im are gradient-dim-1, ..., last N_im are gradient-dim-D. Add
502 // element-wise to image1.E (RowVector, size N_im) and image1.G
503 // (N_im x D), with per-component trust-region cap.
504 for (Index_t i = 0; i < N_im; ++i) {
505 if (!std::isfinite(image1.E(0, i))) {
506 image1.G.row(i).setZero();
507 continue;
508 }
509 image1.E(0, i) += cap(image1.E(0, i), corr(i));
510 }
511 for (Index_t d = 0; d < D; ++d) {
512 for (Index_t i = 0; i < N_im; ++i) {
513 if (!std::isfinite(image1.E(0, i))) continue;
514 const double component = image1.G(i, d);
515 if (!std::isfinite(component)) {
516 image1.G(i, d) = 0.0;
517 continue;
518 }
519 const double c =
520 corr(static_cast<Eigen::Index>((d + 1) * N_im + i));
521 image1.G(i, d) += cap(component, c);
522 }
523 }
524}
void assembleMatrixOfRepetitiveCoordinates(const gpr::Coord &coord, gpr::EigenMatrix &matrix, Eigen::VectorXd &ind)
Assemble Eigen matrix with repetitive rows based on provided set of coordinates R.
static constexpr double kTrustTau
uint32_t Index_t
Definition Macros.h:17
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20

◆ compute()

bool gpr::laplace::TCovSecondOrder::compute ( const GaussianProcessRegression & gpr,
const Eigen::MatrixXd & H_inv )
nodiscard

Populate the cache at the current GPR state (after decomposeCovarianceMatrix at theta_star and alpha = K_star^-1 y).

Parameters
gprConfigured GPR (must have valid L and a at theta*).
H_invInverse Hessian (p x p) from the Laplace cache.
Returns
true on success; false if K_star is singular or hypers are invalid (fall back to MAP or to the 1st-order TCOV-INLA path).

Definition at line 209 of file TCovSecondOrder.cpp.

211{
212 invalidate();
213
214 if (gpr.sexpat_cov_func == nullptr) return false;
215 if (gpr.getRMatrix().size() == 0) return false;
216 if (gpr.getAlpha().size() == 0) return false;
217 // The triangular solves below consult the ScaLAPACK factor cache when
218 // the dense L member is empty, so require a USABLE factor rather than
219 // dense dimensions (hasTrainingCholeskyFactor covers both states).
220 if (!gpr.hasTrainingCholeskyFactor(gpr.getRMatrix().rows())) return false;
221
222 // Partial scope: log_sn is not touched (A2 gives all (log_sn, *) pairs
223 // zero, A3 gives cross-cov log_sn derivs zero). We only need K_d for
224 // d in {0 (log_magn), 1..n_ls (log_ls)}.
225 const auto& ls_ref = gpr.sexpat_cov_func->getLengthScaleRef();
226 const Eigen::Index n_ls = ls_ref.size();
227 if (n_ls < 1) return false;
228
229 // SexpatCF directional API guards on lengthScale.size() <= 1 with an
230 // empty-matrix early return. Without a working directional API on
231 // single-pair-type systems, the cache cannot be populated -- refuse
232 // and let the caller fall back to MAP. Production atomistic systems
233 // (d016, CuH2 multi-pairtype) have n_ls > 1.
234 if (n_ls <= 1) return false;
235
236 n_ls_ = static_cast<std::size_t>(n_ls);
237 const int p = static_cast<int>(H_inv.rows());
238 const int p_expected = 1 + static_cast<int>(n_ls) + 1; // magn + ls + sn
239 if (p != p_expected) return false;
240 if (H_inv.cols() != p) return false;
241
242 H_inv_ = H_inv;
243 alpha_star_ = gpr.getAlpha();
244
245 Eigen::VectorXd uDdim;
246 gpr.extractUniqueIndices(gpr.getRIndices(), uDdim);
247
248 // Build K_d (1st directional) AND K_{dd} (2nd directional) for
249 // d = 0..n_ls in a single directional pass along e_d in the
250 // (1 + n_ls)-dim SexpatCF direction space. The noise dim is not
251 // part of the SexpatCF direction vector.
252 const Eigen::Index p_sex = 1 + n_ls;
253 K_d_.clear();
254 K_d_.reserve(n_ls_ + 1);
255 std::vector<EigenMatrix> K_dd_diag; // K_{dd} = d^2 K / d theta_d^2
256 K_dd_diag.reserve(n_ls_ + 1);
257 EigenMatrix first, second;
258 for (Eigen::Index d = 0; d <= n_ls; ++d) {
259 Eigen::VectorXd e_d = Eigen::VectorXd::Zero(p_sex);
260 e_d(d) = 1.0;
261 first.resize(0, 0);
262 second.resize(0, 0);
263 gpr.assembleDirectionalCovarianceDerivatives(
264 gpr.getRMatrix(), gpr.getRIndices(), uDdim, e_d, first, second);
265 if (first.size() == 0 || second.size() == 0) {
266 invalidate();
267 return false;
268 }
269 first = gpr.symmetricMatrixInTrainingFactorLayout(first);
270 second = gpr.symmetricMatrixInTrainingFactorLayout(second);
271 K_d_.push_back(std::move(first));
272 K_dd_diag.push_back(std::move(second));
273 }
274
275 // Build off-diagonal K_{ij} = d^2 K / d theta_i d theta_j for i < j
276 // via polarisation (A7 identity):
277 // K_{ij} = 0.5 * (d^2 K/d(e_i+e_j)^2 - K_{ii} - K_{jj})
278 // The sum-direction (e_i + e_j) needs one directional probe per
279 // pair. p(p+1)/2 - p = n_ls * (n_ls + 1) / 2 mixed pairs.
280 // We index K_ij_full_ flat: entry (i, j) with i <= j lives at
281 // index ij_flat_index(i, j).
282 const std::size_t p_eff = n_ls_ + 1; // number of d dims with non-zero K_d
283 K_ij_full_.clear();
284 K_ij_full_.resize(p_eff * (p_eff + 1) / 2);
285
286 // Fill diagonal slots (i == i) with K_{ii} from the probes above.
287 for (std::size_t i = 0; i < p_eff; ++i) {
288 K_ij_full_[ijFlatIndex(i, i)] = std::move(K_dd_diag[i]);
289 }
290
291 // Fill off-diagonal pairs via polarisation. `second` is reused.
292 for (Eigen::Index i = 0; i < static_cast<Eigen::Index>(p_eff); ++i) {
293 for (Eigen::Index j = i + 1; j < static_cast<Eigen::Index>(p_eff);
294 ++j) {
295 Eigen::VectorXd sum_dir = Eigen::VectorXd::Zero(p_sex);
296 sum_dir(i) = 1.0;
297 sum_dir(j) = 1.0;
298 first.resize(0, 0);
299 second.resize(0, 0);
300 gpr.assembleDirectionalCovarianceDerivatives(
301 gpr.getRMatrix(), gpr.getRIndices(), uDdim, sum_dir, first,
302 second);
303 if (second.size() == 0) {
304 invalidate();
305 return false;
306 }
307 second = gpr.symmetricMatrixInTrainingFactorLayout(second);
308 // K_{ij} = 0.5 * (second - K_{ii} - K_{jj})
309 EigenMatrix Kij =
310 0.5 * (second -
311 K_ij_full_[ijFlatIndex(static_cast<std::size_t>(i),
312 static_cast<std::size_t>(i))] -
313 K_ij_full_[ijFlatIndex(static_cast<std::size_t>(j),
314 static_cast<std::size_t>(j))]);
315 K_ij_full_[ijFlatIndex(static_cast<std::size_t>(i),
316 static_cast<std::size_t>(j))] =
317 std::move(Kij);
318 }
319 }
320
321 // z_d = K^{-1} K_d alpha_star for d = 0..n_ls.
322 z_.clear();
323 z_.reserve(p_eff);
324 for (std::size_t d = 0; d < p_eff; ++d) {
325 const Eigen::VectorXd Kd_alpha = K_d_[d] * alpha_star_;
326 z_.push_back(gpr.solveTrainingCovarianceInFactorLayout(Kd_alpha));
327 }
328
329 // beta_{ij} = K^{-1} (K_i z_j + K_j z_i - K_{ij} alpha_star) for
330 // each i <= j. Symmetric, so we only store upper-triangular (i<=j).
331 beta_full_.clear();
332 beta_full_.resize(p_eff * (p_eff + 1) / 2);
333 for (std::size_t i = 0; i < p_eff; ++i) {
334 for (std::size_t j = i; j < p_eff; ++j) {
335 const auto& K_ij = K_ij_full_[ijFlatIndex(i, j)];
336 Eigen::VectorXd rhs;
337 if (i == j) {
338 rhs = 2.0 * (K_d_[i] * z_[i]) - K_ij * alpha_star_;
339 } else {
340 rhs = K_d_[i] * z_[j] + K_d_[j] * z_[i] - K_ij * alpha_star_;
341 }
342 beta_full_[ijFlatIndex(i, j)] =
343 gpr.solveTrainingCovarianceInFactorLayout(rhs);
344 }
345 }
346
347 // Keep the partial-scope beta_ for callers that read it; populate
348 // beta_[0..n_ls] as (0, d) pairs per its API contract.
349 beta_.clear();
350 beta_.reserve(p_eff);
351 for (std::size_t d = 0; d < p_eff; ++d) {
352 beta_.push_back(beta_full_[ijFlatIndex(0, d)]);
353 }
354
355 valid_ = true;
356 return true;
357}
void invalidate() noexcept
Invalidate (drops all cached vectors).

◆ invalidate()

void gpr::laplace::TCovSecondOrder::invalidate ( )
inlinenoexcept

Invalidate (drops all cached vectors).

Definition at line 104 of file TCovSecondOrder.h.

105 {
106 valid_ = false;
107 z_.clear();
108 beta_.clear();
109 beta_full_.clear();
110 K_d_.clear();
111 K_ij_full_.clear();
112 alpha_star_.resize(0);
113 H_inv_.resize(0, 0);
114 n_ls_ = 0;
115 }

◆ nLs()

std::size_t gpr::laplace::TCovSecondOrder::nLs ( ) const
inlinenodiscardnoexcept

Number of cached lengthscale dimensions (0..n_ls).

Definition at line 98 of file TCovSecondOrder.h.

99 {
100 return n_ls_;
101 }

◆ valid()

bool gpr::laplace::TCovSecondOrder::valid ( ) const
inlinenodiscardnoexcept

Is the cache populated and usable?

Definition at line 92 of file TCovSecondOrder.h.

93 {
94 return valid_;
95 }

Member Data Documentation

◆ kTrustTau

double gpr::laplace::TCovSecondOrder::kTrustTau = 0.5
staticconstexpr

Trust-region cap on the per-component Taylor correction: applyCorrection writes image1.{E,G} += sign(corr) * min(abs(corr), kTrustTau * abs(MAP)). With kTrustTau < 1 the corrected gradient stays in the same hemisphere as MAP – proven by sympy TR2 in python/tests/test_sympy_laplace_trust_region.py. Exposed as a class constant so tests can reference the same value.

Definition at line 72 of file TCovSecondOrder.h.


The documentation for this class was generated from the following files: