Loading...
Searching...
No Matches
CovarianceAssembly.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// Covariance matrix assembly: full training kernel, train-vs-query
6// kernel, distributed tile assembly, plus the supporting helpers
7// (assignBlockToMatrix, accumulateBlockContribution,
8// extractCoordinatesByIndex, removeColumn, extractUniqueIndices).
9
16#include "../BlockOwnership.h"
18#include "../PhaseTimers.h"
19#include "Helpers.h"
21#ifdef GPR_LINALG_SCALAPACK
22#include <mpi.h>
23
26#endif
27
28#include <Eigen/Core>
29#include <algorithm>
30#include <atomic>
31#include <chrono>
32#include <cmath>
33#include <cstddef>
34#include <cstdio>
35#include <cstdlib>
36#include <limits>
37#include <stdexcept>
38#include <string>
39#include <unordered_set>
40#include <utility>
41#include <vector>
42
43namespace gpr {
44
45// Cumulative wall time spent rebuilding the training kernel geometry
46// (prepareTrainingKernelGeometry). Attribution probe for the incremental-
47// geometry redesign: compared against the end-to-end wall it shows whether the
48// per-outer full O(D^2 N^2) geometry rebuild is worth making incremental.
50
51using detail::addConstantCovarianceBlock;
52
53namespace {
54
55// Assemble the SexpAt training-cov contribution from a precomputed
56// per-block geometry cache. Each block's CrossBlockGeometry was built
57// at unit lengthscale by prepareTrainingKernelGeometry; this walks the
58// stored blocks, evaluates each one at the current theta via
59// SexpatCF::evaluateCrossBlockGeometry, and accumulates into Ktemp
60// via the same assignBlockToMatrix pattern as the live applyCovariance-
61// Function. The serial_per_rank flag is passed through and ownsBlock
62// (gpr/ml/BlockOwnership.h) is used so that np > 1 stays bit-equivalent.
63namespace {
64struct ObservationChannelBlock {
65 Eigen::Index start;
66 Eigen::Index count;
67};
68
69// Sorted channel values identify contiguous blocks. Missing derivative
70// components do not reserve rows in the assembled observation matrix.
71ObservationChannelBlock observationChannelBlock(const Eigen::VectorXd& indices,
72 Index_t channel)
73{
74 if (indices.size() == 0) return {0, 0};
75 const double value = static_cast<double>(channel);
76 const double* begin = indices.data();
77 const double* end = begin + indices.size();
78 const double* first = std::lower_bound(begin, end, value);
79 const double* last = std::upper_bound(first, end, value);
80 return {first - begin, last - first};
81}
82
85linalg::AvailableMemory geometryCacheBudgetBytes(int sharing_ranks)
86{
87 auto budget = linalg::availableHostBudget();
88 if (budget) *budget = *budget / 2 / std::max(1, sharing_ranks);
89 return budget;
90}
91} // namespace
92} // namespace
93
95 const FieldMatrixd& x_loc,
97 double far_field_radius)
98{
100 const Index_t n_conf = static_cast<Index_t>(x_loc.rows());
101 const Index_t n_coord =
102 3 * static_cast<Index_t>(conf_info.atoms_mov.type.size());
103 if (n_conf == 0 || n_coord == 0 || x_loc.cols() < n_coord ||
104 conf_info.n_pt == 0)
105 return false;
106 const std::vector<int> fpt = InverseDistanceDescriptor::featurePairtypes(
107 conf_info, far_field_radius);
108 const Index_t d_feat = static_cast<Index_t>(fpt.size());
109 if (d_feat <= 0) return false;
110 out.n_pt = conf_info.n_pt;
111 out.features_by_pt.assign(static_cast<std::size_t>(conf_info.n_pt), {});
112 for (Index_t f = 0; f < d_feat; ++f) {
113 const int pt = fpt[static_cast<std::size_t>(f)];
114 if (pt < 0 || pt >= conf_info.n_pt) return false;
115 out.features_by_pt[static_cast<std::size_t>(pt)].push_back(f);
116 }
117 out.Q.resize(n_conf, d_feat);
118 out.J.assign(static_cast<std::size_t>(n_coord),
119 EigenMatrix::Zero(n_conf, d_feat));
120 Eigen::VectorXd phi;
121 EigenMatrix J_phi;
122 for (Index_t i = 0; i < n_conf; ++i) {
123 Coord xi(1, n_coord);
124 xi.row(0) = x_loc.block(i, 0, 1, n_coord);
126 J_phi, far_field_radius);
127 if (phi.size() != d_feat || J_phi.rows() != d_feat ||
128 J_phi.cols() != n_coord || !phi.allFinite() || !J_phi.allFinite()) {
129 return false;
130 }
131 out.Q.row(i) = phi.transpose();
132 for (Index_t d = 0; d < n_coord; ++d) {
133 out.J[static_cast<std::size_t>(d)].row(i) =
134 J_phi.col(d).transpose();
135 }
136 }
137 out.valid = true;
138 return true;
139}
140
142 Index_t block_n, Index_t block_m,
143 uint8_t derivative_options,
145{
147 out.derivative_options = derivative_options;
148 if (!factors.valid || derivative_options == 0) {
149 out.valid = derivative_options == 0;
150 return out.valid;
151 }
152 // Block dimension values count the energy block as 0; coordinate d of
153 // the Jacobian is dimension value d + 1.
154 const Index_t dn = block_n - 1;
155 const Index_t dm = block_m - 1;
156 const Index_t n_dims = static_cast<Index_t>(factors.J.size());
157 const bool want_d2 =
158 (derivative_options & OptionsForGradCalculation::D2) != 0;
159 const bool want_d12 =
160 (derivative_options & OptionsForGradCalculation::D12) != 0;
161 if (dn < 0 || dn >= n_dims ||
162 ((want_d2 || want_d12) && (dm < 0 || dm >= n_dims))) {
163 return false;
164 }
165 const EigenMatrix& Jn = factors.J[static_cast<std::size_t>(dn)];
166 const EigenMatrix* Jm = (want_d2 || want_d12)
167 ? &factors.J[static_cast<std::size_t>(dm)]
168 : nullptr;
169 const Index_t n_conf = factors.Q.rows();
170 const Eigen::VectorXd ones = Eigen::VectorXd::Ones(n_conf);
171 out.d1.assign(static_cast<std::size_t>(factors.n_pt), FieldMatrixd());
172 if (want_d2)
173 out.d2.assign(static_cast<std::size_t>(factors.n_pt), FieldMatrixd());
174 if (want_d12)
175 out.d12.assign(static_cast<std::size_t>(factors.n_pt), FieldMatrixd());
176 for (Index_t pt = 0; pt < factors.n_pt; ++pt) {
177 const auto& F = factors.features_by_pt[static_cast<std::size_t>(pt)];
178 const Index_t nf = static_cast<Index_t>(F.size());
179 EigenMatrix Qf(n_conf, nf), Jnf(n_conf, nf),
180 Jmf(n_conf, want_d2 || want_d12 ? nf : 0);
181 for (Index_t k = 0; k < nf; ++k) {
182 Qf.col(k) = factors.Q.col(F[static_cast<std::size_t>(k)]);
183 Jnf.col(k) = Jn.col(F[static_cast<std::size_t>(k)]);
184 if (Jm) Jmf.col(k) = Jm->col(F[static_cast<std::size_t>(k)]);
185 }
186 const Eigen::VectorXd cn = (Jnf.array() * Qf.array()).rowwise().sum();
187 // Convention of buildCrossBlockDerivativesOnly (measured against
188 // the walked blocks in FactoredBlockDerivativesMatchTheWalkedGeometry):
189 // the stored fields are twice the pair-type derivatives, d1 and d2
190 // (d1, d2 with the sign of the derivative, d12 with that sign too).
191 out.d1[static_cast<std::size_t>(pt)] =
192 4.0 * cn * ones.transpose() - 4.0 * Jnf * Qf.transpose();
193 if (want_d2) {
194 const Eigen::VectorXd cm =
195 (Jmf.array() * Qf.array()).rowwise().sum();
196 out.d2[static_cast<std::size_t>(pt)] =
197 4.0 * ones * cm.transpose() - 4.0 * Qf * Jmf.transpose();
198 }
199 if (want_d12) {
200 out.d12[static_cast<std::size_t>(pt)] =
201 -4.0 * Jnf * Jmf.transpose();
202 }
203 }
204 out.valid = true;
205 return true;
206}
207
208namespace {
209bool trainingBlockGeometryUsable(const TrainingKernelGeometry& geometry,
210 const TrainingKernelGeometryBlock& block)
211{
212 const auto& stored = block.geometry;
213 if (stored.valid) return true;
214 // Streamed derivatives may be absent: the factors or coordinates supply
215 // them. An invalid populated descriptor still rejects the whole fit.
216 return geometry.streamed && block.derivative_options != 0 &&
217 stored.derivative_options == 0 && stored.distance.empty() &&
218 stored.d1.empty() && stored.d2.empty() && stored.d12.empty();
219}
220} // namespace
221
223 const SexpatCF& covariance, const TrainingKernelGeometry& geom,
224 const TrainingKernelGeometryBlock& block,
226{
227 if (!trainingBlockGeometryUsable(geom, block)) return nullptr;
228 if (!geom.streamed || block.derivative_options == 0) {
229 return &block.geometry;
230 }
231 const auto dim_block = [&](Index_t dim) -> const FieldMatrixd* {
232 if (dim < 0 || dim >= static_cast<Index_t>(geom.x_loc_by_dim.size()) ||
233 geom.x_loc_by_dim[static_cast<std::size_t>(dim)].size() == 0) {
234 return nullptr;
235 }
236 return &geom.x_loc_by_dim[static_cast<std::size_t>(dim)];
237 };
238 const FactoredTrainingGeometry* factors = &geom.factors;
239 if (!factors->valid && geom.lazy_factors) {
240 auto& cached = *geom.lazy_factors;
241 std::call_once(cached.initialize, [&] {
242 (void)buildFactoredTrainingGeometry(
243 cached.configuration, cached.coordinates, cached.factors,
244 cached.far_field_radius);
245 });
246 factors = &cached.factors;
247 }
248 if (factors->valid) {
250 *factors, block.block_n, block.block_m,
251 block.derivative_options, scratch)
252 ? &scratch
253 : nullptr;
254 }
255 const FieldMatrixd* x1 = dim_block(block.block_n);
256 const FieldMatrixd* x2 = dim_block(block.block_m);
257 if (x1 == nullptr || x2 == nullptr) return nullptr;
258 FieldMatrixIdx dims1(1, 1), dims2(1, 1);
259 dims1(0, 0) = block.block_n;
260 dims2(0, 0) = block.block_m;
261 if (!geom.shared_coordinates)
262 return covariance.buildCrossBlockGeometry(
263 *x1, *x2, block.derivative_options, dims1, dims2, scratch)
264 ? &scratch
265 : nullptr;
266 if (!covariance.buildCrossBlockDerivativesOnly(
267 *x1, *x2, block.derivative_options, dims1, dims2, scratch)) {
268 return nullptr;
269 }
270 return &scratch;
271}
272
273namespace {
274bool activeLogParameters(SexpatCF* kernel, const Eigen::VectorXd& theta,
275 const std::vector<bool>& active,
276 const std::vector<Eigen::Index>& derivatives,
277 Eigen::VectorXd& result)
278{
279 if (kernel == nullptr || kernel->usesManifoldChart()) return false;
280 const Eigen::Index count = kernel->getLengthScaleRef().size();
281 if (count <= 0 || theta.size() != count + 1 ||
282 active.size() != static_cast<std::size_t>(count) || !theta.allFinite())
283 return false;
284 const double amplitude = std::exp(theta(0));
285 if (!(amplitude > 0.0) || !std::isfinite(amplitude)) return false;
286 for (const auto index: derivatives)
287 if (index <= 0 || index > count || !active[index - 1]) return false;
288 result = theta;
289 for (Eigen::Index index = 0; index < count; ++index) {
290 if (!active[index]) {
291 // Infinite length gives the exact zero weight in the SE metric.
292 result(index + 1) = std::numeric_limits<double>::infinity();
293 } else if (!std::isfinite(std::exp(-2.0 * theta(index + 1)))) {
294 return false;
295 }
296 }
297 return true;
298}
299
303[[nodiscard]] bool pairLocalCoversGeometry(const TrainingKernelGeometry& geom)
304{
305 if (!geom.shared_coordinates) return false;
306 const auto& local = geom.pair_local;
307 // uDdim lists the gradient channels 1..D; the energy channel 0 is
308 // implicit.
309 if (!local.valid || local.n_conf != geom.num_repetitive_indices ||
310 geom.n != local.n_conf * (local.dof + 1) ||
311 geom.uDdim.size() != local.dof)
312 return false;
313 for (Eigen::Index k = 0; k < geom.uDdim.size(); ++k)
314 if (static_cast<Eigen::Index>(geom.uDdim(k)) != k + 1) return false;
315 return true;
316}
317
321[[nodiscard]] bool assemblePairLocalCovariance(
322 linalg::BackendContext& workspace, const pairlocal::Geometry& local,
323 const pairlocal::Weights& weights, EigenMatrix& Ktemp,
324 std::vector<EigenMatrix>* covariance_derivatives,
325 const std::vector<Eigen::Index>* derivative_indices,
326 const EigenMatrix* contraction_weight, Eigen::VectorXd* contractions,
327 bool do_reduce, bool serial_per_rank,
328 const std::vector<Index_t>* placement = nullptr)
329{
330 const Index_t n_conf = static_cast<Index_t>(local.n_conf);
331 const Index_t tile = static_cast<Index_t>(local.dof) + 1;
332 const Index_t n = n_conf * tile;
333 const std::size_t n_tiles = static_cast<std::size_t>(n_conf) *
334 static_cast<std::size_t>(n_conf + 1) / 2;
335 const auto context =
336 serial_per_rank ? linalg::MpiContext::local() : workspace.mpi();
337 const auto rank = static_cast<std::size_t>(context.rank);
338 const auto ranks = static_cast<std::size_t>(context.nprocs);
339 const std::size_t owned =
340 rank < n_tiles ? 1 + (n_tiles - 1 - rank) / ranks : 0;
341 const auto tile_pair = [&](std::size_t index, Index_t& i, Index_t& j) {
342 // Lower triangle numbered row by row: (0,0), (1,0), (1,1), ...
343 Index_t row = static_cast<Index_t>(
344 (std::sqrt(8.0 * static_cast<double>(index) + 1.0) - 1.0) / 2.0);
345 while (static_cast<std::size_t>(row) * (row + 1) / 2 > index)
346 --row;
347 while (static_cast<std::size_t>(row + 1) * (row + 2) / 2 <= index)
348 ++row;
349 i = row;
350 j = static_cast<Index_t>(index -
351 static_cast<std::size_t>(row) * (row + 1) / 2);
352 };
353 if (contractions != nullptr) {
354 if (contraction_weight == nullptr || derivative_indices == nullptr ||
355 contraction_weight->rows() != n || contraction_weight->cols() != n)
356 return false;
357 Ktemp.resize(0, 0);
358 const Eigen::Index parameter_count =
360 for (const auto parameter: *derivative_indices)
361 if (parameter <= 0 || parameter >= parameter_count) return false;
362 const std::size_t workers = std::min(
363 owned, static_cast<std::size_t>(workspace.local().concurrency()));
364 // Each pair owns two columns, retaining the direct and transposed
365 // products separately so the final sum follows the serial order.
366 Eigen::MatrixXd products = Eigen::MatrixXd::Zero(
367 parameter_count, static_cast<Eigen::Index>(2 * n_tiles));
368 const double* weight = contraction_weight->data();
369 const Index_t row_stride = n_conf;
370 const Index_t col_stride = n_conf * n;
372 owned, std::memory_order_relaxed);
373 workspace.local().forEach(workers, [&](std::size_t worker) {
374 pairlocal::TileEvaluator evaluator(local, weights);
375 Eigen::VectorXd part;
376 for (std::size_t position = worker; position < owned;
377 position += workers) {
378 const std::size_t index = rank + position * ranks;
379 Index_t i = 0, j = 0;
380 tile_pair(index, i, j);
381 evaluator.prepare(i, j);
382 evaluator.contract(weight + i + j * n, row_stride, col_stride,
383 /*lower_only=*/false, part);
384 products.col(static_cast<Eigen::Index>(2 * index)) = part;
385 if (i == j) continue;
386 // <W_ji, dK_ij^T> through the transposed strides.
387 evaluator.contract(weight + j + i * n, col_stride, row_stride,
388 /*lower_only=*/false, part);
389 products.col(static_cast<Eigen::Index>(2 * index + 1)) = part;
390 }
391 });
392 // Workers enter no collectives. Every entry has one owner, so this
393 // reduction gathers values without changing their rounding order.
394 for (Eigen::Index offset = 0; offset < products.size();) {
395 const int count = static_cast<int>(std::min<Eigen::Index>(
396 products.size() - offset, std::numeric_limits<int>::max()));
397 linalg::disjoint_sum_bcast(products.data() + offset, count,
398 context);
399 offset += count;
400 }
401 std::vector<linalg::CompensatedSum> sums(
402 static_cast<std::size_t>(parameter_count));
403 for (std::size_t index = 0; index < n_tiles; ++index) {
404 Index_t i = 0, j = 0;
405 tile_pair(index, i, j);
406 const auto column = static_cast<Eigen::Index>(2 * index);
407 for (Eigen::Index p = 0; p < parameter_count; ++p)
408 sums[static_cast<std::size_t>(p)].add(products(p, column));
409 if (i == j) continue;
410 for (Eigen::Index p = 0; p < parameter_count; ++p)
411 sums[static_cast<std::size_t>(p)].add(products(p, column + 1));
412 }
413 contractions->resize(
414 1 + static_cast<Eigen::Index>(derivative_indices->size()));
415 (*contractions)(0) = sums[0].value();
416 for (std::size_t k = 0; k < derivative_indices->size(); ++k) {
417 const Eigen::Index parameter = (*derivative_indices)[k];
418 (*contractions)(static_cast<Eigen::Index>(k) + 1) =
419 sums[static_cast<std::size_t>(parameter)].value();
420 }
421 return contractions->allFinite();
422 }
423 if (placement != nullptr &&
424 placement->size() != static_cast<std::size_t>(n))
425 return false;
426 Ktemp.setZero(n, n);
427 std::vector<Eigen::Index> derivative_parameters;
428 if (covariance_derivatives != nullptr) {
429 if (derivative_indices == nullptr) return false;
430 derivative_parameters = *derivative_indices;
431 const Eigen::Index parameter_count =
433 for (const auto parameter: derivative_parameters)
434 if (parameter <= 0 || parameter >= parameter_count) return false;
435 covariance_derivatives->assign(1 + derivative_parameters.size(),
436 EigenMatrix::Zero(n, n));
437 }
438 const std::size_t workers = std::min(
439 owned, static_cast<std::size_t>(workspace.local().concurrency()));
440 workspace.local().forEach(workers, [&](std::size_t worker) {
441 pairlocal::TileEvaluator evaluator(local, weights);
442 Eigen::MatrixXd block;
443 // Row r of the channel-major layout lands at placement[r]; the
444 // writes and their order are those of the unplaced assembly.
445 const auto at = [&](Index_t row) {
446 return placement != nullptr
447 ? (*placement)[static_cast<std::size_t>(row)]
448 : row;
449 };
450 const auto scatter = [&](const Eigen::MatrixXd& values,
451 EigenMatrix& destination, Index_t i,
452 Index_t j) {
453 for (Index_t c = 0; c < tile; ++c) {
454 for (Index_t cc = 0; cc < tile; ++cc) {
455 destination(at(c * n_conf + i), at(cc * n_conf + j)) =
456 values(c, cc);
457 destination(at(cc * n_conf + j), at(c * n_conf + i)) =
458 values(c, cc);
459 }
460 }
461 };
462 for (std::size_t position = worker; position < owned;
463 position += workers) {
464 const std::size_t index = rank + position * ranks;
465 Index_t i = 0, j = 0;
466 tile_pair(index, i, j);
467 evaluator.prepare(i, j);
468 evaluator.tile(0, block);
469 scatter(block, Ktemp, i, j);
470 for (std::size_t k = 0; k < derivative_parameters.size(); ++k) {
471 const Eigen::Index parameter = derivative_parameters[k];
472 evaluator.tile(parameter, block);
473 scatter(block, (*covariance_derivatives)[k + 1], i, j);
474 }
475 }
476 });
477 if (do_reduce) {
478 // One rank owns each tile and its transpose. Summing zero-filled
479 // partial matrices preserves every computed covariance value.
480 const auto gather = [&](EigenMatrix& matrix) {
481 for (Eigen::Index offset = 0; offset < matrix.size();) {
482 const int count = static_cast<int>(std::min<Eigen::Index>(
483 matrix.size() - offset, std::numeric_limits<int>::max()));
484 linalg::disjoint_sum_bcast(matrix.data() + offset, count,
485 context);
486 offset += count;
487 }
488 };
489 gather(Ktemp);
490 if (covariance_derivatives != nullptr)
491 for (std::size_t k = 1; k < covariance_derivatives->size(); ++k)
492 gather((*covariance_derivatives)[k]);
493 }
494 if (covariance_derivatives != nullptr)
495 covariance_derivatives->front() = Ktemp;
496 return true;
497}
498
499[[nodiscard]] bool assembleSexpatCovFromGeometry(
501 const TrainingKernelGeometry& geom, SexpatCF& sexpat_cf,
502 const Eigen::VectorXd& ind_Ddim, EigenMatrix& Ktemp, bool do_reduce,
503 bool serial_per_rank, const Eigen::VectorXd* supplied_theta = nullptr,
504 std::vector<EigenMatrix>* covariance_derivatives = nullptr,
505 const std::vector<Eigen::Index>* derivative_indices = nullptr,
506 const EigenMatrix* contraction_weight = nullptr,
507 Eigen::VectorXd* contractions = nullptr, bool* replicated = nullptr,
508 const std::vector<Index_t>* placement = nullptr)
509{
510 const Index_t n = static_cast<Index_t>(geom.n);
511 const bool contract_only = contractions != nullptr;
512 if (placement != nullptr && contract_only) return false;
513 if (replicated != nullptr) *replicated = false;
514 // Validity belongs to the training geometry, independent of the
515 // representation used to assemble it. Every participating rank rejects
516 // a block invalidated by any member of the fitting communicator.
517 double invalid_geometry = std::any_of(
518 geom.blocks.begin(), geom.blocks.end(), [&](const auto& block) {
519 return !trainingBlockGeometryUsable(geom, block);
520 });
521 if (do_reduce && !serial_per_rank)
522 linalg::ordered_sum_bcast(&invalid_geometry, 1, workspace.mpi());
523 if (invalid_geometry != 0.0) return false;
524 if (pairLocalCoversGeometry(geom) && !sexpat_cf.usesManifoldChart()) {
525 const Eigen::VectorXd theta_local = supplied_theta != nullptr
526 ? *supplied_theta
527 : sexpat_cf.combineParameters();
529 theta_local, geom.pair_local.n_pt);
530 if (weights.valid) {
531 if (replicated != nullptr) *replicated = do_reduce;
532 ++gpr.pair_local_assemblies_for_testing_;
533 return assemblePairLocalCovariance(
534 workspace, geom.pair_local, weights, Ktemp,
535 covariance_derivatives, derivative_indices, contraction_weight,
536 contractions, do_reduce, serial_per_rank, placement);
537 }
538 if (std::getenv("GPR_GEOM_DEBUG"))
539 std::fprintf(stderr,
540 "[geom] pair-local weights rejected: theta=%lld "
541 "n_pt=%lld\n",
542 static_cast<long long>(theta_local.size()),
543 static_cast<long long>(geom.pair_local.n_pt));
544 } else if (std::getenv("GPR_GEOM_DEBUG")) {
545 std::fprintf(stderr,
546 "[geom] pair-local skipped: valid=%d n=%lld rep=%lld "
547 "udim=%lld n_conf=%lld dof=%lld n_pt=%lld chart=%d\n",
548 geom.pair_local.valid ? 1 : 0,
549 static_cast<long long>(geom.n),
550 static_cast<long long>(geom.num_repetitive_indices),
551 static_cast<long long>(geom.uDdim.size()),
552 static_cast<long long>(geom.pair_local.n_conf),
553 static_cast<long long>(geom.pair_local.dof),
554 static_cast<long long>(geom.pair_local.n_pt),
555 sexpat_cf.usesManifoldChart() ? 1 : 0);
556 }
557 if (placement != nullptr) return false;
558 if (contract_only) {
559 if (contraction_weight == nullptr || derivative_indices == nullptr ||
560 covariance_derivatives != nullptr)
561 return false;
562 Ktemp.resize(0, 0);
563 } else {
564 Ktemp.setZero(n, n);
565 }
566 const bool geom_dbg = std::getenv("GPR_GEOM_DEBUG") != nullptr;
567 if (geom_dbg)
568 std::fprintf(stderr, "[geom] ktemp n=%lld rss_mb=%.0f\n",
569 static_cast<long long>(n),
571
572 const Eigen::VectorXd theta = supplied_theta != nullptr
573 ? *supplied_theta
574 : sexpat_cf.combineParameters();
575 if (theta.size() < 2) return false;
576
577 // Build the shared kernel once per inner iter: exp(theta(0)) *
578 // exp(-0.5 * sum_pt inv_l_pt^2 * dist_neg_per_pt). Reused across all
579 // (block_n, block_m) blocks since the atom positions are identical
580 // by construction of assembleMatrixOfRepetitiveCoordinates. One exp()
581 // call instead of one per block (946-fold reduction on PETMAD d016
582 // D=42 with 43 dim slices).
583 FieldMatrixd shared_kernel;
584 if (!sexpat_cf.buildSharedKernel(geom.shared_distance_neg_per_pt, theta,
585 shared_kernel)) {
586 return false;
587 }
588
589 if (covariance_derivatives != nullptr) {
590 if (derivative_indices == nullptr) return false;
591 covariance_derivatives->assign(1 + derivative_indices->size(),
592 EigenMatrix::Zero(n, n));
593 }
594 EigenMatrix block_products;
595 if (contract_only)
596 block_products.setZero(geom.blocks.size(),
597 1 + derivative_indices->size());
598#ifdef GPR_LINALG_SCALAPACK
599 auto& mpi_st = workspace.distributed();
600 mpi_st.initialize();
601 const int mpi_rank = mpi_st.myrank();
602 const int mpi_np = mpi_st.nprocs();
603#else
604 const int mpi_rank = 0;
605 const int mpi_np = 1;
606#endif
607 std::vector<std::size_t> owned;
608 owned.reserve(geom.blocks.size());
609 for (std::size_t index = 0; index < geom.blocks.size(); ++index)
610 if (ownsBlock(index, mpi_rank, mpi_np, serial_per_rank))
611 owned.push_back(index);
612 const std::size_t workers =
613 std::min(owned.size(),
614 static_cast<std::size_t>(workspace.local().concurrency()));
615 std::vector<uint8_t> valid_workers(workers, 1);
616 // A channel block and its transpose have one owner. Scratch is bounded
617 // by worker count; shared matrices are allocated before workers enter.
618 workspace.local().forEach(workers, [&](std::size_t worker) {
619 FieldMatrixd block_out;
620 FieldMatrixd block_kernel;
621 std::vector<FieldMatrixd> block_derivatives;
622 SexpatCF::CrossBlockGeometry streamed_scratch;
623 for (std::size_t task = worker; task < owned.size(); task += workers) {
624 const std::size_t index = owned[task];
625 const auto& block = geom.blocks[index];
626 if (geom_dbg && (index % 64 == 0))
627 std::fprintf(stderr, "[geom] block %zu/%zu rss_mb=%.0f\n",
628 index, geom.blocks.size(),
630
631 const bool energy_block = block.derivative_options == 0;
632 const SexpatCF::CrossBlockGeometry* block_geometry = nullptr;
633 const FieldMatrixd* kernel = &shared_kernel;
634 const std::vector<FieldMatrixd>* distances =
635 &geom.shared_distance_neg_per_pt;
636 if (energy_block) {
637 block_out = shared_kernel;
638 } else {
639 block_geometry = resolveTrainingBlockGeometry(
640 sexpat_cf, geom, block, streamed_scratch);
641 if (block_geometry == nullptr) {
642 valid_workers[worker] = 0;
643 return;
644 }
645 if (!geom.shared_coordinates) {
646 distances = &block_geometry->distance;
647 if (!sexpat_cf.buildSharedKernel(*distances, theta,
648 block_kernel)) {
649 valid_workers[worker] = 0;
650 return;
651 }
652 kernel = &block_kernel;
653 }
654 if (!sexpat_cf.evaluateCrossBlockGeometryWithSharedKernel(
655 *block_geometry, *kernel, theta, block_out)) {
656 valid_workers[worker] = 0;
657 return;
658 }
659 }
660 const auto assign = [&](const FieldMatrixd& values,
661 EigenMatrix& destination) {
662 gpr.assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_n,
663 block.block_m, values, destination);
664 if (block.block_n != block.block_m)
665 gpr.assignBlockToMatrix(ind_Ddim, ind_Ddim, block.block_m,
666 block.block_n, values, destination,
667 /*transpose=*/true);
668 };
669 if (!contract_only) assign(block_out, Ktemp);
670 if ((covariance_derivatives != nullptr || contract_only) &&
671 !derivative_indices->empty()) {
672 bool valid = false;
673 if (energy_block) {
674 valid = sexpat_cf.calculateGradOfCovMatrixFromGeometry(
675 *kernel, *distances, theta, block_derivatives,
676 derivative_indices);
677 } else if (block.derivative_options ==
679 valid =
680 sexpat_cf
681 .calculateGradOfCovMatrixWithDerivativesFromGeometry(
682 *block_geometry, *kernel, *distances, theta,
683 block_derivatives, derivative_indices);
684 } else {
685 valid =
686 sexpat_cf
687 .calculateGradOfCovMatrixWithDerivatives2FromGeometry(
688 *block_geometry, *kernel, *distances, theta,
689 block_derivatives, derivative_indices);
690 }
691 if (!valid ||
692 block_derivatives.size() != derivative_indices->size()) {
693 valid_workers[worker] = 0;
694 return;
695 }
696 if (!contract_only)
697 for (std::size_t i = 0; i < block_derivatives.size(); ++i)
698 assign(block_derivatives[i],
699 (*covariance_derivatives)[i + 1]);
700 }
701 if (contract_only) {
702 const Eigen::Index rows = block_out.rows();
703 const Eigen::Index row =
704 observationChannelBlock(ind_Ddim, block.block_n).start;
705 const Eigen::Index col =
706 observationChannelBlock(ind_Ddim, block.block_m).start;
707 const auto product = [&](const FieldMatrixd& values) {
708 const double direct =
709 (contraction_weight->block(row, col, rows, rows)
710 .array() *
711 values.array())
712 .sum();
713 if (row == col) return direct;
714 return direct +
715 (contraction_weight->block(col, row, rows, rows)
716 .array() *
717 values.transpose().array())
718 .sum();
719 };
720 block_products(index, 0) = product(block_out);
721 for (std::size_t i = 0; i < derivative_indices->size(); ++i)
722 block_products(index, i + 1) =
723 product(block_derivatives[i]);
724 }
725 }
726 });
727 double failed = std::find(valid_workers.begin(), valid_workers.end(), 0) !=
728 valid_workers.end();
729#ifdef GPR_LINALG_SCALAPACK
730 // All owners agree on failure before entering covariance collectives.
731 if (do_reduce && !serial_per_rank && mpi_np > 1)
732 workspace.ordered_sum_bcast(&failed, 1);
733#endif
734 if (failed != 0.0) return false;
735
736 if (contract_only) {
737#ifdef GPR_LINALG_SCALAPACK
738 // One owner writes each block product. Collectives occur only after
739 // host workers join, and the final sum uses the same block order.
740 if (do_reduce && !serial_per_rank && mpi_np > 1)
741 workspace.disjoint_sum_bcast(
742 block_products.data(), static_cast<int>(block_products.size()));
743#endif
744 contractions->resize(block_products.cols());
745 for (Eigen::Index parameter = 0; parameter < block_products.cols();
746 ++parameter) {
748 for (Eigen::Index block = 0; block < block_products.rows(); ++block)
749 sum.add(block_products(block, parameter));
750 (*contractions)(parameter) = sum.value();
751 }
752 return contractions->allFinite();
753 }
754
755#ifdef GPR_LINALG_SCALAPACK
756 // One owner per (block, transpose-partner) pair: disjoint support,
757 // exact under Allreduce (see disjoint_sum_bcast).
758 if (do_reduce && !serial_per_rank && mpi_np > 1) {
759 workspace.disjoint_sum_bcast(Ktemp.data(),
760 static_cast<int>(Ktemp.size()));
761 if (covariance_derivatives != nullptr)
762 for (std::size_t i = 1; i < covariance_derivatives->size(); ++i) {
763 auto& derivative = (*covariance_derivatives)[i];
764 workspace.disjoint_sum_bcast(
765 derivative.data(), static_cast<int>(derivative.size()));
766 }
767 }
768#else
769 (void)do_reduce;
770#endif
771 if (covariance_derivatives != nullptr)
772 covariance_derivatives->front() = Ktemp;
773 return true;
774}
775
783struct JointOperand {
784 Coord positions; // geometry rows for this operand
785 std::vector<Eigen::Index> geometry; // per input row
786 std::vector<Eigen::Index> channel; // per input row
787};
788
789[[nodiscard]] bool extractCompleteJointPositions(const EigenMatrix& rows,
790 const Eigen::VectorXd& indices,
791 Eigen::Index dimensions,
792 JointOperand& operand)
793{
794 const Eigen::Index channels = dimensions + 1;
795 if (dimensions <= 0 || rows.rows() <= 0 || rows.cols() < dimensions ||
796 indices.size() != rows.rows() || rows.rows() % channels != 0 ||
797 !rows.leftCols(dimensions).allFinite())
798 return false;
799 const Eigen::Index count = rows.rows() / channels;
800 for (const bool observation_major: {false, true}) {
801 const auto row_index = [&](Eigen::Index image, Eigen::Index channel) {
802 return observation_major ? image * channels + channel
803 : channel * count + image;
804 };
805 bool complete = true;
806 for (Eigen::Index image = 0; image < count && complete; ++image) {
807 const auto position =
808 rows.row(row_index(image, 0)).head(dimensions);
809 for (Eigen::Index channel = 0; channel < channels; ++channel) {
810 const Eigen::Index row = row_index(image, channel);
811 if (indices(row) != channel ||
812 !(rows.row(row).head(dimensions).array() ==
813 position.array())
814 .all()) {
815 complete = false;
816 break;
817 }
818 }
819 }
820 if (!complete) continue;
821 operand.positions.resize(count, dimensions);
822 operand.geometry.resize(static_cast<std::size_t>(rows.rows()));
823 operand.channel.resize(static_cast<std::size_t>(rows.rows()));
824 for (Eigen::Index image = 0; image < count; ++image) {
825 operand.positions.row(image) =
826 rows.row(row_index(image, 0)).head(dimensions);
827 for (Eigen::Index channel = 0; channel < channels; ++channel) {
828 const auto row =
829 static_cast<std::size_t>(row_index(image, channel));
830 operand.geometry[row] = image;
831 operand.channel[row] = channel;
832 }
833 }
834 return true;
835 }
836 return false;
837}
838
839[[nodiscard]] JointOperand extractJointPositions(const EigenMatrix& rows,
840 const Eigen::VectorXd& indices,
841 Eigen::Index dimensions)
842{
843 auto reject = [&](const char* why) {
844 throw std::invalid_argument(
845 std::string("composite covariance requires complete joint "
846 "observation rows: ") +
847 why + " (rows=" + std::to_string(rows.rows()) +
848 ", cols=" + std::to_string(rows.cols()) +
849 ", indices=" + std::to_string(indices.size()) +
850 ", manifold dimensions=" + std::to_string(dimensions) + ")");
851 };
852 if (rows.rows() != indices.rows() || dimensions <= 0 ||
853 rows.cols() < dimensions || indices.size() == 0) {
854 reject("operand shape");
855 }
856 const Eigen::Index n_rows = rows.rows();
857 JointOperand out;
858 out.geometry.resize(static_cast<std::size_t>(n_rows));
859 out.channel.resize(static_cast<std::size_t>(n_rows));
860 std::vector<Eigen::Index> first_row; // first row of each geometry
861 for (Eigen::Index r = 0; r < n_rows; ++r) {
862 const double raw_channel = indices(r);
863 const Eigen::Index channel = static_cast<Eigen::Index>(raw_channel);
864 if (!(raw_channel == static_cast<double>(channel)) || channel < 0 ||
865 channel > dimensions) {
866 throw std::invalid_argument(
867 "composite covariance rows carry an invalid channel index");
868 }
869 Eigen::Index g = -1;
870 for (Eigen::Index k = 0;
871 k < static_cast<Eigen::Index>(first_row.size()); ++k) {
872 if ((rows.row(first_row[static_cast<std::size_t>(k)])
873 .head(dimensions)
874 .array() == rows.row(r).head(dimensions).array())
875 .all()) {
876 g = k;
877 break;
878 }
879 }
880 if (g < 0) {
881 g = static_cast<Eigen::Index>(first_row.size());
882 first_row.push_back(r);
883 }
884 out.geometry[static_cast<std::size_t>(r)] = g;
885 out.channel[static_cast<std::size_t>(r)] = channel;
886 }
887 const Eigen::Index n_geom = static_cast<Eigen::Index>(first_row.size());
888 // Completeness: each geometry has channels 0..D exactly once.
889 std::vector<Eigen::Index> seen(
890 static_cast<std::size_t>(n_geom * (dimensions + 1)), 0);
891 for (Eigen::Index r = 0; r < n_rows; ++r) {
892 const std::size_t slot = static_cast<std::size_t>(
893 out.geometry[static_cast<std::size_t>(r)] * (dimensions + 1) +
894 out.channel[static_cast<std::size_t>(r)]);
895 if (++seen[slot] != 1) reject("duplicate channel for a geometry");
896 }
897 if (n_rows != n_geom * (dimensions + 1)) {
898 reject((std::string("a geometry is missing channels; distinct "
899 "geometries=") +
900 std::to_string(n_geom) + ", finite=" +
901 (rows.leftCols(dimensions).allFinite() ? "yes" : "no") +
902 ", first-column range=[" +
903 std::to_string(rows.col(0).minCoeff()) + ", " +
904 std::to_string(rows.col(0).maxCoeff()) + "]")
905 .c_str());
906 }
907 out.positions.resize(n_geom, dimensions);
908 for (Eigen::Index g = 0; g < n_geom; ++g) {
909 out.positions.row(g) =
910 rows.row(first_row[static_cast<std::size_t>(g)]).head(dimensions);
911 }
912 if (!out.positions.allFinite()) {
913 throw std::invalid_argument(
914 "composite covariance geometry contains non-finite values");
915 }
916 return out;
917}
918
921[[nodiscard]] EigenMatrix scatterJointBlock(const EigenMatrix& joint,
922 const JointOperand& left,
923 const JointOperand& right)
924{
925 const Eigen::Index nl = left.positions.rows();
926 const Eigen::Index nr = right.positions.rows();
927 EigenMatrix out(static_cast<Eigen::Index>(left.geometry.size()),
928 static_cast<Eigen::Index>(right.geometry.size()));
929 for (Eigen::Index i = 0; i < out.rows(); ++i) {
930 const Eigen::Index li = left.channel[static_cast<std::size_t>(i)] * nl +
931 left.geometry[static_cast<std::size_t>(i)];
932 for (Eigen::Index j = 0; j < out.cols(); ++j) {
933 const Eigen::Index rj =
934 right.channel[static_cast<std::size_t>(j)] * nr +
935 right.geometry[static_cast<std::size_t>(j)];
936 out(i, j) = joint(li, rj);
937 }
938 }
939 return out;
940}
941
945[[nodiscard]] EigenMatrix scatterJointBlockToRows(
946 const EigenMatrix& joint, const JointOperand& left,
947 const JointOperand& right, const std::vector<Index_t>& row_placement)
948{
949 const Eigen::Index nl = left.positions.rows();
950 const Eigen::Index nr = right.positions.rows();
951 EigenMatrix out(static_cast<Eigen::Index>(left.geometry.size()),
952 static_cast<Eigen::Index>(right.geometry.size()));
953 for (Eigen::Index j = 0; j < out.cols(); ++j) {
954 const Eigen::Index rj =
955 right.channel[static_cast<std::size_t>(j)] * nr +
956 right.geometry[static_cast<std::size_t>(j)];
957 for (Eigen::Index i = 0; i < out.rows(); ++i) {
958 const auto ui = static_cast<std::size_t>(i);
959 const Eigen::Index li = left.channel[ui] * nl + left.geometry[ui];
960 out(row_placement[ui], j) = 0.0 + joint(li, rj);
961 }
962 }
963 return out;
964}
965
966} // namespace
967
968std::optional<bool>
970 const TrainingKernelGeometry& geom, const Eigen::VectorXd& indices,
971 const Eigen::VectorXd& direction, EigenMatrix& first, EigenMatrix& second,
972 int rank, int ranks) const
973{
974 if (!use_pair_local_directional_tiles_ || !use_pair_local_tiles_)
975 return std::nullopt;
976 if (!geom.valid || ranks < 1 || rank < 0 || rank >= ranks) return false;
977 if (!pairLocalCoversGeometry(geom) || sexpat_cov_func == nullptr ||
978 sexpat_cov_func->usesManifoldChart() ||
979 sexpat_cov_func->usesGeodesicHeatKernel())
980 return std::nullopt;
981 const Eigen::Index configurations = geom.pair_local.n_conf;
982 const Eigen::Index tile = geom.pair_local.dof + 1;
983 if (indices.size() != geom.n) return false;
984 for (Eigen::Index channel = 0; channel < tile; ++channel)
985 for (Eigen::Index i = 0; i < configurations; ++i)
986 if (indices(channel * configurations + i) != channel)
987 return std::nullopt;
988 if (std::any_of(geom.blocks.begin(), geom.blocks.end(),
989 [&](const auto& block) {
990 return !trainingBlockGeometryUsable(geom, block);
991 }))
992 return false;
993 const Eigen::VectorXd theta = sexpat_cov_func->combineParameters();
994 const auto weights =
996 if (!weights.valid || direction.size() < theta.size() ||
997 !direction.allFinite())
998 return false;
999 // Weights and the probe direction are read here. The cached geometry
1000 // holds coordinates only; these matrices are not stored.
1001 const Eigen::VectorXd kernel_direction = direction.head(theta.size());
1002 first.setZero(geom.n, geom.n);
1003 second.setZero(geom.n, geom.n);
1004 std::vector<std::pair<Eigen::Index, Eigen::Index>> owned_pairs;
1005 owned_pairs.reserve(static_cast<std::size_t>(configurations) *
1006 static_cast<std::size_t>(configurations + 1) / 2);
1007 std::size_t tile_index = 0;
1008 for (Eigen::Index i = 0; i < configurations; ++i)
1009 for (Eigen::Index j = 0; j <= i; ++j) {
1010 if (tile_index++ % static_cast<std::size_t>(ranks) !=
1011 static_cast<std::size_t>(rank))
1012 continue;
1013 owned_pairs.emplace_back(i, j);
1014 }
1015 // One configuration pair writes a disjoint (D+1)^2 tile. n = 10 has
1016 // 55 pairs, below the fine-grain team threshold, and each pair is the
1017 // whole probe, so the coarse grain is what scales the team.
1018 std::atomic<int> failed{0};
1019 backend().local().forEach(
1020 owned_pairs.size(),
1021 [&](std::size_t task) {
1022 if (failed.load(std::memory_order_relaxed) != 0) return;
1023 const auto [i, j] = owned_pairs[task];
1024 pairlocal::TileEvaluator evaluator(geom.pair_local, weights);
1025 Eigen::MatrixXd block_first, block_second;
1026 evaluator.prepare(i, j);
1027 evaluator.directional(kernel_direction, block_first, block_second);
1028 if (!block_first.allFinite() || !block_second.allFinite()) {
1029 failed.store(1, std::memory_order_relaxed);
1030 return;
1031 }
1032 for (Eigen::Index r = 0; r < tile; ++r)
1033 for (Eigen::Index c = 0; c < tile; ++c) {
1034 const Eigen::Index row = r * configurations + i;
1035 const Eigen::Index column = c * configurations + j;
1036 first(row, column) = block_first(r, c);
1037 second(row, column) = block_second(r, c);
1038 if (i != j) {
1039 first(column, row) = block_first(r, c);
1040 second(column, row) = block_second(r, c);
1041 }
1042 }
1043 },
1045 if (failed.load(std::memory_order_relaxed) != 0) return false;
1046 pair_local_directional_tiles_for_testing_ += owned_pairs.size();
1047 return true;
1048}
1049
1051 const EigenMatrix& x, const Eigen::VectorXd& indices, SexpatCF& covariance,
1052 EigenMatrix& result) const
1053{
1054 const auto kernel = covariance.assembledOperator();
1055 if (!kernel) return false;
1056 JointOperand operand;
1057 if (covariance.usesManifoldChart()) {
1058 operand =
1059 extractJointPositions(x, indices, covariance.manifoldDimensions());
1060 } else if (!extractCompleteJointPositions(
1061 x, indices, covariance.geodesicHeatKernel()->dimensions(),
1062 operand)) {
1063 return false;
1064 }
1065 result = scatterJointBlock(
1066 kernel->jointEnergyGradientCovariance(operand.positions), operand,
1067 operand);
1068 if (covariance.usesManifoldChart())
1070 operand.positions.rows(), 0);
1071 return true;
1072}
1073
1075 const EigenMatrix& left, const EigenMatrix& right,
1076 const Eigen::VectorXd& left_indices, const Eigen::VectorXd& right_indices,
1077 SexpatCF& covariance, EigenMatrix& result) const
1078{
1079 if (!covariance.usesManifoldChart()) {
1080 const Eigen::Index dimensions = 3 * atoms_config.atoms_mov.type.size();
1081 JointOperand left_operand, right_operand;
1082 if (!extractCompleteJointPositions(left, left_indices, dimensions,
1083 left_operand) ||
1084 !extractCompleteJointPositions(right, right_indices, dimensions,
1085 right_operand))
1086 return false;
1087 const auto kernel = covariance.assembledOperator();
1088 const EigenMatrix joint =
1089 kernel ? kernel->jointEnergyGradientCrossCovariance(
1090 left_operand.positions, right_operand.positions)
1091 : Sexpat(covariance)
1093 left_operand.positions, right_operand.positions);
1094 result = scatterJointBlock(joint, left_operand, right_operand);
1095 return true;
1096 }
1097 const Eigen::Index dimensions = covariance.manifoldDimensions();
1098 const JointOperand left_operand =
1099 extractJointPositions(left, left_indices, dimensions);
1100 const JointOperand right_operand =
1101 extractJointPositions(right, right_indices, dimensions);
1102 const auto kernel = covariance.assembledOperator();
1103 result =
1104 scatterJointBlock(kernel->jointEnergyGradientCrossCovariance(
1105 left_operand.positions, right_operand.positions),
1106 left_operand, right_operand);
1108 left_operand.positions.rows(), right_operand.positions.rows());
1109 return true;
1110}
1111
1113 const EigenMatrix& x, const Eigen::VectorXd& indices, SexpatCF& covariance,
1114 std::vector<EigenMatrix>& derivatives) const
1115{
1116 derivatives.clear();
1117 if (!covariance.usesManifoldChart()) return false;
1118 const JointOperand operand =
1119 extractJointPositions(x, indices, covariance.manifoldDimensions());
1120 const auto derivative_block =
1122 auto kernel = std::make_shared<ManifoldEnergyForceKernel>(
1123 covariance.manifoldChart(), covariance.getMagnSigma2(),
1124 covariance.getLengthScaleRef()(0, 0));
1125 kernel->setDerivative(mode);
1126 const Pullback pullback{
1127 std::shared_ptr<const ManifoldEnergyForceKernel>(kernel)};
1128 return scatterJointBlock(
1129 pullback.jointEnergyGradientCovariance(operand.positions),
1130 operand, operand);
1131 };
1132 // d/d log s^2: the joint block is linear in s^2, so the derivative is the
1133 // block itself. d/d log l: the chart kernel derivative (k a r^2 and its
1134 // energy/gradient images) evaluated by the same operator algebra.
1135 derivatives.push_back(derivative_block(
1137 derivatives.push_back(derivative_block(
1139 const Eigen::Index n_length = covariance.getLengthScaleRef().size();
1140 for (Eigen::Index k = 1; k < n_length; ++k) {
1141 derivatives.emplace_back(EigenMatrix::Zero(derivatives.front().rows(),
1142 derivatives.front().cols()));
1143 }
1144 for (auto& derivative: derivatives)
1145 applyKernelNugget(derivative, x.rows());
1146 return true;
1147}
1148
1149bool GaussianProcessRegression::
1150 assembleCompositeJointCovarianceSecondDerivative(
1151 const EigenMatrix& x, const Eigen::VectorXd& indices,
1152 SexpatCF& covariance, const Eigen::VectorXd& direction,
1153 EigenMatrix& second) const
1154{
1155 if (!covariance.usesManifoldChart() || direction.size() < 2) return false;
1156 const JointOperand operand =
1157 extractJointPositions(x, indices, covariance.manifoldDimensions());
1158 const auto block = [&](ManifoldEnergyForceKernel::Derivative mode) {
1159 auto kernel = std::make_shared<ManifoldEnergyForceKernel>(
1160 covariance.manifoldChart(), covariance.getMagnSigma2(),
1161 covariance.getLengthScaleRef()(0, 0));
1162 kernel->setDerivative(mode);
1163 const Pullback pullback{
1164 std::shared_ptr<const ManifoldEnergyForceKernel>(kernel)};
1165 return scatterJointBlock(
1166 pullback.jointEnergyGradientCovariance(operand.positions), operand,
1167 operand);
1168 };
1169 const double pu = direction(0);
1170 const double pv = direction(1);
1171 second = pu * pu * block(ManifoldEnergyForceKernel::Derivative::Value);
1172 if (pv != 0.0) {
1173 second.noalias() +=
1174 (2.0 * pu * pv) *
1176 second.noalias() +=
1177 (pv * pv) *
1179 }
1180 applyKernelNugget(second, x.rows());
1181 return true;
1182}
1183
1185 const EigenMatrix& x, const Eigen::VectorXd& x_ind,
1186 TrainingKernelGeometry& out, bool reused) const
1187{
1189 // RAII timer: accumulate this build's wall into g_geom_build_seconds on
1190 // every return path (attribution probe for the incremental-geometry work).
1191 struct GeomTimer {
1192 std::chrono::steady_clock::time_point t0 =
1193 std::chrono::steady_clock::now();
1194 ~GeomTimer()
1195 {
1196 g_geom_build_seconds += std::chrono::duration<double>(
1197 std::chrono::steady_clock::now() - t0)
1198 .count();
1199 }
1200 } geom_timer;
1201 struct PrepReport {
1202 const TrainingKernelGeometry& g;
1203 double rss0 = PhaseTimers::residentMegabytes();
1204 ~PrepReport()
1205 {
1206 if (std::getenv("GPR_GEOM_DEBUG"))
1207 std::fprintf(
1208 stderr,
1209 "[geom] prepare n=%lld dims=%lld blocks=%zu streamed=%d "
1210 "rss_mb %.0f -> %.0f\n",
1211 static_cast<long long>(g.n),
1212 static_cast<long long>(g.x_loc_by_dim.size()),
1213 g.blocks.size(), g.streamed ? 1 : 0, rss0,
1215 }
1216 } prep_report{out};
1217
1218 out.clear();
1219 if (sexpat_cov_func == nullptr) return false;
1220 // The pair-distance geometry evaluates the ambient Sexpat operator; a
1221 // charted composite is not a function of pair distances.
1222 if (sexpat_cov_func->usesManifoldChart() ||
1223 sexpat_cov_func->usesGeodesicHeatKernel())
1224 return false;
1225 if (x.cols() < 2) {
1226 // The 1D path in applyCovarianceFunction takes a different code path
1227 // (blocked [Kff Kdf; Kdf D] layout). Skip the geometry cache there;
1228 // CuH2/PETMAD do not hit this branch.
1229 if (std::getenv("GPR_GEOM_DEBUG"))
1230 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1231 __LINE__);
1232 return false;
1233 }
1234 const detail::ObservationChannelLayout channels(x_ind);
1235 if (!channels.valid())
1236 throw std::invalid_argument(
1237 "observation channels must be grouped in order");
1238 if (x_ind.size() != x.rows() || channels.rowsPerChannel() <= 0 ||
1239 channels.block(0).count == 0)
1240 return false;
1241
1242 extractUniqueIndices(x_ind, out.uDdim);
1243 out.num_repetitive_indices = getNumberOfRepetitiveIndices(x_ind);
1244 out.n = x.rows();
1245
1246 FieldMatrixd x_loc_0, x_loc_1, x_loc_2;
1247 FieldMatrixIdx dims1(1, 1), dims2(1, 1);
1248
1249 x_loc_0.resize(out.num_repetitive_indices, x.cols() + 1);
1250 x_loc_0.setZero();
1251 x_loc_1.resize(out.num_repetitive_indices, x.cols() + 1);
1252 x_loc_1.setZero();
1253 x_loc_2.resize(out.num_repetitive_indices, x.cols() + 1);
1254 x_loc_2.setZero();
1255
1256 extractCoordinatesByIndex(x, x_ind, 0, x_loc_0);
1257
1258 const Eigen::Index coordinate_dimensions =
1259 3 * sexpat_cov_func->getConfInfo().atoms_mov.type.size();
1260 if (coordinate_dimensions <= 0 || x.cols() < coordinate_dimensions)
1261 return false;
1262 out.shared_coordinates =
1263 channels.repeatsCoordinates(x, coordinate_dimensions);
1264
1265 // The energy block supplies the base distance at unit lengthscale.
1266 // Repeated Cartesian positions share it across every channel block;
1267 // distinct positions require each derivative block's own distance.
1268 if (!sexpat_cov_func->buildSharedDistanceForTrainingGeometry(
1269 x_loc_0, out.shared_distance_neg_per_pt)) {
1270 if (std::getenv("GPR_GEOM_DEBUG"))
1271 std::fprintf(
1272 stderr,
1273 "[geom] fallback: shared distance (n_pt=%d rows=%lld)\n",
1274 static_cast<int>(atoms_config.n_pt),
1275 static_cast<long long>(x.rows()));
1276 if (std::getenv("GPR_GEOM_DEBUG"))
1277 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1278 __LINE__);
1279 return false;
1280 }
1281
1282 // The pair-local tiles serve every assembly and gradient that can use
1283 // them; the block geometry below remains for the others.
1284 if (use_pair_local_tiles_ && out.shared_coordinates)
1285 (void)pairlocal::buildGeometry(sexpat_cov_func->getConfInfo(),
1286 Eigen::MatrixXd(x_loc_0), out.pair_local,
1287 sexpat_cov_func->farFieldRadius());
1288
1289 // Kff: (0, 0), derivative_options = 0. Distance field left empty;
1290 // shared tensor populated above.
1291 {
1293 b.block_n = 0;
1294 b.block_m = 0;
1295 b.derivative_options = 0;
1296 if (!sexpat_cov_func->buildCrossBlockDerivativesOnly(
1297 x_loc_0, x_loc_0, /*derivative_options=*/0, dims1, dims2,
1298 b.geometry)) {
1299 if (std::getenv("GPR_GEOM_DEBUG"))
1300 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1301 __LINE__);
1302 return false;
1303 }
1304 out.blocks.push_back(std::move(b));
1305 }
1306
1307 const uint8_t full_grad = OptionsForGradCalculation::D1 |
1310 {
1311 // Footprint of the cached derivative tensors: one per-pair-type
1312 // n_conf x n_conf field for each D1 block and three for each of
1313 // the D(D+1)/2 full blocks.
1314 // Measured, not modelled: build one full block and count its
1315 // bytes (the walked builder stores more than the three per-pair-type
1316 // fields its interface names), then scale by the block count.
1317 const double D = static_cast<double>(out.uDdim.size());
1318 double bytes = 0.0;
1319 if (out.uDdim.size() > 0) {
1320 FieldMatrixIdx d1(1, 1), d2(1, 1);
1321 d1(0, 0) = static_cast<Index_t>(out.uDdim[0]);
1322 d2(0, 0) = d1(0, 0);
1323 FieldMatrixd x_probe = x_loc_0;
1324 x_probe.setZero();
1325 extractCoordinatesByIndex(x, x_ind, d1(0, 0), x_probe);
1327 if (sexpat_cov_func->buildCrossBlockDerivativesOnly(
1328 x_probe, x_probe,
1332 d1, d2, probe)) {
1333 auto field_bytes = [](const std::vector<FieldMatrixd>& v) {
1334 double b = 0.0;
1335 for (const auto& m: v)
1336 b += static_cast<double>(m.size()) * sizeof(double);
1337 return b;
1338 };
1339 const double per_full_block =
1340 field_bytes(probe.d1) + field_bytes(probe.d2) +
1341 field_bytes(probe.d12) + field_bytes(probe.distance);
1342 const double per_d1_block = field_bytes(probe.d1);
1343 bytes = per_full_block * D * (D + 1.0) / 2.0 + per_d1_block * D;
1344 }
1345 }
1346 // The derivative cache competes with dense fit workspaces. Large
1347 // workloads use factored derivatives; smaller caches may spill as
1348 // allocation headroom decreases.
1349 const double n_joint = static_cast<double>(x.rows());
1350 const double working_set = 4.0 * n_joint * n_joint * sizeof(double);
1351 // With the pair-local tiles no consumer reads the cached block
1352 // tensors on the fit path; the streamed factors serve the rest.
1353 // Workload size chooses the derivative arithmetic. Memory pressure
1354 // changes only storage: a cache that spills uses the same walked
1355 // derivatives, so ranks with different headroom produce the same bits.
1356 const bool force_streamed =
1357 std::getenv("GPR_GEOM_FORCE_STREAM") != nullptr;
1358 // Explicit streaming of one-use geometry requests the factored
1359 // builder. A reusable cache keeps its arithmetic when it spills.
1360 const bool factored_derivatives =
1361 out.shared_coordinates &&
1362 (out.pair_local.valid ||
1363 (!reused && (bytes > working_set || force_streamed)));
1364 const auto budget =
1365 factored_derivatives
1367 : geometryCacheBudgetBytes(backend().memorySharingRanks());
1368 out.streamed = !out.shared_coordinates || factored_derivatives ||
1369 (budget && bytes > static_cast<double>(*budget)) ||
1370 force_streamed;
1371 if (out.streamed) {
1372 const Index_t max_dim =
1373 out.uDdim.size() > 0
1374 ? static_cast<Index_t>(out.uDdim.maxCoeff())
1375 : 0;
1376 out.x_loc_by_dim.assign(static_cast<std::size_t>(max_dim) + 1,
1377 FieldMatrixd());
1378 out.x_loc_by_dim[0] = x_loc_0;
1379 if (pairLocalCoversGeometry(out)) {
1380 out.lazy_factors =
1381 std::make_shared<LazyFactoredTrainingGeometry>(
1382 sexpat_cov_func->getConfInfo(), x_loc_0,
1383 sexpat_cov_func->farFieldRadius());
1384 } else if (factored_derivatives) {
1386 sexpat_cov_func->getConfInfo(), x_loc_0, out.factors,
1387 sexpat_cov_func->farFieldRadius());
1388 }
1389 if (std::getenv("GPR_GEOM_DEBUG"))
1390 std::fprintf(
1391 stderr,
1392 "[geom] streamed geometry: cache would be %.2f GB "
1393 "against a %.2f GB budget\n",
1394 bytes / 1e9,
1395 budget ? static_cast<double>(*budget) / 1e9 : -1.0);
1396 }
1397 }
1398 auto build_derivative_geometry =
1399 [&](const FieldMatrixd& x1_block, const FieldMatrixd& x2_block,
1400 const uint8_t derivative_options, const FieldMatrixIdx& block_dims1,
1401 const FieldMatrixIdx& block_dims2,
1403 if (out.streamed) {
1404 // Descriptor only; the consumer rebuilds the tensors per block.
1406 geometry.derivative_options = derivative_options;
1407 geometry.valid = true;
1408 return true;
1409 }
1410 if (derivative_options != 0) {
1411 ++out.derivative_geometry_build_calls_for_testing;
1412 }
1413 return sexpat_cov_func->buildCrossBlockDerivativesOnly(
1414 x1_block, x2_block, derivative_options, block_dims1, block_dims2,
1415 geometry);
1416 };
1417
1418 for (Index_t n = 0; n < out.uDdim.size(); ++n) {
1419 dims1(0, 0) = static_cast<Index_t>(out.uDdim[n]);
1420 x_loc_1.setZero();
1421 extractCoordinatesByIndex(x, x_ind, dims1(0, 0), x_loc_1);
1422 if (out.streamed &&
1423 dims1(0, 0) < static_cast<Index_t>(out.x_loc_by_dim.size())) {
1424 out.x_loc_by_dim[static_cast<std::size_t>(dims1(0, 0))] = x_loc_1;
1425 }
1426
1427 // Kdf at (block_n, 0): D1 only. ginput4 equivalent.
1428 {
1430 b.block_n = dims1(0, 0);
1431 b.block_m = 0;
1432 b.derivative_options = OptionsForGradCalculation::D1;
1433 if (!build_derivative_geometry(x_loc_1, x_loc_0,
1435 dims2, b.geometry)) {
1436 if (std::getenv("GPR_GEOM_DEBUG"))
1437 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1438 __LINE__);
1439 return false;
1440 }
1441 out.blocks.push_back(std::move(b));
1442 }
1443
1444 // D at (block_n, block_n): full grad on (x_loc_1, x_loc_1). ginput2.
1445 {
1447 b.block_n = dims1(0, 0);
1448 b.block_m = dims1(0, 0);
1449 b.derivative_options = full_grad;
1450 if (!build_derivative_geometry(x_loc_1, x_loc_1, full_grad, dims1,
1451 dims1, b.geometry)) {
1452 if (std::getenv("GPR_GEOM_DEBUG"))
1453 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1454 __LINE__);
1455 return false;
1456 }
1457 out.blocks.push_back(std::move(b));
1458 }
1459
1460 // Kdf2 at (block_n, block_m) with block_m > block_n: ginput3.
1461 for (Index_t m = n + 1; m < out.uDdim.size(); ++m) {
1462 dims2(0, 0) = static_cast<Index_t>(out.uDdim[m]);
1463 x_loc_2.setZero();
1464 extractCoordinatesByIndex(x, x_ind, dims2(0, 0), x_loc_2);
1466 b.block_n = dims1(0, 0);
1467 b.block_m = dims2(0, 0);
1468 b.derivative_options = full_grad;
1469 if (!build_derivative_geometry(x_loc_1, x_loc_2, full_grad, dims1,
1470 dims2, b.geometry)) {
1471 if (std::getenv("GPR_GEOM_DEBUG"))
1472 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1473 __LINE__);
1474 return false;
1475 }
1476 out.blocks.push_back(std::move(b));
1477 }
1478 }
1479
1480 // Index blocks by (block_n, block_m) so the gradient walk can find
1481 // cached geometry per block without linear scan.
1482 out.block_index_by_nm.clear();
1483 for (std::size_t i = 0; i < out.blocks.size(); ++i) {
1484 const auto& blk = out.blocks[i];
1485 out.block_index_by_nm[{blk.block_n, blk.block_m}] = i;
1486 }
1487 out.n_pairtypes =
1488 static_cast<Index_t>(out.shared_distance_neg_per_pt.size());
1489
1490 // Per-rank owned-subset geometry. At np>1 each rank's owned observation
1491 // subset is distinct (determined by the BLACS grid below), so the full
1492 // geometry's blocks don't directly apply to the permuted gradient walk.
1493 // At np=1 the subset has the full shape, but it keeps the same assembly
1494 // path as distributed runs and preserves the validated dimer trajectory.
1495#ifdef GPR_LINALG_SCALAPACK
1496 if (out.streamed) {
1497 // The per-rank subsets copy the cached tensors; a streamed geometry
1498 // has none and its consumers take the full-block path.
1499 out.has_per_rank_subset = false;
1500 out.valid = true;
1501 return true;
1502 }
1503 auto& _mpi_st_subset = backend().distributed();
1504 _mpi_st_subset.initialize();
1505 const Index_t proc_rows = static_cast<Index_t>(_mpi_st_subset.nprow());
1506 const Index_t proc_cols = static_cast<Index_t>(_mpi_st_subset.npcol());
1507 const Index_t my_row = static_cast<Index_t>(_mpi_st_subset.myrow());
1508 const Index_t my_col = static_cast<Index_t>(_mpi_st_subset.mycol());
1509 std::vector<Index_t> owned_obs_rows;
1510 std::vector<Index_t> owned_obs_cols;
1511 for (Index_t obs = 0; obs < out.num_repetitive_indices; ++obs) {
1512 if (obs % proc_rows == my_row) owned_obs_rows.push_back(obs);
1513 if (obs % proc_cols == my_col) owned_obs_cols.push_back(obs);
1514 }
1515 const auto build_obs_subset = [&](Index_t dim_ind,
1516 const std::vector<Index_t>& obs_inds,
1517 FieldMatrixd& x_loc_subset) {
1518 x_loc_subset.resize(static_cast<Index_t>(obs_inds.size()),
1519 x.cols() + 1);
1520 x_loc_subset.setZero();
1521 const Eigen::Index start =
1522 observationChannelBlock(x_ind, dim_ind).start;
1523 for (std::size_t local_idx = 0; local_idx < obs_inds.size();
1524 ++local_idx) {
1525 x_loc_subset.block(static_cast<Index_t>(local_idx), 0, 1,
1526 x.cols()) =
1527 x.block(start + obs_inds[local_idx], 0, 1, x.cols());
1528 }
1529 };
1530 const auto fill_subset = [&](TrainingKernelGeometrySubset& subset,
1531 const std::vector<Index_t>& obs_rows,
1532 const std::vector<Index_t>& obs_cols) -> bool {
1533 subset.clear();
1534 if (obs_rows.empty() || obs_cols.empty()) {
1535 subset.valid = true;
1536 return true;
1537 }
1538 // When this rank owns the entire observation set on both axes (np=1,
1539 // and any full-owning rank) the subset is built on exactly the full
1540 // geometry's coordinates, so the shared distance and every block are
1541 // bit-for-bit identical to the full geometry's. Reuse them (the
1542 // (m,n) shape via transpose) instead of recomputing dist_at +
1543 // per-pair derivatives. The geometry is a deterministic function of
1544 // the coordinates, so this is bit-identical; np>1 partial subsets
1545 // skip the reuse and rebuild as before.
1546 const auto is_full_obs = [&](const std::vector<Index_t>& inds) {
1547 if (static_cast<Index_t>(inds.size()) !=
1548 out.num_repetitive_indices) {
1549 if (std::getenv("GPR_GEOM_DEBUG"))
1550 std::fprintf(
1551 stderr,
1552 "[geom] subset contains %zu of %lld observations\n",
1553 inds.size(),
1554 static_cast<long long>(out.num_repetitive_indices));
1555 return false;
1556 }
1557 for (std::size_t i = 0; i < inds.size(); ++i)
1558 if (inds[i] != static_cast<Index_t>(i)) return false;
1559 return true;
1560 };
1561 const bool diag_reusable_from_full =
1562 is_full_obs(obs_rows) && is_full_obs(obs_cols);
1563 FieldMatrixd x_loc_0_rows, x_loc_0_cols;
1564 build_obs_subset(0, obs_rows, x_loc_0_rows);
1565 build_obs_subset(0, obs_cols, x_loc_0_cols);
1566
1567 // Shared distance for this rank's (rows × cols) shape.
1568 if (diag_reusable_from_full) {
1569 subset.shared_distance_neg_per_pt = out.shared_distance_neg_per_pt;
1570 } else {
1571 FieldMatrixd unit_length_scale(1,
1572 sexpat_cov_func->getConfInfo().n_pt);
1573 unit_length_scale.setOnes();
1574 aux::Distance distance_calc;
1575 distance_calc.setFarFieldRadius(sexpat_cov_func->farFieldRadius());
1576 std::vector<FieldMatrixd> dist_pt;
1577 distance_calc.dist_at_vec(x_loc_0_rows, x_loc_0_cols,
1578 sexpat_cov_func->getConfInfo(),
1579 unit_length_scale, dist_pt);
1580 if (dist_pt.size() !=
1581 static_cast<std::size_t>(sexpat_cov_func->getConfInfo().n_pt)) {
1582 if (std::getenv("GPR_GEOM_DEBUG"))
1583 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1584 __LINE__);
1585 return false;
1586 }
1587 subset.shared_distance_neg_per_pt.resize(dist_pt.size());
1588 for (std::size_t pt = 0; pt < dist_pt.size(); ++pt) {
1589 subset.shared_distance_neg_per_pt[pt] = -dist_pt[pt];
1590 }
1591 }
1592 subset.n_rows = static_cast<Index_t>(obs_rows.size());
1593 subset.n_cols = static_cast<Index_t>(obs_cols.size());
1594
1595 FieldMatrixIdx ds1(1, 1), ds2(1, 1);
1596 // Kff at (0, 0) -- block value uses shared kernel directly; we
1597 // store an empty-derivatives placeholder block so find((0, 0))
1598 // returns a valid entry.
1599 {
1601 b.block_n = 0;
1602 b.block_m = 0;
1603 b.derivative_options = 0;
1604 if (!sexpat_cov_func->buildCrossBlockDerivativesOnly(
1605 x_loc_0_rows, x_loc_0_cols, /*derivative_options=*/0, ds1,
1606 ds2, b.geometry)) {
1607 if (std::getenv("GPR_GEOM_DEBUG"))
1608 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1609 __LINE__);
1610 return false;
1611 }
1612 subset.blocks.push_back(std::move(b));
1613 }
1614 FieldMatrixd x_loc_1_rows, x_loc_1_cols, x_loc_2_rows, x_loc_2_cols;
1615 for (Index_t n = 0; n < out.uDdim.size(); ++n) {
1616 ds1(0, 0) = static_cast<Index_t>(out.uDdim[n]);
1617 build_obs_subset(ds1(0, 0), obs_rows, x_loc_1_rows);
1618 build_obs_subset(ds1(0, 0), obs_cols, x_loc_1_cols);
1619
1620 // Kdf at (block_n, 0): reuse the full geometry's identical block
1621 // when this rank owns the whole obs set on both axes.
1622 {
1624 b.block_n = ds1(0, 0);
1625 b.block_m = 0;
1626 b.derivative_options = OptionsForGradCalculation::D1;
1627 bool reused = false;
1628 if (diag_reusable_from_full) {
1629 const auto it = out.block_index_by_nm.find({ds1(0, 0), 0});
1630 if (it != out.block_index_by_nm.end() &&
1631 out.blocks[it->second].derivative_options ==
1632 b.derivative_options) {
1633 b.geometry = out.blocks[it->second].geometry;
1634 reused = true;
1635 }
1636 }
1637 if (!reused &&
1638 !build_derivative_geometry(x_loc_1_rows, x_loc_0_cols,
1640 ds1, ds2, b.geometry)) {
1641 if (std::getenv("GPR_GEOM_DEBUG"))
1642 std::fprintf(stderr,
1643 "[geom] fallback at prepare line %d\n",
1644 __LINE__);
1645 return false;
1646 }
1647 subset.blocks.push_back(std::move(b));
1648 }
1649 // D at (block_n, block_n): reuse the full geometry's identical
1650 // diagonal block when this rank owns the whole obs set on both
1651 // axes (bit-identical copy, skips a rebuild); otherwise build.
1652 {
1654 b.block_n = ds1(0, 0);
1655 b.block_m = ds1(0, 0);
1656 b.derivative_options = OptionsForGradCalculation::D1 |
1659 bool reused = false;
1660 if (diag_reusable_from_full) {
1661 const auto it =
1662 out.block_index_by_nm.find({ds1(0, 0), ds1(0, 0)});
1663 if (it != out.block_index_by_nm.end() &&
1664 out.blocks[it->second].derivative_options ==
1665 b.derivative_options) {
1666 b.geometry = out.blocks[it->second].geometry;
1667 reused = true;
1668 }
1669 }
1670 if (!reused &&
1671 !build_derivative_geometry(x_loc_1_rows, x_loc_1_cols,
1672 b.derivative_options, ds1, ds1,
1673 b.geometry)) {
1674 if (std::getenv("GPR_GEOM_DEBUG"))
1675 std::fprintf(stderr,
1676 "[geom] fallback at prepare line %d\n",
1677 __LINE__);
1678 return false;
1679 }
1680 subset.blocks.push_back(std::move(b));
1681 }
1682 // Kdf2 at (n, m) and (m, n) for m > n. The permuted gradient
1683 // walk hits both shapes: (df_rows, dg_cols) for (n, m) and
1684 // (dg_rows, df_cols) for (m, n). Build both so dispatch covers
1685 // every block.
1686 for (Index_t m = n + 1; m < out.uDdim.size(); ++m) {
1687 ds2(0, 0) = static_cast<Index_t>(out.uDdim[m]);
1688 build_obs_subset(ds2(0, 0), obs_rows, x_loc_2_rows);
1689 build_obs_subset(ds2(0, 0), obs_cols, x_loc_2_cols);
1690 {
1692 b.block_n = ds1(0, 0);
1693 b.block_m = ds2(0, 0);
1694 b.derivative_options = OptionsForGradCalculation::D1 |
1697 bool reused = false;
1698 if (diag_reusable_from_full) {
1699 const auto it =
1700 out.block_index_by_nm.find({ds1(0, 0), ds2(0, 0)});
1701 if (it != out.block_index_by_nm.end() &&
1702 out.blocks[it->second].derivative_options ==
1703 b.derivative_options) {
1704 b.geometry = out.blocks[it->second].geometry;
1705 reused = true;
1706 }
1707 }
1708 if (!reused &&
1709 !build_derivative_geometry(x_loc_1_rows, x_loc_2_cols,
1710 b.derivative_options, ds1,
1711 ds2, b.geometry)) {
1712 if (std::getenv("GPR_GEOM_DEBUG"))
1713 std::fprintf(stderr,
1714 "[geom] fallback at prepare line %d\n",
1715 __LINE__);
1716 return false;
1717 }
1718 subset.blocks.push_back(std::move(b));
1719 }
1720 {
1722 b.block_n = ds2(0, 0);
1723 b.block_m = ds1(0, 0);
1724 b.derivative_options = OptionsForGradCalculation::D1 |
1727 // (m,n) is the transpose of the full geometry's (n,m)
1728 // block: dist(m,n)=dist(n,m)^T, and the first/second
1729 // derivative roles swap with the row/col axes, so
1730 // d1(m,n)=d2(n,m)^T, d2(m,n)=d1(n,m)^T, d12(m,n)=
1731 // d12(n,m)^T. The kernel is symmetric so this equals a
1732 // rebuild bit-for-bit. Only fires when this rank owns
1733 // the full obs set on both axes.
1734 bool reused = false;
1735 if (diag_reusable_from_full) {
1736 const auto it =
1737 out.block_index_by_nm.find({ds1(0, 0), ds2(0, 0)});
1738 if (it != out.block_index_by_nm.end() &&
1739 out.blocks[it->second].derivative_options ==
1740 b.derivative_options) {
1741 const auto& src = out.blocks[it->second].geometry;
1742 auto transpose_vec =
1743 [](const std::vector<FieldMatrixd>& in,
1744 std::vector<FieldMatrixd>& dst) {
1745 dst.resize(in.size());
1746 for (std::size_t p = 0; p < in.size(); ++p)
1747 dst[p] = in[p].transpose();
1748 };
1749 b.geometry.derivative_options =
1750 src.derivative_options;
1751 transpose_vec(src.distance, b.geometry.distance);
1752 transpose_vec(src.d2, b.geometry.d1);
1753 transpose_vec(src.d1, b.geometry.d2);
1754 transpose_vec(src.d12, b.geometry.d12);
1755 b.geometry.valid = src.valid;
1756 reused = true;
1757 }
1758 }
1759 if (!reused &&
1760 !build_derivative_geometry(x_loc_2_rows, x_loc_1_cols,
1761 b.derivative_options, ds2,
1762 ds1, b.geometry)) {
1763 if (std::getenv("GPR_GEOM_DEBUG"))
1764 std::fprintf(stderr,
1765 "[geom] fallback at prepare line %d\n",
1766 __LINE__);
1767 return false;
1768 }
1769 subset.blocks.push_back(std::move(b));
1770 }
1771 }
1772 }
1773 subset.block_index_by_nm.clear();
1774 for (std::size_t i = 0; i < subset.blocks.size(); ++i) {
1775 const auto& blk = subset.blocks[i];
1776 subset.block_index_by_nm[{blk.block_n, blk.block_m}] = i;
1777 }
1778 subset.valid = true;
1779 return true;
1780 };
1781 if (!fill_subset(out.rows_cols, owned_obs_rows, owned_obs_cols) ||
1782 !fill_subset(out.cols_rows, owned_obs_cols, owned_obs_rows)) {
1783 if (std::getenv("GPR_GEOM_DEBUG"))
1784 std::fprintf(stderr, "[geom] fallback at prepare line %d\n",
1785 __LINE__);
1786 return false;
1787 }
1788 out.has_per_rank_subset = true;
1789#endif
1790
1791 out.valid = true;
1792 return true;
1793}
1794
1796 const EigenMatrix& x, const Eigen::VectorXd& x_ind) const
1797{
1798 if (sexpat_cov_func == nullptr || sexpat_cov_func->usesManifoldChart() ||
1799 sexpat_cov_func->usesGeodesicHeatKernel()) {
1801 return nullptr;
1802 }
1803 bool same_layout = true;
1804#ifdef GPR_LINALG_SCALAPACK
1805 if (fit_geometry_cache_.valid && fit_geometry_cache_.has_per_rank_subset) {
1806 auto& distributed = backend().distributed();
1807 distributed.initialize();
1808 same_layout =
1809 fit_geometry_cache_grid_ ==
1810 std::array<int, 4>{distributed.nprow(), distributed.npcol(),
1811 distributed.myrow(), distributed.mycol()};
1812 }
1813#endif
1814 if (fit_geometry_cache_.valid && same_layout &&
1815 fit_geometry_cache_pair_local_ == use_pair_local_tiles_ &&
1816 fit_geometry_cache_rows_.rows() == x.rows() &&
1817 fit_geometry_cache_rows_.cols() == x.cols() &&
1818 fit_geometry_cache_rows_ == x &&
1819 fit_geometry_cache_indices_.size() == x_ind.size() &&
1820 fit_geometry_cache_indices_ == x_ind &&
1821 detail::sameSexpatGeometry(fit_geometry_cache_conf_,
1822 sexpat_cov_func->getConfInfo(),
1823 fit_geometry_cache_far_field_radius_,
1824 sexpat_cov_func->farFieldRadius()))
1825 return &fit_geometry_cache_;
1827 if (!prepareTrainingKernelGeometry(x, x_ind, fit_geometry_cache_,
1828 /*reused=*/true)) {
1829 fit_geometry_cache_.clear();
1830 return nullptr;
1831 }
1832 ++fit_geometry_builds_for_testing_;
1833 fit_geometry_cache_rows_ = x;
1834 fit_geometry_cache_indices_ = x_ind;
1835 fit_geometry_cache_conf_ = sexpat_cov_func->getConfInfo();
1836 fit_geometry_cache_pair_local_ = use_pair_local_tiles_;
1837 fit_geometry_cache_far_field_radius_ = sexpat_cov_func->farFieldRadius();
1838#ifdef GPR_LINALG_SCALAPACK
1839 if (fit_geometry_cache_.has_per_rank_subset) {
1840 const auto& distributed = backend().distributed();
1841 fit_geometry_cache_grid_ = {distributed.nprow(), distributed.npcol(),
1842 distributed.myrow(), distributed.mycol()};
1843 }
1844#endif
1845 return &fit_geometry_cache_;
1846}
1847
1849{
1850 fit_geometry_cache_.clear();
1851 fit_geometry_cache_rows_.resize(0, 0);
1852 fit_geometry_cache_indices_.resize(0);
1853 fit_geometry_cache_conf_ = AtomsConfiguration{};
1854 fit_geometry_cache_pair_local_ = false;
1855 fit_geometry_cache_far_field_radius_ = 0.0;
1856 fit_geometry_cache_grid_ = {};
1857}
1858
1859double GaussianProcessRegression::kernelNuggetCoefficient(
1860 Eigen::Index observations) const
1861{
1862 if (!principled_nugget_) return 0.0;
1863 const double kappa =
1864 kappa_max_ > 1.0 ? kappa_max_ : detail::principledKappaMaxDefault();
1865 return detail::computePrincipledNugget(observations, 0, kappa, false);
1866}
1867
1868void GaussianProcessRegression::applyKernelNugget(
1869 EigenMatrix& kernel, Eigen::Index observations) const
1870{
1871 const double eta = kernelNuggetCoefficient(observations);
1872 if (eta > 0.0) kernel.diagonal().array() += eta * kernel.diagonal().array();
1873}
1874
1876 const EigenMatrix& x, const Eigen::VectorXd& x_ind, EigenMatrix& cov_matrix,
1877 bool serial_per_rank, bool include_constant, bool include_noise)
1878{
1879 Index_t n = (Index_t)x.rows();
1880 Eigen::VectorXd uDdim; // unique derivatives' dimensions
1881 EigenMatrix Ktemp;
1882
1883 // The per-block assembly below walks every (block_n, block_m) pair and
1884 // recomputes dist_at plus its exp() for each one, over coordinates that
1885 // assembleMatrixOfRepetitiveCoordinates replicated IDENTICALLY across
1886 // all D+1 blocks -- only the appended dimension tag differs. The
1887 // geometry route builds that shared content once and applies it
1888 // elementwise per block, which is the same saving the hyperparameter
1889 // sweep already takes through INLA and the gradient path. Leaving the
1890 // rematerialize on the per-block route cost roughly a second of wall
1891 // per training row on the Baker board, which is where the surrogate
1892 // spent the time it saved on true forces.
1893 TrainingKernelGeometry shared_geometry;
1894 const TrainingKernelGeometry* shared = nullptr;
1895 if (sexpat_cov_func != nullptr) {
1897 // The cached blocks serve every later evaluation at this design,
1898 // including the gradient at the same theta.
1899 shared = fitGeometryFor(x, x_ind);
1900 if (shared == nullptr &&
1901 prepareTrainingKernelGeometry(x, x_ind, shared_geometry)) {
1902 shared = &shared_geometry;
1903 }
1904 }
1905 if (shared != nullptr && evaluateTrainingCovarianceMatrixFromGeometry(
1906 *shared, x, x_ind, cov_matrix, serial_per_rank,
1907 include_constant, include_noise)) {
1908 return;
1909 }
1911 if (std::getenv("GPR_GEOM_DEBUG"))
1912 std::fprintf(stderr, "[geom] legacy assembly n=%lld\n",
1913 static_cast<long long>(n));
1914
1915 cov_matrix.resize(n, n);
1916 cov_matrix.setZero();
1917
1918 extractUniqueIndices(x_ind, uDdim);
1919
1920#ifdef GPR_LINALG_SCALAPACK
1921 if (serial_per_rank) {
1922 // Local path required by callers that hold rank-divergent kernel
1923 // state (e.g. SVGD per-particle predict, evaluateEnergyAnd-
1924 // GradientLocal): every rank assembles the full kernel without
1925 // touching MPI / BLACS. applyCovarianceFunction with
1926 // serial_per_rank=true skips both the round-robin block
1927 // distribution and the Allreduce. The LikGaussian noise diagonal
1928 // is rank-local already.
1929 addConstantCovarianceBlock(
1930 include_constant ? const_cov_fun.get() : nullptr, x_ind, x_ind,
1931 cov_matrix);
1932 applyCovarianceFunction(x, x_ind, uDdim, *sexpat_cov_func, Ktemp,
1933 /*do_reduce=*/false, /*serial_per_rank=*/true);
1934 cov_matrix.noalias() += Ktemp;
1935 applyKernelNugget(cov_matrix, n);
1936 if (!include_constant)
1937 detail::addSeparatedConstantNugget(const_cov_fun.get(), x_ind,
1938 kernelNuggetCoefficient(n),
1939 cov_matrix);
1940 if (include_noise)
1941 cov_matrix.diagonal() += lik_gaussian->evaluateTrainingVariance(x);
1942 } else {
1943 // Public dense assembly contract: every rank receives the same
1944 // covariance matrix. The direct Cholesky path uses
1945 // decomposeCovarianceMatrixScalapack and bypasses this dense API.
1946 auto& _st = backend().distributed();
1947 const int tile_size =
1948 static_cast<int>(detail::storedObservationChannelCount(x_ind));
1949 _st.initialize(tile_size);
1950 const auto ownership = applyCovarianceFunction(
1951 x, x_ind, uDdim, *sexpat_cov_func, Ktemp, false /* no reduce */);
1952
1953 // Reduce the one-owner-per-block sexpat partials BEFORE the
1954 // constant block and noise diagonal: every Ktemp entry then has
1955 // exactly one contributor, so the disjoint Allreduce is exact
1956 // and the subsequent rank-local const + lik adds reproduce the
1957 // single-rank assembly order (const, sexpat, lik) bit-for-bit
1958 // at every rank count.
1959 if (_st.nprocs() > 1 &&
1960 ownership == CovarianceAssemblyOwnership::Disjoint) {
1961 backend().disjoint_sum_bcast(Ktemp.data(),
1962 static_cast<int>(Ktemp.size()));
1963 ++distributed_training_covariance_assemblies_for_testing_;
1964 }
1965 addConstantCovarianceBlock(
1966 include_constant ? const_cov_fun.get() : nullptr, x_ind, x_ind,
1967 cov_matrix);
1968 cov_matrix.noalias() += Ktemp;
1969 applyKernelNugget(cov_matrix, n);
1970 if (!include_constant)
1971 detail::addSeparatedConstantNugget(const_cov_fun.get(), x_ind,
1972 kernelNuggetCoefficient(n),
1973 cov_matrix);
1974 if (include_noise)
1975 cov_matrix.diagonal() += lik_gaussian->evaluateTrainingVariance(x);
1976 }
1977#else
1978 (void)serial_per_rank;
1979 // Non-MPI path: sequential dense assembly.
1980 addConstantCovarianceBlock(include_constant ? const_cov_fun.get() : nullptr,
1981 x_ind, x_ind, cov_matrix);
1982
1983 applyCovarianceFunction(x, x_ind, uDdim, *sexpat_cov_func, Ktemp);
1984 cov_matrix.noalias() += Ktemp;
1985 applyKernelNugget(cov_matrix, n);
1986 if (!include_constant)
1987 detail::addSeparatedConstantNugget(
1988 const_cov_fun.get(), x_ind, kernelNuggetCoefficient(n), cov_matrix);
1989
1990#ifndef NDEBUG
1991 gpr::assertMsg(lik_gaussian != nullptr,
1992 "Object of Gausian likelihood is not allocated!");
1993#endif
1994 if (include_noise)
1995 cov_matrix.diagonal() += lik_gaussian->evaluateTrainingVariance(x);
1996#endif
1997
1998 // log_man << "Training covariance matrix is " << cov_matrix.size() << "
1999 // over ( " << cov_matrix.rows() << ", " << cov_matrix.cols() << " )" <<
2000 // "\n";
2002}
2003
2005 const TrainingKernelGeometry& geom, const Eigen::VectorXd& x_ind,
2006 const Eigen::VectorXd& theta, const std::vector<bool>& active_lengths,
2007 EigenMatrix& covariance, bool serial_per_rank,
2008 std::vector<EigenMatrix>* covariance_derivatives)
2009{
2010 std::vector<Eigen::Index> derivative_lengths;
2011 for (std::size_t index = 0; index < active_lengths.size(); ++index)
2012 if (active_lengths[index]) derivative_lengths.push_back(index + 1);
2014 geom, x_ind, theta, active_lengths, covariance, serial_per_rank,
2015 covariance_derivatives, derivative_lengths);
2016}
2017
2019 const TrainingKernelGeometry& geom, const Eigen::VectorXd& x_ind,
2020 const Eigen::VectorXd& theta, const std::vector<bool>& active_lengths,
2021 EigenMatrix& covariance, bool serial_per_rank,
2022 std::vector<EigenMatrix>* covariance_derivatives,
2023 const std::vector<Eigen::Index>& derivative_lengths)
2024{
2025 const auto fail = [&]() {
2026 covariance.resize(0, 0);
2027 if (covariance_derivatives != nullptr) covariance_derivatives->clear();
2028 return false;
2029 };
2030 if (!geom.valid || geom.n <= 0 || geom.n != x_ind.size() ||
2031 sexpat_cov_func == nullptr || sexpat_cov_func->usesManifoldChart())
2032 return fail();
2033 Eigen::VectorXd active_theta;
2034 if (!x_ind.allFinite() ||
2035 !activeLogParameters(sexpat_cov_func.get(), theta, active_lengths,
2036 derivative_lengths, active_theta))
2037 return fail();
2038 if (!assembleSexpatCovFromGeometry(
2039 *this, backend(), geom, *sexpat_cov_func, x_ind, covariance,
2040 /*do_reduce=*/true, serial_per_rank, &active_theta,
2041 covariance_derivatives, &derivative_lengths, nullptr, nullptr) ||
2042 !covariance.allFinite())
2043 return fail();
2044 if (covariance_derivatives != nullptr)
2045 for (const auto& derivative: *covariance_derivatives)
2046 if (!derivative.allFinite()) return fail();
2047 return true;
2048}
2049
2051 const TrainingKernelGeometry& geom, const Eigen::VectorXd& x_ind,
2052 const Eigen::VectorXd& theta, const std::vector<bool>& active_lengths,
2053 const EigenMatrix& weight,
2054 const std::vector<Eigen::Index>& derivative_lengths,
2055 Eigen::VectorXd& contractions, bool serial_per_rank)
2056{
2057 contractions.resize(0);
2058 Eigen::VectorXd active_theta;
2059 if (!geom.valid || geom.n <= 0 || geom.n != x_ind.size() ||
2060 !x_ind.allFinite() || weight.rows() != geom.n ||
2061 weight.cols() != geom.n || !weight.allFinite() ||
2062 !activeLogParameters(sexpat_cov_func.get(), theta, active_lengths,
2063 derivative_lengths, active_theta))
2064 return false;
2065 EigenMatrix unused;
2066 if (!assembleSexpatCovFromGeometry(
2067 *this, backend(), geom, *sexpat_cov_func, x_ind, unused,
2068 /*do_reduce=*/true, serial_per_rank, &active_theta, nullptr,
2069 &derivative_lengths, &weight, &contractions)) {
2070 contractions.resize(0);
2071 return false;
2072 }
2073 return true;
2074}
2075
2076#ifdef GPR_LINALG_SCALAPACK
2077GaussianProcessRegression::DistributedCovarianceStatus
2078GaussianProcessRegression::assembleTrainingCovarianceDistributedFromGeometry(
2079 const TrainingKernelGeometry& geom, const EigenMatrix& x,
2080 const Eigen::VectorXd& x_ind, std::vector<double>& covariance,
2081 int* descriptor)
2082{
2084 const bool invalid =
2085 !geom.valid || geom.n != x.rows() || x.rows() <= 0 ||
2086 x.rows() > std::numeric_limits<int>::max() ||
2087 x_ind.size() != x.rows() || sexpat_cov_func == nullptr ||
2088 lik_gaussian == nullptr ||
2089 std::any_of(geom.blocks.begin(), geom.blocks.end(),
2090 [&](const auto& block) {
2091 return !trainingBlockGeometryUsable(geom, block);
2092 });
2093 bool usable =
2094 !invalid && pairLocalCoversGeometry(geom) && hasTrainingPermutation();
2095 pairlocal::Weights weights;
2096 if (usable) {
2097 usable = !sexpat_cov_func->usesManifoldChart() &&
2098 !sexpat_cov_func->usesGeodesicHeatKernel();
2100 sexpat_cov_func->combineParameters(), geom.pair_local.n_pt);
2101 usable = usable && weights.valid &&
2102 training_permutation_.perm.size() ==
2103 static_cast<std::size_t>(x.rows());
2104 }
2105 const Eigen::Index tile = geom.pair_local.dof + 1;
2106 const Eigen::Index configurations = geom.pair_local.n_conf;
2107 if (usable) {
2108 for (Eigen::Index i = 0; i < configurations && usable; ++i)
2109 for (Eigen::Index channel = 0; channel < tile; ++channel)
2110 if (training_permutation_.perm[i * tile + channel] !=
2111 channel * configurations + i ||
2112 x_ind(channel * configurations + i) != channel) {
2113 usable = false;
2114 break;
2115 }
2116 }
2117 // Every rank takes the same assembly path, including a rank whose
2118 // geometry has been invalidated independently of its peers.
2119 double state_flags[2] = {invalid ? 1.0 : 0.0, usable ? 0.0 : 1.0};
2120 backend().ordered_sum_bcast(state_flags, 2);
2121 if (state_flags[0] != 0.0) return DistributedCovarianceStatus::Invalid;
2122 if (state_flags[1] != 0.0) return DistributedCovarianceStatus::Unsupported;
2123
2124 auto& state = backend().distributed();
2125 const int n = static_cast<int>(x.rows());
2126 state.make_desc(n, n, descriptor);
2127 const int leading = descriptor[8];
2128 covariance.assign(static_cast<std::size_t>(leading) * state.local_cols(n),
2129 0.0);
2130 const Eigen::VectorXd noise =
2131 permuteTrainingVector(lik_gaussian->evaluateTrainingVariance(x));
2132 std::vector<std::pair<Eigen::Index, Eigen::Index>> owned;
2133 const bool aligned = state.block_size() == tile;
2134 // A rectangle intersects this rank when both of its index intervals
2135 // contain a block owned by the corresponding process coordinate.
2136 const auto intersects = [&](Eigen::Index configuration, int coordinate,
2137 int processes) {
2138 const Eigen::Index first = configuration * tile / state.block_size();
2139 const Eigen::Index last =
2140 ((configuration + 1) * tile - 1) / state.block_size();
2141 const Eigen::Index next =
2142 first + (coordinate - first % processes + processes) % processes;
2143 return next <= last;
2144 };
2145 std::vector<bool> owned_rows(configurations), owned_columns(configurations);
2146 for (Eigen::Index i = 0; i < configurations; ++i) {
2147 owned_rows[i] = intersects(i, state.myrow(), state.nprow());
2148 owned_columns[i] = intersects(i, state.mycol(), state.npcol());
2149 }
2150 for (Eigen::Index i = 0; i < configurations; ++i) {
2151 if (!owned_rows[i]) continue;
2152 for (Eigen::Index j = 0; j <= i; ++j)
2153 if (owned_columns[j]) owned.emplace_back(i, j);
2154 }
2155 const Eigen::VectorXd channels =
2156 Eigen::VectorXd::LinSpaced(tile, 0.0, static_cast<double>(tile - 1));
2157 const std::size_t workers =
2158 std::min(owned.size(),
2159 static_cast<std::size_t>(backend().local().concurrency()));
2160 backend().local().forEach(workers, [&](std::size_t worker) {
2161 pairlocal::TileEvaluator evaluator(geom.pair_local, weights);
2162 Eigen::MatrixXd block;
2163 EigenMatrix values(tile, tile);
2164 for (std::size_t k = worker; k < owned.size(); k += workers) {
2165 const auto [i, j] = owned[k];
2166 evaluator.prepare(i, j);
2167 evaluator.tile(0, block);
2168 values.setZero();
2169 values.noalias() += block;
2170 if (i == j) {
2171 applyKernelNugget(values, n);
2172 detail::addSeparatedConstantNugget(
2173 const_cov_fun.get(), channels, kernelNuggetCoefficient(n),
2174 values);
2175 values.diagonal() += noise.segment(i * tile, tile);
2176 if (jitter_sigma2 > 0.0)
2177 values.diagonal().array() += jitter_sigma2;
2178 }
2179 const auto local_offset = [&](int row, int column) {
2180 const int local_row = state.local_index_for_global(
2181 row, state.block_size(), state.myrow(), state.nprow());
2182 const int local_column = state.local_index_for_global(
2183 column, state.block_size(), state.mycol(), state.npcol());
2184 return static_cast<std::size_t>(local_row) +
2185 static_cast<std::size_t>(local_column) * leading;
2186 };
2187 if (aligned) {
2188 Eigen::Map<EigenMatrix, 0, Eigen::OuterStride<>> destination(
2189 covariance.data() + local_offset(i * tile, j * tile), tile,
2190 tile, Eigen::OuterStride<>(leading));
2191 destination = values;
2192 } else {
2193 for (Eigen::Index c = 0; c < tile; ++c)
2194 for (Eigen::Index r = 0; r < tile; ++r)
2195 if (state.owns_global_entry(i * tile + r, j * tile + c))
2196 covariance[local_offset(
2197 i * tile + r, j * tile + c)] = values(r, c);
2198 }
2199 }
2200 });
2201 ++distributed_training_covariance_assemblies_for_testing_;
2202 ++pair_local_assemblies_for_testing_;
2203 ++training_geometry_apply_calls_for_testing_;
2204 is_training_cov_matrix_evaluated = true;
2205 return DistributedCovarianceStatus::Assembled;
2206}
2207#endif
2208
2210 const TrainingKernelGeometry& geom, const EigenMatrix& x,
2211 const Eigen::VectorXd& x_ind, EigenMatrix& cov_matrix, bool serial_per_rank,
2212 bool include_constant, bool include_noise)
2213{
2215 const auto asm_t0 = std::chrono::steady_clock::now();
2216 struct AsmReport {
2217 const std::chrono::steady_clock::time_point& t0;
2218 Eigen::Index rows;
2219 std::size_t blocks;
2220 ~AsmReport()
2221 {
2222 if (std::getenv("GPR_GEOM_DEBUG")) {
2223 const double ms = std::chrono::duration<double, std::milli>(
2224 std::chrono::steady_clock::now() - t0)
2225 .count();
2226 std::fprintf(
2227 stderr,
2228 "[geom] apply n=%lld blocks=%zu ms=%.1f rss_mb=%.0f\n",
2229 static_cast<long long>(rows), blocks, ms,
2231 }
2232 }
2233 } asm_report{asm_t0, x.rows(), geom.blocks.size()};
2234 double invalid_geometry =
2235 !geom.valid || geom.n != x.rows() || x.rows() <= 0 ||
2236 x.rows() > std::numeric_limits<int>::max() ||
2237 x_ind.size() != x.rows() || !x_ind.allFinite() ||
2238 sexpat_cov_func == nullptr || lik_gaussian == nullptr ||
2239 std::any_of(geom.blocks.begin(), geom.blocks.end(),
2240 [&](const auto& block) {
2241 return !trainingBlockGeometryUsable(geom, block);
2242 });
2243 // All participants reject invalid geometry before any rank enters the
2244 // matrix reduction. Rank-local queries leave the factor's grid intact.
2245 if (!serial_per_rank)
2246 linalg::ordered_sum_bcast(&invalid_geometry, 1, backend().mpi());
2247 if (invalid_geometry != 0.0) {
2248 if (std::getenv("GPR_GEOM_DEBUG"))
2249 std::fprintf(stderr, "[geom] fallback at apply line %d\n",
2250 __LINE__);
2251 return false;
2252 }
2253 const Index_t n = static_cast<Index_t>(x.rows());
2254 if (std::getenv("GPR_GEOM_DEBUG"))
2255 std::fprintf(stderr, "[geom] apply entry rss_mb=%.0f\n",
2257 cov_matrix.resize(n, n);
2258 cov_matrix.setZero();
2259
2260 EigenMatrix Ktemp;
2261#ifdef GPR_LINALG_SCALAPACK
2262 auto& _st = backend().distributed();
2263 // serial_per_rank callers assemble rank-locally and must not touch
2264 // BLACS: initialize() rebuilds the grid whenever the requested block
2265 // size differs from the live one, and that drops the cached Cholesky
2266 // factor. A query side carries one channel per configuration, so it
2267 // requests a block size of 1 against a training grid tiled by D+1 and
2268 // would destroy a factor the caller still needs.
2269 if (!serial_per_rank) {
2270 const int tile_size =
2271 static_cast<int>(detail::storedObservationChannelCount(x_ind));
2272 _st.initialize(tile_size);
2273 }
2274 if (std::getenv("GPR_GEOM_DEBUG"))
2275 std::fprintf(stderr, "[geom] after st.init rss_mb=%.0f\n",
2277 bool replicated = false;
2278 if (!assembleSexpatCovFromGeometry(
2279 *this, backend(), geom, *sexpat_cov_func, x_ind, Ktemp,
2280 /*do_reduce=*/false, serial_per_rank, nullptr, nullptr, nullptr,
2281 nullptr, nullptr, &replicated)) {
2282 if (std::getenv("GPR_GEOM_DEBUG"))
2283 std::fprintf(stderr, "[geom] fallback at apply line %d\n",
2284 __LINE__);
2285 return false;
2286 }
2287 // Reduce the one-owner-per-block sexpat partials BEFORE the
2288 // constant block and noise diagonal: disjoint support keeps the
2289 // Allreduce exact, and the rank-local const + lik adds reproduce
2290 // the single-rank assembly order bit-for-bit at every rank count.
2291 if (!replicated && !serial_per_rank && _st.nprocs() > 1) {
2292 backend().disjoint_sum_bcast(Ktemp.data(),
2293 static_cast<int>(Ktemp.size()));
2294 ++distributed_training_covariance_assemblies_for_testing_;
2295 }
2296 addConstantCovarianceBlock(include_constant ? const_cov_fun.get() : nullptr,
2297 x_ind, x_ind, cov_matrix);
2298 cov_matrix.noalias() += Ktemp;
2299 applyKernelNugget(cov_matrix, n);
2300 if (!include_constant)
2301 detail::addSeparatedConstantNugget(
2302 const_cov_fun.get(), x_ind, kernelNuggetCoefficient(n), cov_matrix);
2303 if (std::getenv("GPR_GEOM_DEBUG"))
2304 std::fprintf(stderr, "[geom] after sexpat rss_mb=%.0f\n",
2306 if (include_noise)
2307 cov_matrix.diagonal() += lik_gaussian->evaluateTrainingVariance(x);
2308 if (std::getenv("GPR_GEOM_DEBUG"))
2309 std::fprintf(stderr, "[geom] after lik rss_mb=%.0f\n",
2311#else
2312 addConstantCovarianceBlock(include_constant ? const_cov_fun.get() : nullptr,
2313 x_ind, x_ind, cov_matrix);
2314 if (!assembleSexpatCovFromGeometry(
2315 *this, backend(), geom, *sexpat_cov_func, x_ind, Ktemp,
2316 /*do_reduce=*/!serial_per_rank, serial_per_rank)) {
2317 if (std::getenv("GPR_GEOM_DEBUG"))
2318 std::fprintf(stderr, "[geom] fallback at apply line %d\n",
2319 __LINE__);
2320 return false;
2321 }
2322 cov_matrix.noalias() += Ktemp;
2323 applyKernelNugget(cov_matrix, n);
2324 if (!include_constant)
2325 detail::addSeparatedConstantNugget(
2326 const_cov_fun.get(), x_ind, kernelNuggetCoefficient(n), cov_matrix);
2327 if (include_noise)
2328 cov_matrix.diagonal() += lik_gaussian->evaluateTrainingVariance(x);
2329#endif
2331 ++training_geometry_apply_calls_for_testing_;
2332 if (log_training_geometry_) {
2333 std::fprintf(stderr, "[geom] apply count=%zu n=%lld blocks=%zu\n",
2334 training_geometry_apply_calls_for_testing_,
2335 static_cast<long long>(geom.n), geom.blocks.size());
2336 }
2337 return true;
2338}
2339
2341 const EigenMatrix& x, const Eigen::VectorXd& x_ind, EigenMatrix& cov_matrix,
2342 bool include_noise)
2343{
2344#ifdef GPR_LINALG_SCALAPACK
2345 (void)x;
2346 (void)x_ind;
2347 (void)cov_matrix;
2348 (void)include_noise;
2349 return false;
2350#else
2351 if (!hasTrainingPermutation() || sexpat_cov_func == nullptr ||
2352 lik_gaussian == nullptr)
2353 return false;
2354 TrainingKernelGeometry local_geometry;
2355 const TrainingKernelGeometry* geom = nullptr;
2356 {
2358 geom = fitGeometryFor(x, x_ind);
2359 if (geom == nullptr &&
2360 prepareTrainingKernelGeometry(x, x_ind, local_geometry))
2361 geom = &local_geometry;
2362 }
2363 return geom != nullptr &&
2365 *geom, x, x_ind, cov_matrix, include_noise);
2366#endif
2367}
2368
2369bool GaussianProcessRegression::
2370 evaluateTrainingCovarianceInFactorOrderFromGeometry(
2371 const TrainingKernelGeometry& geom, const EigenMatrix& x,
2372 const Eigen::VectorXd& x_ind, EigenMatrix& cov_matrix,
2373 bool include_noise)
2374{
2375#ifdef GPR_LINALG_SCALAPACK
2376 (void)geom;
2377 (void)x;
2378 (void)x_ind;
2379 (void)cov_matrix;
2380 (void)include_noise;
2381 return false;
2382#else
2383 const Index_t n = static_cast<Index_t>(x.rows());
2384 if (!hasTrainingPermutation() || sexpat_cov_func == nullptr ||
2385 lik_gaussian == nullptr || n <= 0 ||
2386 x.rows() > std::numeric_limits<int>::max() || x_ind.size() != n ||
2387 !x_ind.allFinite() ||
2388 training_permutation_.inv_perm.size() != static_cast<std::size_t>(n) ||
2389 !geom.valid || geom.n != n ||
2390 std::any_of(geom.blocks.begin(), geom.blocks.end(),
2391 [&](const auto& block) {
2392 return !trainingBlockGeometryUsable(geom, block);
2393 }))
2394 return false;
2396 const auto& placement = training_permutation_.inv_perm;
2397 EigenMatrix Ktemp;
2398 if (!assembleSexpatCovFromGeometry(
2399 *this, backend(), geom, *sexpat_cov_func, x_ind, Ktemp,
2400 /*do_reduce=*/true, /*serial_per_rank=*/false, nullptr, nullptr,
2401 nullptr, nullptr, nullptr, nullptr, &placement))
2402 return false;
2403 // The same sequence as the channel-major assembly with the constant
2404 // excluded, each diagonal entry moved to its factor position.
2405 cov_matrix.resize(n, n);
2406 cov_matrix.setZero();
2407 cov_matrix.noalias() += Ktemp;
2408 Ktemp.resize(0, 0);
2409 applyKernelNugget(cov_matrix, n);
2410 if (const_cov_fun != nullptr) {
2411 const double eta = kernelNuggetCoefficient(n);
2412 if (eta != 0.0) {
2413 const Eigen::Index count =
2414 detail::leadingDerivativeBlockSize(x_ind, 0.0);
2415 for (Eigen::Index row = 0; row < count; ++row) {
2416 const auto at = placement[static_cast<std::size_t>(row)];
2417 cov_matrix(at, at) += eta * const_cov_fun->getConstSigma2();
2418 }
2419 }
2420 }
2421 if (include_noise) {
2422 const Eigen::VectorXd noise = lik_gaussian->evaluateTrainingVariance(x);
2423 for (Eigen::Index row = 0; row < n; ++row) {
2424 const auto at = placement[static_cast<std::size_t>(row)];
2425 cov_matrix(at, at) += noise(row);
2426 }
2427 }
2429 ++training_geometry_apply_calls_for_testing_;
2430 ++factor_order_assemblies_for_testing_;
2431 return true;
2432#endif
2433}
2434
2436 const EigenMatrix& query, const Eigen::VectorXd& query_ind,
2437 EigenMatrix& cross) const
2438{
2439#ifdef GPR_LINALG_SCALAPACK
2440 (void)query;
2441 (void)query_ind;
2442 (void)cross;
2443 return false;
2444#else
2445 const auto& placement = training_permutation_.inv_perm;
2446 if (!hasTrainingPermutation() || sexpat_cov_func == nullptr ||
2447 sexpat_cov_func->usesManifoldChart() ||
2448 placement.size() != static_cast<std::size_t>(R_matrix.rows()))
2449 return false;
2450 const Eigen::Index dimensions = 3 * atoms_config.atoms_mov.type.size();
2451 JointOperand left, right;
2452 if (!extractCompleteJointPositions(R_matrix, R_indices, dimensions, left) ||
2453 !extractCompleteJointPositions(query, query_ind, dimensions, right))
2454 return false;
2455 const auto kernel = sexpat_cov_func->assembledOperator();
2456 const EigenMatrix joint = kernel
2457 ? kernel->jointEnergyGradientCrossCovariance(
2458 left.positions, right.positions)
2461 left.positions, right.positions);
2462 cross = scatterJointBlockToRows(joint, left, right, placement);
2463 if (const_cov_fun != nullptr && const_cov_fun->getConstSigma2() != 0.0) {
2464 const double const_sigma2 = const_cov_fun->getConstSigma2();
2465 const Eigen::Index row_block =
2466 detail::leadingDerivativeBlockSize(R_indices, 0.0);
2467 const Eigen::Index col_block =
2468 detail::leadingDerivativeBlockSize(query_ind, 0.0);
2469 if (row_block > 0 && col_block > 0 && row_block <= cross.rows() &&
2470 col_block <= cross.cols()) {
2471 for (Eigen::Index col = 0; col < col_block; ++col)
2472 for (Eigen::Index row = 0; row < row_block; ++row)
2473 cross(placement[static_cast<std::size_t>(row)], col) +=
2474 const_sigma2;
2475 }
2476 }
2477 ++factor_order_cross_assemblies_for_testing_;
2478 return true;
2479#endif
2480}
2481
2483 const EigenMatrix& query, const Eigen::VectorXd& query_ind,
2484 bool serial_per_rank) const
2485{
2486 EigenMatrix cross;
2487 if (evaluateTrainingCrossCovarianceInFactorOrder(query, query_ind, cross))
2488 return cross;
2489 evaluateCovarianceMatrix(R_matrix, query, R_indices, query_ind, cross,
2490 serial_per_rank);
2491 return permuteTrainingRows(cross);
2492}
2493
2495 const EigenMatrix& x1, const EigenMatrix& x2, const Eigen::VectorXd& x1_ind,
2496 const Eigen::VectorXd& x2_ind, EigenMatrix& C, bool serial_per_rank) const
2497{
2498 Index_t n = (Index_t)x1.rows();
2499 Index_t n1 = (Index_t)x2.rows();
2500 EigenMatrix Ktemp;
2501 Eigen::VectorXd uDdim, uDdim2;
2502
2503 C.resize(n, n1);
2504
2505 C.setZero();
2506 extractUniqueIndices(x1_ind, uDdim);
2507 extractUniqueIndices(x2_ind, uDdim2);
2508
2509 // applyCrossCovarianceFunction's ownsBlock gating already
2510 // becomes a no-op when do_reduce=false (see the inl-side macro);
2511 // the do_reduce=false branch also skips the trailing MPI_Allreduce.
2512 // serial_per_rank=true therefore translates to do_reduce=false
2513 // here, giving every rank the full kernel without any collective.
2514 const bool do_reduce = !serial_per_rank;
2515 applyCrossCovarianceFunction(x1, x2, x1_ind, uDdim, x2_ind, uDdim2,
2516 *sexpat_cov_func, Ktemp, do_reduce);
2517 C.noalias() += Ktemp;
2518
2519 addConstantCovarianceBlock(const_cov_fun.get(), x1_ind, x2_ind, C);
2520}
2521
2522#ifdef GPR_LINALG_SCALAPACK
2523void GaussianProcessRegression::assembleCrossCovarianceDistributed(
2524 const EigenMatrix& x1, const EigenMatrix& x2, const Eigen::VectorXd& x1_ind,
2525 const Eigen::VectorXd& x2_ind, std::vector<double>& cov_dist, int* desc,
2526 linalg::BackendContext* workspace, bool lower_only)
2527{
2528 if (x1.rows() == 0 || x2.rows() == 0 || x1_ind.size() == 0 ||
2529 x2_ind.size() == 0) {
2530 cov_dist.clear();
2531 if (desc != nullptr) std::fill(desc, desc + 9, 0);
2532 return;
2533 }
2534
2535 auto& st = (workspace ? *workspace : backend()).distributed();
2536 const Index_t obs_tile_size1 =
2537 static_cast<Index_t>(detail::storedObservationChannelCount(x1_ind));
2538 const Index_t obs_tile_size2 =
2539 static_cast<Index_t>(detail::storedObservationChannelCount(x2_ind));
2540 st.initialize(static_cast<int>(obs_tile_size1));
2541
2542 const int m = static_cast<int>(x1.rows());
2543 const int n = static_cast<int>(x2.rows());
2544 const auto rectangular_tiles = [](const Eigen::VectorXd& indices,
2545 Index_t tile_size) {
2546 if (tile_size == 0 || indices.size() % tile_size != 0) return false;
2547 for (Eigen::Index row = tile_size; row < indices.size(); ++row)
2548 if (indices(row) != indices(row % tile_size)) return false;
2549 return true;
2550 };
2551 if (!rectangular_tiles(x1_ind, obs_tile_size1) ||
2552 !rectangular_tiles(x2_ind, obs_tile_size2)) {
2553 const auto rows = buildStructuredPermutation(x1_ind);
2554 const auto columns = buildStructuredPermutation(x2_ind);
2555 const EigenMatrix grouped_x1 = permuteMatrixRows(x1, rows);
2556 const EigenMatrix grouped_x2 = permuteMatrixRows(x2, columns);
2557 const Eigen::VectorXd grouped_ind1 = permuteVector(x1_ind, rows);
2558 const Eigen::VectorXd grouped_ind2 = permuteVector(x2_ind, columns);
2559 Eigen::VectorXd derivatives1, derivatives2;
2560 extractUniqueIndices(grouped_ind1, derivatives1);
2561 extractUniqueIndices(grouped_ind2, derivatives2);
2562 EigenMatrix covariance;
2563 applyCrossCovarianceFunction(
2564 grouped_x1, grouped_x2, grouped_ind1, derivatives1, grouped_ind2,
2565 derivatives2, *sexpat_cov_func, covariance, /*do_reduce=*/false);
2566 addConstantCovarianceBlock(const_cov_fun.get(), grouped_ind1,
2567 grouped_ind2, covariance);
2568 st.make_desc(m, n, desc);
2569 const int leading = desc[8];
2570 cov_dist.assign(static_cast<std::size_t>(leading) * st.local_cols(n),
2571 0.0);
2572 for (int column = 0; column < n; ++column) {
2573 const int global_column = columns.perm[column];
2574 for (int row = 0; row < m; ++row) {
2575 const int global_row = rows.perm[row];
2576 if ((lower_only && global_row < global_column) ||
2577 !st.owns_global_entry(global_row, global_column))
2578 continue;
2579 const int local_row = st.local_index_for_global(
2580 global_row, st.block_size(), st.myrow(), st.nprow());
2581 const int local_column = st.local_index_for_global(
2582 global_column, st.block_size(), st.mycol(), st.npcol());
2583 cov_dist[local_row + static_cast<std::size_t>(local_column) *
2584 leading] = covariance(row, column);
2585 }
2586 }
2587 return;
2588 }
2589 gpr::assertMsg(
2590 obs_tile_size1 > 0 && obs_tile_size2 > 0 && m % obs_tile_size1 == 0 &&
2591 n % obs_tile_size2 == 0,
2592 "ScaLAPACK cross-covariance assembly requires observation blocks");
2593
2594 st.make_desc(m, n, desc);
2595 const int local_rows = st.local_rows(m);
2596 cov_dist.assign(static_cast<size_t>(local_rows) * st.local_cols(n), 0.0);
2597
2598 const Index_t n_obs1 = static_cast<Index_t>(m) / obs_tile_size1;
2599 const Index_t n_obs2 = static_cast<Index_t>(n) / obs_tile_size2;
2600 const Eigen::VectorXd tile_ind1 = x1_ind.head(obs_tile_size1);
2601 const Eigen::VectorXd tile_ind2 = x2_ind.head(obs_tile_size2);
2602 Eigen::VectorXd tile_uDdim1, tile_uDdim2;
2603 extractUniqueIndices(tile_ind1, tile_uDdim1);
2604 extractUniqueIndices(tile_ind2, tile_uDdim2);
2605
2606 auto owns_any_entry = [&](const int row_start, const Index_t row_count,
2607 const int col_start, const Index_t col_count) {
2608 for (Index_t local_j = 0; local_j < col_count; ++local_j) {
2609 const int global_j = col_start + static_cast<int>(local_j);
2610 for (Index_t local_i = 0; local_i < row_count; ++local_i) {
2611 const int global_i = row_start + static_cast<int>(local_i);
2612 if (st.owns_global_entry(global_i, global_j)) return true;
2613 }
2614 }
2615 return false;
2616 };
2617
2618 EigenMatrix tile_cov;
2619 EigenMatrix tile_temp;
2620 pairlocal::TiledLayoutSource tiles;
2621 if (use_pair_local_tiles_ && !sexpat_cov_func->usesManifoldChart() &&
2622 !sexpat_cov_func->usesGeodesicHeatKernel())
2623 (void)tiles.prepare(sexpat_cov_func->getConfInfo(),
2624 sexpat_cov_func->combineParameters(), x1,
2625 obs_tile_size1, tile_ind1, x2, obs_tile_size2,
2626 tile_ind2, sexpat_cov_func->farFieldRadius());
2627 // With both tiles equal to the block size every tile has one owner and
2628 // contiguous local storage.
2629 const bool whole_tiles =
2630 st.block_size() == obs_tile_size1 && obs_tile_size1 == obs_tile_size2;
2631 for (Index_t obs_i = 0; obs_i < n_obs1; ++obs_i) {
2632 const int row_start = static_cast<int>(obs_i * obs_tile_size1);
2633 const EigenMatrix x_tile_i = x1.middleRows(row_start, obs_tile_size1);
2634
2635 for (Index_t obs_j = 0; obs_j < n_obs2; ++obs_j) {
2636 if (lower_only && obs_j > obs_i) break;
2637 const int col_start = static_cast<int>(obs_j * obs_tile_size2);
2638 if (whole_tiles ? !st.owns_global_entry(row_start, col_start)
2639 : !owns_any_entry(row_start, obs_tile_size1,
2640 col_start, obs_tile_size2))
2641 continue;
2642
2643 tile_cov.resize(obs_tile_size1, obs_tile_size2);
2644 tile_cov.setZero();
2645
2646 if (tiles.ready()) {
2647 tiles.tile(obs_i, obs_j, tile_temp);
2648 } else {
2649 const EigenMatrix x_tile_j =
2650 x2.middleRows(col_start, obs_tile_size2);
2651 applyCrossCovarianceFunction(
2652 x_tile_i, x_tile_j, tile_ind1, tile_uDdim1, tile_ind2,
2653 tile_uDdim2, *sexpat_cov_func, tile_temp, false);
2654 }
2655 tile_cov.noalias() += tile_temp;
2656 addConstantCovarianceBlock(const_cov_fun.get(), tile_ind1,
2657 tile_ind2, tile_cov);
2658
2659 if (whole_tiles) {
2660 const int dist_i = st.local_index_for_global(
2661 row_start, st.block_size(), st.myrow(), st.nprow());
2662 const int dist_j = st.local_index_for_global(
2663 col_start, st.block_size(), st.mycol(), st.npcol());
2664 Eigen::Map<EigenMatrix, 0, Eigen::OuterStride<>> target(
2665 cov_dist.data() + static_cast<size_t>(dist_i) +
2666 static_cast<size_t>(dist_j) * local_rows,
2667 obs_tile_size1, obs_tile_size2,
2668 Eigen::OuterStride<>(local_rows));
2669 target = tile_cov;
2670 continue;
2671 }
2672 for (Index_t local_j = 0; local_j < obs_tile_size2; ++local_j) {
2673 const int global_j = col_start + static_cast<int>(local_j);
2674 for (Index_t local_i = 0; local_i < obs_tile_size1; ++local_i) {
2675 const int global_i = row_start + static_cast<int>(local_i);
2676 if (!st.owns_global_entry(global_i, global_j)) continue;
2677
2678 const int dist_i = st.local_index_for_global(
2679 global_i, st.block_size(), st.myrow(), st.nprow());
2680 const int dist_j = st.local_index_for_global(
2681 global_j, st.block_size(), st.mycol(), st.npcol());
2682 cov_dist[static_cast<size_t>(dist_i) +
2683 static_cast<size_t>(dist_j) * local_rows] =
2684 tile_cov(local_i, local_j);
2685 }
2686 }
2687 }
2688 }
2689}
2690#endif
2691
2693 const Eigen::VectorXd& ind_Ddim1, const Eigen::VectorXd& ind_Ddim2,
2694 const Index_t row_val, const Index_t col_val, const FieldMatrixd& field,
2695 EigenMatrix& matrix, bool transpose_field) const
2696{
2697 const auto row_block = observationChannelBlock(ind_Ddim1, row_val);
2698 const auto col_block = observationChannelBlock(ind_Ddim2, col_val);
2699 const Eigen::Index i_start = row_block.start;
2700 const Eigen::Index j_start = col_block.start;
2701 const Eigen::Index block_rows = row_block.count;
2702 const Eigen::Index block_cols = col_block.count;
2703
2704 if (!transpose_field) {
2705 matrix.block(i_start, j_start, block_rows, block_cols) =
2706 field.block(0, 0, block_rows, block_cols);
2707 } else {
2708 matrix.block(i_start, j_start, block_rows, block_cols) =
2709 field.block(0, 0, block_cols, block_rows).transpose();
2710 }
2711}
2712
2714 const Eigen::VectorXd& ind_Ddim1, const Eigen::VectorXd& ind_Ddim2,
2715 const Index_t row_val, const Index_t col_val, const FieldMatrixd& field,
2716 const EigenMatrix& invC, const Eigen::VectorXd& b, double& trace_accum,
2717 double& quad_accum, bool transpose_field, bool accumulate_quad,
2718 double diagonal_nugget, EigenMatrix* trace_sink)
2719{
2720 const EigenMatrix* trace_probe_W = hutch_trace_W_;
2721 const EigenMatrix* trace_probe_Z = hutch_trace_Z_;
2722 const EigenMatrix* hssvd_trace_basis = hssvd_trace_basis_;
2723 const EigenMatrix* hssvd_trace_weighted_basis = hssvd_trace_weighted_basis_;
2724 const auto row_block = observationChannelBlock(ind_Ddim1, row_val);
2725 const auto col_block = observationChannelBlock(ind_Ddim2, col_val);
2726 const Eigen::Index i_start = row_block.start;
2727 const Eigen::Index j_start = col_block.start;
2728 const Eigen::Index block_rows = row_block.count;
2729 const Eigen::Index block_cols = col_block.count;
2730
2731 const bool hutchinson =
2732 trace_probe_W != nullptr && trace_probe_Z != nullptr;
2733 const bool hssvd_trace =
2734 hssvd_trace_basis != nullptr && hssvd_trace_weighted_basis != nullptr &&
2735 (hssvd_trace_inv_noise_ > 0.0 || hssvd_trace_direct_inverse_) &&
2736 hssvd_trace_basis->rows() >= i_start + block_rows &&
2737 hssvd_trace_weighted_basis->rows() >= j_start + block_cols &&
2738 hssvd_trace_basis->cols() == hssvd_trace_weighted_basis->cols();
2739
2740 // Stochastic trace term: sum_j (W_block.col(j))^T field_block
2741 // (Z_block.col(j)) accumulated over blocks. With M = field_block *
2742 // Z_block (block_rows x m) this is the Frobenius inner product
2743 // <W_block, M>. The quadratic term below is byte-identical to the exact
2744 // path -- only the trace contribution is swapped.
2745 auto trace_probe_contrib = [&](const auto& field_block) -> double {
2746 const Eigen::Index m = trace_probe_W->cols();
2747 const auto W_block = trace_probe_W->block(i_start, 0, block_rows, m);
2748 const auto Z_block = trace_probe_Z->block(j_start, 0, block_cols, m);
2749 return (W_block.array() * (field_block * Z_block).array()).sum();
2750 };
2751
2752 auto hssvd_trace_contrib = [&](const auto& field_block) -> double {
2753 double diagonal_trace = 0.0;
2754 if (i_start == j_start && block_rows == block_cols) {
2755 diagonal_trace = field_block.trace();
2756 }
2757 const Eigen::Index rank = hssvd_trace_basis->cols();
2758 const auto U_block =
2759 hssvd_trace_basis->block(i_start, 0, block_rows, rank);
2760 const auto Urho_block =
2761 hssvd_trace_weighted_basis->block(j_start, 0, block_cols, rank);
2762 const double projected_trace =
2763 (U_block.array() * (field_block * Urho_block).array()).sum();
2764 if (hssvd_trace_direct_inverse_) return projected_trace;
2765 return hssvd_trace_inv_noise_ * (diagonal_trace - projected_trace);
2766 };
2767
2768 auto contract_block = [&](const auto& field_block) {
2769 if (trace_sink != nullptr) {
2770 trace_sink->block(i_start, j_start, block_rows, block_cols) =
2771 field_block;
2772 } else if (hssvd_trace) {
2773 trace_accum += hssvd_trace_contrib(field_block);
2774 } else if (hutchinson) {
2775 trace_accum += trace_probe_contrib(field_block);
2776 } else {
2777 const auto inv_block =
2778 invC.block(i_start, j_start, block_rows, block_cols);
2779 trace_accum += (inv_block.array() * field_block.array()).sum();
2780 }
2781 if (accumulate_quad) {
2782 const auto b_row = b.segment(i_start, block_rows);
2783 const auto b_col = b.segment(j_start, block_cols);
2784 quad_accum += b_row.dot(field_block * b_col);
2785 }
2786 };
2787
2788 auto accumulate_from_block = [&](const auto& field_block) {
2789 if (diagonal_nugget > 0.0 && i_start == j_start &&
2790 block_rows == block_cols) {
2791 EigenMatrix regularized = field_block;
2792 regularized.diagonal().array() +=
2793 diagonal_nugget * field_block.diagonal().array();
2794 contract_block(regularized);
2795 if (!accumulate_quad) {
2796 quad_accum += diagonal_nugget *
2797 (b.segment(i_start, block_rows).array().square() *
2798 field_block.diagonal().array())
2799 .sum();
2800 }
2801 } else {
2802 contract_block(field_block);
2803 }
2804 };
2805
2806 if (!transpose_field) {
2807 const auto field_block = field.block(0, 0, block_rows, block_cols);
2808 accumulate_from_block(field_block);
2809 } else {
2810 const auto field_block =
2811 field.block(0, 0, block_cols, block_rows).transpose();
2812 accumulate_from_block(field_block);
2813 }
2814}
2815
2817 const EigenMatrix& x, const Eigen::VectorXd& ind_Ddim, const Index_t ind,
2818 FieldMatrixd& x_loc) const
2819{
2820 const auto block = observationChannelBlock(ind_Ddim, ind);
2821 const Eigen::Index n_cols = x.cols();
2822 if (ind_Ddim.size() != x.rows() || x_loc.cols() < n_cols)
2823 throw std::invalid_argument(
2824 "coordinate channel block has invalid shape");
2825 if (block.count != x_loc.rows()) {
2826 x_loc.resize(block.count, x_loc.cols());
2827 x_loc.setZero();
2828 }
2829 x_loc.block(0, 0, block.count, n_cols) =
2830 x.block(block.start, 0, block.count, n_cols);
2831}
2832
2834 EigenMatrix& matrix)
2835{
2836 // Index_t is unsigned, so cols() - 1 on an empty matrix wraps to
2837 // 4294967295 and feeds that to block() and conservativeResize().
2838 if (matrix.cols() == 0) return;
2839 const Eigen::Index num_rows = matrix.rows();
2840 const Eigen::Index num_cols = matrix.cols() - 1;
2841 const Eigen::Index ind = static_cast<Eigen::Index>(column_ind);
2842 if (ind > num_cols) return;
2843
2844 if (ind < num_cols)
2845 matrix.block(0, ind, num_rows, num_cols - ind) =
2846 matrix.block(0, ind + 1, num_rows, num_cols - ind);
2847
2848 matrix.conservativeResize(num_rows, num_cols);
2849}
2850
2852 const Eigen::VectorXd& input_ind, Eigen::VectorXd& output_ind) const
2853{
2854 // NOTE: O(n log n) scan; fine for typical sizes (n < 1000)
2855 std::vector<double> unique_ind_loc;
2856
2857 unique_ind_loc.insert(unique_ind_loc.begin(), input_ind.data(),
2858 input_ind.data() + input_ind.size());
2859
2860 // Erase all non-positive values
2861 auto it = std::remove_if(unique_ind_loc.begin(), unique_ind_loc.end(),
2862 [](const double value) { return value <= 0; });
2863 unique_ind_loc.erase(it, unique_ind_loc.end());
2864
2865 // erase all duplicates and sort
2866 sort(unique_ind_loc.begin(), unique_ind_loc.end());
2867 unique_ind_loc.erase(unique(unique_ind_loc.begin(), unique_ind_loc.end()),
2868 unique_ind_loc.end());
2869
2870 Eigen::Map<Eigen::VectorXd> map(unique_ind_loc.data(),
2871 unique_ind_loc.size());
2872 output_ind = map;
2873}
2874
2876 const EigenMatrix& x_ordered, const Eigen::VectorXd& ind_ordered,
2877 const Eigen::VectorXd& noise_ordered, double extra_uniform_noise,
2878 EigenMatrix& signal_cov, const Eigen::VectorXd& constant_update,
2879 Eigen::VectorXd& factor_constant, bool factor_order)
2880{
2881 const bool unsupported =
2883 lik_gaussian == nullptr || sexpat_cov_func->usesManifoldChart() ||
2884 sexpat_cov_func->usesGeodesicHeatKernel() || principled_nugget_;
2885 const AtomsConfiguration& effective_conf =
2886 (sexpat_cov_func != nullptr &&
2887 sexpat_cov_func->getConfInfo().atoms_mov.type.size() > 0)
2888 ? sexpat_cov_func->getConfInfo()
2889 : atoms_config;
2890
2891 if (!detail::prepareRigidDeflationState(
2892 use_rigid_null_deflation_, factor_order, effective_conf, x_ordered,
2893 ind_ordered, noise_ordered, extra_uniform_noise, unsupported,
2895 rigid_deflation_.reset();
2896 if (report_level >= 2) {
2897 log_man << "Rigid-null deflation skipped: reason="
2898 << rigid_deflation_diag_.reason
2899 << " full_rows=" << rigid_deflation_diag_.full_rows
2900 << ".\n";
2901 }
2902 return false;
2903 }
2904
2905 if (!detail::verifySignalKernelRigidNullspace(signal_cov, rigid_deflation_,
2907 rigid_deflation_.reset();
2908 if (report_level >= 2) {
2909 log_man << "Rigid-null deflation skipped: reason="
2910 << rigid_deflation_diag_.reason << " kr_rel="
2911 << rigid_deflation_diag_.kernel_relative_null_norm << ".\n";
2912 }
2913 return false;
2914 }
2915
2916 signal_cov = rigid_deflation_.projectSymmetric(signal_cov);
2917 if (factor_order) {
2918 for (Eigen::Index i = 0; i < rigid_deflation_.num_geometries; ++i) {
2919 const auto& blk =
2920 rigid_deflation_.blocks[static_cast<std::size_t>(i)];
2921 signal_cov(blk.deflated_row_offset, blk.deflated_row_offset) +=
2922 noise_ordered(blk.full_row_offset) + extra_uniform_noise;
2923 if (blk.deflated_grad_dim > 0) {
2924 signal_cov.diagonal()
2925 .segment(blk.deflated_row_offset + 1, blk.deflated_grad_dim)
2926 .array() += blk.grad_noise_variance;
2927 }
2928 }
2929 if (constant_update.size() == x_ordered.rows()) {
2930 factor_constant = rigid_deflation_.projectVector(constant_update);
2931 }
2932 }
2933 rigid_deflation_.active = true;
2934 if (report_level >= 2) {
2935 log_man << "Rigid-null deflation applied: reason="
2936 << rigid_deflation_diag_.reason
2937 << " rows=" << rigid_deflation_diag_.full_rows << "->"
2938 << rigid_deflation_diag_.deflated_rows
2939 << " rigid_modes=" << rigid_deflation_diag_.rigid_modes
2940 << " kr_rel=" << rigid_deflation_diag_.kernel_relative_null_norm
2941 << ".\n";
2942 }
2943 return true;
2944}
2945
2946} // namespace gpr
Linear algebra abstraction layer for GPR hot-path operations.
@ x
Definition Enums.h:28
@ D1
Definition Enums.h:19
@ D12
Definition Enums.h:21
@ D2
Definition Enums.h:20
Memory a rank may claim before a large distributed workspace.
Methods to calculate distances between atoms.
Definition Distance.h:154
void dist_at_vec(const gpr::Coord &x1, const gpr::Coord &x2, const gpr::AtomsConfiguration &conf_info, const gpr::FieldMatrixd &lengthscale, std::vector< gpr::FieldMatrixd > &dist)
Similar to dist_at but calculates vector of distances for every pair of moving and frozen atoms.
Definition Distance.cpp:796
void setFarFieldRadius(double radius)
Definition Distance.cpp:299
linalg::BackendContext & backend() const
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)
bool evaluateTrainingCrossCovarianceInFactorOrder(const EigenMatrix &query, const Eigen::VectorXd &query_ind, EigenMatrix &cross) const
void evaluateCovarianceMatrix(const EigenMatrix &x1, const EigenMatrix &x2, const Eigen::VectorXd &x1_ind, const Eigen::VectorXd &x2_ind, EigenMatrix &C, bool serial_per_rank=false) const
Evaluate covariance matrix between two input vectors.
bool evaluateTrainingCovarianceInFactorOrder(const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool include_noise=true)
std::optional< bool > tryPairLocalDirectionalCovariance(const TrainingKernelGeometry &geom, const Eigen::VectorXd &indices, const Eigen::VectorXd &direction, EigenMatrix &first, EigenMatrix &second, int rank=0, int ranks=1) const
bool assembleCompositeJointCovarianceDerivatives(const EigenMatrix &x, const Eigen::VectorXd &indices, SexpatCF &covariance, std::vector< EigenMatrix > &derivatives) const
detail::RigidDeflationState rigid_deflation_
void removeColumn(const Index_t column_ind, EigenMatrix &matrix)
Remove column from the dense matrix.
EigenMatrix trainingCrossCovarianceInFactorRows(const EigenMatrix &query, const Eigen::VectorXd &query_ind, bool serial_per_rank) const
void assignBlockToMatrix(const Eigen::VectorXd &ind_Ddim1, const Eigen::VectorXd &ind_Ddim2, const Index_t row_val, const Index_t col_val, const FieldMatrixd &field, EigenMatrix &matrix, bool transpose_field=false) const
Assign field to matrix according to indices form ind_Ddim1 and ind_Ddim2.
EigenMatrix permuteTrainingRows(const EigenMatrix &input) const
bool prepareTrainingKernelGeometry(const EigenMatrix &x, const Eigen::VectorXd &x_ind, TrainingKernelGeometry &out, bool reused=false) const
bool assembleCompositeJointCrossCovariance(const EigenMatrix &left, const EigenMatrix &right, const Eigen::VectorXd &left_indices, const Eigen::VectorXd &right_indices, SexpatCF &covariance, EigenMatrix &result) const
bool evaluateActiveCovarianceFromGeometry(const TrainingKernelGeometry &geom, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &theta, const std::vector< bool > &active_lengths, EigenMatrix &covariance, bool serial_per_rank=false, std::vector< EigenMatrix > *covariance_derivatives=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 accumulateBlockContribution(const Eigen::VectorXd &ind_Ddim1, const Eigen::VectorXd &ind_Ddim2, const Index_t row_val, const Index_t col_val, const FieldMatrixd &field, const EigenMatrix &invC, const Eigen::VectorXd &b, double &trace_accum, double &quad_accum, bool transpose_field=false, bool accumulate_quad=true, double diagonal_nugget=0.0, EigenMatrix *trace_sink=nullptr)
Accumulate trace and quadratic-form contributions from one block.
bool evaluateTrainingCovarianceInFactorOrderFromGeometry(const TrainingKernelGeometry &geom, const EigenMatrix &x, const Eigen::VectorXd &x_ind, EigenMatrix &cov_matrix, bool include_noise=true)
bool assembleCompositeJointCovariance(const EigenMatrix &x, const Eigen::VectorXd &indices, SexpatCF &covariance, EigenMatrix &result) const
RigidDeflationDiagnostic rigid_deflation_diag_
void extractCoordinatesByIndex(const EigenMatrix &x, const Eigen::VectorXd &ind_Ddim, const Index_t ind, FieldMatrixd &x_loc) const
Extract coordinates from x using value ind from ind_Ddim.
virtual bool supportsRigidNullDeflation() const noexcept
void extractUniqueIndices(const Eigen::VectorXd &input_ind, Eigen::VectorXd &output_ind) const
Extract unique indices from the input vector.
bool contractActiveCovarianceDerivatives(const TrainingKernelGeometry &geom, const Eigen::VectorXd &x_ind, const Eigen::VectorXd &theta, const std::vector< bool > &active_lengths, const EigenMatrix &weight, const std::vector< Eigen::Index > &derivative_lengths, Eigen::VectorXd &contractions, bool serial_per_rank=false)
Index_t getNumberOfRepetitiveIndices(const Eigen::VectorXd &ind_Ddim) const
Count number of the first repetitive indices in ind_Ddim .
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
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).
Eigen::MatrixXd jointEnergyGradientCovariance(const Eigen::MatrixXd &positions) const override
Joint covariance in Observation order [E; G_col0; ...; G_colD-1].
Pair-type inverse-distance squared-exponential primitive.
Definition SexpatCF.h:74
bool buildCrossBlockGeometry(const Coord &x1, const Coord &x2, uint8_t derivative_options, const FieldMatrixIdx &dims1, const FieldMatrixIdx &dims2, CrossBlockGeometry &geometry) const
Build theta-independent pairtype geometry for a covariance block.
Definition SexpatCF.cpp:806
void addManifoldGeometryRowsEvaluatedForTesting(Eigen::Index left_rows, Eigen::Index right_rows) const noexcept
Definition SexpatCF.h:638
const std::shared_ptr< const geometry::InternalCoordinateChart > & manifoldChart() const noexcept
Definition SexpatCF.h:622
std::shared_ptr< const KernelOperator > assembledOperator() const
The configured base and optional additive heat component.
Definition SexpatCF.cpp:585
bool usesManifoldChart() const noexcept
Definition SexpatCF.h:616
Eigen::Index manifoldDimensions() const noexcept
Definition SexpatCF.h:626
double getMagnSigma2()
Definition SexpatCF.inl:53
const std::shared_ptr< const GeodesicHeatEnergyForceKernel > & geodesicHeatKernel() const noexcept
Definition SexpatCF.h:657
bool buildCrossBlockDerivativesOnly(const Coord &x1, const Coord &x2, uint8_t derivative_options, const FieldMatrixIdx &dims1, const FieldMatrixIdx &dims2, CrossBlockGeometry &geometry) const
Populate only the derivative fields (d1, d2, d12) of a CrossBlockGeometry, skipping the per-pairtype ...
Definition SexpatCF.cpp:931
FieldMatrixd & getLengthScaleRef()
Definition SexpatCF.inl:58
Eigen::MatrixXd jointEnergyGradientCrossCovariance(const Eigen::MatrixXd &left_positions, const Eigen::MatrixXd &right_positions) const override
Assemble all Cartesian channels from one sparse pair walk per geometry.
const LocalExecutor & local() const noexcept
void forEach(std::size_t count, Operation &&operation, Grain grain=Grain::Fine) const
Eigen::Index parameterCount() const noexcept
1 + number of log lengths.
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
Eigen::Vector3d at(const FieldMatrixd &mat, Index_t i)
std::optional< std::int64_t > AvailableMemory
void disjoint_sum_bcast(double *data, int count, const MpiContext &context)
void ordered_sum_bcast(double *data, int count, const MpiContext &context)
AvailableMemory availableHostBudget()
bool buildGeometry(const AtomsConfiguration &configuration, const Eigen::MatrixXd &positions, Geometry &geometry)
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::VectorXd permuteVector(const Eigen::VectorXd &input, const StructuredPermutation &p)
const SexpatCF::CrossBlockGeometry * resolveTrainingBlockGeometry(const SexpatCF &covariance, const TrainingKernelGeometry &geom, const TrainingKernelGeometryBlock &block, SexpatCF::CrossBlockGeometry &scratch)
Eigen::Matrix< Index_t, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixIdx
Definition Macros.h:29
bool buildFactoredTrainingGeometry(const AtomsConfiguration &conf_info, const FieldMatrixd &x_loc, FactoredTrainingGeometry &out, double far_field_radius=0.0)
StructuredPermutation buildStructuredPermutation(const Eigen::VectorXd &ind_Ddim)
FieldMatrixd Coord
Definition Macros.h:35
uint32_t Index_t
Definition Macros.h:17
EigenMatrix permuteMatrixRows(const EigenMatrix &input, const StructuredPermutation &p)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
bool buildCrossBlockDerivativesFactored(const FactoredTrainingGeometry &factors, Index_t block_n, Index_t block_m, uint8_t derivative_options, SexpatCF::CrossBlockGeometry &out)
bool ownsBlock(long block_idx, int rank, int nprocs, bool serial_per_rank)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
double g_geom_build_seconds
Stores configurations of all atoms in the system.
Definition Structures.h:832
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844
std::vector< std::vector< Index_t > > features_by_pt
std::vector< EigenMatrix > J
per dimension, n_conf x d_feat
static int geometry_builds
static std::atomic_size_t pair_contraction_tiles
Configuration pairs contracted by this process, excluding transposes.
static double residentMegabytes() noexcept
static double assembly_seconds
std::vector< FieldMatrixd > d2
Definition SexpatCF.h:280
std::vector< FieldMatrixd > d12
Definition SexpatCF.h:281
std::vector< FieldMatrixd > distance
Definition SexpatCF.h:278
std::vector< FieldMatrixd > d1
Definition SexpatCF.h:279
bool shared_coordinates
Channel blocks carry the same Cartesian positions.
std::vector< TrainingKernelGeometryBlock > blocks
FactoredTrainingGeometry factors
streamed blocks come from here
std::shared_ptr< LazyFactoredTrainingGeometry > lazy_factors
std::vector< FieldMatrixd > x_loc_by_dim
indexed by dimension value
std::vector< TrainingKernelGeometryBlock > blocks
std::vector< FieldMatrixd > shared_distance_neg_per_pt
std::map< std::pair< Index_t, Index_t >, std::size_t > block_index_by_nm
static MpiContext local() noexcept
Definition MpiContext.h:75
Eigen::Index dof
3 x moving atoms