Loading...
Searching...
No Matches
gpr::RFFModel Class Reference

Random Fourier Features (RFF) approximation to the SE kernel. More...

#include <gpr/ml/RFFModel.h>

Public Types

enum class  NormalEquationBackend { Eigen , Cutlass }

Public Member Functions

 RFFModel ()=default
 RFFModel (std::shared_ptr< const linalg::MpiCommunicator > communication)
void build (SexpatCF &kernel, const AtomsConfiguration &conf_info, const Observation &training_data, int D_rff, double noise_var=1e-6, double grad_noise_var=1e-4)
 Build the RFF model from trained hyperparameters and data.
void calculatePotential (Observation &image) const
 Predict energy and gradient at test configurations.
void calculateVariance (Observation &image) const
 Predict energy/gradient variance at test configurations.
bool meanHessianVector (const Eigen::VectorXd &x, const Eigen::VectorXd &v, Eigen::VectorXd &action) const
 Exact Hessian of the predicted energy at x applied to v.
bool isBuilt () const
NormalEquationBackend normalEquationBackend () const noexcept
const char * normalEquationBackendName () const noexcept

Detailed Description

Random Fourier Features (RFF) approximation to the SE kernel.

Approximates the SexpatCF kernel with D_rff random cosine features, then solves Bayesian linear regression in the feature space. Training cost is O(N * D * D_rff + D_rff^3), prediction is O(D_rff * D) per test point – compared to O((N*(D+1))^3) for exact GP.

The spectral density of the SE kernel with effective variance 1/(2*l^2) per feature is N(0, 2/l^2). Per-pairtype ARD lengthscales are applied: each feature f has pairtype p(f), and W[:,f] ~ N(0, 2/l_p^2).

Workflow:

  1. Train exact GP on subset to optimize hyperparameters
  2. Call build() with trained kernel and all training data
  3. Call calculatePotential() / calculateVariance() for prediction
Note
The factor-of-2 convention: dist_at computes d = sqrt(sum 2*s2*delta^2), and the kernel is k = sigma^2 * exp(-0.5*d^2). Expanding: k = sigma^2 * exp(-sum s2*delta^2) where s2 = 1/l^2. This is an SE kernel with effective variance 1/(2*l^2) per feature, so the spectral density is N(0, 2*s2*I) = N(0, 2/l^2 * I).
See also
InverseDistanceDescriptor for the feature map from Cartesian coordinates to inverse distances.
SexpatCF for the exact kernel this approximates.

Definition at line 51 of file RFFModel.h.

Member Enumeration Documentation

◆ NormalEquationBackend

Enumerator
Eigen 
Cutlass 

Definition at line 57 of file RFFModel.h.

57 {
58 Eigen,
59 Cutlass,
60 };

Constructor & Destructor Documentation

◆ RFFModel() [1/2]

gpr::RFFModel::RFFModel ( )
default

◆ RFFModel() [2/2]

gpr::RFFModel::RFFModel ( std::shared_ptr< const linalg::MpiCommunicator > communication)
explicit

Definition at line 35 of file RFFModel.cpp.

36 : communication_(std::move(communication))
37{
38 if (!communication_)
39 throw std::invalid_argument("RFF model requires communication");
40}

Member Function Documentation

◆ build()

void gpr::RFFModel::build ( SexpatCF & kernel,
const AtomsConfiguration & conf_info,
const Observation & training_data,
int D_rff,
double noise_var = 1e-6,
double grad_noise_var = 1e-4 )

Build the RFF model from trained hyperparameters and data.

Parameters
kernelTrained SexpatCF with optimized magnSigma2 and lengthScale values.
conf_infoConfiguration argument retained for callers. The kernel configuration defines the descriptor and its reference chart.
training_dataAll training observations (R, E, G).
D_rffNumber of random features.
noise_varEnergy-channel noise variance for each joint observation.
grad_noise_varGradient-channel noise variance for each joint observation.

Definition at line 42 of file RFFModel.cpp.

45{
46 built_ = false;
47 inverse_.reset();
48 detail::requireJointTrainingObservation(training_data, "RFFModel::build");
49 D_rff_ = D_rff;
50 normal_equation_backend_ = NormalEquationBackend::Eigen;
51 conf_info_.copy(kernel.getConfInfo());
52 far_field_radius_ = kernel.farFieldRadius();
53
54 int d_feat = InverseDistanceDescriptor::featureDimension(conf_info_,
55 far_field_radius_);
56 Eigen::Index N = training_data.R.rows();
57 Eigen::Index D = training_data.R.cols(); // 3 * N_mov
58
59 // --- Sample frequencies from spectral density ---
60 // The SE kernel with dist_at convention has effective per-feature
61 // variance 1/(2*l^2), giving spectral density N(0, 2/l^2).
62 // s2 = 1/l^2, so std_dev = sqrt(2 * s2) = sqrt(2) / l.
63 FieldMatrixd& ls = kernel.getLengthScaleRef();
65 conf_info_, far_field_radius_);
66
67 // s2 per pairtype: s2[p] = 1/l_p^2
68 Eigen::Index n_pt = ls.size();
69 Eigen::VectorXd s2(n_pt);
70 for (Eigen::Index p = 0; p < n_pt; ++p) {
71 double l = *(ls.data() + p);
72 s2(p) = 1.0 / (l * l);
73 }
74 // If single lengthscale (non-ARD), replicate to all pairtypes
75 if (n_pt == 1 && conf_info_.n_pt > 1) {
76 double ref = s2(0);
77 s2.resize(conf_info_.n_pt);
78 s2.setConstant(ref);
79 }
80
81 // Sample W: each column f has std_dev = sqrt(2 * s2[pt[f]])
82 std::mt19937 rng(42); // fixed seed for reproducibility
83 std::normal_distribution<double> normal(0.0, 1.0);
84 std::uniform_real_distribution<double> uniform(0.0, 2.0 * M_PI);
85
86 W_.resize(D_rff, d_feat);
87 b_.resize(D_rff);
88 for (int f = 0; f < d_feat; ++f) {
89 const int ptf = pt[static_cast<std::size_t>(f)];
90 double s2_f = 0.0;
91 if (ptf >= 0 && ptf < s2.size()) {
92 s2_f = s2(ptf);
93 } else if (s2.size() == 1) {
94 s2_f = s2(0);
95 } else {
96 continue;
97 }
98 const double std_dev = std::sqrt(2.0 * s2_f);
99 for (int r = 0; r < D_rff; ++r) {
100 W_(r, f) = normal(rng) * std_dev;
101 }
102 }
103 for (int r = 0; r < D_rff; ++r) {
104 b_(r) = uniform(rng);
105 }
106
107 double sigma = std::sqrt(kernel.getMagnSigma2());
108 c_ = sigma * std::sqrt(2.0 / D_rff);
109
110 // --- Build design matrix Z ---
111 // Layout: [energy rows (N); gradient rows (N*D)]
112 // Gradient rows are in column-major order within each point:
113 // row N + (i-1)*D + d for point i, dimension d (0-indexed: N + i*D + d)
114 //
115 // Constant-feature column (D_eff = D_rff + 1, last column): the
116 // ConstantCF kernel adds a constant offset to the GP energy that
117 // a pure cosine-feature RFF cannot represent (cos(W phi + b)
118 // has zero mean over the random b ~ U(0, 2 pi) for a generic
119 // input). Without this column the BLR cannot fit the data's
120 // constant component and the predict mean produces large errors
121 // (downstream the dimer's curvature finite-difference goes NaN).
122 // Mirror of the Rust ChemGP implementation
123 // (rg_main/Rust/ChemGP/crates/chemgp-core/src/rff.rs lines 91-93).
124 // The constant feature is 1.0 on energy rows and 0.0 on gradient
125 // rows (the constant kernel has no spatial derivative).
126 const Eigen::Index D_eff = D_rff + 1;
127
128 // --- MPI distribution of Z assembly + ZtP*Z ----------------------
129 //
130 // With MPI (GPR_HAVE_MPI build + MPI_Initialized at runtime + np
131 // > 1): partition the N training points across ranks via a contig
132 // [my_lo, my_hi) slab. Each rank assembles its local Z_loc
133 // (n_loc_rows x D_eff with n_loc_rows = (my_hi - my_lo) * (1 + D)),
134 // forms its partial A_loc = Z_loc^T diag(prec_loc) Z_loc and
135 // rhs_loc = Z_loc^T diag(prec_loc) y_loc. Multi-rank builds reduce
136 // the compact normal equations to rank 0, scatter A into the BLACS
137 // grid, and factor the distributed matrix through KernelInverse.
138 //
139 // Why collect A + rhs rather than Z: the global Z is
140 // n_obs x D_eff = O(N * D * D_rff) entries, vs A which is fixed at
141 // D_eff^2 = O(D_rff^2). For N >> D_rff (the regime where RFF wins
142 // over exact GP) the reduction volume drops from O(N * D * D_rff)
143 // to O(D_rff^2) -- 4-5 orders of magnitude smaller for the smoke
144 // sizes (~200 obs * 15 dim * 256 features vs 257^2).
145 int mpi_nprocs = 1;
146 int mpi_rank = 0;
147#ifdef GPR_HAVE_CUTLASS
148 int mpi_local_nprocs = 1;
149 int mpi_local_rank = 0;
150#endif
151#ifdef GPR_HAVE_MPI
152 {
153 int mpi_up = 0;
154 MPI_Initialized(&mpi_up);
155 if (mpi_up) {
156 if (!communication_)
157 communication_ =
158 std::make_shared<linalg::MpiCommunicator>(MPI_COMM_WORLD);
159 const auto process_group = communication_->view();
160 mpi_nprocs = process_group.nprocs;
161 mpi_rank = process_group.rank;
162
163#ifdef GPR_HAVE_CUTLASS
164 // Device selection uses the node-local ranks of this process
165 // group; other searches need not enter this collective.
166 MPI_Comm local_comm = MPI_COMM_NULL;
167 MPI_Comm_split_type(process_group.comm, MPI_COMM_TYPE_SHARED,
168 mpi_rank, MPI_INFO_NULL, &local_comm);
169 if (local_comm != MPI_COMM_NULL) {
170 MPI_Comm_size(local_comm, &mpi_local_nprocs);
171 MPI_Comm_rank(local_comm, &mpi_local_rank);
172 MPI_Comm_free(&local_comm);
173 }
174#endif
175 }
176 }
177#endif
178
179 // Contig slab partition: rank r owns points [N*r/np, N*(r+1)/np).
180 // Falls back to the full range when np == 1, so the serial path is
181 // covered by the same code below (no separate uniprocessor branch).
182 // --- Energy reference (MPI-uniform training_data.E(0,0) read) ---
183 const auto energy_at = [&](Eigen::Index row) -> double {
184 return training_data.E.rows() == 1 ? training_data.E(0, row)
185 : training_data.E(row, 0);
186 };
187 e_ref_ = training_data.E.size() > 0 ? energy_at(0) : 0.0;
188
189 // Fixed canonical observation tiles so local GEMM blocking and exact
190 // cross-rank accumulation are independent of mpi_nprocs.
191 constexpr Eigen::Index kObsTile = 8;
192 const Eigen::Index n_obs_tiles = (N + kObsTile - 1) / kObsTile;
193 std::vector<EigenMatrix> owned_A_tiles;
194 std::vector<linalg::ExactSum> rhs_exact(static_cast<std::size_t>(D_eff));
195 Eigen::VectorXd phi;
196 EigenMatrix J_phi;
197
198 for (Eigen::Index tile = mpi_rank; tile < n_obs_tiles; tile += mpi_nprocs) {
199 const Eigen::Index tile_lo = tile * kObsTile;
200 const Eigen::Index n_loc = std::min(kObsTile, N - tile_lo);
201 const Eigen::Index n_loc_rows = n_loc * (1 + D);
202 EigenMatrix Z_loc = EigenMatrix::Zero(n_loc_rows, D_eff);
203 Eigen::VectorXd y_loc(n_loc_rows);
204 Eigen::VectorXd prec_loc(n_loc_rows);
205
206 for (Eigen::Index i_loc = 0; i_loc < n_loc; ++i_loc) {
207 const Eigen::Index i = tile_lo + i_loc;
208 Coord xi(1, D);
209 xi.row(0) = training_data.R.row(i);
211 xi, conf_info_, phi, J_phi, far_field_radius_);
212
213 Eigen::VectorXd u = W_ * phi + b_;
214 Eigen::VectorXd z = c_ * u.array().cos().matrix();
215
216 Z_loc.row(i_loc).head(D_rff) = z.transpose();
217 Z_loc(i_loc, D_rff) = 1.0;
218 y_loc(i_loc) = energy_at(i) - e_ref_;
219 prec_loc(i_loc) = 1.0 / noise_var;
220
221 Eigen::VectorXd sin_u = u.array().sin().matrix();
222 EigenMatrix WJ = W_ * J_phi;
223 for (Eigen::Index d = 0; d < D; ++d) {
224 const Eigen::Index row = n_loc + i_loc * D + d;
225 Z_loc.row(row).head(D_rff) =
226 (-c_ * sin_u.array() * WJ.col(d).array())
227 .matrix()
228 .transpose();
229 y_loc(row) = training_data.G(i, d);
230 prec_loc(row) = 1.0 / grad_noise_var;
231 }
232 }
233
234 EigenMatrix ZtP_loc = Z_loc.transpose();
235 for (Eigen::Index j = 0; j < n_loc_rows; ++j) {
236 ZtP_loc.col(j) *= prec_loc(j);
237 }
238
239 EigenMatrix A_tile(D_eff, D_eff);
240 Eigen::VectorXd rhs_tile(D_eff);
241 bool used_cutlass = false;
242#ifdef GPR_HAVE_CUTLASS
244 mpi_local_nprocs)) {
245 A_tile = linalg::cutlass::gemm_nn(ZtP_loc, Z_loc);
246 EigenMatrix y_mat(y_loc.rows(), 1);
247 y_mat.col(0) = y_loc;
248 const EigenMatrix rhs_mat =
249 linalg::cutlass::gemm_nn(ZtP_loc, y_mat);
250 rhs_tile = rhs_mat.col(0);
251 used_cutlass = true;
252 normal_equation_backend_ = NormalEquationBackend::Cutlass;
253 }
254#endif
255 if (!used_cutlass) {
256 A_tile.noalias() = ZtP_loc * Z_loc;
257 rhs_tile.noalias() = ZtP_loc * y_loc;
258 }
259 owned_A_tiles.push_back(std::move(A_tile));
260 for (Eigen::Index r = 0; r < D_eff; ++r) {
261 rhs_exact[static_cast<std::size_t>(r)].add(rhs_tile(r));
262 }
263 }
264
265#ifdef GPR_HAVE_MPI
266 if (mpi_nprocs > 1) {
267#ifndef GPR_LINALG_SCALAPACK
268 throw std::runtime_error(
269 "RFFModel::build: multi-rank MPI RFF requires "
270 "linalg_backend=scalapack");
271#endif
272 }
273#endif
274
275 if (mpi_nprocs > 1) {
276 linalg::exact_sum_bcast(rhs_exact.data(), static_cast<int>(D_eff),
277 communication_->view());
278 }
279 Eigen::VectorXd rhs(D_eff);
280 for (Eigen::Index r = 0; r < D_eff; ++r)
281 rhs(r) = rhs_exact[static_cast<std::size_t>(r)].value();
282
283 EigenMatrix A(D_eff, D_eff);
284 constexpr Eigen::Index kRowBatch = 32;
285 std::vector<linalg::ExactSum> row_exact;
286 for (Eigen::Index r0 = 0; r0 < D_eff; r0 += kRowBatch) {
287 const Eigen::Index rlen = std::min(kRowBatch, D_eff - r0);
288 row_exact.assign(static_cast<std::size_t>(rlen * D_eff),
289 linalg::ExactSum{});
290 for (const auto& tile_mat: owned_A_tiles) {
291 for (Eigen::Index col = 0; col < D_eff; ++col) {
292 for (Eigen::Index dr = 0; dr < rlen; ++dr) {
293 row_exact[static_cast<std::size_t>(dr + col * rlen)].add(
294 tile_mat(r0 + dr, col));
295 }
296 }
297 }
298 if (mpi_nprocs > 1) {
299 linalg::exact_sum_bcast(row_exact.data(),
300 static_cast<int>(rlen * D_eff),
301 communication_->view());
302 }
303 for (Eigen::Index col = 0; col < D_eff; ++col) {
304 for (Eigen::Index dr = 0; dr < rlen; ++dr) {
305 A(r0 + dr, col) =
306 row_exact[static_cast<std::size_t>(dr + col * rlen)]
307 .value();
308 }
309 }
310 }
311 if (mpi_nprocs > 1 && mpi_rank != 0) {
312 A.resize(0, 0);
313 rhs.resize(0);
314 }
315
316 // BLR ridge: A <- A + I (regularises the small-D_rff overdetermined
317 // system; same coefficient as the serial BLR path). The energy rows
318 // are centered on training_data.E(0, 0) during y_loc assembly so the
319 // BLR coefficients stay small
320 // when the absolute energy magnitude must be represented by random
321 // cosine features; mirror of ChemGP's chemgp-core/src/predict.rs
322 // build_pred_model_full).
323 A.diagonal().array() += 1.0;
324
325 // Factorise A = L L^T through the build-selected KernelInverse impl.
326 // ScalapackPDPotrfInverse scatters rank 0's A through the BLACS grid
327 // and runs pdpotrf on the distributed slab so the (D_eff x D_eff)
328 // Cholesky and every downstream solve is a real ScaLAPACK collective,
329 // matching the dimer / GP training-cov factorisation pattern.
330 // DenseLLTInverse is the rank-local Eigen LLT fallback for the eigen
331 // backend or for the np == 1 single-rank case.
332 //
333 // Per-instance L state in both impls is the explicit reason the RFF
334 // factorisation does not pollute DistributedState's singleton L cache,
335 // which the GP-side decomposeCovarianceMatrixScalapack owns and
336 // reuses via cached_L() across hot-path calculateVariance calls.
337 auto try_factor = [&](double ridge_bump) -> bool {
338 if (ridge_bump > 0.0) A.diagonal().array() += ridge_bump;
339
340#ifdef GPR_LINALG_SCALAPACK
341 if (mpi_nprocs > 1) {
342 if (!distributed_state_)
343 distributed_state_ =
344 std::make_shared<linalg::DistributedState>(communication_);
345 auto& st = *distributed_state_;
346 st.initialize();
347 int desc[9];
348 std::vector<double> A_dist = st.scatter(
349 A, static_cast<int>(D_eff), static_cast<int>(D_eff), desc);
350 auto inv = std::make_unique<linalg::ScalapackPDPotrfInverse>(
351 distributed_state_);
352 if (!inv->factorise(std::move(A_dist), desc,
353 static_cast<int>(D_eff))) {
354 return false;
355 }
356 inverse_ = std::move(inv);
357 return true;
358 }
359#endif
360 auto inv = std::make_unique<linalg::DenseLLTInverse>();
361 if (!inv->factorise(A)) return false;
362 inverse_ = std::move(inv);
363 return true;
364 };
365
366 bool ok = try_factor(0.0);
367 if (!ok) ok = try_factor(1e-6);
368 if (!ok) {
369 throw std::runtime_error(
370 "RFFModel::build: Cholesky failed even after 1e-6 ridge bump");
371 }
372
373 // alpha = A^{-1} rhs, where rhs is the collective
374 // sum_r Z_r^T diag(prec_r) y_r. Single solve through the per-instance
375 // KernelInverse -- pdtrsm collectives under scalapack, Eigen LLT
376 // solve_mat under eigen.
377 alpha_ = inverse_->solve(rhs);
378
379 built_ = true;
380}
@ z
Definition Enums.h:28
static std::vector< int > featurePairtypes(const AtomsConfiguration &conf_info)
Pairtype index for each feature.
static void computeWithJacobian(const Coord &x, const AtomsConfiguration &conf_info, Eigen::VectorXd &phi, EigenMatrix &J_phi)
Compute phi(x) and its Jacobian d(phi)/d(x).
static int featureDimension(const AtomsConfiguration &conf_info)
Number of features after omitting EMPTY pairtypes.
bool availableForLocalRank(int local_rank, int local_nprocs) noexcept
Definition CutlassGemm.h:53
EigenMatrix gemm_nn(const EigenMatrix &A, const EigenMatrix &B)
Definition CutlassGemm.h:61
void exact_sum_bcast(ExactSum *sums, int count, const MpiContext &context)
FieldMatrixd Coord
Definition Macros.h:35
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25

◆ calculatePotential()

void gpr::RFFModel::calculatePotential ( Observation & image) const

Predict energy and gradient at test configurations.

Fills image.E and image.G from the RFF model.

Parameters
[in,out]imageObservation with R set; E and G are filled.

Definition at line 382 of file RFFModel.cpp.

383{
384 Eigen::Index N_test = image.R.rows();
385 Eigen::Index D = image.R.cols();
386
387 // Layout matches the rest of the GPR predict path
388 // (writeBMAOutput / calculatePotential MAP convention):
389 // image.E is (1, N_test) row vector -- caller indexes E(0, k)
390 // image.G is (N_test, D) -- caller indexes G(k, d)
391 // The dimer reads approx_obs.E(0, 1) for the second image during
392 // rotation/translation steps, so E uses the row-vector layout here.
393 image.E.resize(1, N_test);
394 image.G.resize(N_test, D);
395
396 Eigen::VectorXd phi;
397 EigenMatrix J_phi;
398
399 // alpha layout matches the constant-feature build: alpha[0..D_rff)
400 // are the cosine-feature weights, alpha[D_rff] is the constant
401 // offset. Predict separately so the constant always contributes
402 // to energy but never to the gradient.
403 const Eigen::Index D_rff = W_.rows();
404 const auto alpha_cos = alpha_.head(D_rff);
405 const double alpha_const = (alpha_.size() > D_rff) ? alpha_(D_rff) : 0.0;
406
407 for (Eigen::Index i = 0; i < N_test; ++i) {
408 Coord xi(1, D);
409 xi.row(0) = image.R.row(i);
410
412 xi, conf_info_, phi, J_phi, far_field_radius_);
413
414 Eigen::VectorXd u = W_ * phi + b_;
415 Eigen::VectorXd z = c_ * u.array().cos().matrix();
416
417 // Energy prediction: cosine-feature contribution + constant
418 // offset + reference energy added back (mirror of ChemGP's
419 // apply_prior_to_prediction with PriorMeanConfig::Zero;
420 // prior_e = reference_energy in that branch). E is the
421 // (1, N_test) row vector laid out by the resize above.
422 image.E(0, i) = z.dot(alpha_cos) + alpha_const + e_ref_;
423
424 // Gradient prediction: G_d = J_z[:,d]^T * alpha_cos
425 // (constant kernel has zero spatial derivative)
426 Eigen::VectorXd sin_u = u.array().sin().matrix();
427 EigenMatrix WJ = W_ * J_phi; // (D_rff x D)
428 for (Eigen::Index d = 0; d < D; ++d) {
429 Eigen::VectorXd jz_d =
430 (-c_ * sin_u.array() * WJ.col(d).array()).matrix();
431 image.G(i, d) = jz_d.dot(alpha_cos);
432 }
433 }
434}

◆ calculateVariance()

void gpr::RFFModel::calculateVariance ( Observation & image) const

Predict energy/gradient variance at test configurations.

Fills image.E and image.G with predictive variances.

Parameters
[in,out]imageObservation with R set; E and G filled with variances.

Definition at line 464 of file RFFModel.cpp.

465{
466 Eigen::Index N_test = image.R.rows();
467 Eigen::Index D = image.R.cols();
468
469 // (1, N_test) layout to match the rest of the GPR predict path
470 // (see calculatePotential above for the rationale).
471 image.E.resize(1, N_test);
472 image.G.resize(N_test, D);
473
474 if (!inverse_) {
475 throw std::logic_error(
476 "RFFModel::calculateVariance called before build()");
477 }
478
479 Eigen::VectorXd phi;
480 EigenMatrix J_phi;
481
482 for (Eigen::Index i = 0; i < N_test; ++i) {
483 Coord xi(1, D);
484 xi.row(0) = image.R.row(i);
485
487 xi, conf_info_, phi, J_phi, far_field_radius_);
488
489 Eigen::VectorXd u = W_ * phi + b_;
490
491 // Energy feature vector with the constant column at index
492 // D_rff (matches the build's D_eff = D_rff + 1 layout).
493 const Eigen::Index D_rff = W_.rows();
494 Eigen::VectorXd z_eff(D_rff + 1);
495 z_eff.head(D_rff) = c_ * u.array().cos().matrix();
496 z_eff(D_rff) = 1.0;
497
498 // Energy variance: var(E) = z^T A^{-1} z. The KernelInverse
499 // .solve() returns A^{-1} z; one z.dot(...) finishes the
500 // quadratic form. Under scalapack this is two pdtrsm collectives
501 // on a single-column RHS through the per-instance L_dist_;
502 // under eigen it's an Eigen::LLT solve.
503 const Eigen::VectorXd Ainv_z = inverse_->solve(z_eff);
504 image.E(0, i) = z_eff.dot(Ainv_z);
505
506 // Gradient variance: constant column has zero spatial
507 // derivative, so the gradient feature vector is
508 // (-c sin(u) * W J_phi[:,d]) padded with a trailing 0.
509 Eigen::VectorXd sin_u = u.array().sin().matrix();
510 EigenMatrix WJ = W_ * J_phi;
511 for (Eigen::Index d = 0; d < D; ++d) {
512 Eigen::VectorXd jz_d_eff(D_rff + 1);
513 jz_d_eff.head(D_rff) =
514 (-c_ * sin_u.array() * WJ.col(d).array()).matrix();
515 jz_d_eff(D_rff) = 0.0;
516 const Eigen::VectorXd Ainv_jz = inverse_->solve(jz_d_eff);
517 image.G(i, d) = jz_d_eff.dot(Ainv_jz);
518 }
519 }
520}

◆ isBuilt()

bool gpr::RFFModel::isBuilt ( ) const
inline

Definition at line 111 of file RFFModel.h.

112 {
113 return built_;
114 }

◆ meanHessianVector()

bool gpr::RFFModel::meanHessianVector ( const Eigen::VectorXd & x,
const Eigen::VectorXd & v,
Eigen::VectorXd & action ) const
nodiscard

Exact Hessian of the predicted energy at x applied to v.

Differentiates calculatePotential's mean twice: the cosine features through the descriptor Jacobian, plus the descriptor curvature along v weighted by the feature gradient. False before build() or for a shape mismatch.

Definition at line 436 of file RFFModel.cpp.

439{
440 action.resize(0);
441 if (!built_ || x.size() == 0 || v.size() != x.size()) return false;
442 Coord xi(1, x.size());
443 xi.row(0) = x.transpose();
444 Eigen::VectorXd phi;
445 EigenMatrix J_phi, H_phi_direction;
447 xi, conf_info_, v, phi, J_phi, H_phi_direction, far_field_radius_);
448 if (phi.size() != W_.cols()) return false;
449 // m = c alpha^T cos(u), u = W phi + b, so with s = alpha o sin(u):
450 // H v = J^T W^T (-c alpha o cos(u) o (W J v)) + (D_v J)^T W^T (-c s).
451 const Eigen::Index D_rff = W_.rows();
452 const auto alpha_cos = alpha_.head(D_rff);
453 const Eigen::VectorXd u = W_ * phi + b_;
454 const Eigen::VectorXd curvature =
455 (-c_ * alpha_cos.array() * u.array().cos() * (W_ * (J_phi * v)).array())
456 .matrix();
457 const Eigen::VectorXd slope =
458 (-c_ * alpha_cos.array() * u.array().sin()).matrix();
459 action = J_phi.transpose() * (W_.transpose() * curvature) +
460 H_phi_direction.transpose() * (W_.transpose() * slope);
461 return action.allFinite();
462}
@ x
Definition Enums.h:28
static void computeWithJacobianAndDirectionalHessian(const Coord &x, const AtomsConfiguration &conf_info, const Eigen::VectorXd &direction, Eigen::VectorXd &phi, EigenMatrix &J_phi, EigenMatrix &H_phi_direction)
Compute phi(x), d(phi)/d(x), and D_direction d(phi)/d(x).

◆ normalEquationBackend()

NormalEquationBackend gpr::RFFModel::normalEquationBackend ( ) const
inlinenodiscardnoexcept

Definition at line 115 of file RFFModel.h.

116 {
117 return normal_equation_backend_;
118 }

◆ normalEquationBackendName()

const char * gpr::RFFModel::normalEquationBackendName ( ) const
inlinenodiscardnoexcept

Definition at line 119 of file RFFModel.h.

120 {
121 switch (normal_equation_backend_) {
123 return "eigen";
125 return "cutlass";
126 }
127 return "unknown";
128 }

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