Loading...
Searching...
No Matches
DevicePosterior.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
4
5#ifdef GPR_LINALG_KOKKOS
6#include <cstring>
7#include <vector>
8
13
14namespace gpr {
15
16namespace {
18void accountDeviceTransfers(const linalg::KokkosMolecularStats& before,
20{
21 DeviceResidency::input_bytes += after.input_bytes - before.input_bytes;
22 DeviceResidency::output_bytes += after.output_bytes - before.output_bytes;
23}
24} // namespace
25
27{
28 return sexpat_cov_func && const_cov_fun && lik_gaussian &&
29 !atomic_environment_model_ && !use_hssvd_backend_ &&
30 !use_correction_ && !sexpat_cov_func->usesManifoldChart() &&
31 !sexpat_cov_func->usesGeodesicHeatKernel() &&
32 hyperparameter_objective_mode_ ==
34 sexpat_cov_func->getLengthScaleRef().size() ==
35 sexpat_cov_func->getConfInfo().n_pt;
36}
37
39{
40 return device_posterior_ && device_posterior_->valid();
41}
42
44 const EigenMatrix& x, const Eigen::VectorXd& indices,
45 const Eigen::VectorXd& targets, bool placeholder_targets)
46{
47 if (!canUseDevicePosterior() || x.rows() == 0) {
48 if (x.rows() != 0) {
50 // The same properties canUseDevicePosterior tests, one count each.
51 using R = DeviceResidency;
52 const auto count = [](bool unsupported, R::Reason reason) {
53 if (unsupported) ++R::fallback_reasons[reason];
54 };
55 count(!sexpat_cov_func, R::NoPairKernel);
56 count(!const_cov_fun, R::NoConstantKernel);
57 count(!lik_gaussian, R::NonGaussianLikelihood);
58 count(static_cast<bool>(atomic_environment_model_),
59 R::EnvironmentModel);
60 count(use_hssvd_backend_, R::StableBasis);
61 count(use_correction_, R::ResidualCorrection);
62 count(sexpat_cov_func && sexpat_cov_func->usesManifoldChart(),
63 R::ManifoldChart);
64 count(sexpat_cov_func && sexpat_cov_func->usesGeodesicHeatKernel(),
65 R::GeodesicHeatKernel);
66 count(hyperparameter_objective_mode_ !=
68 R::ObjectiveNotNlml);
69 count(sexpat_cov_func &&
70 sexpat_cov_func->getLengthScaleRef().size() !=
71 sexpat_cov_func->getConfInfo().n_pt,
72 R::LengthScalesNotPerPairType);
73 }
74 device_posterior_.reset();
75 return std::nullopt;
76 }
77 const auto& configuration = sexpat_cov_func->getConfInfo();
78 const double far = sexpat_cov_func->farFieldRadius();
79 if (!device_posterior_ || device_posterior_.use_count() > 1 ||
80 !device_posterior_->matchesConfiguration(configuration, far))
81 device_posterior_ = std::make_shared<linalg::KokkosMolecularPosterior>(
82 configuration, far);
85 const Eigen::VectorXd ordered_indices = permuteTrainingVector(indices);
86 const Eigen::VectorXd noise =
87 lik_gaussian->evaluateTrainingVariance(ordered);
88 const auto& length_matrix = sexpat_cov_func->getLengthScaleRef();
89 const Eigen::VectorXd lengths = Eigen::Map<const Eigen::VectorXd>(
90 length_matrix.data(), length_matrix.size());
91 double result = std::numeric_limits<double>::infinity();
92 bool factor_changed = false;
93 const auto condition = [&](double jitter) {
94 const auto started = std::chrono::steady_clock::now();
95 const double factor_before = linalg::teamFactorWallSeconds();
96 const double solve_before = linalg::teamSolveWallSeconds();
97 const auto before = device_posterior_->stats();
98 const double value = device_posterior_->condition(
99 ordered, ordered_indices, permuteTrainingVector(targets), noise,
100 lengths, sexpat_cov_func->getMagnSigma2(),
101 const_cov_fun->getConstSigma2(), kernelNuggetCoefficient(x.rows()),
102 jitter, require_factor_append_);
103 const double factor = linalg::teamFactorWallSeconds() - factor_before;
104 const double solve = linalg::teamSolveWallSeconds() - solve_before;
105 const double wall = std::chrono::duration<double>(
106 std::chrono::steady_clock::now() - started)
107 .count();
108 PhaseTimers::assembly_seconds += std::max(0.0, wall - factor - solve);
111 const auto after = device_posterior_->stats();
114 after.factorizations - before.factorizations;
115 DeviceResidency::appends += after.appends - before.appends;
116 DeviceResidency::reuses += after.reuses - before.reuses;
117 accountDeviceTransfers(before, after);
118 full_cholesky_factorizations_for_testing_ +=
119 after.factorizations - before.factorizations;
120 incremental_cholesky_updates_for_testing_ +=
121 after.appends - before.appends;
122 serial_factor_reuses_for_testing_ += after.reuses - before.reuses;
123 factor_changed = factor_changed ||
124 after.factorizations != before.factorizations ||
125 after.appends != before.appends;
126 return value;
127 };
128 result = condition(jitter_sigma2);
129 double rescue = std::max(jitter_sigma2, 1e-10);
130 for (int attempt = 0;
131 !require_factor_append_ && !std::isfinite(result) && attempt < 5;
132 ++attempt) {
133 result = condition(jitter_sigma2 + rescue);
134 rescue *= 10.0;
135 }
136 device_targets_placeholder_ = placeholder_targets;
137 is_decomposed_succesfully = std::isfinite(result);
140 L.resize(0, 0);
141 C.resize(0, 0);
142 a.resize(0);
143 b.resize(0);
144 dense_results_.clear();
145 if (factor_changed) training_inverse_diagonal_.resize(0);
146 serial_factor_signature_.valid = false;
147 hssvd_basis_valid_ = false;
148 descriptor_predictor_ready_ = false;
149 hssvd_variance_calibration_factor_ = 1.0;
150 return result;
151}
152
154 Eigen::VectorXd& gradient)
155{
156 if (!hasDevicePosterior()) return false;
157 const auto before = device_posterior_->stats();
158 const double noise =
159 theta_includes_likelihood_noise_ ? likelihoodNoiseVariance() : 0.0;
160 const double data_scale = hyperparameterDataTermScale();
161 // Inside a tied objective the members of a tie group hold one length,
162 // and the optimizer reads only the sum of their derivatives. The device
163 // then contracts each group once. A group splits into its active and its
164 // held members: the active sum goes to the first active member, where
165 // the mask below keeps it and the tie reduction adds it to the leader;
166 // the held sum is dropped, as the mask would drop its entries. Any other
167 // caller, and a point where the lengths of a group differ, gets one
168 // derivative per pair type.
169 std::vector<int> type_group, group_slot;
170 const auto& length_matrix = sexpat_cov_func->getLengthScaleRef();
171 const Eigen::Index types = length_matrix.size();
172 if (tied_length_scale_gradient_ && lengthScaleTiesActive(types)) {
173 const auto& ties = length_scale_ties_;
174 const auto& active = scg_opt_settings.active_parameters;
175 const double* length = length_matrix.data();
176 const std::size_t count = static_cast<std::size_t>(types);
177 std::vector<int> active_group(count, -1), held_group(count, -1);
178 type_group.resize(count);
179 bool tied = true;
180 for (std::size_t t = 0; t < count; ++t) {
181 const auto leader = static_cast<std::size_t>(ties.leader[t]);
182 if (leader >= count ||
183 std::memcmp(&length[t], &length[leader], sizeof(double)) != 0) {
184 tied = false;
185 break;
186 }
187 const bool is_active = t + 1 >= active.size() || active[t + 1];
188 int& group = (is_active ? active_group : held_group)[leader];
189 if (group < 0) {
190 group = static_cast<int>(group_slot.size());
191 group_slot.push_back(is_active ? static_cast<int>(t) : -1);
192 }
193 type_group[t] = group;
194 }
195 if (!tied) {
196 type_group.clear();
197 group_slot.clear();
198 }
199 }
200 gradient = type_group.empty()
201 ? device_posterior_->gradient(noise, data_scale)
202 : device_posterior_->gradient(noise, type_group, group_slot,
203 data_scale);
205 accountDeviceTransfers(before, device_posterior_->stats());
206 const FieldMatrixd prior = sexpat_cov_func->calculateLogPriorGradient();
207 if (prior.size() > gradient.size())
208 throw std::logic_error("kernel prior exceeds device parameter count");
209 if (!unregularized_marginal_likelihood_ && prior.size())
210 gradient.head(prior.size()) -=
211 Eigen::Map<const Eigen::VectorXd>(prior.data(), prior.size());
212 const auto& active = scg_opt_settings.active_parameters;
213 const std::size_t held = std::min<std::size_t>(
214 active.size(), static_cast<std::size_t>(gradient.size()));
215 for (std::size_t i = 0; i < held; ++i)
216 if (!active[i]) gradient(static_cast<Eigen::Index>(i)) = 0.0;
217 return true;
218}
219
221 bool variance)
222{
223 if (!hasDevicePosterior()) return false;
224 EigenMatrix rows;
225 Eigen::VectorXd indices, result;
226 aux::AuxiliaryFunctionality auxiliary;
227 auxiliary.assembleMatrixOfRepetitiveCoordinates(image.R, rows, indices);
228 const auto before = device_posterior_->stats();
229 device_posterior_->predict(
230 rows, indices, variance ? nullptr : &result,
231 variance ? &result : nullptr,
234 accountDeviceTransfers(before, device_posterior_->stats());
235 if (variance) {
236 priorFromKernelDiagonal(rows, result);
237 result *= hssvd_variance_calibration_factor_;
238 }
239 const Eigen::Index n = image.R.rows(), d = image.R.cols();
240 image.E = Eigen::Map<const Eigen::RowVectorXd>(result.data(), n);
241 image.G = Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic,
242 Eigen::Dynamic, Eigen::ColMajor>>(
243 result.data() + n, n, d);
244 if (!variance) ++num_of_potential_calls;
245 return true;
246}
247
249{
250 hssvd_variance_calibration_factor_ = 1.0;
251 const Eigen::VectorXd alpha = device_posterior_->downloadAlpha();
252 if (alpha.size() < 2) return;
254 alpha, device_posterior_->downloadFactorDiagonal()))
255 return;
256 const Eigen::VectorXd& inverse_diagonal =
258 if (inverse_diagonal.size() == alpha.size())
259 hssvd_variance_calibration_factor_ =
260 looVarianceCalibrationFactor(alpha, inverse_diagonal);
261}
262
264{
265 if (hasDevicePosterior() && L.rows() != device_posterior_->order()) {
266 const auto before = device_posterior_->stats();
267 L = device_posterior_->downloadFactor();
270 static_cast<std::size_t>(L.size()) * sizeof(double);
271 accountDeviceTransfers(before, device_posterior_->stats());
272 }
273}
275{
276 if (hasDevicePosterior() && a.size() != device_posterior_->order()) {
277 const auto before = device_posterior_->stats();
278 a = device_posterior_->downloadAlpha();
281 static_cast<std::size_t>(a.size()) * sizeof(double);
282 accountDeviceTransfers(before, device_posterior_->stats());
283 }
284}
285
286} // namespace gpr
287#else
288namespace gpr {
289
291{
292 return false;
293}
295{
296 return false;
297}
299 const EigenMatrix&, const Eigen::VectorXd&, const Eigen::VectorXd&, bool)
300{
301 return std::nullopt;
302}
304{
305 return false;
306}
308{
309 return false;
310}
314
315} // namespace gpr
316#endif
@ x
Definition Enums.h:28
Correctly rounded Schur-complement diagonals from Cholesky solves.
void assembleMatrixOfRepetitiveCoordinates(const gpr::Coord &coord, gpr::EigenMatrix &matrix, Eigen::VectorXd &ind)
Assemble Eigen matrix with repetitive rows based on provided set of coordinates R.
Eigen::VectorXd permuteTrainingVector(const Eigen::VectorXd &input) const
std::optional< double > conditionDevicePosterior(const EigenMatrix &rows, const Eigen::VectorXd &indices, const Eigen::VectorXd &targets, bool placeholder_targets=false)
const Eigen::VectorXd & trainingInverseDiagonalInFactorLayout() const
Definition Predict.cpp:523
linalg::linop::DenseResultCache dense_results_
bool predictDevicePosterior(Observation &image, bool variance)
EigenMatrix rowsInTrainingFactorLayout(const EigenMatrix &input) const
std::shared_ptr< linalg::KokkosMolecularPosterior > device_posterior_
bool hasDevicePosterior() const noexcept
std::unique_ptr< SexpatCF > sexpat_cov_func
std::shared_ptr< const linalg::KokkosFactor > resident_training_factor_
void prepareTrainingPermutation(const Eigen::VectorXd &x_ind)
virtual double hyperparameterDataTermScale() const
bool lengthScaleTiesActive(Eigen::Index length_count) const noexcept
bool devicePosteriorGradient(Eigen::VectorXd &gradient)
double teamFactorWallSeconds()
double teamSolveWallSeconds()
bool stablePosteriorVarianceEnabled() noexcept
Whether stable posterior variance reductions are enabled.
Definition ExactSchur.h:40
Gaussian-process regression, kernels, priors, and the searches that run on the surrogate.
Definition Macros.h:16
bool looCalibrationIsUnityFromCholeskyDiagonal(const Eigen::VectorXd &alpha, const Eigen::VectorXd &diagonal)
double looVarianceCalibrationFactor(const Eigen::VectorXd &alpha, const Eigen::VectorXd &inv_diag)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
Eigen::Matrix< double, EigenDynamic, EigenDynamic, FieldMatrixStorage > FieldMatrixd
Definition Macros.h:25
static std::atomic_size_t coefficient_downloads
static std::atomic_size_t input_bytes
static std::atomic_size_t factor_downloads
static std::atomic_size_t coefficient_download_bytes
static std::atomic_size_t factor_download_bytes
static std::atomic_size_t conditions
static std::atomic_size_t appends
static std::atomic_size_t reuses
static std::atomic_size_t host_fallbacks
static std::atomic_size_t output_bytes
static std::atomic_size_t gradients
static std::atomic_size_t predictions
static std::atomic_size_t factorizations
Observation data: energy, gradient and positions.
static double cholesky_seconds
static double assembly_seconds
static double posterior_seconds