Loading...
Searching...
No Matches
AtomicInducingPosterior.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
4
5#include <algorithm>
6#include <cmath>
7#include <exception>
8#include <limits>
9#include <map>
10#include <mutex>
11#include <numbers>
12#include <set>
13#include <stdexcept>
14#include <utility>
15
21#include "JointObservation.h"
22
23namespace gpr {
24namespace {
25using Matrix = EigenMatrix;
26using Vector = Eigen::VectorXd;
27
28using PriorSum = linalg::CompensatedSum;
29
30// Eigen's GEMM and LLT follow Eigen::nbThreads. A team larger than one
31// splits the product (Eigen's parallelize_gemm) and the sum is not the
32// serial sum. prior_trace - gram.trace() then falls below the tolerance in
33// nonnegativeVariance. The same team does not finish inside the suite
34// timeout when the machine is already saturated: the product waits on a
35// peer the runtime never scheduled. Products here stay on one thread,
36// which is the library product policy.
37//
38// The guard serializes every holder on one process-wide mutex. It must only
39// cover local arithmetic: a collective (MPI_Allreduce, the exact-sum
40// broadcast) entered under it would block while holding the mutex, and two
41// fits on different communicators, or two threads of one rank that reach
42// their collectives in a different order, would then wait on each other
43// through the mutex and the network. fit, evaluate and the statistics
44// reduction therefore take the guard around their local sections only.
45using SerialEigenProducts = linalg::ScopedSerialEigenThreads;
46
47// Keep the rounded product and its FMA residual separate until the complete
48// covariance channel is accumulated; signed Jacobian pairs can cancel exactly.
49void addTripleProduct(PriorSum& total, double scale, double left, double right)
50{
51 const double product = left * right;
52 total.addProduct(scale, product);
53 total.addProduct(scale, std::fma(left, right, -product));
54}
55
56void addScaled(PriorSum& total, double scale, const PriorSum& value)
57{
58 total.addProduct(scale, value.sum);
59 total.addProduct(scale, value.corr);
60}
61
62void addScaledProduct(PriorSum& total, double scale, const PriorSum& left,
63 const PriorSum& right)
64{
65 addTripleProduct(total, scale, left.sum, right.sum);
66 addTripleProduct(total, scale, left.sum, right.corr);
67 addTripleProduct(total, scale, left.corr, right.sum);
68 addTripleProduct(total, scale, left.corr, right.corr);
69}
70
71template <class Left, class Right>
72PriorSum compensatedDot(const Eigen::MatrixBase<Left>& left,
73 const Eigen::MatrixBase<Right>& right)
74{
75 PriorSum result;
76 for (Eigen::Index feature = 0; feature < left.size(); ++feature)
77 result.addProduct(left.derived().coeff(feature),
78 right.derived().coeff(feature));
79 return result;
80}
81
82PriorSum compensatedProjection(const std::vector<PriorSum>& values,
83 const Vector& delta)
84{
85 PriorSum result;
86 for (Eigen::Index feature = 0; feature < delta.size(); ++feature)
87 addScaled(result, delta(feature), values[feature]);
88 return result;
89}
90
91void shareFailure(const linalg::MpiContext& context,
92 const std::exception_ptr& failure)
93{
94#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
95 if (context.is_distributed()) {
96 int failed = failure ? 1 : 0;
97 if (MPI_Allreduce(MPI_IN_PLACE, &failed, 1, MPI_INT, MPI_MAX,
98 context.comm) != MPI_SUCCESS)
99 throw std::runtime_error("could not share atomic fit status");
100 if (failed && !failure)
101 throw std::runtime_error("atomic fit failed on another rank");
102 }
103#endif
104 if (failure) std::rethrow_exception(failure);
105}
106
107double nonnegativeVariance(double value, double prior)
108{
109 const double tolerance = 256.0 * std::numeric_limits<double>::epsilon() *
110 std::max(1.0, std::abs(prior));
111 if (!std::isfinite(value) || value < -tolerance)
112 throw std::runtime_error("atomic posterior variance is invalid");
113 return std::max(0.0, value);
114}
115
116// Cholesky factor and solves routed through portable_tiles so compact
117// arithmetic does not depend on Eigen's process-global thread count and
118// never mutates it.
119class SerialCholesky final : public linalg::KernelInverse {
120public:
121 [[nodiscard]] bool factorise(const Matrix& K)
122 {
123 if (K.rows() != K.cols()) {
124 factored_ = false;
125 return false;
126 }
127 lower_ = K;
129 lower_.data(), lower_.outerStride(), lower_.rows())) {
130 factored_ = false;
131 return false;
132 }
133 factored_ = true;
134 return true;
135 }
136
137 [[nodiscard]] Kind kind() const noexcept override
138 {
139 return Kind::RankLocal;
140 }
141
142 [[nodiscard]] Vector solve(const Vector& rhs) const override
143 {
144 if (!factored_) {
145 throw std::logic_error(
146 "SerialCholesky: solve called before factorise");
147 }
148 Vector result = rhs;
150 lower_.data(), lower_.outerStride(), true, result.data(),
151 result.rows(), lower_.rows(), 1);
153 lower_.data(), lower_.outerStride(), false, result.data(),
154 result.rows(), lower_.rows(), 1);
155 return result;
156 }
157
158 [[nodiscard]] Matrix solve_mat(const Matrix& rhs) const override
159 {
160 if (!factored_) {
161 throw std::logic_error(
162 "SerialCholesky: solve_mat called before factorise");
163 }
164 Matrix result = rhs;
166 lower_.data(), lower_.outerStride(), true, result.data(),
167 result.outerStride(), lower_.rows(), result.cols());
169 lower_.data(), lower_.outerStride(), false, result.data(),
170 result.outerStride(), lower_.rows(), result.cols());
171 return result;
172 }
173
174 [[nodiscard]] double log_det() const override
175 {
176 if (!factored_) {
177 throw std::logic_error(
178 "SerialCholesky: log_det called before factorise");
179 }
180 return 2.0 * lower_.diagonal().array().log().sum();
181 }
182
183 [[nodiscard]] double trace_inv_times(const Matrix& A) const override
184 {
185 return solve_mat(A).trace();
186 }
187
188private:
189 Matrix lower_;
190 bool factored_{false};
191};
192} // namespace
193
195 struct Parameters {
196 double magnitude = 0.0, energy_noise = 0.0, gradient_noise = 0.0;
198 std::map<int, Eigen::Index> species_index;
199 };
200 struct Environment {
201 std::vector<int> atomic_numbers;
202 Matrix values;
203 std::vector<Matrix> jacobians;
204 // Jacobian rows map to Cartesian coordinates through support.
205 std::vector<std::vector<Eigen::Index>> support;
206 };
214 Eigen::Index index;
216 std::vector<PriorTracePair> prior_trace;
217 };
218 struct Statistics {
219 Matrix gram;
220 Vector rhs;
221 std::vector<Matrix> dgram;
222 std::vector<Vector> drhs;
224
225 template <class Visitor>
226 void visit(Visitor&& visitor)
227 {
228 const auto entries = [&](auto& values) {
229 for (Eigen::Index index = 0; index < values.size(); ++index)
230 visitor(values.data()[index]);
231 };
232 const auto triangle = [&](Matrix& matrix) {
233 for (Eigen::Index column = 0; column < matrix.cols(); ++column)
234 for (Eigen::Index row = column; row < matrix.rows(); ++row)
235 visitor(matrix(row, column));
236 };
237 triangle(gram);
238 entries(rhs);
239 entries(target_norm);
240 entries(prior_trace);
241 for (auto& values: dgram)
242 triangle(values);
243 for (auto& values: drhs)
244 entries(values);
245 }
246 };
247 struct Whitening {
248 Matrix lower;
249 std::vector<Matrix> derivative;
250 };
251 struct Evaluation {
255 std::unique_ptr<SerialCholesky> posterior;
257 };
262
263 std::shared_ptr<const linalg::MpiCommunicator> communication;
268 std::vector<int> species;
269 std::vector<TrainingEnvironment> local_environments;
271 bool prepared = false, fitted = false;
274 std::unique_ptr<linalg::KernelInverse> posterior_factor;
276 std::mutex pending_mutex;
277 std::unique_ptr<PendingEvaluation> pending_evaluation;
278
280 {
281 std::unique_ptr<PendingEvaluation> discarded;
282 {
283 const std::lock_guard lock(pending_mutex);
284 discarded.swap(pending_evaluation);
285 }
286 }
287 void retainEvaluation(const Vector& theta, Evaluation evaluation)
288 {
289 auto pending = std::make_unique<PendingEvaluation>(
290 PendingEvaluation{theta, std::move(evaluation)});
291 {
292 const std::lock_guard lock(pending_mutex);
293 pending.swap(pending_evaluation);
294 }
295 }
296 std::unique_ptr<PendingEvaluation> takePending(const Vector& theta)
297 {
298 std::unique_ptr<PendingEvaluation> pending;
299 {
300 const std::lock_guard lock(pending_mutex);
301 pending.swap(pending_evaluation);
302 }
303 if (pending && (pending->theta.size() != theta.size() ||
304 !(pending->theta.array() == theta.array()).all()))
305 pending.reset();
306 return pending;
307 }
308
310 {
311 return communication ? communication->view()
313 }
314 Eigen::Index dimensions() const
315 {
316 return observations.R.cols();
317 }
318 Eigen::Index parameters() const
319 {
320 return 3 + species.size();
321 }
322 void clearFit() noexcept
323 {
324 fitted = false;
325 inducing_lower.resize(0, 0);
326 posterior_factor.reset();
327 coefficients.resize(0);
328 }
329 void requireFit() const
330 {
331 if (!fitted) throw std::logic_error("atomic posterior is not fitted");
332 }
333 template <class Environments>
334 void validateValues(const Environments& environment) const
335 {
336 const Eigen::Index atoms = environment.values.rows();
337 if (atoms <= 0 || environment.values.cols() != basis.values.cols() ||
338 !environment.values.allFinite() ||
339 environment.atomic_numbers.size() !=
340 static_cast<std::size_t>(atoms))
341 throw std::invalid_argument("invalid atomic descriptor layout");
342 for (const int element: environment.atomic_numbers)
343 if (!std::binary_search(species.begin(), species.end(), element))
344 throw std::invalid_argument(
345 "invalid atomic descriptor species");
346 }
347 void validateEnvironment(const AtomicEnvironments& environment) const
348 {
349 validateValues(environment);
350 const Eigen::Index atoms = environment.values.rows();
351 if (environment.jacobians.size() != static_cast<std::size_t>(atoms))
352 throw std::invalid_argument("invalid atomic descriptor layout");
353 for (Eigen::Index atom = 0; atom < atoms; ++atom) {
354 const auto& jacobian = environment.jacobians[atom];
355 if (jacobian.rows() != dimensions() ||
356 jacobian.cols() != basis.values.cols() || !jacobian.allFinite())
357 throw std::invalid_argument(
358 "invalid atomic descriptor Jacobian");
359 }
360 }
362 {
363 validateEnvironment(environment);
364 Environment result{std::move(environment.atomic_numbers),
365 std::move(environment.values),
366 {},
367 {}};
368 result.support.resize(environment.jacobians.size());
369 result.jacobians.reserve(environment.jacobians.size());
370 for (std::size_t atom = 0; atom < environment.jacobians.size();
371 ++atom) {
372 const auto& jacobian = environment.jacobians[atom];
373 auto& support = result.support[atom];
374 for (Eigen::Index row = 0; row < jacobian.rows(); ++row)
375 if ((jacobian.row(row).array() != 0.0).any())
376 support.push_back(row);
377 Matrix compact(support.size(), jacobian.cols());
378 for (std::size_t row = 0; row < support.size(); ++row)
379 compact.row(row) = jacobian.row(support[row]);
380 result.jacobians.push_back(std::move(compact));
381 }
382 return result;
383 }
384
386 {
387 validateValues(environment);
388 const auto atoms = static_cast<std::size_t>(environment.values.rows());
389 if (environment.dimensions != dimensions() ||
390 environment.jacobians.size() != atoms ||
391 environment.support.size() != atoms)
392 throw std::invalid_argument(
393 "invalid supported atomic descriptor layout");
394 for (std::size_t atom = 0; atom < atoms; ++atom) {
395 auto& jacobian = environment.jacobians[atom];
396 auto& support = environment.support[atom];
397 if (jacobian.rows() != static_cast<Eigen::Index>(support.size()) ||
398 jacobian.cols() != basis.values.cols() || !jacobian.allFinite())
399 throw std::invalid_argument(
400 "invalid supported atomic Jacobian");
401 Eigen::Index previous = -1;
402 std::vector<Eigen::Index> retained;
403 for (std::size_t row = 0; row < support.size(); ++row) {
404 if (support[row] <= previous || support[row] >= dimensions())
405 throw std::invalid_argument(
406 "invalid atomic Cartesian row support");
407 previous = support[row];
408 if ((jacobian.row(row).array() != 0.0).any())
409 retained.push_back(row);
410 }
411 if (retained.size() != support.size()) {
412 Matrix compact(retained.size(), jacobian.cols());
413 std::vector<Eigen::Index> indices;
414 indices.reserve(retained.size());
415 for (std::size_t row = 0; row < retained.size(); ++row) {
416 compact.row(row) = jacobian.row(retained[row]);
417 indices.push_back(support[retained[row]]);
418 }
419 jacobian = std::move(compact);
420 support = std::move(indices);
421 }
422 }
423 return {std::move(environment.atomic_numbers),
424 std::move(environment.values), std::move(environment.jacobians),
425 std::move(environment.support)};
426 }
427
428 Environment descriptorRows(const Vector& position) const
429 {
431 return cacheEnvironment(supported_descriptor(position));
432 return cacheEnvironment(descriptor(position));
433 }
434
435 std::vector<PriorTracePair> cachePriorTrace(
436 const Environment& environment) const
437 {
438 std::vector<PriorTracePair> result;
439 std::map<int, std::size_t> counts;
440 for (const int element: environment.atomic_numbers)
441 ++counts[element];
442 std::size_t pairs = 0;
443 for (const auto& [element, count]: counts)
444 pairs += count * (count + 1) / 2;
445 result.reserve(pairs);
446 for (Eigen::Index a = 0; a < environment.values.rows(); ++a)
447 for (Eigen::Index b = 0; b <= a; ++b) {
448 const int element = environment.atomic_numbers[a];
449 if (element != environment.atomic_numbers[b]) continue;
450 const Vector delta =
451 (environment.values.row(a) - environment.values.row(b))
452 .transpose();
453 PriorTracePair pair{
454 delta.squaredNorm(), {}, {}, element, a == b};
455 const auto& left = environment.support[a];
456 const auto& right = environment.support[b];
457 std::size_t ia = 0, ib = 0;
458 while (ia < left.size() && ib < right.size()) {
459 if (left[ia] < right[ib]) {
460 ++ia;
461 continue;
462 }
463 if (right[ib] < left[ia]) {
464 ++ib;
465 continue;
466 }
467 const auto ja = environment.jacobians[a].row(ia);
468 const auto jb = environment.jacobians[b].row(ib);
469 addScaled(pair.direct, 1.0, compensatedDot(ja, jb));
470 addScaledProduct(pair.projection_product, 1.0,
471 compensatedDot(ja, delta),
472 compensatedDot(jb, delta));
473 ++ia;
474 ++ib;
475 }
476 result.push_back(pair);
477 }
478 return result;
479 }
480
481 Vector priorTrace(const std::vector<PriorTracePair>& pairs,
482 const Parameters& params) const
483 {
484 // Uniform energy and gradient noises weight separate prior traces.
485 // Each pair retains both components of its compensated geometry sums.
486 std::vector<PriorSum> energy(2 + species.size()),
487 gradient(2 + species.size());
488 for (const auto& pair: pairs) {
489 const double length = params.lengths.at(pair.element);
490 const double inverse = 1.0 / (length * length);
491 const double distance = inverse * pair.squared_distance;
492 const double value = (pair.diagonal ? 1.0 : 2.0) *
493 params.magnitude * std::exp(-0.5 * distance);
494 const double direct_weight = value * inverse;
495 const double product_weight = -direct_weight * inverse;
496 energy[0].add(value);
497 addScaled(gradient[0], direct_weight, pair.direct);
498 addScaled(gradient[0], product_weight, pair.projection_product);
499 const auto derivative = 1 + params.species_index.at(pair.element);
500 energy[derivative].addProduct(value, distance);
501 addScaled(gradient[derivative], direct_weight * (distance - 2.0),
502 pair.direct);
503 addScaled(gradient[derivative], product_weight * (distance - 4.0),
504 pair.projection_product);
505 }
506 Vector result = Vector::Zero(parameters() + 1);
507 for (std::size_t index = 0; index < energy.size(); ++index) {
508 PriorSum weighted;
509 addScaled(weighted, 1.0 / params.energy_noise, energy[index]);
510 addScaled(weighted, 1.0 / params.gradient_noise, gradient[index]);
511 result(index) = weighted.value();
512 }
513 result(1) = result(0);
514 PriorSum energy_noise, gradient_noise;
515 addScaled(energy_noise, -1.0 / params.energy_noise, energy[0]);
516 addScaled(gradient_noise, -1.0 / params.gradient_noise, gradient[0]);
517 result(parameters() - 1) = energy_noise.value();
518 result(parameters()) = gradient_noise.value();
519 return result;
520 }
521
522 Parameters parse(const Vector& theta) const
523 {
524 if (!prepared)
525 throw std::logic_error("atomic observations are not prepared");
526 if (theta.size() != parameters() || !theta.allFinite())
527 throw std::invalid_argument("invalid atomic posterior parameters");
528 Parameters result;
529 result.magnitude = std::exp(theta(0));
530 result.energy_noise = std::exp(theta(theta.size() - 2));
531 result.gradient_noise = std::exp(theta(theta.size() - 1));
532 if (!(result.magnitude > 0.0) || !std::isfinite(result.magnitude) ||
533 !(result.energy_noise > 0.0) ||
534 !std::isfinite(result.energy_noise) ||
535 !std::isfinite(1.0 / result.energy_noise) ||
536 !(result.gradient_noise > 0.0) ||
537 !std::isfinite(result.gradient_noise) ||
538 !std::isfinite(1.0 / result.gradient_noise))
539 throw std::invalid_argument("invalid atomic covariance scale");
540 for (Eigen::Index index = 0;
541 index < static_cast<Eigen::Index>(species.size()); ++index) {
542 const double length = std::exp(theta(index + 1));
543 const double inverse = 1.0 / (length * length);
544 if (!(length > 0.0) || !std::isfinite(length) || !(inverse > 0.0) ||
545 !std::isfinite(inverse))
546 throw std::invalid_argument("invalid atomic length scale");
547 result.lengths.emplace(species[index], length);
548 result.species_index.emplace(species[index], index + 1);
549 }
550 return result;
551 }
552
553 std::vector<Matrix> inducingKernel(const Parameters& params) const
554 {
555 const Eigen::Index m = basis.values.rows();
556 std::vector<Matrix> matrices(1 + parameters(), Matrix::Zero(m, m));
557 for (Eigen::Index a = 0; a < m; ++a)
558 for (Eigen::Index b = 0; b <= a; ++b) {
559 const int element = basis.atomic_numbers[a];
560 if (element != basis.atomic_numbers[b]) continue;
561 const double length = params.lengths.at(element);
562 const double distance =
563 (basis.values.row(a) - basis.values.row(b)).squaredNorm() /
564 (length * length);
565 const double value =
566 params.magnitude * std::exp(-0.5 * distance);
567 matrices[0](a, b) = matrices[0](b, a) = value;
568 matrices[1](a, b) = matrices[1](b, a) = value;
569 const auto derivative = 1 + params.species_index.at(element);
570 matrices[derivative](a, b) = matrices[derivative](b, a) =
571 value * distance;
572 }
573 matrices[0].diagonal().array() += params.magnitude * relative_jitter;
574 matrices[1].diagonal().array() += params.magnitude * relative_jitter;
575 return matrices;
576 }
577
578 static Matrix whitenRows(const Matrix& rows, const Matrix& lower)
579 {
580 Matrix transposed = rows.transpose();
582 lower.data(), lower.outerStride(), true, transposed.data(),
583 transposed.outerStride(), lower.rows(), transposed.cols());
584 return transposed.transpose();
585 }
586
587 Whitening whitening(const Parameters& params) const
588 {
589 const auto kernel = inducingKernel(params);
590 Matrix factor = kernel[0];
592 factor.data(), factor.outerStride(), factor.rows()))
593 throw std::runtime_error(
594 "atomic inducing covariance is not positive definite");
595 Whitening result;
596 result.lower = factor.triangularView<Eigen::Lower>();
597 result.derivative.assign(
598 1 + species.size(),
599 Matrix::Zero(basis.values.rows(), basis.values.rows()));
600 // A scales with magnitude, including its relative regularization.
601 result.derivative[0].diagonal().setConstant(0.5);
602 for (std::size_t parameter = 1; parameter < result.derivative.size();
603 ++parameter) {
604 Matrix left = kernel[parameter + 1];
606 result.lower.data(), result.lower.outerStride(), true,
607 left.data(), left.outerStride(), result.lower.rows(),
608 left.cols());
609 const Matrix normalized = whitenRows(left, result.lower);
610 result.derivative[parameter] =
611 normalized.triangularView<Eigen::Lower>();
612 result.derivative[parameter].diagonal() *= 0.5;
613 }
614 return result;
615 }
616
617 std::vector<Matrix> crossRows(const Environment& cached,
618 const Parameters& params, bool derivatives,
619 bool energy_only = false) const
620 {
621 const auto& environment = cached;
622 const Eigen::Index m = basis.values.rows();
623 const Eigen::Index d = energy_only ? 0 : dimensions();
624 const Eigen::Index count = derivatives ? 2 + species.size() : 1;
625 std::vector<Matrix> rows(count, Matrix::Zero(d + 1, m));
626 for (Eigen::Index atom = 0; atom < environment.values.rows(); ++atom) {
627 const int element = environment.atomic_numbers[atom];
628 const double length = params.lengths.at(element);
629 const double inverse = 1.0 / (length * length);
630 for (Eigen::Index center = 0; center < m; ++center) {
631 if (element != basis.atomic_numbers[center]) continue;
632 const Vector delta =
633 (environment.values.row(atom) - basis.values.row(center))
634 .transpose();
635 const double distance = inverse * delta.squaredNorm();
636 const double value =
637 params.magnitude * std::exp(-0.5 * distance);
638 rows[0](0, center) += value;
639 const auto derivative = 1 + params.species_index.at(element);
640 if (derivatives)
641 rows[derivative](0, center) += value * distance;
642 if (energy_only) continue;
643 for (std::size_t index = 0; index < cached.support[atom].size();
644 ++index) {
645 const Eigen::Index row = cached.support[atom][index];
646 const double gradient =
647 -value * inverse *
648 environment.jacobians[atom].row(index).dot(delta);
649 rows[0](row + 1, center) += gradient;
650 if (derivatives)
651 rows[derivative](row + 1, center) +=
652 (distance - 2.0) * gradient;
653 }
654 }
655 }
656 if (derivatives) rows[1] = rows[0];
657 return rows;
658 }
659
661 std::vector<Vector> priorDiagonal(const Environment& cached,
662 const Parameters& params,
663 bool derivatives,
664 bool energy_only = false) const
665 {
666 const auto& environment = cached;
667 const Eigen::Index d = energy_only ? 0 : dimensions();
668 std::vector<std::vector<PriorSum>> sums(
669 derivatives ? 2 + species.size() : 1, std::vector<PriorSum>(d + 1));
670 for (Eigen::Index a = 0; a < environment.values.rows(); ++a)
671 for (Eigen::Index b = 0; b <= a; ++b) {
672 const int element = environment.atomic_numbers[a];
673 if (element != environment.atomic_numbers[b]) continue;
674 const double length = params.lengths.at(element);
675 const double inverse = 1.0 / (length * length);
676 const Vector delta =
677 (environment.values.row(a) - environment.values.row(b))
678 .transpose();
679 const double distance = inverse * delta.squaredNorm();
680 const double value = (a == b ? 1.0 : 2.0) * params.magnitude *
681 std::exp(-0.5 * distance);
682 const double direct_weight = value * inverse;
683 const double product_weight = -direct_weight * inverse;
684 sums[0][0].add(value);
685 const auto derivative = 1 + params.species_index.at(element);
686 if (derivatives)
687 sums[derivative][0].addProduct(value, distance);
688 if (energy_only) continue;
689 const auto& left = cached.support[a];
690 const auto& right = cached.support[b];
691 std::size_t ia = 0, ib = 0;
692 while (ia < left.size() && ib < right.size()) {
693 if (left[ia] < right[ib]) {
694 ++ia;
695 continue;
696 }
697 if (right[ib] < left[ia]) {
698 ++ib;
699 continue;
700 }
701 const Eigen::Index row = left[ia];
702 const auto ja = environment.jacobians[a].row(ia);
703 const auto jb = environment.jacobians[b].row(ib);
704 const PriorSum direct = compensatedDot(ja, jb);
705 const PriorSum dl = compensatedDot(ja, delta);
706 const PriorSum dr = compensatedDot(jb, delta);
707 addScaled(sums[0][row + 1], direct_weight, direct);
708 addScaledProduct(sums[0][row + 1], product_weight, dl, dr);
709 if (derivatives) {
710 addScaled(sums[derivative][row + 1],
711 direct_weight * (distance - 2.0), direct);
712 addScaledProduct(sums[derivative][row + 1],
713 product_weight * (distance - 4.0), dl,
714 dr);
715 }
716 ++ia;
717 ++ib;
718 }
719 }
720 std::vector<Vector> diagonal(sums.size(), Vector(d + 1));
721 for (std::size_t channel = 0; channel < sums.size(); ++channel)
722 for (Eigen::Index row = 0; row <= d; ++row)
723 diagonal[channel](row) = sums[channel][row].value();
724 if (derivatives) diagonal[1] = diagonal[0];
725 return diagonal;
726 }
727
728 Matrix priorBlock(const Environment& left, const Environment& right,
729 const Parameters& params) const
730 {
731 const Eigen::Index channels = dimensions() + 1;
732 std::vector<PriorSum> sums(channels * channels);
733 const auto entry = [&](Eigen::Index row,
734 Eigen::Index column) -> PriorSum& {
735 return sums[column * channels + row];
736 };
737 for (Eigen::Index a = 0; a < left.values.rows(); ++a)
738 for (Eigen::Index b = 0; b < right.values.rows(); ++b) {
739 const int element = left.atomic_numbers[a];
740 if (element != right.atomic_numbers[b]) continue;
741 const double length = params.lengths.at(element);
742 const double inverse = 1.0 / (length * length);
743 const Vector delta =
744 (left.values.row(a) - right.values.row(b)).transpose();
745 const double value =
746 params.magnitude *
747 std::exp(-0.5 * inverse * delta.squaredNorm());
748 const double direct_weight = value * inverse;
749 const double product_weight = -direct_weight * inverse;
750 const auto& ja = left.jacobians[a];
751 const auto& jb = right.jacobians[b];
752 std::vector<PriorSum> dl(ja.rows()), dr(jb.rows());
753 for (Eigen::Index row = 0; row < ja.rows(); ++row)
754 dl[row] = compensatedDot(ja.row(row), delta);
755 for (Eigen::Index row = 0; row < jb.rows(); ++row)
756 dr[row] = compensatedDot(jb.row(row), delta);
757 entry(0, 0).add(value);
758 for (std::size_t i = 0; i < left.support[a].size(); ++i) {
759 const Eigen::Index row = 1 + left.support[a][i];
760 addScaled(entry(row, 0), -direct_weight, dl[i]);
761 for (std::size_t j = 0; j < right.support[b].size(); ++j) {
762 auto& gradient = entry(row, 1 + right.support[b][j]);
763 addScaled(gradient, direct_weight,
764 compensatedDot(ja.row(i), jb.row(j)));
765 addScaledProduct(gradient, product_weight, dl[i],
766 dr[j]);
767 }
768 }
769 for (std::size_t j = 0; j < right.support[b].size(); ++j)
770 addScaled(entry(0, 1 + right.support[b][j]), direct_weight,
771 dr[j]);
772 }
773 Matrix block(channels, channels);
774 for (Eigen::Index column = 0; column < channels; ++column)
775 for (Eigen::Index row = 0; row < channels; ++row)
776 block(row, column) = entry(row, column).value();
777 return block;
778 }
779
781 const Whitening& transform) const
782 {
783 const Eigen::Index m = basis.values.rows(), p = parameters(),
784 d = dimensions();
785 Statistics result{Matrix::Zero(m, m),
786 Vector::Zero(m),
787 std::vector<Matrix>(p, Matrix::Zero(m, m)),
788 std::vector<Vector>(p, Vector::Zero(m)),
789 Vector::Zero(p + 1),
790 Vector::Zero(p + 1)};
791 std::size_t entry_count = 0;
792 result.visit([&](double&) { ++entry_count; });
793 std::vector<linalg::ExactSum> exact(entry_count);
794 std::exception_ptr failure;
795 try {
796 [[maybe_unused]] const SerialEigenProducts serial_products;
797 Vector precision =
798 Vector::Constant(d + 1, 1.0 / params.gradient_noise);
799 precision(0) = 1.0 / params.energy_noise;
800 for (const auto& [index, environment, prior_trace]:
802 Statistics contribution{
803 Matrix::Zero(m, m),
804 Vector::Zero(m),
805 std::vector<Matrix>(p, Matrix::Zero(m, m)),
806 std::vector<Vector>(p, Vector::Zero(m)),
807 Vector::Zero(p + 1),
808 Vector::Zero(p + 1)};
809 auto cross = crossRows(environment, params, true);
810 cross[0] = whitenRows(cross[0], transform.lower);
811 for (std::size_t parameter = 0;
812 parameter < transform.derivative.size(); ++parameter) {
813 cross[parameter + 1] =
814 whitenRows(cross[parameter + 1], transform.lower);
816 cross[parameter + 1], cross[0],
817 transform.derivative[parameter]);
818 }
819 contribution.prior_trace = priorTrace(prior_trace, params);
820 Vector target(d + 1);
821 target(0) = observations.E.data()[index] - energy_reference;
822 target.tail(d) = observations.G.row(index).transpose();
823 const Vector weighted_target = precision.cwiseProduct(target);
824 const Matrix weighted_cross = precision.asDiagonal() * cross[0];
826 contribution.gram.data(), contribution.gram.outerStride(),
827 cross[0].data(), cross[0].outerStride(),
828 weighted_cross.data(), weighted_cross.outerStride(), m, m,
829 d + 1, 1.0, true, false);
830 contribution.rhs.noalias() +=
831 cross[0].transpose() * weighted_target;
832 contribution.target_norm(0) += target.dot(weighted_target);
833 for (Eigen::Index parameter = 0;
834 parameter < static_cast<Eigen::Index>(species.size()) + 1;
835 ++parameter) {
836 Matrix term = Matrix::Zero(m, m);
838 term.data(), term.outerStride(),
839 cross[parameter + 1].data(),
840 cross[parameter + 1].outerStride(),
841 weighted_cross.data(), weighted_cross.outerStride(), m,
842 m, d + 1, 1.0, true, false);
843 contribution.dgram[parameter] += term + term.transpose();
844 contribution.drhs[parameter].noalias() +=
845 cross[parameter + 1].transpose() * weighted_target;
846 }
847 for (const bool gradient: {false, true}) {
848 const Eigen::Index parameter = p - (gradient ? 1 : 2);
849 const Eigen::Index offset = gradient ? 1 : 0;
850 const Eigen::Index count = gradient ? d : 1;
851 const auto block = cross[0].middleRows(offset, count);
852 const auto weighted_block =
853 weighted_cross.middleRows(offset, count);
855 contribution.dgram[parameter].data(),
856 contribution.dgram[parameter].outerStride(),
857 block.data(), block.outerStride(),
858 weighted_block.data(), weighted_block.outerStride(), m,
859 m, count, -1.0, true, false);
860 contribution.drhs[parameter].noalias() -=
861 block.transpose() *
862 weighted_target.segment(offset, count);
863 contribution.target_norm(parameter + 1) -=
864 target.segment(offset, count)
865 .dot(weighted_target.segment(offset, count));
866 }
867 // Each addend has a fixed configuration-sized evaluation;
868 // exact merging preserves it across every MPI partition.
869 std::size_t entry = 0;
870 contribution.visit([&](double value) {
871 if (!std::isfinite(value))
872 throw std::runtime_error(
873 "atomic fit statistics are not finite");
874 exact[entry++].add(value);
875 });
876 }
877 } catch (...) {
878 failure = std::current_exception();
879 }
880 shareFailure(context(), failure);
881 constexpr std::size_t chunk = 4096;
882 for (std::size_t offset = 0; offset < exact.size(); offset += chunk)
884 exact.data() + offset,
885 static_cast<int>(std::min(chunk, exact.size() - offset)),
886 context());
887 std::size_t entry = 0;
888 result.visit([&](double& value) { value = exact[entry++].value(); });
889 result.gram = result.gram.selfadjointView<Eigen::Lower>();
890 for (auto& derivative: result.dgram)
891 derivative = derivative.selfadjointView<Eigen::Lower>();
892 return result;
893 }
894
895 Evaluation evaluate(const Vector& theta) const
896 {
897 Parameters params;
898 Whitening transform;
899 std::exception_ptr failure;
900 try {
901 [[maybe_unused]] const SerialEigenProducts serial_products;
902 params = parse(theta);
903 transform = whitening(params);
904 } catch (...) {
905 failure = std::current_exception();
906 }
907 shareFailure(context(), failure);
908 const auto sums = statistics(params, transform);
909 // Every collective of this evaluation is behind us; what follows is
910 // local to the rank.
911 [[maybe_unused]] const SerialEigenProducts serial_products;
912 auto posterior = std::make_unique<SerialCholesky>();
913 Matrix covariance = sums.gram;
914 covariance.diagonal().array() += 1.0;
915 if (!posterior->factorise(covariance))
916 throw std::runtime_error(
917 "atomic whitened covariance is not positive definite");
918 const Vector beta = posterior->solve(sums.rhs);
919 const double gap = nonnegativeVariance(
920 sums.prior_trace(0) - sums.gram.trace(), sums.prior_trace(0));
921 const double n = static_cast<double>(observations.R.rows());
922 const double d = static_cast<double>(dimensions());
923 const double log_noise = n * (std::log(params.energy_noise) +
924 d * std::log(params.gradient_noise));
925 Objective objective;
926 objective.trace_penalty = 0.5 * gap;
927 objective.value =
928 0.5 * (sums.target_norm(0) - sums.rhs.dot(beta) +
929 posterior->log_det() + log_noise +
930 n * (d + 1.0) * std::log(2.0 * std::numbers::pi) + gap);
931 objective.gradient.resize(parameters());
932 for (Eigen::Index parameter = 0; parameter < parameters();
933 ++parameter) {
934 const Matrix& change = sums.dgram[parameter];
935 const double log_noise_derivative =
936 parameter == parameters() - 2 ? n
937 : parameter == parameters() - 1 ? n * d
938 : 0.0;
939 objective.gradient(parameter) =
940 0.5 *
941 (sums.target_norm(parameter + 1) -
942 2.0 * sums.drhs[parameter].dot(beta) +
943 beta.dot(change * beta) + posterior->trace_inv_times(change) +
944 log_noise_derivative + sums.prior_trace(parameter + 1) -
945 change.trace());
946 }
947 if (!std::isfinite(objective.value) ||
948 !objective.gradient.allFinite() || !beta.allFinite())
949 throw std::runtime_error(
950 "atomic variational objective is not finite");
951 return {std::move(objective), std::move(params),
952 std::move(transform.lower), std::move(posterior), beta};
953 }
954
955 Environment query(const Eigen::VectorXd& position) const
956 {
957 requireFit();
958 if (position.size() != dimensions() || !position.allFinite())
959 throw std::invalid_argument("invalid atomic posterior query");
960 return descriptorRows(position);
961 }
962 Environment queryValues(const Eigen::VectorXd& position) const
963 {
964 requireFit();
965 if (position.size() != dimensions() || !position.allFinite())
966 throw std::invalid_argument("invalid atomic posterior query");
968 return descriptorRows(position);
969 auto environment =
972 validateValues(environment);
973 else
974 validateEnvironment(environment);
975 return {std::move(environment.atomic_numbers),
976 std::move(environment.values),
977 {},
978 {}};
979 }
980 void validateQueries(const EigenMatrix& positions) const
981 {
982 requireFit();
983 if (positions.cols() != dimensions() || !positions.allFinite())
984 throw std::invalid_argument(
985 "invalid atomic posterior query layout");
986 }
987};
988
990 std::shared_ptr<const linalg::MpiCommunicator> communication)
991 : impl_(std::make_unique<Impl>())
992{
993 impl_->communication = std::move(communication);
994}
997 AtomicInducingPosterior&&) noexcept = default;
999 AtomicInducingPosterior&&) noexcept = default;
1000
1002 const Observation& observations,
1003 SpeciesEnvironmentKernel::Descriptor descriptor, Basis basis,
1004 double inducing_relative_jitter, std::optional<double> energy_reference,
1005 SpeciesEnvironmentKernel::Descriptor values_descriptor,
1006 SpeciesEnvironmentKernel::SupportedDescriptor supported_descriptor)
1007{
1008 invalidate();
1009 std::exception_ptr failure;
1010 try {
1011 detail::requireJointTrainingObservation(observations,
1012 "atomic inducing posterior");
1013 if ((!descriptor && !supported_descriptor) ||
1014 basis.values.rows() <= 0 || basis.values.cols() <= 0 ||
1015 basis.atomic_numbers.size() !=
1016 static_cast<std::size_t>(basis.values.rows()) ||
1017 !basis.values.allFinite() || !(inducing_relative_jitter >= 0.0) ||
1018 !std::isfinite(inducing_relative_jitter) ||
1019 (energy_reference && !std::isfinite(*energy_reference)))
1020 throw std::invalid_argument("invalid atomic inducing basis");
1021 std::set<int> species(basis.atomic_numbers.begin(),
1022 basis.atomic_numbers.end());
1023 if (*species.begin() <= 0)
1024 throw std::invalid_argument("invalid atomic inducing species");
1025 impl_->observations = observations;
1026 impl_->descriptor = std::move(descriptor);
1027 impl_->values_descriptor = std::move(values_descriptor);
1028 impl_->supported_descriptor = std::move(supported_descriptor);
1029 impl_->basis = std::move(basis);
1030 impl_->species.assign(species.begin(), species.end());
1031 impl_->relative_jitter = inducing_relative_jitter;
1032 impl_->energy_reference =
1033 energy_reference.value_or(observations.E.data()[0]);
1034 const auto context = impl_->context();
1035 for (Eigen::Index row = context.rank; row < observations.R.rows();
1036 row += context.nprocs) {
1037 auto environment =
1038 impl_->descriptorRows(observations.R.row(row).transpose());
1039 auto prior_trace = impl_->cachePriorTrace(environment);
1040 impl_->local_environments.push_back(
1041 {row, std::move(environment), std::move(prior_trace)});
1042 }
1043 } catch (...) {
1044 failure = std::current_exception();
1045 }
1046 try {
1047 shareFailure(impl_->context(), failure);
1048 } catch (...) {
1049 invalidate();
1050 throw;
1051 }
1052 impl_->prepared = true;
1053}
1054
1056 const noexcept
1057{
1058 return impl_->species;
1059}
1061 double magnitude_variance,
1063 double energy_noise_variance, double gradient_noise_variance) const
1064{
1065 Vector theta(impl_->parameters());
1066 theta(0) = std::log(magnitude_variance);
1067 for (Eigen::Index index = 0;
1068 index < static_cast<Eigen::Index>(impl_->species.size()); ++index)
1069 theta(index + 1) = std::log(lengths.at(impl_->species[index]));
1070 theta(theta.size() - 2) = std::log(energy_noise_variance);
1071 theta(theta.size() - 1) = std::log(gradient_noise_variance);
1072 (void)impl_->parse(theta);
1073 return theta;
1074}
1076 const Vector& theta) const
1077{
1078 impl_->clearPending();
1079 try {
1080 auto evaluation = impl_->evaluate(theta);
1081 Objective objective = evaluation.objective;
1082 impl_->retainEvaluation(theta, std::move(evaluation));
1083 return objective;
1084 } catch (const std::exception&) {
1085 impl_->clearPending();
1086 return {std::numeric_limits<double>::infinity(),
1087 Vector::Constant(impl_->parameters(),
1088 std::numeric_limits<double>::quiet_NaN()),
1089 std::numeric_limits<double>::infinity()};
1090 }
1091}
1092bool AtomicInducingPosterior::fit(const Vector& theta)
1093{
1094 impl_->clearFit();
1095 try {
1096 auto pending = impl_->takePending(theta);
1097 int reuse = pending ? 1 : 0;
1098#if defined(GPR_HAVE_MPI) || defined(GPR_LINALG_SCALAPACK)
1099 const auto context = impl_->context();
1100 if (context.is_distributed() &&
1101 MPI_Allreduce(MPI_IN_PLACE, &reuse, 1, MPI_INT, MPI_MIN,
1102 context.comm) != MPI_SUCCESS)
1103 throw std::runtime_error("could not share atomic fit reuse status");
1104#endif
1105 // Every rank follows the same collective sequence even when only some
1106 // ranks retain an evaluation at the requested parameters.
1107 if (!reuse) pending.reset();
1108 auto evaluation =
1109 reuse ? std::move(pending->evaluation) : impl_->evaluate(theta);
1110 impl_->fitted_parameters = std::move(evaluation.parameters);
1111 impl_->inducing_lower = std::move(evaluation.inducing_lower);
1112 impl_->posterior_factor = std::move(evaluation.posterior);
1113 impl_->coefficients = std::move(evaluation.coefficients);
1114 impl_->fitted = true;
1115 return true;
1116 } catch (const std::exception&) {
1117 impl_->clearPending();
1118 return false;
1119 }
1120}
1122{
1123 return impl_->fitted;
1124}
1126{
1127 impl_->clearPending();
1128 impl_->clearFit();
1129 impl_->prepared = false;
1130 impl_->observations.clear();
1131 impl_->descriptor = {};
1132 impl_->values_descriptor = {};
1133 impl_->supported_descriptor = {};
1134 impl_->basis = {};
1135 impl_->species.clear();
1136 impl_->local_environments.clear();
1137}
1139{
1140 return impl_->observations.R.rows() * (impl_->dimensions() + 1);
1141}
1142Eigen::Index AtomicInducingPosterior::inducingCount() const noexcept
1143{
1144 return impl_->basis.values.rows();
1145}
1147{
1148 std::size_t elements = 0;
1149 for (const auto& cached: impl_->local_environments)
1150 for (const auto& jacobian: cached.environment.jacobians)
1151 elements += static_cast<std::size_t>(jacobian.size());
1152 return elements;
1153}
1154
1156 const Eigen::VectorXd& position) const
1157{
1158 const auto environment = impl_->query(position);
1159 double inverse_length = 0.0;
1160 for (std::size_t atom = 0; atom < environment.support.size(); ++atom) {
1161 double norm = 0.0;
1162 const auto& jacobian = environment.jacobians[atom];
1163 for (Eigen::Index row = 0; row < jacobian.rows(); ++row)
1164 norm = std::hypot(norm, jacobian.row(row).norm());
1165 inverse_length = std::max(inverse_length,
1166 norm / impl_->fitted_parameters.lengths.at(
1167 environment.atomic_numbers[atom]));
1168 }
1169 if (!std::isfinite(inverse_length))
1170 throw std::runtime_error("atomic Cartesian length scale is not finite");
1171 return inverse_length;
1172}
1173
1175{
1176 impl_->validateQueries(image.R);
1177 image.E.resize(1, image.R.rows());
1178 image.G.resize(image.R.rows(), image.R.cols());
1179 std::vector<Impl::Environment> environments;
1180 environments.reserve(static_cast<std::size_t>(image.R.rows()));
1181 for (Eigen::Index row = 0; row < image.R.rows(); ++row)
1182 environments.push_back(impl_->query(image.R.row(row).transpose()));
1183
1184 [[maybe_unused]] const SerialEigenProducts serial_products;
1185 for (Eigen::Index row = 0; row < image.R.rows(); ++row) {
1186 const Matrix cross = Impl::whitenRows(
1187 impl_->crossRows(environments[row], impl_->fitted_parameters,
1188 false)[0],
1189 impl_->inducing_lower);
1190 if (cross.cols() > std::numeric_limits<int>::max() ||
1191 cross.rows() > std::numeric_limits<int>::max())
1192 throw std::length_error("atomic prediction product is too large");
1193 const Matrix columns = cross.transpose();
1194 std::vector<linalg::StoredProduct> products(cross.rows());
1195 for (Eigen::Index channel = 0; channel < cross.rows(); ++channel)
1196 products[channel] = {columns.col(channel).data(),
1197 impl_->coefficients.data(),
1198 static_cast<int>(cross.cols())};
1199 Vector mean(cross.rows());
1200 linalg::evaluateStoredProducts(products.data(),
1201 static_cast<int>(products.size()),
1202 linalg::productMode(), mean.data());
1203 image.E(0, row) = impl_->energy_reference + mean(0);
1204 image.G.row(row) = mean.tail(impl_->dimensions()).transpose();
1205 }
1206}
1208{
1209 impl_->validateQueries(image.R);
1210 image.E.resize(1, image.R.rows());
1211 image.G.resize(image.R.rows(), image.R.cols());
1212 std::vector<Impl::Environment> environments;
1213 environments.reserve(static_cast<std::size_t>(image.R.rows()));
1214 for (Eigen::Index row = 0; row < image.R.rows(); ++row)
1215 environments.push_back(impl_->query(image.R.row(row).transpose()));
1216
1217 [[maybe_unused]] const SerialEigenProducts serial_products;
1218 for (Eigen::Index row = 0; row < image.R.rows(); ++row) {
1219 const Matrix cross = Impl::whitenRows(
1220 impl_->crossRows(environments[row], impl_->fitted_parameters,
1221 false)[0],
1222 impl_->inducing_lower);
1223 const Vector prior = impl_->priorDiagonal(
1224 environments[row], impl_->fitted_parameters, false)[0];
1225 const Matrix correction =
1226 impl_->posterior_factor->solve_mat(cross.transpose()) -
1227 cross.transpose();
1228 Vector variance =
1229 prior + cross.cwiseProduct(correction.transpose()).rowwise().sum();
1230 for (Eigen::Index channel = 0; channel < variance.size(); ++channel)
1231 variance(channel) =
1232 nonnegativeVariance(variance(channel), prior(channel));
1233 image.E(0, row) = variance(0);
1234 image.G.row(row) = variance.tail(impl_->dimensions()).transpose();
1235 }
1236}
1238 const EigenMatrix& positions, Eigen::RowVectorXd& variance) const
1239{
1240 impl_->validateQueries(positions);
1241 variance.resize(positions.rows());
1242 std::vector<Impl::Environment> environments;
1243 environments.reserve(static_cast<std::size_t>(positions.rows()));
1244 for (Eigen::Index row = 0; row < positions.rows(); ++row)
1245 environments.push_back(
1246 impl_->queryValues(positions.row(row).transpose()));
1247
1248 [[maybe_unused]] const SerialEigenProducts serial_products;
1249 for (Eigen::Index row = 0; row < positions.rows(); ++row) {
1250 const Matrix cross = Impl::whitenRows(
1251 impl_->crossRows(environments[row], impl_->fitted_parameters, false,
1252 true)[0],
1253 impl_->inducing_lower);
1254 const double prior = impl_->priorDiagonal(
1255 environments[row], impl_->fitted_parameters, false, true)[0](0);
1256 const Matrix correction =
1257 impl_->posterior_factor->solve_mat(cross.transpose()) -
1258 cross.transpose();
1259 const double value =
1260 prior + cross.cwiseProduct(correction.transpose()).sum();
1261 variance(row) = nonnegativeVariance(value, prior);
1262 }
1263}
1265 EigenMatrix& covariance) const
1266{
1267 impl_->validateQueries(positions);
1268 const Eigen::Index n = positions.rows(), d = impl_->dimensions();
1269 std::vector<Impl::Environment> environments;
1270 environments.reserve(static_cast<std::size_t>(n));
1271 for (Eigen::Index row = 0; row < n; ++row)
1272 environments.push_back(impl_->query(positions.row(row).transpose()));
1273
1274 [[maybe_unused]] const SerialEigenProducts serial_products;
1275 Matrix cross(n * (d + 1), impl_->basis.values.rows());
1276 for (Eigen::Index row = 0; row < n; ++row) {
1277 const Matrix block = Impl::whitenRows(
1278 impl_->crossRows(environments[row], impl_->fitted_parameters,
1279 false)[0],
1280 impl_->inducing_lower);
1281 for (Eigen::Index channel = 0; channel <= d; ++channel)
1282 cross.row(channel * n + row) = block.row(channel);
1283 }
1284 covariance.resize(n * (d + 1), n * (d + 1));
1285 for (Eigen::Index i = 0; i < n; ++i)
1286 for (Eigen::Index j = 0; j <= i; ++j) {
1287 const Matrix block = impl_->priorBlock(
1288 environments[i], environments[j], impl_->fitted_parameters);
1289 for (Eigen::Index a = 0; a <= d; ++a)
1290 for (Eigen::Index b = 0; b <= d; ++b) {
1291 covariance(a * n + i, b * n + j) = block(a, b);
1292 covariance(b * n + j, a * n + i) = block(a, b);
1293 }
1294 }
1295 const Vector prior = covariance.diagonal();
1296 const Matrix delta = impl_->posterior_factor->solve_mat(cross.transpose()) -
1297 cross.transpose();
1299 covariance.data(), covariance.outerStride(), cross.data(),
1300 cross.outerStride(), delta.data(), delta.outerStride(),
1301 covariance.rows(), covariance.cols(), cross.cols(), 1.0, false, false);
1302 covariance = 0.5 * (covariance + covariance.transpose()).eval();
1303 for (Eigen::Index index = 0; index < covariance.rows(); ++index)
1304 covariance(index, index) =
1305 nonnegativeVariance(covariance(index, index), prior(index));
1306}
1308 const Vector& weights) const
1309{
1310 impl_->validateQueries(positions);
1311 const Eigen::Index n = positions.rows(), d = impl_->dimensions();
1312 if (weights.size() != n * (d + 1) || !weights.allFinite())
1313 throw std::invalid_argument("invalid atomic functional weights");
1314 std::vector<Impl::Environment> environments;
1315 environments.reserve(static_cast<std::size_t>(n));
1316 for (Eigen::Index row = 0; row < n; ++row)
1317 environments.push_back(impl_->query(positions.row(row).transpose()));
1318
1319 [[maybe_unused]] const SerialEigenProducts serial_products;
1320 std::vector<std::vector<std::vector<PriorSum>>> projected;
1321 Vector inducing = Vector::Zero(impl_->basis.values.rows());
1322 for (Eigen::Index row = 0; row < n; ++row) {
1323 Vector local(d + 1);
1324 for (Eigen::Index channel = 0; channel <= d; ++channel)
1325 local(channel) = weights(channel * n + row);
1326 const Matrix cross = Impl::whitenRows(
1327 impl_->crossRows(environments[row], impl_->fitted_parameters,
1328 false)[0],
1329 impl_->inducing_lower);
1330 inducing.noalias() += cross.transpose() * local;
1331 projected.emplace_back();
1332 const auto& environment = environments[row];
1333 for (std::size_t atom = 0; atom < environment.jacobians.size();
1334 ++atom) {
1335 const auto& support = environment.support[atom];
1336 const auto& jacobian = environment.jacobians[atom];
1337 std::vector<PriorSum> features(jacobian.cols());
1338 for (std::size_t index = 0; index < support.size(); ++index)
1339 for (Eigen::Index feature = 0; feature < jacobian.cols();
1340 ++feature)
1341 features[feature].addProduct(jacobian(index, feature),
1342 local(1 + support[index]));
1343 projected.back().push_back(std::move(features));
1344 }
1345 }
1346 PriorSum prior;
1347 for (Eigen::Index i = 0; i < n; ++i)
1348 for (Eigen::Index j = 0; j < n; ++j)
1349 for (Eigen::Index a = 0; a < environments[i].values.rows(); ++a)
1350 for (Eigen::Index b = 0; b < environments[j].values.rows();
1351 ++b) {
1352 const int element = environments[i].atomic_numbers[a];
1353 if (element != environments[j].atomic_numbers[b]) continue;
1354 const double length =
1355 impl_->fitted_parameters.lengths.at(element);
1356 const double inverse = 1.0 / (length * length);
1357 const Vector delta = (environments[i].values.row(a) -
1358 environments[j].values.row(b))
1359 .transpose();
1360 const double kernel =
1361 impl_->fitted_parameters.magnitude *
1362 std::exp(-0.5 * inverse * delta.squaredNorm());
1363 const auto& pi = projected[i][a];
1364 const auto& pj = projected[j][b];
1365 const PriorSum left = compensatedProjection(pi, delta);
1366 const PriorSum right = compensatedProjection(pj, delta);
1367 const double direct_weight = kernel * inverse;
1368 addTripleProduct(prior, kernel, weights(i), weights(j));
1369 addScaledProduct(prior, direct_weight,
1370 PriorSum{weights(i), 0.0}, right);
1371 addScaledProduct(prior, -direct_weight,
1372 PriorSum{weights(j), 0.0}, left);
1373 for (std::size_t feature = 0; feature < pi.size();
1374 ++feature)
1375 addScaledProduct(prior, direct_weight, pi[feature],
1376 pj[feature]);
1377 addScaledProduct(prior, -direct_weight * inverse, left,
1378 right);
1379 }
1380 const double prior_value = prior.value();
1381 const double value =
1382 prior_value +
1383 inducing.dot(impl_->posterior_factor->solve(inducing) - inducing);
1384 return nonnegativeVariance(value, prior_value);
1385}
1386} // namespace gpr
Abstract operator interface for K^{-1} actions used by Laplace Hessian probe loops and Williams-Rasmu...
bool fit(const Eigen::VectorXd &log_theta)
double inverseCartesianLengthScale(const Eigen::VectorXd &position) const
Eigen::VectorXd initialParameters(double magnitude_variance, const SpeciesEnvironmentKernel::LengthScales &lengths, double energy_noise_variance, double gradient_noise_variance) const
void prepare(const Observation &observations, SpeciesEnvironmentKernel::Descriptor descriptor, Basis basis, double inducing_relative_jitter=0.0, std::optional< double > energy_reference=std::nullopt, SpeciesEnvironmentKernel::Descriptor values_descriptor={}, SpeciesEnvironmentKernel::SupportedDescriptor supported_descriptor={})
double functionalVariance(const EigenMatrix &positions, const Eigen::VectorXd &weights) const
Eigen::Index inducingCount() const noexcept
void calculateCovariance(const EigenMatrix &positions, EigenMatrix &covariance) const
Joint layout: every energy, followed by each Cartesian gradient column.
void calculateVariance(Observation &image) const
std::size_t cachedJacobianElements() const noexcept
const std::vector< int > & parameterSpecies() const noexcept
Objective evaluate(const Eigen::VectorXd &log_theta) const
Eigen::Index observationCount() const noexcept
AtomicInducingPosterior(std::shared_ptr< const linalg::MpiCommunicator > communication={})
void calculateEnergyVariance(const EigenMatrix &positions, Eigen::RowVectorXd &variance) const
void calculatePotential(Observation &image) const
std::function< AtomicEnvironments(const Eigen::VectorXd &)> Descriptor
std::function< SupportedAtomicEnvironments(const Eigen::VectorXd &)> SupportedDescriptor
Eigen::MatrixXd Matrix
Eigen::VectorXd Vector
void solveLeftGeneral(const double *factor, std::ptrdiff_t factor_stride, bool lower_factor, double *rhs, std::ptrdiff_t rhs_stride, std::ptrdiff_t order, std::ptrdiff_t columns, ParallelItems run, void *run_context)
void addMatrixProduct(double *out, std::ptrdiff_t out_stride, const double *left, std::ptrdiff_t left_stride, const double *right, std::ptrdiff_t right_stride, std::ptrdiff_t rows, std::ptrdiff_t columns, std::ptrdiff_t depth, double scale, bool transpose_left, bool transpose_right)
bool factorLowerGeneral(double *matrix, std::ptrdiff_t stride, std::ptrdiff_t order, ParallelItems run, void *run_context)
void subtractProduct(Target &&out, const Left &left, const Right &right)
void evaluateStoredProducts(const StoredProduct *products, int count, ProductMode mode, double *values)
ProductMode productMode()
void exact_sum_bcast(ExactSum *sums, int count, const MpiContext &context)
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
STL namespace.
std::vector< Eigen::MatrixXd > jacobians
std::vector< std::vector< Eigen::Index > > support
void validateEnvironment(const AtomicEnvironments &environment) const
SpeciesEnvironmentKernel::Descriptor descriptor
Evaluation evaluate(const Vector &theta) const
Statistics statistics(const Parameters &params, const Whitening &transform) const
Environment cacheEnvironment(AtomicEnvironments environment) const
std::shared_ptr< const linalg::MpiCommunicator > communication
Environment query(const Eigen::VectorXd &position) const
Matrix priorBlock(const Environment &left, const Environment &right, const Parameters &params) const
std::unique_ptr< PendingEvaluation > pending_evaluation
Whitening whitening(const Parameters &params) const
Environment queryValues(const Eigen::VectorXd &position) const
void validateQueries(const EigenMatrix &positions) const
Vector priorTrace(const std::vector< PriorTracePair > &pairs, const Parameters &params) const
std::vector< Matrix > crossRows(const Environment &cached, const Parameters &params, bool derivatives, bool energy_only=false) const
std::vector< TrainingEnvironment > local_environments
Parameters parse(const Vector &theta) const
Environment descriptorRows(const Vector &position) const
std::unique_ptr< PendingEvaluation > takePending(const Vector &theta)
std::vector< Matrix > inducingKernel(const Parameters &params) const
SpeciesEnvironmentKernel::Descriptor values_descriptor
std::unique_ptr< linalg::KernelInverse > posterior_factor
Environment cacheEnvironment(SupportedAtomicEnvironments environment) const
SpeciesEnvironmentKernel::SupportedDescriptor supported_descriptor
void retainEvaluation(const Vector &theta, Evaluation evaluation)
std::vector< PriorTracePair > cachePriorTrace(const Environment &environment) const
std::vector< Vector > priorDiagonal(const Environment &cached, const Parameters &params, bool derivatives, bool energy_only=false) const
Direct prior diagonals require only vectors of Cartesian components.
void validateValues(const Environments &environment) const
static Matrix whitenRows(const Matrix &rows, const Matrix &lower)
Observation data: energy, gradient and positions.
FieldMatrixd E
std::vector< Eigen::MatrixXd > jacobians
std::vector< std::vector< Eigen::Index > > support
static MpiContext local() noexcept
Definition MpiContext.h:75