Loading...
Searching...
No Matches
KokkosMolecularPosterior.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
4
5#include <Eigen/Eigenvalues>
6#include <algorithm>
7#include <array>
8#include <cmath>
9#include <limits>
10#include <map>
11#include <stdexcept>
12#include <vector>
13
15#include "ExactSchur.h"
17#include "KokkosDeviceOps.h"
18#include "KokkosJointKernel.h"
19#include "TeamFactor.h"
20
21namespace gpr::linalg {
22namespace {
23using Exec = detail::exec_space;
26using Posterior = detail::KokkosDensePosterior<Exec>;
27using Spatial = Kokkos::View<double***, Kokkos::LayoutLeft, V::memory_space>;
28
29struct Cell {
30 int rank = 0;
31 double basis[3][3]{}, dual[3][3]{}, dual_norm[3]{};
32
33 explicit Cell(const double* cell)
34 {
35 Eigen::Matrix<double, 3, Eigen::Dynamic> matrix(3, 0);
36 for (int row = 0; row < 3; ++row) {
37 Eigen::Vector3d vector(cell[3 * row], cell[3 * row + 1],
38 cell[3 * row + 2]);
39 if (!vector.allFinite())
40 throw std::invalid_argument("cell must be finite");
41 if (vector.squaredNorm() == 0.0) continue;
42 matrix.conservativeResize(3, rank + 1);
43 matrix.col(rank++) = vector;
44 }
45 if (!rank) return;
46 const auto gram = (matrix.transpose() * matrix).eval();
47 Eigen::LDLT<Eigen::MatrixXd> factor(gram);
48 if (factor.info() != Eigen::Success || !factor.isPositive())
49 throw std::invalid_argument(
50 "periodic basis must have independent vectors");
51 const Eigen::MatrixXd inverse = factor.solve(matrix.transpose());
52 if (!inverse.allFinite() ||
53 !(inverse * matrix)
54 .isApprox(Eigen::MatrixXd::Identity(rank, rank), 1e-10))
55 throw std::invalid_argument(
56 "periodic dual is numerically singular");
57 for (int r = 0; r < rank; ++r) {
58 dual_norm[r] = inverse.row(r).norm();
59 for (int d = 0; d < 3; ++d) {
60 basis[r][d] = matrix(d, r);
61 dual[r][d] = inverse(r, d);
62 }
63 }
64 }
65
66 // The dual bounds every lattice coefficient of a shorter displacement,
67 // including cells whose closest image lies outside the adjacent 27 cells.
68 KOKKOS_INLINE_FUNCTION bool wrap(double* displacement) const
69 {
70 if (!rank) return true;
71 double fractional[3]{},
72 best[3]{displacement[0], displacement[1], displacement[2]};
73 for (int r = 0; r < rank; ++r) {
74 for (int d = 0; d < 3; ++d)
75 fractional[r] += dual[r][d] * displacement[d];
76 const double shift = Kokkos::floor(fractional[r] + 0.5);
77 for (int d = 0; d < 3; ++d)
78 best[d] -= shift * basis[r][d];
79 }
80 double best2 =
81 best[0] * best[0] + best[1] * best[1] + best[2] * best[2];
82 const double radius = Kokkos::sqrt(best2);
83 long long lo[3]{}, hi[3]{};
84 for (int r = 0; r < rank; ++r) {
85 const double bound = radius * dual_norm[r];
86 const double pad = 32 * std::numeric_limits<double>::epsilon() *
87 (1 + Kokkos::abs(fractional[r]) + bound);
88 const double a = Kokkos::ceil(fractional[r] - bound - pad);
89 const double b = Kokkos::floor(fractional[r] + bound + pad);
90 if (!Kokkos::isfinite(a) || !Kokkos::isfinite(b) || a < -9e18 ||
91 b > 9e18)
92 return false;
93 lo[r] = static_cast<long long>(a);
94 hi[r] = static_cast<long long>(b);
95 }
96 for (long long i = lo[0]; i <= hi[0]; ++i)
97 for (long long j = lo[1]; j <= hi[1]; ++j)
98 for (long long k = lo[2]; k <= hi[2]; ++k) {
99 const long long shifts[3]{i, j, k};
100 double candidate[3]{displacement[0], displacement[1],
101 displacement[2]};
102 for (int r = 0; r < rank; ++r)
103 for (int d = 0; d < 3; ++d)
104 candidate[d] -= shifts[r] * basis[r][d];
105 const double norm2 = candidate[0] * candidate[0] +
106 candidate[1] * candidate[1] +
107 candidate[2] * candidate[2];
108 if (norm2 < best2) {
109 best2 = norm2;
110 for (int d = 0; d < 3; ++d)
111 best[d] = candidate[d];
112 }
113 }
114 for (int d = 0; d < 3; ++d)
115 displacement[d] = best[d];
116 return true;
117 }
118};
119
120struct Pair {
121 int first = 0, second = 0, type = 0;
122 bool linear = false;
123 double centre[3]{}, slope[3]{};
124};
125struct DescriptorKernel {
126 V::matrix xyz, q;
127 Spatial spatial;
128 Kokkos::View<Pair*, V::memory_space> vocabulary;
129 V::matrix fixed;
130 Cell periodic;
131 int nm;
132 double R, shell;
133 Kokkos::View<int, V::memory_space> invalid;
134 KOKKOS_INLINE_FUNCTION void operator()(const int row, const int p) const
135 {
136 const auto pair = vocabulary(p);
137 double dr[3];
138 for (int d = 0; d < 3; ++d)
139 dr[d] = xyz(row, 3 * pair.first + d) -
140 (pair.linear ? pair.centre[d]
141 : pair.second < nm ? xyz(row, 3 * pair.second + d)
142 : fixed(pair.second - nm, d));
143 bool ok = periodic.wrap(dr);
144 double r2 = 0;
145 for (int d = 0; d < 3; ++d)
146 r2 += dr[d] * dr[d];
147 if ((!pair.linear && !(r2 > 0.0)) || !Kokkos::isfinite(r2) || !ok) {
148 Kokkos::atomic_exchange(&invalid(), 1);
149 q(row, p) = 0;
150 for (int d = 0; d < 3; ++d)
151 spatial(row, p, d) = 0;
152 return;
153 }
154 if (pair.linear) {
155 double value = 0;
156 for (int d = 0; d < 3; ++d) {
157 value += pair.slope[d] * dr[d];
158 spatial(row, p, d) = pair.slope[d];
159 }
160 q(row, p) = value;
161 return;
162 }
163 const double r = Kokkos::sqrt(r2), inverse = 1 / r;
164 double value = inverse, slope = -inverse * inverse;
165 if (R > 0 && r >= R) {
166 value = 0;
167 slope = 0;
168 } else if (R > 0 && r > R - shell) {
169 const double u = (R - r) / shell, v = 1 - u;
170 const double sw =
171 u * u * u * Kokkos::fma(v, Kokkos::fma(6.0, v, 3.0), 1.0);
172 const double ds = -30 * u * u * v * v / shell;
173 value = sw * inverse;
174 slope = (ds - sw * inverse) * inverse;
175 }
176 q(row, p) = value;
177 for (int d = 0; d < 3; ++d)
178 spatial(row, p, d) = slope * dr[d] * inverse;
179 }
180};
181// The fixed pair vocabulary as the joint kernel reads it: the two atoms of a
182// pair, the pairs of each moving atom, the pair two moving atoms share, and
183// the type of a pair.
184struct PairTopology {
185 V::ivector first, second, atom_offsets, atom_pairs, shared_pair, pair_type;
186};
187
188struct DescriptorRows {
189 V::matrix q;
190 Spatial spatial;
191 V::ivector channel, geometry;
192 EigenMatrix witness;
193 Eigen::VectorXd indices;
194 Rows rows(const PairTopology& topology) const
195 {
196 return {q,
197 {},
198 channel,
199 geometry,
200 topology.first,
201 topology.second,
202 spatial,
203 topology.atom_offsets,
204 topology.atom_pairs,
205 topology.shared_pair,
206 topology.pair_type};
207 }
208};
209bool sameVector(const Eigen::VectorXd& left, const Eigen::VectorXd& right)
210{
211 return left.size() == right.size() && (left.array() == right.array()).all();
212}
213bool identical(const EigenMatrix& a, const EigenMatrix& b)
214{
215 return a.rows() == b.rows() && a.cols() == b.cols() &&
216 (a.array() == b.array()).all();
217}
218} // namespace
219
221 Exec exec;
223 Cell cell;
224 double far_radius, cutoff, width, nugget = 0.0;
226 Kokkos::View<Pair*, V::memory_space> pairs;
227 V::ivector first, second, pair_type;
229 PairTopology topology() const
230 {
231 return {first, second, atom_offsets,
233 }
237 double configured_jitter = 0.0;
238 DescriptorRows training, query;
242 detail::TransferCounters transfers;
243 Posterior posterior;
244 std::shared_ptr<const KokkosFactor> factor;
245 bool predicted = false;
246 bool predicted_variance = false;
248
249 Impl(const AtomsConfiguration& configuration, double far)
250 : conf(configuration),
251 cell(configuration.cell),
252 far_radius(far),
253 cutoff(conf.pair_cutoff),
254 width(conf.pair_cutoff_width),
255 moving(conf.atoms_mov.type.size()),
256 types(conf.n_pt),
257 posterior(
258 exec,
259 [](const Exec& ex, const Posterior::matrix_type& view) {
261 auto work = view;
262 return detail::kokkosFactorLower(ex, work);
263 },
264 [](const Exec& ex, const Posterior::matrix_type& L,
265 const Posterior::matrix_type& B, bool transpose) {
267 auto work = B;
268 detail::solve_lower(ex, L, work, transpose);
269 },
270 &transfers)
271 {
272 if (!(far >= 0.0) || !std::isfinite(far) || !(cutoff >= 0.0) ||
273 !std::isfinite(cutoff) || !(width >= 0.0) ||
274 !std::isfinite(width) || (far > 0.0 && cutoff > 0.0) ||
275 moving <= 0 || types < 0)
276 throw std::invalid_argument(
277 "invalid molecular descriptor configuration");
278 if (cutoff > 0.0) {
279 if (width == 0.0) width = std::min(1.0, .2 * cutoff);
280 if (width >= cutoff)
281 throw std::invalid_argument(
282 "cutoff shell must be smaller than its radius");
283 }
284 const int n_frozen = conf.atoms_froz_active.type.size();
285 if (conf.atoms_froz_active.positions.size() != 3 * n_frozen ||
286 !conf.atoms_froz_active.positions.allFinite())
287 throw std::invalid_argument(
288 "frozen coordinates have incompatible dimensions");
289 EigenMatrix frozen_host(n_frozen, 3);
290 for (int i = 0; i < n_frozen; ++i)
291 for (int d = 0; d < 3; ++d)
292 frozen_host(i, d) =
293 conf.atoms_froz_active.positions.data()[3 * i + d];
294 frozen = upload(frozen_host, "gpr frozen positions");
295 std::vector<Pair> vocabulary;
296 for (int a = 0; a < moving; ++a) {
297 std::vector<Eigen::Matrix3d> tensor(types, Eigen::Matrix3d::Zero());
298 if (far > 0.0 && (conf.atoms_mov.positions.size() != 3 * moving ||
299 !conf.atoms_mov.positions.allFinite()))
300 throw std::invalid_argument(
301 "far field requires finite reference positions");
302 for (int b = a + 1; b < moving + n_frozen; ++b) {
303 const int at = conf.atoms_mov.type(a);
304 const int bt = b < moving
305 ? conf.atoms_mov.type(b)
306 : conf.atoms_froz_active.type(b - moving);
307 if (at < 0 || bt < 0 || at >= conf.pairtype.rows() ||
308 bt >= conf.pairtype.cols())
309 throw std::invalid_argument(
310 "atom type is outside the pair vocabulary");
311 const int type = conf.pairtype(at, bt);
312 if (type < 0 || type >= types) continue;
313 if (far > 0.0 && b >= moving) {
314 double dr[3];
315 for (int d = 0; d < 3; ++d)
316 dr[d] = conf.atoms_mov.positions.data()[3 * a + d] -
317 frozen_host(b - moving, d);
318 if (!cell.wrap(dr))
319 throw std::invalid_argument(
320 "far field periodic image overflow");
321 const Eigen::Vector3d r(dr[0], dr[1], dr[2]);
322 const double r2 = r.squaredNorm();
323 if (r2 >= far * far) {
324 tensor[type] += r * r.transpose() / (r2 * r2 * r2);
325 continue;
326 }
327 }
328 vocabulary.push_back(Pair{a, b, type});
329 }
330 for (int t = 0; t < types; ++t) {
331 if (tensor[t].isZero(0.0)) continue;
332 const Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> eig(
333 tensor[t]);
334 if (eig.info() != Eigen::Success ||
335 eig.eigenvalues().minCoeff() <
336 -64 * std::numeric_limits<double>::epsilon() *
337 tensor[t].norm())
338 throw std::runtime_error(
339 "far field tensor is not positive semidefinite");
340 for (int d = 0; d < 3; ++d) {
341 Pair p{a, moving + n_frozen + 3 * t + d, t, true};
342 const auto slope =
343 (std::sqrt(std::max(0.0, eig.eigenvalues()(d))) *
344 eig.eigenvectors().col(d))
345 .eval();
346 for (int c = 0; c < 3; ++c) {
347 p.centre[c] =
348 conf.atoms_mov.positions.data()[3 * a + c];
349 p.slope[c] = slope(c);
350 }
351 vocabulary.push_back(p);
352 }
353 }
354 }
355 pairs = decltype(pairs)("gpr pair vocabulary", vocabulary.size());
356 auto ph = Kokkos::create_mirror_view(pairs);
357 first = V::ivector("gpr pair first", vocabulary.size());
358 second = V::ivector("gpr pair second", vocabulary.size());
359 pair_type = V::ivector("gpr pair type", vocabulary.size());
360 auto f = Kokkos::create_mirror_view(first),
361 s = Kokkos::create_mirror_view(second),
362 t = Kokkos::create_mirror_view(pair_type);
363 for (std::size_t p = 0; p < vocabulary.size(); ++p) {
364 ph(p) = vocabulary[p];
365 f(p) = ph(p).first;
366 s(p) = ph(p).second;
367 t(p) = ph(p).type;
368 }
369 detail::audited_deep_copy(exec, pairs, ph,
370 detail::CopyRole::ToExecution);
371 detail::audited_deep_copy(exec, first, f,
372 detail::CopyRole::ToExecution);
373 detail::audited_deep_copy(exec, second, s,
374 detail::CopyRole::ToExecution);
375 detail::audited_deep_copy(exec, pair_type, t,
376 detail::CopyRole::ToExecution);
377 // A Cartesian slope of a pair is nonzero only for its own atoms.
378 // The pairs of each moving atom and the pair of two moving atoms
379 // let a matrix entry visit those alone.
380 std::vector<std::vector<int>> of_atom(moving);
381 std::vector<int> shared(static_cast<std::size_t>(moving) * moving, -1);
382 for (std::size_t p = 0; p < vocabulary.size(); ++p) {
383 const int a = vocabulary[p].first, b = vocabulary[p].second;
384 of_atom[a].push_back(static_cast<int>(p));
385 if (b < moving) {
386 of_atom[b].push_back(static_cast<int>(p));
387 shared[static_cast<std::size_t>(a) * moving + b] =
388 static_cast<int>(p);
389 shared[static_cast<std::size_t>(b) * moving + a] =
390 static_cast<int>(p);
391 }
392 }
393 // By pair type, then by pair: the order in which the sums over all
394 // pairs add the terms of one atom.
395 for (auto& list: of_atom)
396 std::stable_sort(list.begin(), list.end(), [&](int l, int r) {
397 return vocabulary[l].type < vocabulary[r].type;
398 });
399 std::size_t adjacency = 0;
400 for (const auto& list: of_atom)
401 adjacency += list.size();
402 atom_offsets = V::ivector("gpr atom pair offsets", moving + 1);
403 atom_pairs = V::ivector("gpr atom pairs", adjacency);
404 shared_pair = V::ivector("gpr shared pair", shared.size());
405 auto oh = Kokkos::create_mirror_view(atom_offsets),
406 ah = Kokkos::create_mirror_view(atom_pairs),
407 sh = Kokkos::create_mirror_view(shared_pair);
408 int position = 0;
409 for (int a = 0; a < moving; ++a) {
410 oh(a) = position;
411 for (const int pair: of_atom[a])
412 ah(position++) = pair;
413 }
414 oh(moving) = position;
415 for (std::size_t k = 0; k < shared.size(); ++k)
416 sh(k) = shared[k];
417 detail::audited_deep_copy(exec, atom_offsets, oh,
418 detail::CopyRole::ToExecution);
419 detail::audited_deep_copy(exec, atom_pairs, ah,
420 detail::CopyRole::ToExecution);
421 detail::audited_deep_copy(exec, shared_pair, sh,
422 detail::CopyRole::ToExecution);
423 exec.fence("gpr upload fixed pair vocabulary");
424 stats.input_bytes +=
425 vocabulary.size() * (sizeof(Pair) + 3 * sizeof(int)) +
426 (moving + 1 + adjacency + shared.size()) * sizeof(int);
427 pair_index =
428 kokkos_joint::build_pair_type_index(exec, pair_type, types);
429 }
430
431 V::matrix upload(const EigenMatrix& host, const char* label)
432 {
433 V::matrix result(std::string(label), host.rows(), host.cols());
434 detail::audited_deep_copy(exec, result, detail::wrap(host),
435 host.size() * sizeof(double),
436 detail::CopyRole::ToExecution);
437 exec.fence("gpr molecular matrix input");
438 stats.input_bytes += host.size() * sizeof(double);
439 return result;
440 }
441 V::vector upload(const Eigen::VectorXd& host, const char* label)
442 {
443 V::vector result(std::string(label), host.size());
444 detail::audited_deep_copy(exec, result, detail::wrap(host),
445 host.size() * sizeof(double),
446 detail::CopyRole::ToExecution);
447 exec.fence("gpr molecular vector input");
448 stats.input_bytes += host.size() * sizeof(double);
449 return result;
450 }
451 bool describe(DescriptorRows& out, const EigenMatrix& input,
452 const Eigen::VectorXd& channels)
453 {
454 if (identical(out.witness, input) && sameVector(out.indices, channels))
455 return false;
456 if (input.cols() < 3 * moving || channels.size() != input.rows() ||
457 !input.allFinite())
458 throw std::invalid_argument(
459 "molecular observation rows have incompatible dimensions");
460 exec.fence("gpr recycle molecular descriptors");
461 std::map<std::vector<double>, int> unique;
462 std::vector<std::vector<double>> positions;
463 std::vector<int> mapping(input.rows());
464 for (Eigen::Index row = 0; row < input.rows(); ++row) {
465 if (!std::isfinite(channels(row)) || channels(row) < 0 ||
466 channels(row) > 3 * moving ||
467 std::floor(channels(row)) != channels(row))
468 throw std::invalid_argument(
469 "invalid Cartesian observation channel");
470 std::vector<double> key(3 * moving);
471 for (int c = 0; c < 3 * moving; ++c)
472 key[c] = input(row, c);
473 auto [it, inserted] = unique.emplace(key, positions.size());
474 if (inserted) positions.push_back(std::move(key));
475 mapping[row] = it->second;
476 }
477 EigenMatrix host(positions.size(), 3 * moving);
478 for (std::size_t r = 0; r < positions.size(); ++r)
479 for (int c = 0; c < 3 * moving; ++c)
480 host(r, c) = positions[r][c];
481 const auto xyz = upload(host, "gpr compact coordinates");
482 out.channel = V::ivector("gpr observation channel", input.rows());
483 out.geometry = V::ivector("gpr observation geometry", input.rows());
484 auto ch = Kokkos::create_mirror_view(out.channel),
485 map = Kokkos::create_mirror_view(out.geometry);
486 for (Eigen::Index r = 0; r < input.rows(); ++r) {
487 ch(r) = channels(r);
488 map(r) = mapping[r];
489 }
490 detail::audited_deep_copy(exec, out.channel, ch,
491 detail::CopyRole::ToExecution);
492 detail::audited_deep_copy(exec, out.geometry, map,
493 detail::CopyRole::ToExecution);
494 stats.input_bytes += 2 * input.rows() * sizeof(int);
495 out.q = V::matrix("gpr inverse distances", positions.size(),
496 pairs.extent(0));
497 out.spatial = Spatial("gpr pair Cartesian slopes", positions.size(),
498 pairs.extent(0), 3);
499 const auto q = out.q;
500 const auto spatial = out.spatial;
501 const auto vocabulary = pairs;
502 const auto fixed = frozen;
503 const auto periodic = cell;
504 const int nm = moving;
505 const double R = cutoff, shell = width;
506 Kokkos::View<int, V::memory_space> invalid("gpr descriptor status");
507 Kokkos::parallel_for(
508 "gpr molecular descriptors",
509 Kokkos::MDRangePolicy<Exec, Kokkos::Rank<2>>(
510 exec, {0, 0}, {positions.size(), pairs.extent(0)}),
511 DescriptorKernel{xyz, q, spatial, vocabulary, fixed, periodic, nm,
512 R, shell, invalid});
513 int status = 0;
514 Kokkos::View<int, Kokkos::HostSpace,
515 Kokkos::MemoryTraits<Kokkos::Unmanaged>>
516 host_status(&status);
517 detail::audited_deep_copy(exec, host_status, invalid,
518 detail::CopyRole::ToHost);
519 exec.fence("gpr molecular descriptor validation");
520 stats.output_bytes += sizeof(int);
521 if (status)
522 throw std::invalid_argument(
523 "molecular descriptor has a coincident pair or invalid "
524 "periodic image");
525 out.witness = input;
526 out.indices = channels;
527 ++stats.descriptor_builds;
528 stats.descriptor_entries += 4 * q.size();
529 return true;
530 }
531 void release()
532 {
533 factor.reset();
534 training = DescriptorRows{};
535 query = DescriptorRows{};
536 pairs = {};
537 first = {};
538 second = {};
539 pair_type = {};
540 frozen = {};
541 covariance = {};
542 cross = {};
543 targets = {};
544 noise = {};
545 lengths = {};
546 prior = {};
547 pair_index = {};
548 hyper = {};
549 }
550};
551
553 const AtomsConfiguration& configuration, double far)
554{
555 detail::ensure_kokkos();
556 impl_ = std::make_shared<Impl>(configuration, far);
557 Kokkos::push_finalize_hook([weak = std::weak_ptr<Impl>(impl_)] {
558 if (auto owner = weak.lock()) {
559 owner->exec.fence("gpr finalize molecular posterior");
560 owner->release();
561 }
562 });
563}
565{
566 if (impl_ && !Kokkos::is_finalized()) {
567 impl_->exec.fence("gpr destroy molecular posterior");
568 impl_->release();
569 }
570}
572 double far) const
573{
574 const auto& a = impl_->conf;
575 return far == impl_->far_radius && c.n_pt == a.n_pt &&
576 c.pair_cutoff == a.pair_cutoff &&
577 c.pair_cutoff_width == a.pair_cutoff_width &&
578 identical(c.atoms_mov.type.cast<double>(),
579 a.atoms_mov.type.cast<double>()) &&
580 identical(c.atoms_mov.positions, a.atoms_mov.positions) &&
581 identical(c.atoms_froz_active.positions,
582 a.atoms_froz_active.positions) &&
583 identical(c.atoms_froz_active.type.cast<double>(),
584 a.atoms_froz_active.type.cast<double>()) &&
585 identical(c.pairtype.cast<double>(), a.pairtype.cast<double>()) &&
586 std::equal(c.cell, c.cell + 9, a.cell);
587}
588
590 const EigenMatrix& rows, const Eigen::VectorXd& channels,
591 const Eigen::VectorXd& y, const Eigen::VectorXd& noise,
592 const Eigen::VectorXd& lengths, double magnitude, double constant,
593 double nugget, double jitter, bool append_only)
594{
595 auto& s = *impl_;
596 if (lengths.size() != s.types || !(lengths.array() > 0).all() ||
597 !lengths.allFinite())
598 throw std::invalid_argument(
599 "molecular kernel lengths must be finite and positive");
600 if (rows.rows() != channels.size() || rows.rows() != y.size() ||
601 rows.rows() != noise.size() || !y.allFinite() || !noise.allFinite() ||
602 !(noise.array() >= 0.0).all() || !std::isfinite(magnitude) ||
603 !(magnitude > 0.0) || !std::isfinite(constant) || constant < 0.0 ||
604 !std::isfinite(nugget) || nugget < 0.0 || !std::isfinite(jitter) ||
605 jitter < 0.0)
606 throw std::invalid_argument("invalid molecular conditioning inputs");
607 const bool same_parameters =
608 valid() && sameVector(lengths, s.length_witness) &&
609 magnitude == s.hyper.magnitude && constant == s.hyper.energy_constant &&
610 nugget == s.nugget && jitter == s.configured_jitter;
611 if (same_parameters && identical(rows, s.training.witness) &&
612 sameVector(channels, s.training.indices) &&
613 sameVector(noise, s.noise_witness)) {
614 setTargets(y);
615 ++s.stats.reuses;
616 const auto parts = s.posterior.objective_parts();
617 return parts[0] + .5 * parts[1] +
618 .5 * rows.rows() * std::log(2 * std::acos(-1.));
619 }
620 const Eigen::Index old = s.posterior.rows(), extra = rows.rows() - old;
621 const bool prefix =
622 same_parameters && extra > 0 && nugget == 0.0 &&
623 identical(EigenMatrix(rows.topRows(old)), s.training.witness) &&
624 sameVector(Eigen::VectorXd(channels.head(old)), s.training.indices) &&
625 sameVector(Eigen::VectorXd(noise.head(old)), s.noise_witness);
626 if (prefix) {
627 DescriptorRows enlarged;
628 s.describe(enlarged, rows, channels);
629 auto tail = enlarged.rows(s.topology());
630 tail.channel =
631 Kokkos::subview(enlarged.channel, std::make_pair(old, rows.rows()));
632 tail.geometry = Kokkos::subview(enlarged.geometry,
633 std::make_pair(old, rows.rows()));
634 V::matrix cross("gpr append cross", old, extra),
635 diagonal("gpr append diagonal", extra, extra);
637 s.training.rows(s.topology()), tail,
638 s.pair_index, s.hyper, cross);
639 kokkos_joint::assemble_training(s.exec, tail, s.pair_index, s.hyper,
640 0.0, {}, diagonal);
641 const auto device_noise = s.upload(noise, "gpr append noise");
642 const auto device_targets = s.upload(y, "gpr append targets");
643 Kokkos::parallel_for(
644 "gpr append diagonal noise",
645 Kokkos::RangePolicy<Exec>(s.exec, 0, extra),
646 KOKKOS_LAMBDA(const int i) {
647 diagonal(i, i) += device_noise(old + i) + jitter;
648 });
649 const double result =
650 s.posterior.append(cross, diagonal, device_targets);
651 if (std::isfinite(result)) {
652 s.training = std::move(enlarged);
653 s.targets = device_targets;
654 s.noise = device_noise;
655 s.target_witness = y;
656 s.noise_witness = noise;
657 s.predicted = false;
658 s.factor = std::shared_ptr<const KokkosFactor>(new KokkosFactor(
659 detail::KokkosDeviceFactor{s.posterior.factor()}));
660 ++s.stats.appends;
661 return result;
662 }
663 if (append_only) return result;
664 } else if (append_only)
665 return std::numeric_limits<double>::infinity();
666 s.factor.reset();
667 s.predicted = false;
668 s.describe(s.training, rows, channels);
669 s.lengths = s.upload(Eigen::VectorXd(lengths.array().square().inverse()),
670 "gpr inverse squared lengths");
671 s.hyper = {s.lengths, magnitude, constant};
672 s.nugget = nugget;
673 s.configured_jitter = jitter;
674 s.length_witness = lengths;
675 if (!sameVector(s.target_witness, y)) {
676 s.targets = s.upload(y, "gpr observation targets");
677 s.target_witness = y;
678 }
679 if (!sameVector(s.noise_witness, noise)) {
680 s.noise = s.upload(noise, "gpr observation noise");
681 s.noise_witness = noise;
682 }
683 const auto observations = s.training.rows(s.topology());
684 s.covariance =
685 V::matrix("gpr resident joint covariance", rows.rows(), rows.rows());
686 kokkos_joint::assemble_training(s.exec, observations, s.pair_index, s.hyper,
687 nugget, {}, s.covariance);
688 ++s.stats.factorizations;
689 const double value =
690 s.posterior.condition(s.covariance, s.targets, s.noise, {}, jitter);
691 if (std::isfinite(value))
692 s.factor = std::shared_ptr<const KokkosFactor>(
693 new KokkosFactor(detail::KokkosDeviceFactor{s.posterior.factor()}));
694 return value;
695}
696bool KokkosMolecularPosterior::canAppend(Eigen::Index geometries,
697 const Eigen::VectorXd& noise,
698 const Eigen::VectorXd& lengths,
699 double magnitude, double constant,
700 double jitter) const
701{
702 const auto& s = *impl_;
703 return valid() && s.nugget == 0.0 &&
704 geometries > static_cast<Eigen::Index>(s.training.q.extent(0)) &&
705 sameVector(noise, s.noise_witness) &&
706 sameVector(lengths, s.length_witness) &&
707 magnitude == s.hyper.magnitude &&
708 constant == s.hyper.energy_constant && jitter == s.configured_jitter;
709}
711{
712 return impl_->posterior.objective_parts();
713}
715{
716 Eigen::VectorXd result;
717 detail::to_eigen(impl_->posterior.inverse_diagonal(), result);
718 impl_->stats.output_bytes += result.size() * sizeof(double);
719 return result;
720}
721Eigen::VectorXd KokkosMolecularPosterior::gradient(double differentiable_noise,
722 double data_term_scale)
723{
724 return gradient(differentiable_noise, {}, {}, data_term_scale);
725}
726
728 double differentiable_noise, const std::vector<int>& type_group,
729 const std::vector<int>& group_slot, double data_term_scale)
730{
731 if (!valid())
732 throw std::logic_error(
733 "gradient requires a conditioned molecular posterior");
734 auto& s = *impl_;
735 const bool grouped = !type_group.empty();
736 if (grouped && type_group.size() != static_cast<std::size_t>(s.types))
737 throw std::invalid_argument("one group per pair type is required");
738 const int groups = grouped ? static_cast<int>(group_slot.size()) : s.types;
739 V::ivector device_group, device_type;
740 if (grouped) {
741 // A type of each group carries the group's length.
742 std::vector<int> group_type(group_slot.size(), -1);
743 for (int t = 0; t < s.types; ++t) {
744 const int g = type_group[static_cast<std::size_t>(t)];
745 if (g < 0 || g >= groups)
746 throw std::invalid_argument("pair type group out of range");
747 if (group_type[static_cast<std::size_t>(g)] < 0)
748 group_type[static_cast<std::size_t>(g)] = t;
749 }
750 for (const int t: group_type)
751 if (t < 0) throw std::invalid_argument("empty pair type group");
752 device_group = V::ivector("gpr pair type group", type_group.size());
753 device_type = V::ivector("gpr group pair type", group_type.size());
754 auto gh = Kokkos::create_mirror_view(device_group);
755 auto th = Kokkos::create_mirror_view(device_type);
756 for (std::size_t t = 0; t < type_group.size(); ++t)
757 gh(t) = type_group[t];
758 for (std::size_t g = 0; g < group_type.size(); ++g)
759 th(g) = group_type[g];
760 detail::audited_deep_copy(s.exec, device_group, gh,
761 detail::CopyRole::ToExecution);
762 detail::audited_deep_copy(s.exec, device_type, th,
763 detail::CopyRole::ToExecution);
764 s.stats.input_bytes +=
765 (type_group.size() + group_type.size()) * sizeof(int);
766 }
767 const auto weight = s.posterior.objective_weight(data_term_scale);
768 V::vector gradient("gpr kernel parameter contractions", groups + 2);
770 s.exec, s.training.rows(s.topology()), s.pair_index, s.hyper, s.nugget,
771 weight, gradient, V::const_ivector(device_group),
772 V::const_ivector(device_type));
773 Eigen::VectorXd host;
774 detail::to_eigen(gradient, host);
775 s.stats.output_bytes += host.size() * sizeof(double);
776 Eigen::VectorXd result =
777 Eigen::VectorXd::Zero(s.types + 1 + (differentiable_noise > 0.0));
778 result(0) = host(0);
779 if (grouped) {
780 for (int g = 0; g < groups; ++g) {
781 const int slot = group_slot[static_cast<std::size_t>(g)];
782 if (slot >= s.types)
783 throw std::invalid_argument("group slot out of range");
784 if (slot >= 0) result(1 + slot) = host(2 + g);
785 }
786 } else {
787 result.segment(1, s.types) = host.tail(s.types);
788 }
789 if (differentiable_noise > 0.0) {
790 const int n = static_cast<int>(s.posterior.rows());
791 double trace = 0.0;
792 if (n > 0) {
793 constexpr int kTile = 256;
794 const int n_tiles = (n + kTile - 1) / kTile;
795 V::vector tiles(
796 Kokkos::view_alloc(s.exec, Kokkos::WithoutInitializing,
797 "gpr resident noise tiles"),
798 static_cast<std::size_t>(n_tiles));
799 V::vector scalar_out(
800 Kokkos::view_alloc(s.exec, Kokkos::WithoutInitializing,
801 "gpr resident noise scalar"),
802 1);
803 Kokkos::parallel_for(
804 "gpr resident noise contraction tiles",
805 Kokkos::RangePolicy<Exec>(s.exec, 0, n_tiles),
806 KOKKOS_LAMBDA(const int t) {
807 const int begin = t * kTile;
808 const int end = (begin + kTile < n) ? (begin + kTile) : n;
809 double sum = 0.0, corr = 0.0;
810 for (int i = begin; i < end; ++i) {
811 const double term = weight(i, i);
812 const double next = sum + term;
813 corr += Kokkos::abs(sum) >= Kokkos::abs(term)
814 ? (sum - next) + term
815 : (term - next) + sum;
816 sum = next;
817 }
818 tiles(t) = sum + corr;
819 });
820 Kokkos::parallel_for(
821 "gpr resident noise contraction fold",
822 Kokkos::RangePolicy<Exec>(s.exec, 0, 1),
823 KOKKOS_LAMBDA(const int) {
824 double sum = 0.0, corr = 0.0;
825 for (int t = 0; t < n_tiles; ++t) {
826 const double term = tiles(t);
827 const double next = sum + term;
828 corr += Kokkos::abs(sum) >= Kokkos::abs(term)
829 ? (sum - next) + term
830 : (term - next) + sum;
831 sum = next;
832 }
833 scalar_out(0) = sum + corr;
834 });
835 Kokkos::View<double, Kokkos::HostSpace,
836 Kokkos::MemoryTraits<Kokkos::Unmanaged>>
837 host_trace(&trace);
838 detail::audited_deep_copy(s.exec, host_trace,
839 Kokkos::subview(scalar_out, 0),
840 detail::CopyRole::ToHost);
841 s.exec.fence("gpr resident noise contraction");
842 }
843 result(result.size() - 1) = differentiable_noise * trace;
844 s.stats.output_bytes += sizeof(double);
845 }
846 return result;
847}
849 const Eigen::VectorXd& channels,
850 Eigen::VectorXd* mean,
851 Eigen::VectorXd* variance,
852 bool stable_variance)
853{
854 if (!valid())
855 throw std::logic_error(
856 "prediction requires a conditioned molecular posterior");
857 auto& s = *impl_;
858 const bool changed = s.describe(s.query, rows, channels);
859 // A mean of these rows is kept without its variance; the variance is
860 // computed the first time it is asked for. A variance from one mode is
861 // not reused for the other.
862 const bool want_variance = variance != nullptr;
863 if (changed || !s.predicted || (want_variance && !s.predicted_variance) ||
864 (want_variance && stable_variance != s.predicted_stable_variance)) {
865 s.cross = V::matrix("gpr resident cross covariance", s.posterior.rows(),
866 rows.rows());
867 s.prior = V::vector("gpr resident query diagonal", rows.rows());
869 s.exec, s.training.rows(s.topology()), s.query.rows(s.topology()),
870 s.pair_index, s.hyper, s.cross);
871 kokkos_joint::assemble_diagonal(s.exec, s.query.rows(s.topology()),
872 s.pair_index, s.hyper, 0.0, {},
873 s.prior);
874 s.posterior.predict(s.cross, s.prior, want_variance,
875 want_variance && stable_variance);
876 s.predicted = true;
877 s.predicted_variance = want_variance;
878 s.predicted_stable_variance = want_variance && stable_variance;
879 }
880 if (mean) {
881 detail::to_eigen(s.posterior.mean(), *mean);
882 s.stats.output_bytes += mean->size() * sizeof(double);
883 }
884 if (variance) {
885 detail::to_eigen(s.posterior.variance(), *variance);
886 s.stats.output_bytes += variance->size() * sizeof(double);
887 if (stable_variance) {
888 Eigen::VectorXd signal;
889 detail::to_eigen(s.prior, signal);
890 s.stats.output_bytes +=
891 static_cast<std::size_t>(signal.size()) * sizeof(double);
892 requireStableSchurDiagonal(*variance, signal, [&] {
893 return s.factor->schurRelativeError();
894 });
895 }
896 }
897}
898void KokkosMolecularPosterior::setTargets(const Eigen::VectorXd& targets)
899{
900 auto& s = *impl_;
901 if (sameVector(s.target_witness, targets)) return;
902 s.targets = s.upload(targets, "gpr observation targets");
903 s.posterior.set_targets(s.targets);
904 s.target_witness = targets;
905 s.predicted = false;
906}
908{
909 return impl_->factor && impl_->posterior.valid();
910}
911Eigen::Index KokkosMolecularPosterior::order() const noexcept
912{
913 return impl_->posterior.rows();
914}
915std::shared_ptr<const KokkosFactor> KokkosMolecularPosterior::factorHandle()
916 const
917{
918 return impl_->factor;
919}
921{
922 EigenMatrix result;
923 detail::to_eigen(impl_->posterior.factor(), result);
924 impl_->stats.output_bytes += result.size() * sizeof(double);
925 return result;
926}
928{
929 Eigen::VectorXd result;
930 detail::to_eigen(impl_->posterior.alpha(), result);
931 impl_->stats.output_bytes += result.size() * sizeof(double);
932 return result;
933}
935{
936 auto& s = *impl_;
937 const auto factor = s.posterior.factor();
938 const std::size_t order = factor.extent(0);
939 V::vector diagonal("gpr factor diagonal", order);
940 Kokkos::parallel_for(
941 "gpr factor diagonal", Kokkos::RangePolicy<Exec>(s.exec, 0, order),
942 KOKKOS_LAMBDA(const std::size_t i) { diagonal(i) = factor(i, i); });
943 Eigen::VectorXd result;
944 detail::to_eigen(diagonal, result);
945 s.stats.output_bytes += result.size() * sizeof(double);
946 return result;
947}
949{
950 return impl_->training.witness;
951}
953 const EigenMatrix& rows, const Eigen::VectorXd& channels,
954 const Eigen::VectorXd& noise, const Eigen::VectorXd& lengths,
955 double magnitude, double constant, double nugget, double jitter) const
956{
957 const auto& s = *impl_;
958 return valid() && sameVector(lengths, s.length_witness) &&
959 magnitude == s.hyper.magnitude &&
960 constant == s.hyper.energy_constant && nugget == s.nugget &&
961 jitter == s.configured_jitter &&
962 identical(rows, s.training.witness) &&
963 sameVector(channels, s.training.indices) &&
964 sameVector(noise, s.noise_witness);
965}
967{
968 auto result = impl_->stats;
969 result.output_bytes += impl_->transfers.scalar_device_to_host_bytes;
970 return result;
971}
972} // namespace gpr::linalg
@ y
Definition Enums.h:28
Correctly rounded Schur-complement diagonals from Cholesky solves.
Eigen::VectorXd gradient(double differentiable_noise=0.0, double data_term_scale=1.0)
void setTargets(const Eigen::VectorXd &targets)
void predict(const EigenMatrix &rows, const Eigen::VectorXd &channels, Eigen::VectorXd *mean, Eigen::VectorXd *variance, bool stable_variance=false)
bool matchesConfiguration(const AtomsConfiguration &configuration, double far_radius) const
bool matchesTraining(const EigenMatrix &rows, const Eigen::VectorXd &channels, const Eigen::VectorXd &noise, const Eigen::VectorXd &lengths, double magnitude, double constant, double nugget, double jitter) const
std::shared_ptr< const KokkosFactor > factorHandle() const
bool canAppend(Eigen::Index geometries, const Eigen::VectorXd &noise, const Eigen::VectorXd &lengths, double magnitude, double constant, double jitter) const
log magnitude, then log length of each pair type; optional log noise.
double condition(const EigenMatrix &rows, const Eigen::VectorXd &channels, const Eigen::VectorXd &targets, const Eigen::VectorXd &noise, const Eigen::VectorXd &lengths, double magnitude, double constant, double relative_nugget, double jitter, bool append_only=false)
KokkosMolecularPosterior(const AtomsConfiguration &configuration, double far_radius=0.0)
eon_relax_band_t eon_relax_surface_fn void eon_relax_outcome_t * out
int status
void assemble_rectangular(const ExecSpace &exec, const JointRows< ExecSpace > &rows1, const JointRows< ExecSpace > &rows2, const PairTypeIndex< ExecSpace > &index, const JointHyper< ExecSpace > &hyper, const typename Views< ExecSpace >::matrix &K)
void assemble_training(const ExecSpace &exec, const JointRows< ExecSpace > &rows, const PairTypeIndex< ExecSpace > &index, const JointHyper< ExecSpace > &hyper, double eta, const typename Views< ExecSpace >::const_vector &noise, const typename Views< ExecSpace >::matrix &K)
void contract_kernel_derivatives(const ExecSpace &exec, const JointRows< ExecSpace > &rows, const PairTypeIndex< ExecSpace > &index, const JointHyper< ExecSpace > &hyper, double eta, const typename Views< ExecSpace >::const_matrix &W, const typename Views< ExecSpace >::vector &out, const typename Views< ExecSpace >::const_ivector &type_group={}, const typename Views< ExecSpace >::const_ivector &group_type={})
void assemble_diagonal(const ExecSpace &exec, const JointRows< ExecSpace > &rows, const PairTypeIndex< ExecSpace > &index, const JointHyper< ExecSpace > &hyper, double eta, const typename Views< ExecSpace >::const_vector &noise, const typename Views< ExecSpace >::vector &diag)
Dense and structured linear algebra behind the GP: Cholesky and eigen solvers, linear operators,...
void requireStableSchurDiagonal(Eigen::VectorXd &variance, const Eigen::VectorXd &signal, RelativeError &&relative_error)
requireStablePosteriorVariance over a Schur diagonal whose allowance is the forward error of a solve.
Definition ExactSchur.h:174
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Stores configurations of all atoms in the system.
Definition Structures.h:832
AtomsPositionAndType atoms_froz_active
Info on active frozen atoms.
Definition Structures.h:841
AtomsPositionAndType atoms_mov
Info on moving atoms.
Definition Structures.h:844
Kokkos::View< Pair *, V::memory_space > pairs
bool describe(DescriptorRows &out, const EigenMatrix &input, const Eigen::VectorXd &channels)
V::vector upload(const Eigen::VectorXd &host, const char *label)
V::matrix upload(const EigenMatrix &host, const char *label)
Impl(const AtomsConfiguration &configuration, double far)