Loading...
Searching...
No Matches
ActiveGP.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#include "ActiveGP.h"
6
7#include <algorithm>
8#include <cmath>
9#include <stdexcept>
10
11namespace pot {
12
13ActiveGP::ActiveGP(std::shared_ptr<gpr::neb::ActiveLearningSession> session,
14 OracleFn oracle, Config config)
15 : session_(std::move(session)), oracle_(std::move(oracle)), config_(config)
16{
17 if (!session_) throw std::invalid_argument("ActiveGP: null session");
18 if (!oracle_) throw std::invalid_argument("ActiveGP: null oracle");
19 session_->setRefitTrainingRevisions(config_.refit_training_revisions);
20}
21
22std::uint64_t ActiveGP::modelState() const noexcept
23{
24 return session_->surfaceEpoch();
25}
26
27long ActiveGP::trainingSize() const noexcept
28{
29 return static_cast<long>(session_->training_obs.R.rows());
30}
31
32double ActiveGP::noiseSigma() const
33{
34 const double sigma2 = session_->gp.getLikGaussian().getSigma2();
35 return std::sqrt(std::max(sigma2, 0.0));
36}
37
38void ActiveGP::predict(long n_atoms, const double* positions, double* forces,
39 double* energy, double* variance)
40{
41 const long dof = 3 * n_atoms;
42 gpr::Observation query;
43 query.R.resize(1, dof);
44 for (long i = 0; i < dof; ++i)
45 query.R(0, i) = positions[i];
46 session_->predictAtImage(-1, query);
47
48 *energy = (query.E.size() > 0) ? query.E(0, 0) : 0.0;
49 if (query.G.rows() > 0 && query.G.cols() == dof) {
50 for (long i = 0; i < dof; ++i)
51 forces[i] = -query.G(0, i);
52 } else {
53 for (long i = 0; i < dof; ++i)
54 forces[i] = 0.0;
55 }
56
57 double var = 0.0;
58 Eigen::RowVectorXd gate;
59 if (session_->gp.tryGateEnergyVariance(query, gate) && gate.size() > 0) {
60 var = gate(0);
61 } else {
62 gpr::Observation probe = query;
63 session_->gp.calculateVariance(probe);
64 if (probe.E.size() > 0) var = probe.E(0, 0);
65 }
66 *variance = std::max(var, 0.0);
67}
68
69int ActiveGP::acquire(long n_atoms, const double* positions,
70 const int* atomic_nrs, const double* box, double* energy,
71 double* forces, AcquireReason reason, bool learn)
72{
73 if (on_acquire_) on_acquire_(reason);
74 const int rc = oracle_(n_atoms, positions, atomic_nrs, box, energy, forces);
75 ++oracle_calls_;
76 if (rc != 0) return rc;
77 if (!learn) return 0;
78
79 const long dof = 3 * n_atoms;
80 Eigen::VectorXd R(dof);
81 Eigen::VectorXd G(dof);
82 for (long i = 0; i < dof; ++i) {
83 R(i) = positions[i];
84 G(i) = -forces[i];
85 }
86 // Acquisition: the row is recorded (and archived) immediately.
87 // Incorporation -- the refit that moves the surface -- waits for a
88 // declared boundary.
89 session_->appendObservation(R, *energy, G);
90 pending_incorporation_ = true;
91 return 0;
92}
93
95{
96 std::lock_guard<std::mutex> guard(mutex_);
97 if (!pending_incorporation_) return;
98 const std::uint64_t before = session_->surfaceEpoch();
99 // The session's own training-revision cadence decides whether this
100 // is a full hyperparameter refit or a fixed-theta rematerialize.
101 session_->refreshCovarianceCache();
102 pending_incorporation_ = false;
103 const std::uint64_t after = session_->surfaceEpoch();
104 if (after != before && on_model_update_) on_model_update_(after);
105}
106
107int ActiveGP::force(long n_atoms, const double* positions,
108 const int* atomic_nrs, double* forces, double* energy,
109 double* variance, const double* box)
110{
111 if (n_atoms <= 0 || positions == nullptr || forces == nullptr ||
112 energy == nullptr) {
113 return -1;
114 }
115 std::lock_guard<std::mutex> guard(mutex_);
116
117 // Acquired rows do not define a posterior before incorporation.
118 const bool cold = !session_->gp.activateMaterializedPosterior();
119 double var = 0.0;
120 if (!cold) {
121 predict(n_atoms, positions, forces, energy, &var);
122 // *energy is the prediction only after this write. On the cold
123 // path the caller's slot is unread and must not skip acquisition.
124 // A non-finite prediction returns a sized zero gradient and does
125 // not call abs on the force.
126 if (!std::isfinite(*energy)) {
127 for (long i = 0; i < 3 * n_atoms; ++i)
128 forces[i] = 0.0;
129 if (variance != nullptr) *variance = var;
130 return 0;
131 }
132 }
133
134 const double sigma = noiseSigma();
135 const double lo = config_.sigma_lo_factor * sigma;
136 const double hi = config_.sigma_hi_factor * sigma;
137 const double sd = std::sqrt(var);
138
139 // A cold model has no posterior to gate on.
140 bool delegate = cold || sd > lo;
141 AcquireReason reason =
144 bool learn = !(!cold && sd > hi);
145
146 // Certify below force: a surrogate convergence claim is verified
147 // against ground truth before it can stand.
148 if (!delegate && config_.certify_below_force > 0.0) {
149 double max_force = 0.0;
150 bool finite_forces = true;
151 for (long i = 0; i < 3 * n_atoms; ++i) {
152 if (!std::isfinite(forces[i])) {
153 finite_forces = false;
154 break;
155 }
156 max_force = std::max(max_force, std::abs(forces[i]));
157 }
158 if (!finite_forces) {
159 for (long i = 0; i < 3 * n_atoms; ++i)
160 forces[i] = 0.0;
161 } else if (max_force < config_.certify_below_force) {
162 delegate = true;
163 reason = AcquireReason::Certify;
164 learn = true;
165 }
166 }
167
168 if (!delegate) {
169 if (variance != nullptr) *variance = var;
170 return 0;
171 }
172
173 const int rc = acquire(n_atoms, positions, atomic_nrs, box, energy, forces,
174 reason, learn);
175 if (rc != 0) return rc;
176 // The oracle is exact at the point it was called.
177 if (variance != nullptr) *variance = 0.0;
178 return 0;
179}
180
181int ActiveGP::forceBatch(long n_systems, long n_atoms, const double* positions,
182 const int* atomic_nrs, double* forces,
183 double* energies, double* variances,
184 const double* boxes)
185{
186 if (n_systems <= 0 || n_atoms <= 0 || positions == nullptr ||
187 forces == nullptr || energies == nullptr) {
188 return -1;
189 }
190 std::lock_guard<std::mutex> guard(mutex_);
191 const long dof = 3 * n_atoms;
192 // Acquired rows do not define a posterior before incorporation.
193 const bool cold = !session_->gp.activateMaterializedPosterior();
194
195 std::vector<double> var(static_cast<std::size_t>(n_systems), 0.0);
196 long worst = -1;
197 double worst_sd = -1.0;
198 for (long s = 0; s < n_systems; ++s) {
199 if (cold) {
200 for (long i = 0; i < dof; ++i)
201 forces[s * dof + i] = 0.0;
202 energies[s] = 0.0;
203 } else {
204 predict(n_atoms, positions + s * dof, forces + s * dof,
205 &energies[s], &var[static_cast<std::size_t>(s)]);
206 }
207 const double sd = std::sqrt(var[static_cast<std::size_t>(s)]);
208 if (sd > worst_sd) {
209 worst_sd = sd;
210 worst = s;
211 }
212 }
213
214 const double sigma = noiseSigma();
215 const double lo = config_.sigma_lo_factor * sigma;
216 const double hi = config_.sigma_hi_factor * sigma;
217
218 // Acquisition: the least resolved system above the gate is the
219 // one worth a true evaluation this round.
220 if (cold || (worst >= 0 && worst_sd > lo)) {
221 const long pick = cold ? 0 : worst;
222 const bool learn = cold || worst_sd <= hi;
223 const int rc = acquire(n_atoms, positions + pick * dof, atomic_nrs,
224 boxes != nullptr ? boxes + pick * 9 : nullptr,
225 &energies[pick], forces + pick * dof,
226 AcquireReason::Batch, learn);
227 if (rc != 0) return rc;
228 var[static_cast<std::size_t>(pick)] = 0.0;
229 }
230
231 if (variances != nullptr) {
232 for (long s = 0; s < n_systems; ++s) {
233 variances[s] = var[static_cast<std::size_t>(s)];
234 }
235 }
236
237 // The batch call is an incorporation boundary.
238 if (pending_incorporation_) {
239 const std::uint64_t before = session_->surfaceEpoch();
240 session_->refreshCovarianceCache();
241 pending_incorporation_ = false;
242 const std::uint64_t after = session_->surfaceEpoch();
243 if (after != before && on_model_update_) on_model_update_(after);
244 }
245 return 0;
246}
247
248} // namespace pot
double getSigma2() const noexcept
Get sigma2 value (the per-row noise variance added to the energy diagonal of the training kernel by e...
Definition LikGaussian.h:74
AcquireReason
Fired when a point is delegated, before the oracle runs.
Definition ActiveGP.h:64
std::uint64_t modelState() const noexcept
Definition ActiveGP.cpp:22
ActiveGP(std::shared_ptr< gpr::neb::ActiveLearningSession > session, OracleFn oracle, Config config=Config())
Definition ActiveGP.cpp:13
ActiveGPConfig Config
Definition ActiveGP.h:69
void incorporate()
Host-requested incorporation boundary (the ABI hint channel).
Definition ActiveGP.cpp:94
int forceBatch(long n_systems, long n_atoms, const double *positions, const int *atomic_nrs, double *forces, double *energies, double *variances, const double *boxes)
Definition ActiveGP.cpp:181
std::function< int(long n_atoms, const double *positions, const int *atomic_nrs, const double *box, double *energy, double *forces)> OracleFn
Definition ActiveGP.h:59
int force(long n_atoms, const double *positions, const int *atomic_nrs, double *forces, double *energy, double *variance, const double *box)
Definition ActiveGP.cpp:107
long trainingSize() const noexcept
Training rows currently held.
Definition ActiveGP.cpp:27
double variance(const Weights &w, const Matrix &covariance)
Potential wrappers and the batched oracle interface.
STL namespace.
Observation data: energy, gradient and positions.
FieldMatrixd E
void predictAtImage(int i, gpr::Observation &probe)
Definition Session.h:2810
gpr::GaussianProcessRegression gp
Definition Session.h:471