Loading...
Searching...
No Matches
RgminObjective.h
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// Copyright (c) gpridge developers
3// See LICENSE for details.
4
5#ifndef GPR_ML_RGMIN_OBJECTIVE_H_
6#define GPR_ML_RGMIN_OBJECTIVE_H_
7
8#include <rgmin.h>
9
10#include <Eigen/Core>
11#include <cmath>
12#include <concepts>
13#include <cstdint>
14#include <cstdio>
15#include <cstring>
16#include <exception>
17#include <functional>
18#include <limits>
19#include <memory>
20#include <stdexcept>
21#include <utility>
22
24#include "MapObjective.h"
25#include "NlmlCurvature.h"
26#include "PhaseTimers.h"
27#include "RgminAbi.h"
28
29namespace funcmin {
30
34 void operator()(DLManagedTensorVersioned* tensor) const noexcept;
35};
37 std::unique_ptr<DLManagedTensorVersioned, RgminTensorDeleter>;
38
42public:
43 [[nodiscard]] bool failed() const noexcept
44 {
45 return bool(error_);
46 }
47 rgmin_status_t capture(const char* callback) noexcept;
48 void report() const noexcept;
49
50 template <std::invocable Callback>
51 requires std::same_as<std::invoke_result_t<Callback>, rgmin_status_t>
52 rgmin_status_t invoke(const char* name, Callback&& callback) noexcept
53 {
54 if (failed()) return RGMIN_INTERNAL_ERROR;
55 try {
56 return std::invoke(std::forward<Callback>(callback));
57 } catch (...) {
58 return capture(name);
59 }
60 }
61
62private:
63 std::exception_ptr error_;
64 const char* callback_ = nullptr;
65};
66
67} // namespace funcmin
68
69namespace funcmin {
70
71Eigen::Map<const Eigen::VectorXd> tensorToVec(
72 const DLManagedTensorVersioned* tensor);
73Eigen::Map<Eigen::VectorXd> tensorToVec(DLManagedTensorVersioned* tensor);
74
79template <typename ClassName, typename FuncName>
82 const Eigen::VectorXd& x_ind;
83 const Eigen::VectorXd& y;
84 ClassName& holder;
85 const FuncName func;
87 const bool exact_curvature;
88 struct Sample {
89 Eigen::VectorXd w;
90 Eigen::VectorXd gradient;
91 double energy = 0.0;
92 std::size_t objective_work = 0;
93 bool holder_called = false;
94 bool valid = false;
95
96 [[nodiscard]] bool retainable() const
97 {
98 return valid && w.allFinite() && std::isfinite(energy) &&
99 gradient.size() == w.size() && gradient.allFinite();
100 }
101 };
102 bool trace_evaluations = false;
107
109 const Eigen::VectorXd& indices, const Eigen::VectorXd& targets,
110 ClassName& model, FuncName objective,
111 const MapObjectiveConfig& configuration,
112 bool use_exact_curvature, bool retain_step_samples = false,
113 std::function<bool()> stop_requested = {})
114 : x(positions),
115 x_ind(indices),
116 y(targets),
117 holder(model),
118 func(objective),
119 map_cfg(configuration),
120 exact_curvature(use_exact_curvature),
121 retain_samples_(retain_step_samples && !use_exact_curvature),
122 seed_retained_(retain_samples_),
123 stop_requested_(std::move(stop_requested))
124 {
125 if (func == nullptr)
126 throw std::invalid_argument("rgmin requires an objective function");
127 if constexpr (holder_caches_samples_) {
128 if (retain_samples_) {
129 if (const auto* point = holder.cachedObjectiveParameters()) {
130 holder_request_w_ = *point;
131 holder_request_ok_ = point->allFinite();
132 }
133 }
134 }
135 }
136
137 rgmin_status_t captureCallbackError(const char* callback) noexcept
138 {
139 trial_.valid = false;
140 retained_.valid = false;
141 request_ok_ = false;
142 holder_request_ok_ = false;
143 physical_ok_ = false;
144 seed_retained_ = false;
145 return failure.capture(callback);
146 }
147
150 void pinAt(const Eigen::VectorXd& w)
151 {
152 if (!retain_samples_ || failure.failed()) return;
153 if (retained_.retainable() && sameRepresentedPoint(retained_.w, w))
154 return;
155 retained_.valid = false;
156 if (trial_.retainable() && sameRepresentedPoint(trial_.w, w))
157 retained_ = trial_;
158 }
159
160 [[nodiscard]] std::size_t logicalObjectiveWork() const noexcept
161 {
162 return logical_work_;
163 }
164
165 [[nodiscard]] std::size_t physicalObjectiveWork() const noexcept
166 {
167 return physical_work_;
168 }
169
170 const Sample& evalAt(const Eigen::VectorXd& w)
171 {
172 if (stop_requested_ && stop_requested_())
174 // The budget follows a separate single-entry request cache, including
175 // rejected-domain keys and numerical equality of the signs of zero.
176 const bool logical_miss =
177 retain_samples_ &&
178 (!request_ok_ || !sameRequestPoint(request_w_, w));
179 if (logical_miss) {
180 request_ok_ = false;
181 request_w_ = w;
182 }
183 bool charge_work = logical_miss;
184 if constexpr (holder_caches_samples_) {
185 if (holder_request_ok_ && sameRequestPoint(holder_request_w_, w))
186 charge_work = false;
187 }
188 const Sample* sample = nullptr;
189 if (trial_.valid && (retain_samples_ ? sameRepresentedPoint(trial_.w, w)
190 : sameRequestPoint(trial_.w, w))) {
191 sample = &trial_;
192 } else if (retain_samples_ && retained_.valid &&
193 sameRepresentedPoint(retained_.w, w)) {
194 sample = &retained_;
195 }
196 if (sample != nullptr) {
197 if (charge_work) logical_work_ += replayWork(*sample);
198 } else {
199 sample = &evaluate(w, charge_work);
200 }
201 if (logical_miss) {
202 request_ok_ = true;
203 if constexpr (holder_caches_samples_) {
204 // A domain rejection never enters the holder's own cache.
205 if (sample->holder_called) {
206 holder_request_ok_ = sample->retainable();
207 if (holder_request_ok_) holder_request_w_ = w;
208 }
209 }
210 }
211 if (seed_retained_ && sample->retainable()) {
212 retained_ = *sample;
213 seed_retained_ = false;
214 }
215 return *sample;
216 }
217
220 rgmin_status_t restoreHolderAt(const Eigen::VectorXd& w) noexcept
221 {
222 if (failure.failed()) return RGMIN_INTERNAL_ERROR;
223 if (!retain_samples_ ||
224 (physical_ok_ && sameRepresentedPoint(physical_w_, w)))
225 return RGMIN_SUCCESS;
226 try {
227 return evaluate(w, false).retainable() ? RGMIN_SUCCESS
228 : RGMIN_INVALID_PARAMETER;
229 } catch (...) {
230 return captureCallbackError("final objective");
231 }
232 }
233
234private:
235 // A holder with its own one-entry cache exposes its initial key and its
236 // uncached timer weight. A physical cache hit cannot measure that weight.
237 static constexpr bool holder_caches_samples_ =
238 requires(const ClassName& model) {
239 {
240 model.cachedObjectiveParameters()
241 } -> std::same_as<const Eigen::VectorXd*>;
242 {
243 ClassName::objective_cache_miss_work
244 } -> std::convertible_to<std::size_t>;
245 };
246 const bool retain_samples_;
247 bool seed_retained_;
248 Sample trial_;
249 Sample retained_;
250 Eigen::VectorXd request_w_;
251 Eigen::VectorXd holder_request_w_;
252 Eigen::VectorXd physical_w_;
253 bool request_ok_ = false;
254 bool holder_request_ok_ = false;
255 bool physical_ok_ = false;
256 std::size_t logical_work_ = 0;
257 std::size_t physical_work_ = 0;
258 std::function<bool()> stop_requested_;
259
260 static bool sameRequestPoint(const Eigen::VectorXd& a,
261 const Eigen::VectorXd& b)
262 {
263 return a.size() == b.size() && (a - b).lpNorm<Eigen::Infinity>() == 0.0;
264 }
265
266 static bool sameRepresentedPoint(const Eigen::VectorXd& a,
267 const Eigen::VectorXd& b)
268 {
269 return a.size() == b.size() && a.allFinite() && b.allFinite() &&
270 (a.size() == 0 ||
271 std::memcmp(
272 a.data(), b.data(),
273 static_cast<std::size_t>(a.size()) * sizeof(double)) == 0);
274 }
275
276 static std::size_t replayWork(const Sample& sample)
277 {
278 if constexpr (holder_caches_samples_) {
279 if (sample.holder_called && sample.objective_work == 0)
280 return ClassName::objective_cache_miss_work;
281 }
282 return sample.objective_work;
283 }
284
285 const Sample& evaluate(const Eigen::VectorXd& w, bool charge_work)
286 {
287 trial_.valid = false;
288 trial_.w = w;
289 trial_.gradient.resize(w.size());
290 trial_.objective_work = 0;
291 trial_.holder_called = false;
293 trial_.energy = std::numeric_limits<double>::infinity();
294 trial_.gradient.setConstant(
295 std::numeric_limits<double>::quiet_NaN());
296 trial_.valid = true;
297 return trial_;
298 }
299 trial_.energy = 0.0;
300 gpr::EnergyAndGradient eg(trial_.energy, trial_.gradient);
301 const int work_before = gpr::PhaseTimers::objective_count;
302 const auto record_work = [&](bool completed) {
303 const int delta = gpr::PhaseTimers::objective_count - work_before;
304 trial_.objective_work =
305 static_cast<std::size_t>(delta > 0 ? delta : 0);
306 physical_work_ += trial_.objective_work;
307 if (charge_work)
308 logical_work_ +=
309 completed ? replayWork(trial_) : trial_.objective_work;
310 };
311 physical_ok_ = false;
312 trial_.holder_called = true;
313 try {
314 (holder.*func)(w, x, x_ind, y, eg);
315 } catch (...) {
316 record_work(false);
317 throw;
318 }
319 record_work(true);
320 trial_.valid = true;
321 if (retain_samples_) {
322 physical_w_ = w;
323 physical_ok_ = trial_.retainable();
324 }
325 if (trace_evaluations) {
326 double value = trial_.energy;
327 Eigen::VectorXd gradient = trial_.gradient;
328 applyMapPenalty(w, map_cfg, value, &gradient);
329 std::fprintf(stderr, "[map-evaluation] value=%.17g theta=", value);
330 for (Eigen::Index i = 0; i < w.size(); ++i)
331 std::fprintf(stderr, " %.17g", w(i));
332 std::fprintf(stderr, " gradient=");
333 for (Eigen::Index i = 0; i < gradient.size(); ++i)
334 std::fprintf(stderr, " %.17g", gradient(i));
335 std::fprintf(stderr, "\n");
336 }
337 return trial_;
338 }
339};
340
341template <typename Ctx>
342rgmin_status_t rgminEval(void* user, const DLManagedTensorVersioned* x,
343 double* value_out) noexcept
344{
345 auto* ctx = static_cast<Ctx*>(user);
346 *value_out = std::numeric_limits<double>::infinity();
347 if (ctx->failure.failed()) return RGMIN_INTERNAL_ERROR;
348 try {
349 const Eigen::VectorXd w = tensorToVec(x);
350 const auto& sample = ctx->evalAt(w);
351 double energy = sample.energy;
352 if (sample.gradient.size() != w.size() || !std::isfinite(energy))
353 return RGMIN_SUCCESS;
354 applyMapPenalty(w, ctx->map_cfg, energy, nullptr);
355 *value_out = energy;
356 return RGMIN_SUCCESS;
357 } catch (...) {
358 return ctx->captureCallbackError("objective");
359 }
360}
361
362template <typename Ctx>
363rgmin_status_t rgminGrad(void* user, const DLManagedTensorVersioned* x,
364 DLManagedTensorVersioned* grad_out) noexcept
365{
366 auto* ctx = static_cast<Ctx*>(user);
367 auto* gp = reinterpret_cast<double*>(
368 static_cast<uint8_t*>(grad_out->dl_tensor.data) +
369 static_cast<std::size_t>(grad_out->dl_tensor.byte_offset));
370 Eigen::Map<Eigen::VectorXd> gout(gp, grad_out->dl_tensor.shape[0]);
371 gout.setConstant(std::numeric_limits<double>::quiet_NaN());
372 if (ctx->failure.failed()) return RGMIN_INTERNAL_ERROR;
373 try {
374 const Eigen::VectorXd w = tensorToVec(x);
375 const auto& sample = ctx->evalAt(w);
376 double energy = sample.energy;
377 Eigen::VectorXd g = sample.gradient;
378 if (g.size() != w.size() || g.size() != gout.size() ||
379 !std::isfinite(energy))
380 return RGMIN_SUCCESS;
381 applyMapPenalty(w, ctx->map_cfg, energy, &g);
382 projectMapGradient(ctx->map_cfg, g);
383 gout = g;
384 return RGMIN_SUCCESS;
385 } catch (...) {
386 return ctx->captureCallbackError("gradient");
387 }
388}
389
390template <typename Ctx>
391rgmin_status_t rgminCurv(void* user, const DLManagedTensorVersioned* x,
392 const DLManagedTensorVersioned* d,
393 double* curv_out) noexcept
394{
395 auto* ctx = static_cast<Ctx*>(user);
396 *curv_out = std::numeric_limits<double>::quiet_NaN();
397 if (ctx->failure.failed()) return RGMIN_INTERNAL_ERROR;
398 if (!ctx->exact_curvature) return RGMIN_INVALID_PARAMETER;
399 try {
400 const Eigen::VectorXd w = tensorToVec(x);
401 const Eigen::VectorXd dir = tensorToVec(d);
402 double exact = std::numeric_limits<double>::quiet_NaN();
403 if (!ctx->holder.evaluateDirectionalCurvature(ctx->x_ind, ctx->x,
404 ctx->y, dir, exact) ||
405 !std::isfinite(exact)) {
406 return RGMIN_INVALID_PARAMETER;
407 }
408 *curv_out =
409 exact + mapPenaltyDirectionalCurvature(w, dir, ctx->map_cfg);
410 return RGMIN_SUCCESS;
411 } catch (...) {
412 return ctx->captureCallbackError("curvature");
413 }
414}
415
422template <typename Ctx>
423rgmin_status_t rgminNlmlHessianVectorCurv(void* user,
424 const DLManagedTensorVersioned* x,
425 const DLManagedTensorVersioned* d,
426 double* curv_out) noexcept
427{
428 auto* ctx = static_cast<Ctx*>(user);
429 *curv_out = std::numeric_limits<double>::quiet_NaN();
430 if (ctx->failure.failed()) return RGMIN_INTERNAL_ERROR;
431 if (ctx->hessian_vector_fallback) return RGMIN_UNAVAILABLE;
432 try {
433 const Eigen::VectorXd w = tensorToVec(x);
434 const Eigen::VectorXd dir = tensorToVec(d);
435 double exact = std::numeric_limits<double>::quiet_NaN();
436 const bool product = holderNlmlDirectionalCurvature(
437 ctx->holder, ctx->x_ind, ctx->x, ctx->y, dir, exact);
438 const double curvature =
439 exact + mapPenaltyDirectionalCurvature(w, dir, ctx->map_cfg);
440 if (!product || !std::isfinite(curvature)) {
441 ctx->hessian_vector_fallback = true;
442 return RGMIN_UNAVAILABLE;
443 }
444 *curv_out = curvature;
445 return RGMIN_SUCCESS;
446 } catch (...) {
447 return ctx->captureCallbackError("curvature");
448 }
449}
450
451} // namespace funcmin
452
453#endif // GPR_ML_RGMIN_OBJECTIVE_H_
@ x
Definition Enums.h:28
@ y
Definition Enums.h:28
rgmin_status_t capture(const char *callback) noexcept
rgmin_status_t invoke(const char *name, Callback &&callback) noexcept
bool failed() const noexcept
void report() const noexcept
eon_relax_band_t eon_relax_surface_fn void * user
void applyMapPenalty(const Eigen::VectorXd &w, const MapObjectiveConfig &cfg, double &energy, Eigen::VectorXd *gradient)
rgmin_status_t rgminNlmlHessianVectorCurv(void *user, const DLManagedTensorVersioned *x, const DLManagedTensorVersioned *d, double *curv_out) noexcept
rgmin_status_t rgminCurv(void *user, const DLManagedTensorVersioned *x, const DLManagedTensorVersioned *d, double *curv_out) noexcept
bool holderNlmlDirectionalCurvature(Holder &holder, const Eigen::VectorXd &x_ind, const gpr::EigenMatrix &x, const Eigen::VectorXd &y, const Eigen::VectorXd &direction, double &curvature)
Eigen::Map< const Eigen::VectorXd > tensorToVec(const DLManagedTensorVersioned *tensor)
std::unique_ptr< DLManagedTensorVersioned, RgminTensorDeleter > RgminTensorHandle
rgmin_status_t rgminEval(void *user, const DLManagedTensorVersioned *x, double *value_out) noexcept
bool mapParametersInDomain(const Eigen::VectorXd &w, const MapObjectiveConfig &cfg)
rgmin_status_t rgminGrad(void *user, const DLManagedTensorVersioned *x, DLManagedTensorVersioned *grad_out) noexcept
void projectMapGradient(const MapObjectiveConfig &cfg, Eigen::VectorXd &gradient)
double mapPenaltyDirectionalCurvature(const Eigen::VectorXd &w, const Eigen::VectorXd &direction, const MapObjectiveConfig &cfg)
Eigen::Matrix< double, EigenDynamic, EigenDynamic, EigenMatrixStorage > EigenMatrix
Definition Macros.h:20
STL namespace.
RgminNlmlCtx(const gpr::EigenMatrix &positions, const Eigen::VectorXd &indices, const Eigen::VectorXd &targets, ClassName &model, FuncName objective, const MapObjectiveConfig &configuration, bool use_exact_curvature, bool retain_step_samples=false, std::function< bool()> stop_requested={})
const Eigen::VectorXd & x_ind
const MapObjectiveConfig & map_cfg
const Sample & evalAt(const Eigen::VectorXd &w)
const gpr::EigenMatrix & x
void pinAt(const Eigen::VectorXd &w)
std::size_t logicalObjectiveWork() const noexcept
rgmin_status_t captureCallbackError(const char *callback) noexcept
std::size_t physicalObjectiveWork() const noexcept
rgmin_status_t restoreHolderAt(const Eigen::VectorXd &w) noexcept
const Eigen::VectorXd & y
RgminCallbackFailure failure
void operator()(DLManagedTensorVersioned *tensor) const noexcept
static int objective_count